@sourcegraph/amp 0.0.1751544357-g213afc → 0.0.1751558552-ga58f43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +4 -4
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -7353,7 +7353,7 @@ ${B.join(`
7353
7353
  `)}function gr6(A,Q){if(A.state!=="active")return{type:"idle"};let B=cC(Q);if(B)return B;if(A.state==="active"){let J=[];for(let D of Q.messages)if(D.role==="user"){for(let z of D.content)if(z.type==="tool_result"&&z.run.status==="in-progress")J.push(z)}if(J.length>0){let D=J[0],z=y7(Q,D.toolUseID);if(z){let Z=J.slice(1).map((X)=>{return y7(Q,X.toolUseID)?.name||"tool"}).filter(Boolean);return g51(z.name,J.length,Date.now(),z.input,Z.length>0?Z:void 0)}}}return{type:"idle"}}class tf1{dependencies;subthreads=new Map;nextAgentNumber=1;events=new C8;constructor(A){this.dependencies=A}get events$(){return this.events}async trackSubthread(A,Q,B){if(this.subthreads.has(A))return;try{let J=await sZ.getOrCreateForThread({configService:this.dependencies.configService,threadService:this.dependencies.threadService,toolService:this.dependencies.toolService,getThreadEnvironment:If,systemPromptService:this.dependencies.systemPromptService,threadSummaryService:this.dependencies.threadSummaryService,createFileSystem:await Rd,threadHistoryService:this.dependencies.threadHistoryService,mcpService:this.dependencies.mcpService},A);await J.resume();let D=this.nextAgentNumber++,z={threadID:A,worker:J,agentNumber:D,printedMessageIndexes:new Set,printedToolRuns:new Set,requestedToolConfirmations:new Set,taskDescription:Q,isCompleted:!1};if(this.subthreads.set(A,z),Q&&B)this.events.next({type:"subagent-started",subThreadID:A,agentNumber:D,taskDescription:Q,taskPrompt:B});J.status.subscribe(async(X)=>{if(!z.isCompleted){if(X.state==="active"&&X.inferenceState==="cancelled"){z.isCompleted=!0,this.events.next({type:"subagent-cancelled",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task cancelled"});return}if(X.state==="active"&&X.ephemeralError){z.isCompleted=!0,this.events.next({type:"subagent-error",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task failed",error:X.ephemeralError.message||"Unknown error occurred"});return}try{let K=await l6(this.dependencies.threadService.observe(A).pipe(t7((G)=>G!==void 0)));if(K){let G=gr6(X,K);if(this.events.next({type:"subagent-status",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Running task",agentState:G}),X.state==="active"){let q=[];for(let Y of K.messages)if(Y.role==="user"){for(let F of Y.content)if(F.type==="tool_result"&&F.run.status==="in-progress")q.push(F)}for(let Y of q){let F=y7(K,Y.toolUseID);if(F){let E=`${A}-${F.id}`;if(!z.toolStartTimes)z.toolStartTimes=new Map;if(!z.toolStartTimes.has(E))z.toolStartTimes.set(E,Date.now());this.events.next({type:"tool-status",toolUse:F,status:"running",startTime:z.toolStartTimes.get(E),subthreadID:A})}}}}}catch(K){k1.error(`Failed to get thread for status update: ${A}`,K)}}}),gW(this.dependencies.threadService.observe(A).pipe(t7((X)=>X!==void 0))).observable.subscribe((X)=>{if(!X)return;let K=wz(X,"assistant");if(ha(K)&&!z.isCompleted){z.isCompleted=!0,this.events.next({type:"subagent-cancelled",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task cancelled"});return}if(K?.state?.type==="error"&&!z.isCompleted){z.isCompleted=!0,this.events.next({type:"subagent-error",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task failed",error:K.state.error.message||"Unknown error occurred"});return}for(let F of X.messages)if(F.role==="user"){for(let E of F.content)if(E.type==="tool_result"){let w=y7(X,E.toolUseID);if(w&&!z.printedToolRuns.has(E.toolUseID)){let H=E.run.status==="done"?"completed":E.run.status==="error"?"error":E.run.status==="cancelled"?"cancelled":void 0;if(H){z.printedToolRuns.add(E.toolUseID);let M=`${A}-${w.id}`,W=z.toolStartTimes?.get(M);if(this.events.next({type:"tool-status",toolUse:w,status:H,startTime:W,endTime:Date.now(),subthreadID:A}),z.toolStartTimes)z.toolStartTimes.delete(M)}}}}let q=wz(X,"user")?.content.filter((F)=>F.type==="tool_result"&&F.run.status==="blocked-on-user")??[];if(q.length>0&&!z.isCompleted){let F=[];for(let E of q){let w=y7(X,E.toolUseID);if(w&&w.name===o4&&E.run.status==="blocked-on-user"&&E.userInput===void 0&&!z.requestedToolConfirmations.has(E.toolUseID))F.push({useBlock:w,toAllow:E.run.toAllow}),z.requestedToolConfirmations.add(E.toolUseID)}if(F.length>0)this.events.next({type:"subthread-tool-request",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Running task",tools:F})}if(K?.state.type==="complete"&&K?.state.stopReason==="end_turn"&&!z.isCompleted){z.isCompleted=!0;let F=K.content.filter((E)=>E.type==="text").map((E)=>E.text).join(`
7354
7354
 
7355
7355
  `);this.events.next({type:"subagent-finished",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task completed",result:F})}if(!z.isCompleted){let F=yf(X,z.printedMessageIndexes,z.printedToolRuns);if(F.blocks.length>0)this.events.next({type:"subthread-message",subThreadID:A,agentNumber:z.agentNumber,blocks:F.blocks})}}),k1.debug(`Started tracking subthread ${A}`)}catch(J){k1.error(`Failed to track subthread ${A}`,J)}}scanForTaskToolSubthreads(A){for(let Q of A.messages)if(Q.role==="user"){for(let B of Q.content)if(B.type==="tool_result"){let J=y7(A,B.toolUseID);if(J?.name===EQ&&(B.run.status==="in-progress"||B.run.status==="done"||B.run.status==="cancelled")){let D="progress"in B.run?B.run.progress:void 0,z=cy(D);if(z)this.trackSubthread(z,J.input?.description,J.input?.prompt).catch((Z)=>{k1.error(`Failed to track Task tool subthread ${z}`,Z)})}}}}async handleToolConfirmations(A,Q){let B=this.subthreads.get(A);if(!B){k1.error(`No tracker found for subthread ${A}`);return}k1.info(`Sending tool confirmations to subthread ${A}`,{toolCount:Q.size,responses:Array.from(Q.entries()).map(([J,D])=>({id:J,accepted:D}))});for(let[J,D]of Q)k1.info("Sending tool confirmation to subthread worker",{subThreadID:A,toolUseID:J,accepted:D}),await B.worker.handle({type:"user:tool-input",toolUse:J,value:{accepted:D}})}dispose(){for(let A of this.subthreads.values())A.worker.dispose();this.subthreads.clear(),this.events.complete()}}y2();function M4A(A){let Q=["prompt is too long","exceed context limit"],B=A.error?.type==="invalid_request_error"&&Q.some((D)=>A.error?.message?.includes(D)),J=Q.some((D)=>A.message?.includes(D));return B||J}var W4A="Out of credits";Hz();ql();va();D2();b51();AK();A81();aL();import{readdir as br6}from"node:fs/promises";import{homedir as xr6}from"node:os";async function I4A(A,Q){let J=!(await Q81(A,Q)).some((z)=>z.type==="project"),D=await hr6();return{shouldGenerate:J&&D}}async function hr6(){let A=process.cwd(),Q=xr6();if(A===Q)return!1;try{return(await br6(A)).length>0}catch{return!1}}async function N4A(A){await A.handle({type:"user:message",message:{content:[{type:"text",text:mu0}]}})}y2();function a3(A,Q){return(B,J)=>{let D=Q(B,J);if(J.type!=="tick")k1.debug("Transition",{name:A,before:B,event:J,after:D});return D}}y2();import{spawn as V4A}from"node:child_process";import{readlink as mr6,stat as ur6}from"node:fs/promises";import{dirname as C4A,join as pr6}from"node:path";async function O4A(A){try{let Q=new AbortController,B=setTimeout(()=>Q.abort(),500),J=await fetch("https://registry.npmjs.org/@sourcegraph/amp/latest",{signal:Q.signal});if(clearTimeout(B),!J.ok)return{hasUpdate:!1};let z=(await J.json()).version;if(z===void 0)return{hasUpdate:!1};let Z=cr6(A,z),X=Z<0;return k1.info("Version comparison",{currentVersion:A,latestVersion:z,compareResult:Z,hasUpdate:X}),{hasUpdate:X,latestVersion:z}}catch(Q){return{hasUpdate:!1}}}function cr6(A,Q){let B=(Z)=>{let[X,K]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:K}},J=B(A),D=B(Q),z=Math.max(J.parts.length,D.parts.length);for(let Z=0;Z<z;Z++){let X=J.parts[Z]||0,K=D.parts[Z]||0;if(X<K)return-1;if(X>K)return 1}if(J.label===D.label)return 0;if(!J.label&&D.label)return 1;if(J.label&&!D.label)return-1;if(J.label&&D.label)return J.label<D.label?-1:1;return 0}async function lr6(){try{let A=process.argv[1]||"";k1.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{let z=await mr6(A);if(z)Q=z,k1.debug("Resolved symlink",{from:A,to:Q});else k1.debug("Not a symlink or readlink returned empty")}catch(z){k1.debug("Error reading symlink (probably not a symlink)",{error:z})}if(k1.debug("Resolved installation path",{actualPath:Q}),Q.includes("/.local/share/pnpm/"))return k1.debug("Detected pnpm from path pattern: /.local/share/pnpm/"),"pnpm";if(Q.includes("/.config/yarn/global/"))return k1.debug("Detected yarn from path pattern: /.config/yarn/global/"),"yarn";if(Q.includes("/.bun/install/global/"))return k1.debug("Detected bun from path pattern: /.bun/install/global/"),"bun";if(Q.includes("/node_modules/@sourcegraph/amp/")){if(k1.debug("Found generic node_modules path, checking for specific patterns"),Q.includes("/.local/share/pnpm/"))return k1.debug("Detected pnpm from node_modules with pnpm-specific path"),"pnpm";if(Q.includes("/.config/yarn/"))return k1.debug("Detected yarn from node_modules with yarn-specific path"),"yarn";if(Q.includes("/.bun/"))return k1.debug("Detected bun from node_modules with bun-specific path"),"bun";return k1.debug("Defaulting to npm for generic node_modules path"),"npm"}k1.debug("No path pattern matched, checking installation directory for lockfiles");let B=C4A(C4A(Q));k1.debug("Checking installation directory",{installDir:B});let J=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:z,manager:Z}of J)try{let X=pr6(B,z);return k1.debug("Checking for lockfile",{filePath:X}),await ur6(X),k1.debug("Found package manager lockfile",{file:z,manager:Z,filePath:X}),Z}catch(X){k1.debug("Lockfile not found",{file:z,error:X})}k1.debug("No lockfiles found, falling back to environment-based detection");let D=await R4A();return k1.debug("Environment-based detection result",{envDetected:D}),D}catch(A){return k1.debug("Error detecting installed package manager",{error:A}),null}}async function R4A(){let A=process.env.npm_config_user_agent;if(A){if(A.includes("pnpm"))return"pnpm";if(A.includes("yarn"))return"yarn";if(A.includes("bun"))return"bun";if(A.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Q,B,J,D]=await Promise.allSettled([x51("pnpm"),x51("yarn"),x51("bun"),x51("npm")]);if(Q?.status==="fulfilled"&&Q?.value)return"pnpm";if(B?.status==="fulfilled"&&B?.value)return"yarn";if(J?.status==="fulfilled"&&J?.value)return"bun";if(D?.status==="fulfilled"&&D?.value)return"npm";return null}async function x51(A){return new Promise((Q)=>{try{let B=process.env.HOME||process.env.USERPROFILE||"/",D=`env -i ${process.env.SHELL||"/bin/sh"} -l -c 'cd ${B} && ${A} --version'`;k1.debug("Checking command existence",{command:A,fullCommand:D});let z=V4A("/bin/sh",["-c",D],{stdio:"ignore",cwd:process.env.HOME});z.on("close",(Z)=>{k1.debug("Command check result",{command:A,code:Z}),Q(Z===0)}),z.on("error",(Z)=>{k1.debug("Command check error",{command:A,error:Z}),Q(!1)})}catch(B){k1.debug("Error checking command existencer",{command:A,error:B}),Q(!1)}})}function dr6(A,Q){let B=Q?`@sourcegraph/amp@${Q}`:"@sourcegraph/amp";switch(A){case"pnpm":return["pnpm",["add","-g",B]];case"yarn":return["yarn",["global","add",B]];case"bun":return["bun",["add","-g",B]];case"npm":default:return["npm",["install","-g",B]]}}async function L4A(A){let Q=await lr6();if(!Q)Q=await R4A();if(!Q)Q="npm",k1.debug("Falling back to npm for update");k1.debug("Using package manager for update",{packageManager:Q,targetVersion:A});let[B,J]=dr6(Q,A);return new Promise((D,z)=>{let Z=process.env.HOME||process.env.USERPROFILE||"/",X=process.env.SHELL||"/bin/sh",K=`${B} ${J.join(" ")}`,G=`env -i ${X} -l -c 'cd ${Z} && ${K}'`;k1.debug("Running update command",{packageManager:Q,command:B,args:J,fullCommand:G});let q=V4A("/bin/sh",["-c",G],{stdio:"pipe",cwd:process.env.HOME}),Y="",F="";q.stdout?.on("data",(E)=>{Y+=E.toString()}),q.stderr?.on("data",(E)=>{F+=E.toString()}),q.on("close",(E)=>{if(E===0)D();else{let w=F||Y||"No output";z(new Error(`${B} ${J.join(" ")} failed with code ${E}:
7356
- ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function _4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let M=VT(),W=new Set,I=gW(B.observe(E).pipe(t7((S)=>S!==void 0))),N=new Set,V=new Map;await l6(I.observable);let _=await Rd,T=await sZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:If,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{k1.error("Initial resume",S)});let R=T.status.pipe(r6((S)=>{return{type:"worker-state",status:S}})),j=I.observable.pipe(r6((S)=>{return{type:"thread-state",thread:S}})),P=new C8,$=new C8,f=H(FA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=hU(R,j,hU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{k1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(qZ(()=>{b()})).pipe(XT(a3("threadSession",function(S,y){function d(D1){k1.info(`Processing user message: ${D1.slice(0,50)}${D1.length>50?"...":""}`);let A1="tokenUsage"in S?S.tokenUsage:void 0;if(A1&&A1.used/A1.maxAvailable>h51.CRITICAL)return k1.info("Blocking message at worker boundary - critical token usage"),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:"final",updateState:"updateState"in S?S.updateState:"none",toolConfirmationStatus:"toolConfirmationStatus"in S?S.toolConfirmationStatus:new Map,currentAssistantMessageIndex:("currentAssistantMessageIndex"in S?S.currentAssistantMessageIndex:null)??null,hasBeenIdle:"hasBeenIdle"in S?S.hasBeenIdle:!1,threadTitle:"threadTitle"in S?S.threadTitle:null,confirmationQueue:"confirmationQueue"in S?S.confirmationQueue:[]};T.handle({type:"user:message",message:{content:[{type:"text",text:D1}]}}).then(()=>{if(A)A.sync().catch((X1)=>{k1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{k1.error("Handle user message failed",X1)}),$.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});let K1=I.value.last;if(K1){let X1=cC(K1);if(X1)$.next({type:"state",state:X1})}return{...S,type:"awaiting-agent",displayedError:null}}async function a(){$.next({type:"state",state:{type:"compacting"}});let D1=await X.summarizeThread(E);await T.handle({type:"summary:created",summary:{type:"internal",summary:D1.summary}})}function z1(){if(S.type==="awaiting-user-message")return k1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{k1.error("Thread sync error",A1,{threadID:E})}),D1&&S.type!=="confirming-compaction"&&S.type!=="compacting"){let A1=D1.used/D1.maxAvailable,K1=void 0,X1=S.compactionPromptState;if(A1>h51.CRITICAL)K1="critical",X1="final";else if(A1>h51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>h51.SEVERE&&S.compactionPromptState==="first")K1="severe",X1="final";if(K1)return $.next({type:"confirm",confirmation:{type:"compaction",severity:K1}}),{type:"confirming-compaction",severity:K1,tokenUsage:S.tokenUsage,compactionPromptState:X1,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue}}if($.next({type:"accept-message",initial:!S.hasBeenIdle&&!w}),S.type==="awaiting-agent")S.cancelledWithMessage=void 0;if(D1)$.next({type:"token-usage",tokenUsage:D1});return{...S,type:"awaiting-user-message",hasBeenIdle:!0,tokenUsage:D1??null}}function t(D1){if(D1.length>0)k1.info(`Updating allowlist with ${D1.length} entries`,{entries:D1}),K.get("commands.allowlist","global").then((A1)=>{let K1=[...A1??[],...D1];return K.set("commands.allowlist",K1,"global")}).catch((A1)=>{k1.error("Failed to update allowlist",A1)})}if(S.type==="closing")return S;if(y.type==="thread-state"){let D1=y.thread.title||null;if(S.threadTitle!==D1&&D1!==null)$.next({type:"thread-title",title:D1});if(F.scanForTaskToolSubthreads(y.thread),w&&W.size===0&&y.thread.messages.length>0){let K1=yf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=xa(y.thread);if(K1)A1={used:K1.totalInputTokens,maxAvailable:K1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}if(S.type==="awaiting-user-confirmation")if(y.thread.messages.at(-1)?.content.some((K1)=>K1.type==="tool_result"&&(K1.run.status==="in-progress"||K1.run.status==="done"))){let K1=cC(y.thread);if(K1)$.next({type:"state",state:K1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};if(S.type==="awaiting-agent"||S.type==="compacting"){let K1=y.thread.messages.at(-1),X1=yf(y.thread,W,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=cC(y.thread);if(U1)$.next({type:"state",state:U1})}if(N1.length>0){for(let Y1 of N1)if(Y1.type==="toolResult"){let[U1,P1]=Y1.data,R1=P1.run.status==="done"?"completed":P1.run.status==="error"?"error":P1.run.status==="cancelled"?"cancelled":"running";if(R1!=="running")$.next({type:"tool-status",toolUse:U1,status:R1,startTime:V.get(U1.id),endTime:Date.now()}),V.delete(U1.id)}$.next({type:"messages",blocks:N1})}if(y.thread.messages.at(-1)?.content.some((Y1)=>Y1.type==="summary"))return{...z1(),tokenUsage:null,compactionPromptState:"none"};if(K1?.role==="assistant"&&K1?.state.type==="complete"&&K1?.state.stopReason==="end_turn"){$.next({type:"state",state:{type:"idle"}});let Y1=z1();return{...Y1,tokenUsage:A1??Y1.tokenUsage}}if(!I)throw new Error("unexpected: thread is required when waiting for tool input");let s=wz(y.thread,"assistant"),r=s?y.thread.messages.indexOf(s):null;if(r!==null&&r!==S.currentAssistantMessageIndex)k1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:r,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=r;let e=wz(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(s?.content.filter((Y1)=>Y1.type==="tool_use").map((Y1)=>Y1.id)??[]),q1=!1;for(let Y1 of e){if(!G1.has(Y1.toolUseID))continue;let U1=y7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===o4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,k1.info("Added new tool to confirmation tracking",{toolUseID:Y1.toolUseID,toolName:U1.name}),!V.has(U1.id))V.set(U1.id,Date.now());$.next({type:"tool-status",toolUse:U1,status:"blocked-on-user",startTime:V.get(U1.id)})}}if(q1){let Y1=Array.from(S.toolConfirmationStatus.entries()).filter(([U1,P1])=>P1==="awaiting");if(Y1.length>0){let[U1]=Y1[0],P1=e.find((T1)=>T1.toolUseID===U1),R1=P1?y7(y.thread,P1.toolUseID):null;if(P1&&R1)return k1.info(`Starting tool confirmation process for ${Y1.length} tools`,{firstToolID:U1,toolName:R1.name}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:R1,toAllow:P1.run.status==="blocked-on-user"?P1.run.toAllow:void 0}]}}),{...S,type:"collecting-tool-confirmations",currentToolID:U1,tokenUsage:A1}}}}}else if(y.type==="worker-state"){if(S.type==="awaiting-user-confirmation"&&y.status.state==="active"&&y.status.ephemeralError)return S;if(S.type==="collecting-tool-confirmations")return k1.info("Already collecting tool confirmations, ignoring worker-state event"),S;let D1=I.value.last?.messages.at(-1),A1=S.tokenUsage;if(y.status.state==="active"){let K1=I.value.last;if(K1){let X1=xa(K1);if(X1)A1={used:X1.totalInputTokens,maxAvailable:X1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}}if(S.type==="confirming-compaction"||S.type==="compacting")return{...S,tokenUsage:A1};switch(y.status.state){case"initial":if(S.type==="initializing")return S;return z1();case"active":if(y.status.ephemeralError)if(y.status.ephemeralError.message.includes(W4A)){if(S.type==="out-of-credits")return S;return $.next({type:"confirm",confirmation:{type:"out-of-credits"}}),{...S,type:"out-of-credits",tokenUsage:A1}}else if(M4A(y.status.ephemeralError))return k1.info("Context limit error, triggering compaction",{error:y.status.ephemeralError,tokenUsage:A1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:S.compactionPromptState,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue};else if(y.status.ephemeralError.message.includes("401 unauthorized"))return $.next({type:"error",error:{type:"unauthorized"},retryable:!1}),u.unsubscribe(),{...S,type:"closing"};else{let K1=y.status.ephemeralError.message;if(k1.error("Ephemeral error",{error:K1}),S.type==="awaiting-agent"&&S.displayedError!==K1)return $.next({type:"error",error:{type:"other",error:K1},retryable:!1}),{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else return S}switch(y.status.inferenceState){case"running":{let K1=I.value.last;if(K1){let X1=cC(K1);if(X1)$.next({type:"state",state:X1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}if(S.type==="initializing")return{...S,tokenUsage:A1};return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1};case"cancelled":if(S.type==="initializing")return{...S,tokenUsage:A1};if($.next({type:"cancelled"}),$.next({type:"state",state:{type:"idle"}}),S.type==="awaiting-agent"&&S.cancelledWithMessage)return S.cancelledWithMessage=void 0,{...S,tokenUsage:A1};else return{...z1(),tokenUsage:A1};case"idle":if(S.type==="initializing")return{...S,tokenUsage:A1};if(D1?.content.some((K1)=>K1.type==="tool_result"&&K1.run.status==="blocked-on-user"))return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else if(I.value.last?.messages.some((K1)=>K1.role==="user"&&K1.content.some((X1)=>X1.type==="tool_result"&&X1.run.status==="in-progress"))??!1){let K1=I.value.last?.messages.flatMap((N1)=>N1.content).filter((N1)=>N1.type==="tool_result"&&("run"in N1)&&("status"in N1.run)&&N1.run.status==="in-progress"),X1=K1?.length??0;if(X1>0){for(let e of K1||[]){let G1=y7(I.value.last,e.toolUseID);if(G1){if(!V.has(e.toolUseID))V.set(e.toolUseID,Date.now());$.next({type:"tool-status",toolUse:G1,status:"running",startTime:V.get(e.toolUseID)})}}let N1=X1===1&&K1?.[0]&&I.value.last?y7(I.value.last,K1[0].toolUseID):void 0,s=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return y7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,r=N1?g51(N1.name,X1,Date.now(),N1.input,s):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:s};$.next({type:"state",state:r})}else{let N1=I.value.last;if(N1){let s=cC(N1);if(s)$.next({type:"state",state:s});else $.next({type:"state",state:{type:"idle"}})}else $.next({type:"state",state:{type:"idle"}})}return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else if(D1?.role==="assistant"&&D1?.state.type==="complete"&&D1?.state.stopReason==="end_turn")return $.next({type:"state",state:{type:"idle"}}),{...z1(),tokenUsage:A1}}}}else if(y.type==="batch-tool-confirmations-complete")if(S.type==="collecting-tool-confirmations"&&S.subthreadContext)return k1.info("Sending batch tool confirmations to subthread",{subThreadID:S.subthreadContext.subThreadID,toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),F.handleToolConfirmations(S.subthreadContext.subThreadID,y.responses).catch((D1)=>{k1.error("Failed to send subthread tool confirmations",D1)}),k1.info("Transitioning to awaiting-agent after sending subthread confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else return k1.info("Sending batch tool confirmations to worker",{toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),y.responses.forEach((D1,A1)=>{k1.info("Sending individual tool confirmation to worker",{toolUseID:A1,accepted:D1}),T.handle({type:"user:tool-input",toolUse:A1,value:{accepted:D1}}),S.toolConfirmationStatus.set(A1,"sent")}),k1.info("Transitioning to awaiting-agent after sending batch confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else if(y.type==="summary:created"){let D1=I.value.last;if(D1){let A1=xa(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,s=K1.used,r=N1-s,e=N1>0?r/N1*100:0;if(r<=0)k1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:s,reduction:r,threadID:E});else if(e<10)k1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E});else k1.info("Compaction successful",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E})}else k1.warn("No pre-compaction token usage available for validation",{threadID:E});$.next({type:"token-usage",tokenUsage:K1})}}return z1()}else if(y.type==="compaction-result")if(y.result)return z1();else return $.next({type:"error",error:{type:"other",error:"Compaction failed"},retryable:!1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:y.severity}}),{...S,type:"confirming-compaction",severity:y.severity};else if(y.type==="update-start-updating")return{...S,updateState:"updating"};else if(y.type==="update-result")if(y.success)return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"success"};else return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"error"};else if(y.type==="clear-update-status")return{...S,updateState:"none"};else if(y.type==="agent-file-check-complete"){if(S.type==="checking-agent-file")if(y.shouldGenerate)return $.next({type:"confirm",confirmation:{type:"agent-file-creation"}}),{...S,type:"confirming-agent-file-creation"};else return z1()}else if(y.type==="tool-status")return $.next({type:"tool-status",toolUse:y.toolUse,status:y.status,startTime:y.startTime,endTime:y.endTime,subthreadID:y.subthreadID}),S;else if(y.type==="subagent-started"){if(S.type==="initializing")return S;return $.next({type:"subagent-started",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S}else if(y.type==="subagent-status")return $.next({type:"subagent-status",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,agentState:y.agentState}),S;else if(y.type==="subthread-message"){if(y.blocks.length>0)$.next({type:"subthread-messages",subThreadID:y.subThreadID,blocks:y.blocks});return S}else if(y.type==="historic-thread"){if(S.type!=="initializing")throw new Error(`Historic thread event received in unexpected state: ${S.type}`);if(w&&W.size===0&&y.messages.length>0){let A1=yf({id:E,messages:y.messages},W,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(k1.info(`Received tool confirmation request from subthread ${y.subThreadID}`,{subThreadID:y.subThreadID,agentNumber:y.agentNumber,toolCount:y.tools.length,tools:y.tools.map((D1)=>D1.useBlock.name),queueLength:S.confirmationQueue.length}),S.type==="collecting-tool-confirmations"||S.confirmationQueue.length>0)return k1.info("Queueing tool confirmation request",{subThreadID:y.subThreadID,agentNumber:y.agentNumber,currentQueueLength:S.confirmationQueue.length}),{...S,confirmationQueue:[...S.confirmationQueue,{type:"subthread-tool-request",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,tools:y.tools}]};return $.next({type:"confirm",confirmation:{type:"tool-use",tools:y.tools,subthreadID:y.subThreadID,agentNumber:y.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:y.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}}}return S}else if(y.type==="lsp-status")return $.next({type:"lsp-status",lspState:y.lspState}),S;else if(y.type==="ui-input"){if(y.input.type==="initialized")if(S.type==="initializing"){let D1={...S,hasUI:!0};if(D1.hasUI&&D1.hasThread)if(I.value.last?.messages.length===0)return k1.info("Checking agent file status"),I4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{k1.error("Agent file check failed",K1),P.next({type:"agent-file-check-complete",shouldGenerate:!1})}),{...S,type:"checking-agent-file"};else return z1();return D1}else throw new Error(`UI initialized event received in unexpected state: ${S.type}`);else if(y.input.type=="message"){let{message:D1}=y.input;return d(D1)}else if(y.input.type==="interrupt")if(S.type==="awaiting-agent"){if($.next({type:"cancelled"}),sZ.cancel(E),y.input.message)S.cancelledWithMessage=y.input.message;return S}else return S;else if(y.input.type==="exit")return u.unsubscribe(),{...S,type:"closing"};else if(y.input.type==="retry")return sZ.retry(E),{...S,type:"awaiting-agent",displayedError:null};else if(y.input.type==="confirmation"){if(S.type==="out-of-credits"&&y.input.confirmation.type==="out-of-credits")sZ.retry(E);else if(S.type==="confirming-compaction"&&y.input.confirmation.type==="compaction")if(y.input.allow){let D1="tokenUsage"in S?S.tokenUsage:void 0;return $.next({type:"state",state:{type:"compacting"}}),a().then(()=>{k1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{k1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return k1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return k1.error("No current tool ID in collecting-tool-confirmations state"),S;if(k1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){k1.info("Sending tool confirmation to subthread",{subThreadID:S.subthreadContext.subThreadID,toolUseID:S.currentToolID,accepted:y.input.allow});let X1=new Map([[S.currentToolID,y.input.allow]]);if(F.handleToolConfirmations(S.subthreadContext.subThreadID,X1).catch((N1)=>{k1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],s=S.confirmationQueue.slice(1);return k1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:s.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:N1.tools,subthreadID:N1.subThreadID,agentNumber:N1.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:N1.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,taskDescription:N1.taskDescription},confirmationQueue:s}}return k1.info("Transitioning to awaiting-agent after sending subthread confirmation"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}S.toolConfirmationStatus.set(S.currentToolID,y.input.allow?"confirmed":"rejected"),t(y.input.confirmation.addToAllowList);let D1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="awaiting");if(D1.length>0){let[X1]=D1[0];if(!I.value.isSet)return k1.error("Thread not available for finding next tool"),S;let r=(I.value.last.messages.at(-1)?.content.filter((G1)=>G1.type==="tool_result"&&G1.run.status==="blocked-on-user")??[]).find((G1)=>G1.toolUseID===X1),e=r?y7(I.value.last,r.toolUseID):null;if(r&&e)return k1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:r.run.status==="blocked-on-user"?r.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");k1.info("All tool confirmations collected, sending batch response",{totalTools:A1.length,responses:A1.map(([X1,N1])=>({id:X1,accepted:N1==="confirmed"}))});let K1=new Map(A1.map(([X1,N1])=>[X1,N1==="confirmed"]));return P.next({type:"batch-tool-confirmations-complete",responses:K1}),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}else if(y.input.confirmation.type==="agent-file-creation"&&S.type==="confirming-agent-file-creation")if(y.input.allow)return N4A(T).catch((D1)=>{k1.error("Agent file generation failed",D1)}),$.next({type:"state",state:{type:"generating-agent-file"}}),{...S,type:"awaiting-agent",displayedError:null};else return z1();return S}}return S}),{type:"initializing",hasUI:!1,hasThread:!1,tokenUsage:null,compactionPromptState:"none",updateState:"none",toolConfirmationStatus:new Map,currentAssistantMessageIndex:null,hasBeenIdle:!1,threadTitle:null,confirmationQueue:[]})).subscribe({error:(S)=>{k1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)k1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else k1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else k1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return ir6(P).catch((S)=>{k1.debug("Update check startup failed",S)}),await l6(g)}async function ir6(A){try{let Q=await O4A("0.0.1751544357-g213afc");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await L4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){k1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else k1.info("No update available")}catch(Q){k1.debug("Update check failed",Q)}}var h51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();D2();gq();function T4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7356
+ ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function _4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let M=VT(),W=new Set,I=gW(B.observe(E).pipe(t7((S)=>S!==void 0))),N=new Set,V=new Map;await l6(I.observable);let _=await Rd,T=await sZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:If,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{k1.error("Initial resume",S)});let R=T.status.pipe(r6((S)=>{return{type:"worker-state",status:S}})),j=I.observable.pipe(r6((S)=>{return{type:"thread-state",thread:S}})),P=new C8,$=new C8,f=H(FA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=hU(R,j,hU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{k1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(qZ(()=>{b()})).pipe(XT(a3("threadSession",function(S,y){function d(D1){k1.info(`Processing user message: ${D1.slice(0,50)}${D1.length>50?"...":""}`);let A1="tokenUsage"in S?S.tokenUsage:void 0;if(A1&&A1.used/A1.maxAvailable>h51.CRITICAL)return k1.info("Blocking message at worker boundary - critical token usage"),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:"final",updateState:"updateState"in S?S.updateState:"none",toolConfirmationStatus:"toolConfirmationStatus"in S?S.toolConfirmationStatus:new Map,currentAssistantMessageIndex:("currentAssistantMessageIndex"in S?S.currentAssistantMessageIndex:null)??null,hasBeenIdle:"hasBeenIdle"in S?S.hasBeenIdle:!1,threadTitle:"threadTitle"in S?S.threadTitle:null,confirmationQueue:"confirmationQueue"in S?S.confirmationQueue:[]};T.handle({type:"user:message",message:{content:[{type:"text",text:D1}]}}).then(()=>{if(A)A.sync().catch((X1)=>{k1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{k1.error("Handle user message failed",X1)}),$.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});let K1=I.value.last;if(K1){let X1=cC(K1);if(X1)$.next({type:"state",state:X1})}return{...S,type:"awaiting-agent",displayedError:null}}async function a(){$.next({type:"state",state:{type:"compacting"}});let D1=await X.summarizeThread(E);await T.handle({type:"summary:created",summary:{type:"internal",summary:D1.summary}})}function z1(){if(S.type==="awaiting-user-message")return k1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{k1.error("Thread sync error",A1,{threadID:E})}),D1&&S.type!=="confirming-compaction"&&S.type!=="compacting"){let A1=D1.used/D1.maxAvailable,K1=void 0,X1=S.compactionPromptState;if(A1>h51.CRITICAL)K1="critical",X1="final";else if(A1>h51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>h51.SEVERE&&S.compactionPromptState==="first")K1="severe",X1="final";if(K1)return $.next({type:"confirm",confirmation:{type:"compaction",severity:K1}}),{type:"confirming-compaction",severity:K1,tokenUsage:S.tokenUsage,compactionPromptState:X1,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue}}if($.next({type:"accept-message",initial:!S.hasBeenIdle&&!w}),S.type==="awaiting-agent")S.cancelledWithMessage=void 0;if(D1)$.next({type:"token-usage",tokenUsage:D1});return{...S,type:"awaiting-user-message",hasBeenIdle:!0,tokenUsage:D1??null}}function t(D1){if(D1.length>0)k1.info(`Updating allowlist with ${D1.length} entries`,{entries:D1}),K.get("commands.allowlist","global").then((A1)=>{let K1=[...A1??[],...D1];return K.set("commands.allowlist",K1,"global")}).catch((A1)=>{k1.error("Failed to update allowlist",A1)})}if(S.type==="closing")return S;if(y.type==="thread-state"){let D1=y.thread.title||null;if(S.threadTitle!==D1&&D1!==null)$.next({type:"thread-title",title:D1});if(F.scanForTaskToolSubthreads(y.thread),w&&W.size===0&&y.thread.messages.length>0){let K1=yf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=xa(y.thread);if(K1)A1={used:K1.totalInputTokens,maxAvailable:K1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}if(S.type==="awaiting-user-confirmation")if(y.thread.messages.at(-1)?.content.some((K1)=>K1.type==="tool_result"&&(K1.run.status==="in-progress"||K1.run.status==="done"))){let K1=cC(y.thread);if(K1)$.next({type:"state",state:K1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}});return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};if(S.type==="awaiting-agent"||S.type==="compacting"){let K1=y.thread.messages.at(-1),X1=yf(y.thread,W,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=cC(y.thread);if(U1)$.next({type:"state",state:U1})}if(N1.length>0){for(let Y1 of N1)if(Y1.type==="toolResult"){let[U1,P1]=Y1.data,R1=P1.run.status==="done"?"completed":P1.run.status==="error"?"error":P1.run.status==="cancelled"?"cancelled":"running";if(R1!=="running")$.next({type:"tool-status",toolUse:U1,status:R1,startTime:V.get(U1.id),endTime:Date.now()}),V.delete(U1.id)}$.next({type:"messages",blocks:N1})}if(y.thread.messages.at(-1)?.content.some((Y1)=>Y1.type==="summary"))return{...z1(),tokenUsage:null,compactionPromptState:"none"};if(K1?.role==="assistant"&&K1?.state.type==="complete"&&K1?.state.stopReason==="end_turn"){$.next({type:"state",state:{type:"idle"}});let Y1=z1();return{...Y1,tokenUsage:A1??Y1.tokenUsage}}if(!I)throw new Error("unexpected: thread is required when waiting for tool input");let s=wz(y.thread,"assistant"),r=s?y.thread.messages.indexOf(s):null;if(r!==null&&r!==S.currentAssistantMessageIndex)k1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:r,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=r;let e=wz(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(s?.content.filter((Y1)=>Y1.type==="tool_use").map((Y1)=>Y1.id)??[]),q1=!1;for(let Y1 of e){if(!G1.has(Y1.toolUseID))continue;let U1=y7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===o4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,k1.info("Added new tool to confirmation tracking",{toolUseID:Y1.toolUseID,toolName:U1.name}),!V.has(U1.id))V.set(U1.id,Date.now());$.next({type:"tool-status",toolUse:U1,status:"blocked-on-user",startTime:V.get(U1.id)})}}if(q1){let Y1=Array.from(S.toolConfirmationStatus.entries()).filter(([U1,P1])=>P1==="awaiting");if(Y1.length>0){let[U1]=Y1[0],P1=e.find((T1)=>T1.toolUseID===U1),R1=P1?y7(y.thread,P1.toolUseID):null;if(P1&&R1)return k1.info(`Starting tool confirmation process for ${Y1.length} tools`,{firstToolID:U1,toolName:R1.name}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:R1,toAllow:P1.run.status==="blocked-on-user"?P1.run.toAllow:void 0}]}}),{...S,type:"collecting-tool-confirmations",currentToolID:U1,tokenUsage:A1}}}}}else if(y.type==="worker-state"){if(S.type==="awaiting-user-confirmation"&&y.status.state==="active"&&y.status.ephemeralError)return S;if(S.type==="collecting-tool-confirmations")return k1.info("Already collecting tool confirmations, ignoring worker-state event"),S;let D1=I.value.last?.messages.at(-1),A1=S.tokenUsage;if(y.status.state==="active"){let K1=I.value.last;if(K1){let X1=xa(K1);if(X1)A1={used:X1.totalInputTokens,maxAvailable:X1.maxInputTokens},$.next({type:"token-usage",tokenUsage:A1})}}if(S.type==="confirming-compaction"||S.type==="compacting")return{...S,tokenUsage:A1};switch(y.status.state){case"initial":if(S.type==="initializing")return S;return z1();case"active":if(y.status.ephemeralError)if(y.status.ephemeralError.message.includes(W4A)){if(S.type==="out-of-credits")return S;return $.next({type:"confirm",confirmation:{type:"out-of-credits"}}),{...S,type:"out-of-credits",tokenUsage:A1}}else if(M4A(y.status.ephemeralError))return k1.info("Context limit error, triggering compaction",{error:y.status.ephemeralError,tokenUsage:A1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:"critical"}}),{type:"confirming-compaction",severity:"critical",tokenUsage:S.tokenUsage,compactionPromptState:S.compactionPromptState,updateState:S.updateState,toolConfirmationStatus:S.toolConfirmationStatus,currentAssistantMessageIndex:S.currentAssistantMessageIndex,hasBeenIdle:S.hasBeenIdle,threadTitle:S.threadTitle,confirmationQueue:S.confirmationQueue};else if(y.status.ephemeralError.message.includes("401 unauthorized"))return $.next({type:"error",error:{type:"unauthorized"},retryable:!1}),u.unsubscribe(),{...S,type:"closing"};else{let K1=y.status.ephemeralError.message;if(k1.error("Ephemeral error",{error:K1}),S.type==="awaiting-agent"&&S.displayedError!==K1)return $.next({type:"error",error:{type:"other",error:K1},retryable:!1}),{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else return S}switch(y.status.inferenceState){case"running":{let K1=I.value.last;if(K1){let X1=cC(K1);if(X1)$.next({type:"state",state:X1});else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}else $.next({type:"state",state:{type:"waiting-on-model",startTime:Date.now()}})}if(S.type==="initializing")return{...S,tokenUsage:A1};return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1};case"cancelled":if(S.type==="initializing")return{...S,tokenUsage:A1};if($.next({type:"cancelled"}),$.next({type:"state",state:{type:"idle"}}),S.type==="awaiting-agent"&&S.cancelledWithMessage)return S.cancelledWithMessage=void 0,{...S,tokenUsage:A1};else return{...z1(),tokenUsage:A1};case"idle":if(S.type==="initializing")return{...S,tokenUsage:A1};if(D1?.content.some((K1)=>K1.type==="tool_result"&&K1.run.status==="blocked-on-user"))return{...S,type:"awaiting-user-confirmation",tokenUsage:A1};else if(I.value.last?.messages.some((K1)=>K1.role==="user"&&K1.content.some((X1)=>X1.type==="tool_result"&&X1.run.status==="in-progress"))??!1){let K1=I.value.last?.messages.flatMap((N1)=>N1.content).filter((N1)=>N1.type==="tool_result"&&("run"in N1)&&("status"in N1.run)&&N1.run.status==="in-progress"),X1=K1?.length??0;if(X1>0){for(let e of K1||[]){let G1=y7(I.value.last,e.toolUseID);if(G1){if(!V.has(e.toolUseID))V.set(e.toolUseID,Date.now());$.next({type:"tool-status",toolUse:G1,status:"running",startTime:V.get(e.toolUseID)})}}let N1=X1===1&&K1?.[0]&&I.value.last?y7(I.value.last,K1[0].toolUseID):void 0,s=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return y7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,r=N1?g51(N1.name,X1,Date.now(),N1.input,s):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:s};$.next({type:"state",state:r})}else{let N1=I.value.last;if(N1){let s=cC(N1);if(s)$.next({type:"state",state:s});else $.next({type:"state",state:{type:"idle"}})}else $.next({type:"state",state:{type:"idle"}})}return{...S,type:"awaiting-agent",displayedError:null,tokenUsage:A1}}else if(D1?.role==="assistant"&&D1?.state.type==="complete"&&D1?.state.stopReason==="end_turn")return $.next({type:"state",state:{type:"idle"}}),{...z1(),tokenUsage:A1}}}}else if(y.type==="batch-tool-confirmations-complete")if(S.type==="collecting-tool-confirmations"&&S.subthreadContext)return k1.info("Sending batch tool confirmations to subthread",{subThreadID:S.subthreadContext.subThreadID,toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),F.handleToolConfirmations(S.subthreadContext.subThreadID,y.responses).catch((D1)=>{k1.error("Failed to send subthread tool confirmations",D1)}),k1.info("Transitioning to awaiting-agent after sending subthread confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else return k1.info("Sending batch tool confirmations to worker",{toolCount:y.responses.size,responses:Array.from(y.responses.entries()).map(([D1,A1])=>({id:D1,accepted:A1}))}),y.responses.forEach((D1,A1)=>{k1.info("Sending individual tool confirmation to worker",{toolUseID:A1,accepted:D1}),T.handle({type:"user:tool-input",toolUse:A1,value:{accepted:D1}}),S.toolConfirmationStatus.set(A1,"sent")}),k1.info("Transitioning to awaiting-agent after sending batch confirmations"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null};else if(y.type==="summary:created"){let D1=I.value.last;if(D1){let A1=xa(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,s=K1.used,r=N1-s,e=N1>0?r/N1*100:0;if(r<=0)k1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:s,reduction:r,threadID:E});else if(e<10)k1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E});else k1.info("Compaction successful",{preUsed:N1,postUsed:s,reduction:r,reductionPercent:e.toFixed(1),threadID:E})}else k1.warn("No pre-compaction token usage available for validation",{threadID:E});$.next({type:"token-usage",tokenUsage:K1})}}return z1()}else if(y.type==="compaction-result")if(y.result)return z1();else return $.next({type:"error",error:{type:"other",error:"Compaction failed"},retryable:!1}),$.next({type:"confirm",confirmation:{type:"compaction",severity:y.severity}}),{...S,type:"confirming-compaction",severity:y.severity};else if(y.type==="update-start-updating")return{...S,updateState:"updating"};else if(y.type==="update-result")if(y.success)return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"success"};else return setTimeout(()=>{P.next({type:"clear-update-status"})},1e4),{...S,updateState:"error"};else if(y.type==="clear-update-status")return{...S,updateState:"none"};else if(y.type==="agent-file-check-complete"){if(S.type==="checking-agent-file")if(y.shouldGenerate)return $.next({type:"confirm",confirmation:{type:"agent-file-creation"}}),{...S,type:"confirming-agent-file-creation"};else return z1()}else if(y.type==="tool-status")return $.next({type:"tool-status",toolUse:y.toolUse,status:y.status,startTime:y.startTime,endTime:y.endTime,subthreadID:y.subthreadID}),S;else if(y.type==="subagent-started"){if(S.type==="initializing")return S;return $.next({type:"subagent-started",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S}else if(y.type==="subagent-status")return $.next({type:"subagent-status",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,agentState:y.agentState}),S;else if(y.type==="subthread-message"){if(y.blocks.length>0)$.next({type:"subthread-messages",subThreadID:y.subThreadID,blocks:y.blocks});return S}else if(y.type==="historic-thread"){if(S.type!=="initializing")throw new Error(`Historic thread event received in unexpected state: ${S.type}`);if(w&&W.size===0&&y.messages.length>0){let A1=yf({id:E,messages:y.messages},W,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(k1.info(`Received tool confirmation request from subthread ${y.subThreadID}`,{subThreadID:y.subThreadID,agentNumber:y.agentNumber,toolCount:y.tools.length,tools:y.tools.map((D1)=>D1.useBlock.name),queueLength:S.confirmationQueue.length}),S.type==="collecting-tool-confirmations"||S.confirmationQueue.length>0)return k1.info("Queueing tool confirmation request",{subThreadID:y.subThreadID,agentNumber:y.agentNumber,currentQueueLength:S.confirmationQueue.length}),{...S,confirmationQueue:[...S.confirmationQueue,{type:"subthread-tool-request",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,tools:y.tools}]};return $.next({type:"confirm",confirmation:{type:"tool-use",tools:y.tools,subthreadID:y.subThreadID,agentNumber:y.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:y.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}}}return S}else if(y.type==="lsp-status")return $.next({type:"lsp-status",lspState:y.lspState}),S;else if(y.type==="ui-input"){if(y.input.type==="initialized")if(S.type==="initializing"){let D1={...S,hasUI:!0};if(D1.hasUI&&D1.hasThread)if(I.value.last?.messages.length===0)return k1.info("Checking agent file status"),I4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{k1.error("Agent file check failed",K1),P.next({type:"agent-file-check-complete",shouldGenerate:!1})}),{...S,type:"checking-agent-file"};else return z1();return D1}else throw new Error(`UI initialized event received in unexpected state: ${S.type}`);else if(y.input.type=="message"){let{message:D1}=y.input;return d(D1)}else if(y.input.type==="interrupt")if(S.type==="awaiting-agent"){if($.next({type:"cancelled"}),sZ.cancel(E),y.input.message)S.cancelledWithMessage=y.input.message;return S}else return S;else if(y.input.type==="exit")return u.unsubscribe(),{...S,type:"closing"};else if(y.input.type==="retry")return sZ.retry(E),{...S,type:"awaiting-agent",displayedError:null};else if(y.input.type==="confirmation"){if(S.type==="out-of-credits"&&y.input.confirmation.type==="out-of-credits")sZ.retry(E);else if(S.type==="confirming-compaction"&&y.input.confirmation.type==="compaction")if(y.input.allow){let D1="tokenUsage"in S?S.tokenUsage:void 0;return $.next({type:"state",state:{type:"compacting"}}),a().then(()=>{k1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{k1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return k1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return k1.error("No current tool ID in collecting-tool-confirmations state"),S;if(k1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){k1.info("Sending tool confirmation to subthread",{subThreadID:S.subthreadContext.subThreadID,toolUseID:S.currentToolID,accepted:y.input.allow});let X1=new Map([[S.currentToolID,y.input.allow]]);if(F.handleToolConfirmations(S.subthreadContext.subThreadID,X1).catch((N1)=>{k1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],s=S.confirmationQueue.slice(1);return k1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:s.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:N1.tools,subthreadID:N1.subThreadID,agentNumber:N1.agentNumber}}),{...S,type:"collecting-tool-confirmations",currentToolID:N1.tools[0]?.useBlock.id||null,subthreadContext:{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,taskDescription:N1.taskDescription},confirmationQueue:s}}return k1.info("Transitioning to awaiting-agent after sending subthread confirmation"),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}S.toolConfirmationStatus.set(S.currentToolID,y.input.allow?"confirmed":"rejected"),t(y.input.confirmation.addToAllowList);let D1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="awaiting");if(D1.length>0){let[X1]=D1[0];if(!I.value.isSet)return k1.error("Thread not available for finding next tool"),S;let r=(I.value.last.messages.at(-1)?.content.filter((G1)=>G1.type==="tool_result"&&G1.run.status==="blocked-on-user")??[]).find((G1)=>G1.toolUseID===X1),e=r?y7(I.value.last,r.toolUseID):null;if(r&&e)return k1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:r.run.status==="blocked-on-user"?r.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");k1.info("All tool confirmations collected, sending batch response",{totalTools:A1.length,responses:A1.map(([X1,N1])=>({id:X1,accepted:N1==="confirmed"}))});let K1=new Map(A1.map(([X1,N1])=>[X1,N1==="confirmed"]));return P.next({type:"batch-tool-confirmations-complete",responses:K1}),$.next({type:"state",state:{type:"running-tools",startTime:Date.now()}}),{...S,type:"awaiting-agent",displayedError:null}}else if(y.input.confirmation.type==="agent-file-creation"&&S.type==="confirming-agent-file-creation")if(y.input.allow)return N4A(T).catch((D1)=>{k1.error("Agent file generation failed",D1)}),$.next({type:"state",state:{type:"generating-agent-file"}}),{...S,type:"awaiting-agent",displayedError:null};else return z1();return S}}return S}),{type:"initializing",hasUI:!1,hasThread:!1,tokenUsage:null,compactionPromptState:"none",updateState:"none",toolConfirmationStatus:new Map,currentAssistantMessageIndex:null,hasBeenIdle:!1,threadTitle:null,confirmationQueue:[]})).subscribe({error:(S)=>{k1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)k1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else k1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else k1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return ir6(P).catch((S)=>{k1.debug("Update check startup failed",S)}),await l6(g)}async function ir6(A){try{let Q=await O4A("0.0.1751558552-ga58f43");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await L4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){k1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else k1.info("No update available")}catch(Q){k1.debug("Update check failed",Q)}}var h51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();D2();gq();function T4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7357
7357
  `)}return(z)=>{let Z=new C8;if(!J)throw new Error("JSONL UI requires piped input (non-interactive mode)");return k1.debug("setting up JSONL UI"),z.pipe(Zi({onSubscribe:()=>{D({type:"initial",threadID:B}),NT().then(()=>{Z.next({type:"initialized"})})},onUnsubscribe:()=>{k1.debug("JSONL UI stopped")}})).pipe(qZ(()=>{Z.complete()})).pipe(XT(a3("JSONL",(X,K)=>{if(k1.debug("JSONL UI event",{event:K}),X.type==="shutting-down")return X;switch(K.type){case"messages":{let G=(E)=>{return E.map((w)=>{if(w.type==="text"){let{type:H,text:M}=w;return{type:H,text:M}}else if(w.type==="image"){let{type:H,source:M}=w;return{type:H,source:M}}else if(w.type==="tool_result"){let{type:H,toolUseID:M,run:W,userInput:I}=w;return{type:H,toolUseID:M,run:W,userInput:I}}else if(w.type==="thinking"){let{type:H,thinking:M}=w;return{type:H,thinking:M}}else if(w.type==="redacted_thinking"){let{type:H,data:M}=w;return{type:H,data:M}}else if(w.type==="tool_use"){let{type:H,id:M,name:W,input:I}=w,N={type:H,id:M,name:W};if(I!==void 0)N.input=I;return N}else if(w.type==="server_tool_use"){let{type:H,id:M,name:W,input:I}=w;return{type:H,id:M,name:W,input:I}}else if(w.type==="web_search_tool_result"){let{type:H,content:M}=w;return{type:H,content:M}}else if(w.type==="summary"){let{type:H,summary:M}=w;return{type:H,summary:M}}return w})},q=(E)=>{switch(E.status){case"blocked-on-user":case"rejected-by-user":return{status:E.status,toAllow:E.toAllow};case"error":return{status:"error",error:typeof E.error==="object"&&"message"in E.error?E.error:{message:String(E.error)}};case"cancelled":case"in-progress":return{status:E.status,progress:E.progress};case"done":return{status:"done",progress:E.progress,result:E.result,files:E.files};default:return{status:E.status}}},Y=[],F=[];for(let E of K.blocks)if(E.type==="message"){let[w,H]=E.data;if(H.role==="user"){let{role:M,content:W,meta:I}=H,N={role:M,content:G(W),meta:I};Y.push([w,N])}else if(H.role==="assistant"){let{role:M,content:W,state:I}=H,N={role:M,content:G(W),state:I};Y.push([w,N])}else if(H.role==="info"){let{role:M,content:W}=H,I={role:M,content:G(W)};Y.push([w,I])}else Y.push([w,H])}else if(E.type==="toolResult"){let[w,H]=E.data;if(w.input&&H.run!==void 0){let M={type:w.type,id:w.id,name:w.name,input:{}},W={type:H.type,toolUseID:H.toolUseID,run:q(z5(H.run))};F.push([M,W])}else k1.warn("Skipping tool result",{useBlock:w,resultBlock:H})}return D({type:"messages",messages:Y,toolResults:F}),X}case"cancelled":return D({type:"cancelled"}),X;case"tool-status":return D({type:"tool-status",toolUse:{id:K.toolUse.id,name:K.toolUse.name,input:K.toolUse.input},status:K.status,startTime:K.startTime,endTime:K.endTime,subthreadID:K.subthreadID}),X;case"token-usage":return D({type:"token-usage",tokenUsage:K.tokenUsage}),X;case"accept-message":if(X.type==="initializing")return k1.info("Sending piped input",{pipedInput:J}),Z.next({type:"message",message:J}),{type:"running"};else return Z.next({type:"exit"}),X;case"error":return D({type:"error",error:K.error}),Z.next({type:"exit"}),X;case"confirm":{if(K.confirmation.type==="tool-use")for(let{useBlock:G}of K.confirmation.tools){if(G.name===o4&&G.input&&typeof G.input==="object"&&"cmd"in G.input)D({type:"tool-rejected",tool:G.name,command:String(G.input.cmd),message:`Tool call rejected. To allow automatically, add to ${jE}: {"amp.commands.allowlist": [${JSON.stringify(G.input.cmd)}]}`});Z.next({type:"confirmation",confirmation:{type:"tool-use",toolUseID:G.id,addToAllowList:[]},allow:!1})}else if(K.confirmation.type==="compaction")Z.next({type:"confirmation",confirmation:K.confirmation,allow:!0});else if(K.confirmation.type==="agent-file-creation")Z.next({type:"confirmation",confirmation:K.confirmation,allow:!1});else if(K.confirmation.type==="out-of-credits")D({type:"out-of-credits",message:"Insufficient usage balance. Visit https://ampcode.com/pay to buy more usage."}),Z.next({type:"exit"});else Z.next({type:"confirmation",confirmation:K.confirmation,allow:!1});return X}case"subagent-started":return D({type:"subagent-started",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription}),X;case"subagent-finished":return D({type:"subagent-finished",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,result:K.result}),X;case"subagent-cancelled":return D({type:"subagent-cancelled",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription}),X;case"subagent-error":return D({type:"subagent-error",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,error:K.error}),X;case"subagent-status":return D({type:"subagent-status",subThreadID:K.subThreadID,agentNumber:K.agentNumber,taskDescription:K.taskDescription,agentState:K.agentState}),X;case"subthread-messages":{let G=K.blocks.filter((Y)=>Y.type==="message").length,q=K.blocks.filter((Y)=>Y.type==="toolResult").length;return D({type:"subthread-activity",subThreadID:K.subThreadID,messageCount:G,toolResultCount:q}),X}case"state":switch(K.state.type){case"shutting-down":return D({type:"shutdown"}),{type:"shutting-down"};default:return D({type:"state",state:K.state.type}),X}case"lsp-status":return D({type:"lsp-status",lspState:K.lspState}),X}return X}),{type:"initializing"})).subscribe({error:(X)=>{k1.error("Error in JSONL UI:",X),D({type:"error",error:{type:"other",error:X.toString()}}),Z.next({type:"exit"})}}),FA.from(Z)}}y2();AK();y2();import{exec as gf}from"node:child_process";function bf(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")gf("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")gf("powershell [console]::beep(800,200)");else if(process.platform==="linux")gf("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="requires-user-input"){if(process.platform==="darwin")gf("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")gf("powershell [console]::beep(1000,300)");else if(process.platform==="linux")gf("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){k1.error(`Failed to play notification sound (${A}):`,Q)}}D2();y2();import{mkdir as j4A,readFile as P4A,writeFile as ef1,open as ar6}from"node:fs/promises";import{homedir as nr6}from"node:os";import Ld from"node:path";var sr6=Ld.join(Cf||Ld.join(nr6(),".local/share"),"amp"),rr6=Ld.join(sr6,"history.jsonl"),or6=1000;class _d{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(A){this.historyFile=A?.historyFile||rr6,this.maxSize=A?.maxSize||or6,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)this.history=await this.readHistoryFromDisk(),this.loaded=!0}async readHistoryFromDisk(){try{let A=await P4A(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return k1.warn("Failed to read history file",{error:A.message}),[];if(this.historyFile.endsWith(".jsonl")){let Q=this.historyFile.replace(".jsonl",".json");try{let B=await P4A(Q,"utf-8");if(B.trim()){let J=JSON.parse(B);k1.info("Migrating from old history.json to history.jsonl",{oldFile:Q,newFile:this.historyFile,size:J.length}),await this.writeHistoryToDisk(J);try{await import("node:fs/promises").then((D)=>D.unlink(Q))}catch{}return J}}catch{}}return[]}}parseJsonlContent(A){let Q=A.trim().split(`
7358
7358
  `),B=[];for(let J of Q)if(J.trim())try{let D=JSON.parse(J);if(typeof D==="string")B.push(D);else k1.warn("Skipping non-string entry in history",{line:J,type:typeof D})}catch(D){k1.warn("Skipping invalid JSONL line in history",{line:J})}return k1.info("Loaded history from JSONL file",{file:this.historyFile,size:B.length}),B}async writeHistoryToDisk(A){await j4A(Ld.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
7359
7359
  `)+`
@@ -7481,7 +7481,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
7481
7481
  `),d=0,a=0;for(let z1=0;z1<y.length;z1++){let t=g6.default(y[z1]).length;if(d+t>=Y){a=d;break}d+=t+1}if(Y>a){let z1=g6.default.substr(G,a,Y-a);N((t)=>[z1,...t.slice(0,9)]),q((t)=>{let D1=g6.default(t);return D1.slice(0,a).join("")+D1.slice(Y).join("")}),F(a)}return}if(u.ctrl&&b==="k"){let y=G.split(`
7482
7482
  `),d=0,a=g6.default(G).length;for(let z1=0;z1<y.length;z1++){let t=g6.default(y[z1]).length;if(d+t>=Y){a=d+t;break}d+=t+1}if(Y<a){let z1=g6.default.substr(G,Y,a-Y);N((t)=>[z1,...t.slice(0,9)]),q((t)=>{let D1=g6.default(t);return D1.slice(0,Y).join("")+D1.slice(a).join("")})}return}if(u.ctrl&&b==="w"||u.alt&&u.backspace||u.ctrl&&u.backspace){if(Y>0){let y=VQA(G,Y),d=g6.default.substr(G,y,Y-y);N((a)=>[d,...a.slice(0,9)]),q((a)=>{let z1=g6.default(a);return z1.slice(0,y).join("")+z1.slice(Y).join("")}),F(y)}return}if(u.ctrl&&b==="d"||u.delete){if(Y<g6.default(G).length){let y=g6.default.substr(G,Y,1);N((d)=>[y,...d.slice(0,9)]),q((d)=>{let a=g6.default(d);return a.slice(0,Y).join("")+a.slice(Y+1).join("")})}return}if(u.alt&&b==="d"){if(Y<g6.default(G).length){let y=OQA(G,Y),d=g6.default.substr(G,Y,y-Y);N((a)=>[d,...a.slice(0,9)]),q((a)=>{let z1=g6.default(a);return z1.slice(0,Y).join("")+z1.slice(y).join("")})}return}if(u.ctrl&&b==="y"){if(I.length>0){let y=I[0];q((d)=>{let a=g6.default(d);return a.slice(0,Y).join("")+y+a.slice(Y).join("")}),F((d)=>d+g6.default(y).length)}return}let S=u.return&&(u.shift||u.meta||u.ctrl)||!u.return&&b==="\r"||u.escape&&u.meta&&!b||b==="\x1B[27;2;13~"||b==="[27;2;13~"||b==="\x1B[13;2u";if(k1.debug("Modified Enter detection",{isModifiedEnter:S,"key.return":u.return,"key.shift":u.shift,"key.meta":u.meta,"key.ctrl":u.ctrl,keyInput:JSON.stringify(b),hasContent:G.trim().length>0}),S){if($)return;q((y)=>{let d=g6.default(y);return d.slice(0,Y).join("")+`
7483
7483
  `+d.slice(Y).join("")}),F((y)=>y+1);return}if(u.return&&!u.shift&&!u.meta&&!u.ctrl){if($)return;if(G.trim().length>0)g(G.trim());else return;return}if(!u.ctrl&&!u.meta&&!u.tab&&b)q((y)=>{let d=g6.default(y);return d.slice(0,Y).join("")+b+d.slice(Y).join("")}),F((y)=>y+g6.default(b).length)});let g=async(b)=>{if(K({virtualLine:0,column:0}),F(0),w(!0),q(""),N([]),_(!1),R(null),Q)Q.add(b),Q.reset();try{A(b)}catch(u){k1.error("Failed to submit message",u)}finally{w(!1)}};return fA(y6,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:Z,children:M.map((b,u)=>fA(y6,{flexShrink:0,flexDirection:"row",children:fA(y6,{flexGrow:1,flexShrink:0,width:"100%",children:u===X.virtualLine?j9(My1,{children:[fA(h6,{dimColor:B,children:g6.default.substr(b.content,0,X.column)||""}),fA(h6,{inverse:!B,dimColor:B,children:g6.default(b.content)[X.column]??" "}),fA(h6,{dimColor:B,children:g6.default.substr(b.content,X.column+1)||""})]}):fA(h6,{dimColor:B,children:b.content||" "})})},u))})}function P12(A,Q){let B=A.split(`
7484
- `),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var r71=G6(z4(),1);function Vy1({options:A,onSelect:Q,title:B}){let[J,D]=r71.useState(0);if(rM((z,Z)=>{if(Z.downArrow||Z.ctrl&&z.toLowerCase()==="n"||Z.tab&&!Z.shift)D((X)=>(X+1)%A.length);else if(Z.upArrow||Z.ctrl&&z.toLowerCase()==="p"||Z.shift&&Z.tab)D((X)=>(X-1+A.length)%A.length);else if(Z.return&&A[J])Q(A[J].value);else if(Z.escape)Q(null);else if(Z.ctrlC)Q(null)}),r71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return j9(y6,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[B&&fA(y6,{marginBottom:1,children:fA(h6,{bold:!0,children:B})}),A.map((z,Z)=>fA(y6,{children:j9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function S12(A,Q){try{return await A.query(Q)}catch(B){return k1.error("Completion failed",B),[]}}var LQA=10;function v12({messages:A,agentState:Q}){if(Q.type!=="streaming-thinking"&&Q.type!=="streaming-text")return null;let B=A.findLast((z)=>z.type==="message"&&z.data[1].role==="assistant"&&z.data[1].state?.type==="streaming");if(!B||B.type!=="message")return null;let[,J]=B.data;if(!J.content.some((z)=>z.type==="thinking"||z.type==="text"))return null;return fA(y6,{flexDirection:"column",marginBottom:1,children:J.content.map((z,Z)=>{if(z.type==="thinking"){let X=z.thinking,K=cd(X,!0);return fA(y6,{flexDirection:"column",marginTop:Z>0?1:0,children:K.map((G,q)=>fA(y6,{children:fA(h6,{children:G})},q))},Z)}else if(z.type==="text")return fA(y6,{marginTop:Z>0?1:0,children:fA(Cy1,{children:z.text})},Z);return null})})}function $12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=f12(J.useBlock);else B="Confirm tool call"}else B=`Confirm ${A.tools.length} tool calls`;break}case"compaction":B=`Compact thread? (${A.severity} token usage)`;break;case"out-of-credits":B="Insufficient usage balance. Retry?";break;case"agent-file-creation":B="Create AGENT.md file for this codebase?";break}if(Q&&Q.total>1)B=`[${Q.current}/${Q.total}] ${B}`;return B}function f12(A){if(A.name===o4){let Q=A.input;return"Run "+al.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return al.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function k12(A){switch(A.type){case"tool-use":{let B=A.subthreadID===void 0&&A.tools.some((D)=>D.toAllow),J=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];if(B)J.push({value:"always",label:"Always (add to allowlist)"});return J}case"compaction":return[{value:"yes",label:"Yes"},...A.severity!=="critical"?[{value:"no",label:"No"}]:[]];case"out-of-credits":case"agent-file-creation":return[{value:"yes",label:"Yes"},{value:"no",label:"No"}]}}function y12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return j9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:j9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:j9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function _QA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function TQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=Fy1(),[Z,X]=Bk(),[K]=A_.useState(()=>new C8);A_.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=A_.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};A_.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),NT().then(()=>{z.exit()});break;case"idle":if(D)bf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=_QA(N),_=ma({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(W.toolUse.name===EQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)bf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:W.title}));break}default:k1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await S12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};A_.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),rM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA);else if(W.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let M=_QA(G.messages);return fA(CQA,{threadName:G.threadTitle,messages:M,onExit:()=>q({...G,type:"running"})})}return j9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(p71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(g12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&j9(y6,{flexDirection:"column",marginTop:1,children:[fA(v12,{messages:G.messages,agentState:G.agentState}),fA(GQA,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(WQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Vy1,{title:$12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:k12(G.currentConfirmation),onSelect:Y})}),j9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(y12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(RQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Vy1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.map((I)=>({value:I,label:I})),onSelect:w})})})(),j9(y6,{gap:2,children:[j9(y6,{flexGrow:1,children:[G.type==="confirming-exit"&&fA(h6,{dimColor:!0,children:"Ctrl+C again to exit"}),G.type==="confirming"&&fA(h6,{dimColor:!0,children:"Escape to cancel"}),G.type==="running"&&j9(y6,{gap:1,children:[fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Enter to submit,"})}),fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Ctrl+R to expand"})})]})]}),j9(y6,{flexGrow:0,gap:2,children:[fA(x12,{lspState:G.lspState}),G.tokenUsage&&fA(b12,{tokenUsage:G.tokenUsage})]})]})]})]})}function g12({block:A,marginTop:Q=0}){if(A.type==="message"){let[,B]=A.data;if(B.role==="assistant"&&B.state?.type==="streaming")return null;if(!B.content.some((D)=>D.type==="text"&&B.role!=="info"))return null;return fA(y6,{flexDirection:"column",gap:1,marginTop:Q,children:B.content.map((D,z)=>{if(D.type==="text")switch(B.role){case"assistant":return fA(y6,{children:fA(Cy1,{children:D.text})},z);case"user":return fA(y6,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,children:fA(h6,{color:"green",italic:!0,children:D.text})},z);case"info":return fA(y6,{children:fA(h6,{color:"gray",children:D.text})},z)}else if(D.type==="thinking"){let Z=D.thinking,X=cd(Z,!1);if(X.length===0)return null;return fA(y6,{flexDirection:"column",children:X.map((K,G)=>fA(y6,{children:fA(h6,{children:K})},G))},z)}return null})})}else if(A.type==="toolResult"){let[B,J]=A.data,D=s71(B,J,!1);if(D.length===0)return null;return fA(y6,{marginTop:Q,flexDirection:"column",children:D.map((z,Z)=>fA(y6,{children:fA(h6,{children:z})},Z))})}}function b12({tokenUsage:A}){let Q=A.used/A.maxAvailable,B=Math.round(Q*100),J=Math.max(0,Math.min(B,100)),D="▁▂▃▄▅▆▇█",z=Math.floor(J*8/100),X="▁▂▃▄▅▆▇█"[Math.max(0,Math.min(z,7))],K=`${J}% ┃${X}┃`,G=0.8,q=0.9,Y;if(Q>=0.9)Y="red";else if(Q>=0.8)Y="yellow";return fA(h6,{color:Y,children:K})}function x12({lspState:A}){if(!A||Object.keys(A.servers).length===0)return null;let Q=Object.values(A.servers).map((B)=>{let J=B.status==="active"?"✓":B.status==="starting"?"⧗":"×",D=B.status==="active"?"green":B.status==="starting"?"yellow":"red";return{symbol:J,serverName:B.serverName,color:D}});return fA(y6,{gap:1,children:Q.map(({symbol:B,serverName:J,color:D},z)=>j9(h6,{color:D,children:[B," ",J]},z))})}global.React=Oy1.default;function jQA(A){return JA.level=1,(Q)=>{let B=new C8;return Uy1(Oy1.default.createElement(TQA,{inputs:B,outputs:Q,history:A.history,fuzzyServer:A.fuzzyServer,useNotifications:A.useNotifications}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout}).waitUntilExit().then(()=>{B.complete()}).catch((D)=>{B.next({type:"exit"})}),FA.from(B)}}var Ly1=Ry1.join(CAA||Ry1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function _y1(A){try{await m12(Ry1.dirname(Ly1),{recursive:!0}),await p12(Ly1,A,"utf-8")}catch(Q){k1.debug("Failed to save last thread ID",Q)}}async function o71(){try{return(await u12(Ly1,"utf-8")).trim()}catch(A){return null}}var c12=[{name:"notifications",long:"notifications",type:"flag",default:!1,description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when interactive)`},{name:"interactive",long:"interactive",type:"switch",default:!1,description:"Force interactive mode"},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",description:`Custom settings file path (overrides the default location ${jE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(k1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",default:"ui",description:"Output format (ui: interactive terminal, jsonl: JSON Lines for scripts)",choices:["ui","jsonl","new-ui"],hidden:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,description:(A)=>`${A?"Enable":"Disable"} JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp CLI automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.`,hidden:!0}];function l12(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new eZ(Qq.unknownCommand(B),1,Z)}}class SQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=oK1(null),J=await hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function Q_(A,Q){Cd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),nc1("0.0.1751544357-g213afc");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;k1.info("Using settings file",{settingsFile:B});let J=tl(),D=uv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=yX1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new SQA,K=yq(),G=ma1({configService:Z,toolService:K});try{await G.initialized}catch(_){k1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await l6(r8);if(Q.dangerouslyAllowAll)q.settings.dangerouslyAllowAll=!0;if(Q.jetbrains)q.settings["jetbrains.enabled"]=!0;let Y=q.settings["experimental.reviewTool"]??!1,F=q.settings["experimental.tools"]??[];hP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new P51,await E.start();try{await u9A(E,process.cwd())}catch(_){k1.error("Failed to index files for fuzzy completion",_)}w=p9A(E,process.cwd())}else E=new class extends P51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(K7.write(`No API key found. Starting login flow...
7484
+ `),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var r71=G6(z4(),1);function Vy1({options:A,onSelect:Q,title:B}){let[J,D]=r71.useState(0);if(rM((z,Z)=>{if(Z.downArrow||Z.ctrl&&z.toLowerCase()==="n"||Z.tab&&!Z.shift)D((X)=>(X+1)%A.length);else if(Z.upArrow||Z.ctrl&&z.toLowerCase()==="p"||Z.shift&&Z.tab)D((X)=>(X-1+A.length)%A.length);else if(Z.return&&A[J])Q(A[J].value);else if(Z.escape)Q(null);else if(Z.ctrlC)Q(null)}),r71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return j9(y6,{flexDirection:"column",borderStyle:"round",paddingX:1,children:[B&&fA(y6,{marginBottom:1,children:fA(h6,{bold:!0,children:B})}),A.map((z,Z)=>fA(y6,{children:j9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function S12(A,Q){try{return await A.query(Q)}catch(B){return k1.error("Completion failed",B),[]}}var LQA=10;function v12({messages:A,agentState:Q}){if(Q.type!=="streaming-thinking"&&Q.type!=="streaming-text")return null;let B=A.findLast((z)=>z.type==="message"&&z.data[1].role==="assistant"&&z.data[1].state?.type==="streaming");if(!B||B.type!=="message")return null;let[,J]=B.data;if(!J.content.some((z)=>z.type==="thinking"||z.type==="text"))return null;return fA(y6,{flexDirection:"column",marginBottom:1,children:J.content.map((z,Z)=>{if(z.type==="thinking"){let X=z.thinking,K=cd(X,!0);return fA(y6,{flexDirection:"column",marginTop:Z>0?1:0,children:K.map((G,q)=>fA(y6,{children:fA(h6,{children:G})},q))},Z)}else if(z.type==="text")return fA(y6,{marginTop:Z>0?1:0,children:fA(Cy1,{children:z.text})},Z);return null})})}function $12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=f12(J.useBlock);else B="Confirm tool call"}else B=`Confirm ${A.tools.length} tool calls`;break}case"compaction":B=`Compact thread? (${A.severity} token usage)`;break;case"out-of-credits":B="Insufficient usage balance. Retry?";break;case"agent-file-creation":B="Create AGENT.md file for this codebase?";break}if(Q&&Q.total>1)B=`[${Q.current}/${Q.total}] ${B}`;return B}function f12(A){if(A.name===o4){let Q=A.input;return"Run "+al.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return al.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function k12(A){switch(A.type){case"tool-use":{let B=A.subthreadID===void 0&&A.tools.some((D)=>D.toAllow),J=[{value:"yes",label:"Yes"},{value:"no",label:"No"}];if(B)J.push({value:"always",label:"Always (add to allowlist)"});return J}case"compaction":return[{value:"yes",label:"Yes"},...A.severity!=="critical"?[{value:"no",label:"No"}]:[]];case"out-of-credits":case"agent-file-creation":return[{value:"yes",label:"Yes"},{value:"no",label:"No"}]}}function y12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return j9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:j9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:j9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function _QA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function TQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=Fy1(),[Z,X]=Bk(),[K]=A_.useState(()=>new C8);A_.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=A_.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};A_.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),NT().then(()=>{z.exit()});break;case"idle":if(D)bf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=_QA(N),_=ma({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(W.toolUse.name===EQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)bf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:W.title}));break}default:k1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await S12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};A_.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),rM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},LQA);else if(W.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let M=_QA(G.messages);return fA(CQA,{threadName:G.threadTitle,messages:M,onExit:()=>q({...G,type:"running"})})}return j9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(p71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(g12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&j9(y6,{flexDirection:"column",marginTop:1,children:[fA(v12,{messages:G.messages,agentState:G.agentState}),fA(GQA,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(WQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Vy1,{title:$12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:k12(G.currentConfirmation),onSelect:Y})}),j9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(y12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(RQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Vy1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.map((I)=>({value:I,label:I})),onSelect:w})})})(),j9(y6,{gap:2,children:[j9(y6,{flexGrow:1,children:[G.type==="confirming-exit"&&fA(h6,{dimColor:!0,children:"Ctrl+C again to exit"}),G.type==="confirming"&&fA(h6,{dimColor:!0,children:"Escape to cancel"}),G.type==="running"&&j9(y6,{gap:1,children:[fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Enter to submit,"})}),fA(y6,{gap:1,children:fA(h6,{dimColor:!0,children:"Ctrl+R to expand"})})]})]}),j9(y6,{flexGrow:0,gap:2,children:[fA(x12,{lspState:G.lspState}),G.tokenUsage&&fA(b12,{tokenUsage:G.tokenUsage})]})]})]})]})}function g12({block:A,marginTop:Q=0}){if(A.type==="message"){let[,B]=A.data;if(B.role==="assistant"&&B.state?.type==="streaming")return null;if(!B.content.some((D)=>D.type==="text"&&B.role!=="info"))return null;return fA(y6,{flexDirection:"column",gap:1,marginTop:Q,children:B.content.map((D,z)=>{if(D.type==="text")switch(B.role){case"assistant":return fA(y6,{children:fA(Cy1,{children:D.text})},z);case"user":return fA(y6,{borderStyle:"bold",borderColor:"green",borderLeft:!0,borderTop:!1,borderBottom:!1,borderRight:!1,paddingLeft:1,children:fA(h6,{color:"green",italic:!0,children:D.text})},z);case"info":return fA(y6,{children:fA(h6,{color:"gray",children:D.text})},z)}else if(D.type==="thinking"){let Z=D.thinking,X=cd(Z,!1);if(X.length===0)return null;return fA(y6,{flexDirection:"column",children:X.map((K,G)=>fA(y6,{children:fA(h6,{children:K})},G))},z)}return null})})}else if(A.type==="toolResult"){let[B,J]=A.data,D=s71(B,J,!1);if(D.length===0)return null;return fA(y6,{marginTop:Q,flexDirection:"column",children:D.map((z,Z)=>fA(y6,{children:fA(h6,{children:z})},Z))})}}function b12({tokenUsage:A}){let Q=A.used/A.maxAvailable,B=Math.round(Q*100),J=Math.max(0,Math.min(B,100)),D="▁▂▃▄▅▆▇█",z=Math.floor(J*8/100),X="▁▂▃▄▅▆▇█"[Math.max(0,Math.min(z,7))],K=`${J}% ┃${X}┃`,G=0.8,q=0.9,Y;if(Q>=0.9)Y="red";else if(Q>=0.8)Y="yellow";return fA(h6,{color:Y,children:K})}function x12({lspState:A}){if(!A||Object.keys(A.servers).length===0)return null;let Q=Object.values(A.servers).map((B)=>{let J=B.status==="active"?"✓":B.status==="starting"?"⧗":"×",D=B.status==="active"?"green":B.status==="starting"?"yellow":"red";return{symbol:J,serverName:B.serverName,color:D}});return fA(y6,{gap:1,children:Q.map(({symbol:B,serverName:J,color:D},z)=>j9(h6,{color:D,children:[B," ",J]},z))})}global.React=Oy1.default;function jQA(A){return JA.level=1,(Q)=>{let B=new C8;return Uy1(Oy1.default.createElement(TQA,{inputs:B,outputs:Q,history:A.history,fuzzyServer:A.fuzzyServer,useNotifications:A.useNotifications}),{patchConsole:!0,exitOnCtrlC:!1,stdout:A.stdout}).waitUntilExit().then(()=>{B.complete()}).catch((D)=>{B.next({type:"exit"})}),FA.from(B)}}var Ly1=Ry1.join(CAA||Ry1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function _y1(A){try{await m12(Ry1.dirname(Ly1),{recursive:!0}),await p12(Ly1,A,"utf-8")}catch(Q){k1.debug("Failed to save last thread ID",Q)}}async function o71(){try{return(await u12(Ly1,"utf-8")).trim()}catch(A){return null}}var c12=[{name:"notifications",long:"notifications",type:"flag",default:!1,description:(A)=>`${A?"Enable":"Disable"} sound notifications (enabled by default when interactive)`},{name:"interactive",long:"interactive",type:"switch",default:!1,description:"Force interactive mode"},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",description:`Custom settings file path (overrides the default location ${jE})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(k1).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:"Set log file location"},{name:"format",long:"format",type:"option",default:"ui",description:"Output format (ui: interactive terminal, jsonl: JSON Lines for scripts)",choices:["ui","jsonl","new-ui"],hidden:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1,description:(A)=>`${A?"Enable":"Disable"} JetBrains integration. Requires the JetBrains MCP plugin to be installed and you must start Amp in the same directory as your JetBrains project. When enabled, Amp CLI automatically includes your open JetBrains file and text selection with every message, just like it does in VS Code.`,hidden:!0}];function l12(A,Q){let B=Q.args[0],J=Q.commands.map((z)=>z.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let z=J.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(z.length>0)Z=`Did you mean: ${z.join(", ")}? Or run amp --help for all commands.`;throw new eZ(Qq.unknownCommand(B),1,Z)}}class SQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=oK1(null),J=await hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function Q_(A,Q){Cd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),nc1("0.0.1751558552-ga58f43");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;k1.info("Using settings file",{settingsFile:B});let J=tl(),D=uv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=yX1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new SQA,K=yq(),G=ma1({configService:Z,toolService:K});try{await G.initialized}catch(_){k1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await l6(r8);if(Q.dangerouslyAllowAll)q.settings.dangerouslyAllowAll=!0;if(Q.jetbrains)q.settings["jetbrains.enabled"]=!0;let Y=q.settings["experimental.reviewTool"]??!1,F=q.settings["experimental.tools"]??[];hP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new P51,await E.start();try{await u9A(E,process.cwd())}catch(_){k1.error("Failed to index files for fuzzy completion",_)}w=p9A(E,process.cwd())}else E=new class extends P51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(K7.write(`No API key found. Starting login flow...
7485
7485
  `),!await d12(A,J))process.exit(1)}let H=ra1(),M=new LG1(H),W=new RG1(H),I=new lF1(M),N=new tf1({configService:Z,threadService:M,toolService:K,systemPromptService:X,threadSummaryService:I,threadHistoryService:W,mcpService:G}),V=void 0;return k1.info("Starting Amp background services"),V=ln1({threadService:M,threadHistoryService:W,isExtensionDevelopment:!1}),{configService:Z,systemPromptService:X,toolService:K,mcpService:G,threadService:M,threadHistoryService:W,summaryService:I,threadSyncService:V,threadStorage:H,secretStorage:J,settingsStorage:D,fileWatcher:w,fuzzyServer:E,subthreadTracker:N}}async function d12(A,Q){if(A.isInteractiveMode){if(await fE("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return K7.write(`Login cancelled. Run the command again to retry.
7486
7486
  `),!1}return await vQA(A,Q)}async function vQA(A,Q){let B=h12(32).toString("hex"),J=await q4A(A.ampURL,B);K7.write(`If your browser doesn't open automatically, visit:
7487
7487
 
@@ -7496,8 +7496,8 @@ ${A.printer.print(J,{foreground:"blue",style:"bold"})}
7496
7496
  Login successful! You can now use the Amp CLI.
7497
7497
  `),!0}catch(D){return L8.write(`
7498
7498
  Login failed: ${D instanceof Error?D.message:String(D)}
7499
- `),!1}}var i12=new Set(["fuzzy-server"]);function a12(A){let Q=new n41().name("amp").description("AI-powered coding assistant").option("--thread-id [THREAD_ID]","ID of the thread to continue running",void 0);Q.exitOverride((Z)=>{if(Z.code==="commander.help"||Z.code==="commander.version"||Z.exitCode===0)$C(),process.exit(0);let X=Z.originalError??Z;Nf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)K7.write(`0.0.1751544357-g213afc ${A.printer.print("(released 2025-07-03T12:13:05.618Z)",{foreground:"gray"})}
7500
- `);else K7.write(`0.0.1751544357-g213afc (released 2025-07-03T12:13:05.618Z)
7499
+ `),!1}}var i12=new Set(["fuzzy-server"]);function a12(A){let Q=new n41().name("amp").description("AI-powered coding assistant").option("--thread-id [THREAD_ID]","ID of the thread to continue running",void 0);Q.exitOverride((Z)=>{if(Z.code==="commander.help"||Z.code==="commander.version"||Z.exitCode===0)$C(),process.exit(0);let X=Z.originalError??Z;Nf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)K7.write(`0.0.1751558552-ga58f43 ${A.printer.print("(released 2025-07-03T16:11:58.165Z)",{foreground:"gray"})}
7500
+ `);else K7.write(`0.0.1751558552-ga58f43 (released 2025-07-03T16:11:58.165Z)
7501
7501
  `);process.exit(0)}),Q.addHelpText("after",(()=>{let Z="";Z+=A.printer.print("Environment variables:",{style:"bold"})+`
7502
7502
 
7503
7503
  `,Z+=" "+A.printer.print("AMP_API_KEY",{foreground:"green"})+` API key for Amp (see https://ampcode.com/settings)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1751544357-g213afc",
3
+ "version": "0.0.1751558552-ga58f43",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {