@sourcegraph/amp 0.0.1751500949-g9462de → 0.0.1751515778-gc465ed

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
@@ -7325,7 +7325,7 @@ ${B.join(`
7325
7325
  `)}function qs6(A,Q){if(A.state!=="active")return{type:"idle"};let B=pC(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=$7(Q,D.toolUseID);if(z){let Z=J.slice(1).map((X)=>{return $7(Q,X.toolUseID)?.name||"tool"}).filter(Boolean);return T51(z.name,J.length,Date.now(),z.input,Z.length>0?Z:void 0)}}}return{type:"idle"}}class lf1{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 nZ.getOrCreateForThread({configService:this.dependencies.configService,threadService:this.dependencies.threadService,toolService:this.dependencies.toolService,getThreadEnvironment:Hf,systemPromptService:this.dependencies.systemPromptService,threadSummaryService:this.dependencies.threadSummaryService,createFileSystem:await Id,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 B2(this.dependencies.threadService.observe(A).pipe(s7((G)=>G!==void 0)));if(K){let G=qs6(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=$7(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){y1.error(`Failed to get thread for status update: ${A}`,K)}}}),kM(this.dependencies.threadService.observe(A).pipe(s7((X)=>X!==void 0))).observable.subscribe((X)=>{if(!X)return;let K=Ez(X,"assistant");if(Li(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=$7(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 W=`${A}-${w.id}`,M=z.toolStartTimes?.get(W);if(this.events.next({type:"tool-status",toolUse:w,status:H,startTime:M,endTime:Date.now(),subthreadID:A}),z.toolStartTimes)z.toolStartTimes.delete(W)}}}}let q=Ez(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=$7(X,E.toolUseID);if(w&&w.name===s4&&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(`
7326
7326
 
7327
7327
  `);this.events.next({type:"subagent-finished",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task completed",result:F})}if(!z.isCompleted){let F=$f(X,z.printedMessageIndexes,z.printedToolRuns);if(F.blocks.length>0)this.events.next({type:"subthread-message",subThreadID:A,agentNumber:z.agentNumber,blocks:F.blocks})}}),y1.debug(`Started tracking subthread ${A}`)}catch(J){y1.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=$7(A,B.toolUseID);if(J?.name===UQ&&(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=By(D);if(z)this.trackSubthread(z,J.input?.description,J.input?.prompt).catch((Z)=>{y1.error(`Failed to track Task tool subthread ${z}`,Z)})}}}}async handleToolConfirmations(A,Q){let B=this.subthreads.get(A);if(!B){y1.error(`No tracker found for subthread ${A}`);return}y1.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)y1.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 D4A(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 z4A="Out of credits";wz();Zl();Wi();F2();j51();AK();c21();dL();import{readdir as Ys6}from"node:fs/promises";import{homedir as Us6}from"node:os";async function Z4A(A,Q){let J=!(await l21(A,Q)).some((z)=>z.type==="project"),D=await Fs6();return{shouldGenerate:J&&D}}async function Fs6(){let A=process.cwd(),Q=Us6();if(A===Q)return!1;try{return(await Ys6(A)).length>0}catch{return!1}}async function X4A(A){await A.handle({type:"user:message",message:{content:[{type:"text",text:Su0}]}})}y2();function d3(A,Q){return(B,J)=>{let D=Q(B,J);if(J.type!=="tick")y1.debug("Transition",{name:A,before:B,event:J,after:D});return D}}y2();import{spawn as G4A}from"node:child_process";import{readlink as Es6,stat as ws6}from"node:fs/promises";import{dirname as K4A,join as Hs6}from"node:path";async function q4A(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=Ws6(A,z),X=Z<0;return y1.info("Version comparison",{currentVersion:A,latestVersion:z,compareResult:Z,hasUpdate:X}),{hasUpdate:X,latestVersion:z}}catch(Q){return{hasUpdate:!1}}}function Ws6(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 Ms6(){try{let A=process.argv[1]||"";y1.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{let z=await Es6(A);if(z)Q=z,y1.debug("Resolved symlink",{from:A,to:Q});else y1.debug("Not a symlink or readlink returned empty")}catch(z){y1.debug("Error reading symlink (probably not a symlink)",{error:z})}if(y1.debug("Resolved installation path",{actualPath:Q}),Q.includes("/.local/share/pnpm/"))return y1.debug("Detected pnpm from path pattern: /.local/share/pnpm/"),"pnpm";if(Q.includes("/.config/yarn/global/"))return y1.debug("Detected yarn from path pattern: /.config/yarn/global/"),"yarn";if(Q.includes("/.bun/install/global/"))return y1.debug("Detected bun from path pattern: /.bun/install/global/"),"bun";if(Q.includes("/node_modules/@sourcegraph/amp/")){if(y1.debug("Found generic node_modules path, checking for specific patterns"),Q.includes("/.local/share/pnpm/"))return y1.debug("Detected pnpm from node_modules with pnpm-specific path"),"pnpm";if(Q.includes("/.config/yarn/"))return y1.debug("Detected yarn from node_modules with yarn-specific path"),"yarn";if(Q.includes("/.bun/"))return y1.debug("Detected bun from node_modules with bun-specific path"),"bun";return y1.debug("Defaulting to npm for generic node_modules path"),"npm"}y1.debug("No path pattern matched, checking installation directory for lockfiles");let B=K4A(K4A(Q));y1.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=Hs6(B,z);return y1.debug("Checking for lockfile",{filePath:X}),await ws6(X),y1.debug("Found package manager lockfile",{file:z,manager:Z,filePath:X}),Z}catch(X){y1.debug("Lockfile not found",{file:z,error:X})}y1.debug("No lockfiles found, falling back to environment-based detection");let D=await Y4A();return y1.debug("Environment-based detection result",{envDetected:D}),D}catch(A){return y1.debug("Error detecting installed package manager",{error:A}),null}}async function Y4A(){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([P51("pnpm"),P51("yarn"),P51("bun"),P51("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 P51(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'`;y1.debug("Checking command existence",{command:A,fullCommand:D});let z=G4A("/bin/sh",["-c",D],{stdio:"ignore",cwd:process.env.HOME});z.on("close",(Z)=>{y1.debug("Command check result",{command:A,code:Z}),Q(Z===0)}),z.on("error",(Z)=>{y1.debug("Command check error",{command:A,error:Z}),Q(!1)})}catch(B){y1.debug("Error checking command existencer",{command:A,error:B}),Q(!1)}})}function Is6(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 U4A(A){let Q=await Ms6();if(!Q)Q=await Y4A();if(!Q)Q="npm",y1.debug("Falling back to npm for update");y1.debug("Using package manager for update",{packageManager:Q,targetVersion:A});let[B,J]=Is6(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}'`;y1.debug("Running update command",{packageManager:Q,command:B,args:J,fullCommand:G});let q=G4A("/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}:
7328
- ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function F4A({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 W=GT(),M=new Set,I=kM(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await B2(I.observable);let _=await Id,T=await nZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Hf,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{y1.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=W.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=mU(R,j,mU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{y1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await W.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(KZ(()=>{b()})).pipe(zT(d3("threadSession",function(S,y){function d(D1){y1.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>S51.CRITICAL)return y1.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)=>{y1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{y1.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=pC(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 y1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{y1.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>S51.CRITICAL)K1="critical",X1="final";else if(A1>S51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>S51.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)y1.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)=>{y1.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&&M.size===0&&y.thread.messages.length>0){let K1=$f(y.thread,M,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Ri(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=pC(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=$f(y.thread,M,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=pC(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 r=Ez(y.thread,"assistant"),s=r?y.thread.messages.indexOf(r):null;if(s!==null&&s!==S.currentAssistantMessageIndex)y1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:s,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=s;let e=Ez(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(r?.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=$7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===s4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,y1.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?$7(y.thread,P1.toolUseID):null;if(P1&&R1)return y1.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 y1.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=Ri(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(z4A)){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(D4A(y.status.ephemeralError))return y1.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(y1.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=pC(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=$7(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?$7(I.value.last,K1[0].toolUseID):void 0,r=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return $7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,s=N1?T51(N1.name,X1,Date.now(),N1.input,r):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:r};$.next({type:"state",state:s})}else{let N1=I.value.last;if(N1){let r=pC(N1);if(r)$.next({type:"state",state:r});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 y1.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)=>{y1.error("Failed to send subthread tool confirmations",D1)}),y1.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 y1.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)=>{y1.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")}),y1.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=Ri(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,r=K1.used,s=N1-r,e=N1>0?s/N1*100:0;if(s<=0)y1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:r,reduction:s,threadID:E});else if(e<10)y1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E});else y1.info("Compaction successful",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E})}else y1.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&&M.size===0&&y.messages.length>0){let A1=$f({id:E,messages:y.messages},M,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(y1.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 y1.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 y1.info("Checking agent file status"),Z4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{y1.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"}),nZ.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 nZ.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")nZ.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(()=>{y1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{y1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return y1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return y1.error("No current tool ID in collecting-tool-confirmations state"),S;if(y1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){y1.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)=>{y1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],r=S.confirmationQueue.slice(1);return y1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:r.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:r}}return y1.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 y1.error("Thread not available for finding next tool"),S;let s=(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=s?$7(I.value.last,s.toolUseID):null;if(s&&e)return y1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:s.run.status==="blocked-on-user"?s.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");y1.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 X4A(T).catch((D1)=>{y1.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)=>{y1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)y1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else y1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else y1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return Ns6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await B2(g)}async function Ns6(A){try{let Q=await q4A("0.0.1751500949-g9462de");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await U4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){y1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else y1.info("No update available")}catch(Q){y1.debug("Update check failed",Q)}}var S51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();F2();yq();function E4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7328
+ ${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function F4A({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 W=GT(),M=new Set,I=kM(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await B2(I.observable);let _=await Id,T=await nZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Hf,systemPromptService:Y,threadSummaryService:X,createFileSystem:_,threadHistoryService:J,mcpService:D},E);await T.resume().catch((S)=>{y1.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=W.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=mU(R,j,mU(P,f,m,l)),g=new C8;async function b(){if($.next({type:"state",state:{type:"shutting-down"}}),await A?.sync().catch((S)=>{y1.error("Thread sync error",S,{threadID:E})}),F.dispose(),await W.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(KZ(()=>{b()})).pipe(zT(d3("threadSession",function(S,y){function d(D1){y1.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>S51.CRITICAL)return y1.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)=>{y1.error("Thread sync after submit error",X1,{threadID:E})})}).catch((X1)=>{y1.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=pC(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 y1.debug("already accepting, ignoring event",{state:S,event:y}),S;let D1="tokenUsage"in S?S.tokenUsage:void 0;if(A?.sync()?.catch((A1)=>{y1.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>S51.CRITICAL)K1="critical",X1="final";else if(A1>S51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>S51.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)y1.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)=>{y1.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&&M.size===0&&y.thread.messages.length>0){let K1=$f(y.thread,M,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Ri(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=pC(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=$f(y.thread,M,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=pC(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 r=Ez(y.thread,"assistant"),s=r?y.thread.messages.indexOf(r):null;if(s!==null&&s!==S.currentAssistantMessageIndex)y1.info("New assistant message detected, clearing tool confirmations",{oldIndex:S.currentAssistantMessageIndex,newIndex:s,previousToolCount:S.toolConfirmationStatus.size}),S.toolConfirmationStatus.clear(),S.currentAssistantMessageIndex=s;let e=Ez(y.thread,"user")?.content.filter((Y1)=>Y1.type==="tool_result"&&Y1.run.status==="blocked-on-user")??[],G1=new Set(r?.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=$7(y.thread,Y1.toolUseID),P1=S.toolConfirmationStatus.get(Y1.toolUseID);if(U1&&U1.name===s4&&Y1.run.status==="blocked-on-user"&&P1===void 0){if(S.toolConfirmationStatus.set(Y1.toolUseID,"awaiting"),q1=!0,y1.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?$7(y.thread,P1.toolUseID):null;if(P1&&R1)return y1.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 y1.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=Ri(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(z4A)){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(D4A(y.status.ephemeralError))return y1.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(y1.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=pC(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=$7(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?$7(I.value.last,K1[0].toolUseID):void 0,r=X1>1&&K1&&I.value.last?K1.slice(1,Math.min(4,K1.length)).map((e)=>{return $7(I.value.last,e.toolUseID)?.name||"tool"}).filter(Boolean):void 0,s=N1?T51(N1.name,X1,Date.now(),N1.input,r):{type:"running-tools",toolCount:X1,startTime:Date.now(),queuedTools:r};$.next({type:"state",state:s})}else{let N1=I.value.last;if(N1){let r=pC(N1);if(r)$.next({type:"state",state:r});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 y1.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)=>{y1.error("Failed to send subthread tool confirmations",D1)}),y1.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 y1.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)=>{y1.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")}),y1.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=Ri(D1);if(A1){let K1={used:A1.totalInputTokens,maxAvailable:A1.maxInputTokens},X1=S.type==="compacting"?S.preCompactionTokenUsage:null;if(X1){let N1=X1.used,r=K1.used,s=N1-r,e=N1>0?s/N1*100:0;if(s<=0)y1.warn("Compaction did not reduce token usage",{preUsed:N1,postUsed:r,reduction:s,threadID:E});else if(e<10)y1.warn("Compaction reduction was minimal",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E});else y1.info("Compaction successful",{preUsed:N1,postUsed:r,reduction:s,reductionPercent:e.toFixed(1),threadID:E})}else y1.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&&M.size===0&&y.messages.length>0){let A1=$f({id:E,messages:y.messages},M,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(y1.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 y1.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 y1.info("Checking agent file status"),Z4A({filesystem:_(E),configService:Q,threadService:B},I.value.last).then((K1)=>{P.next({type:"agent-file-check-complete",shouldGenerate:K1.shouldGenerate})}).catch((K1)=>{y1.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"}),nZ.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 nZ.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")nZ.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(()=>{y1.info("Compaction completed successfully",{preCompactionTokenUsage:D1}),P.next({type:"compaction-result",result:!0,severity:S.severity})}).catch((A1)=>{y1.error("Compaction failed",A1),P.next({type:"compaction-result",result:!1,severity:S.severity})}),{...S,type:"compacting",preCompactionTokenUsage:D1}}else return y1.info("Compaction cancelled"),z1();else if(S.type==="collecting-tool-confirmations"&&y.input.confirmation.type==="tool-use"){if(!S.currentToolID)return y1.error("No current tool ID in collecting-tool-confirmations state"),S;if(y1.info(`Received confirmation for tool: ${y.input.allow?"accepted":"rejected"}`,{toolUseID:S.currentToolID,subthreadID:y.input.confirmation.subthreadID}),y.input.confirmation.subthreadID&&S.subthreadContext){y1.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)=>{y1.error("Failed to send subthread tool confirmation",N1)}),S.confirmationQueue.length>0){let N1=S.confirmationQueue[0],r=S.confirmationQueue.slice(1);return y1.info("Processing next queued confirmation request",{subThreadID:N1.subThreadID,agentNumber:N1.agentNumber,remainingQueueLength:r.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:r}}return y1.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 y1.error("Thread not available for finding next tool"),S;let s=(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=s?$7(I.value.last,s.toolUseID):null;if(s&&e)return y1.info(`Asking confirmation for next tool: ${e.name}`,{toolUseID:X1,remainingCount:D1.length}),$.next({type:"confirm",confirmation:{type:"tool-use",tools:[{useBlock:e,toAllow:s.run.status==="blocked-on-user"?s.run.toAllow:void 0}]}}),{...S,currentToolID:X1}}let A1=Array.from(S.toolConfirmationStatus.entries()).filter(([X1,N1])=>N1==="confirmed"||N1==="rejected");y1.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 X4A(T).catch((D1)=>{y1.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)=>{y1.error("Error in state machine",S),b()}});if(w)G.get(E).then((S)=>{if(S&&S.messages)y1.info("Sending historic messages for initialization",{threadId:E,messageCount:S.messages.length}),P.next({type:"historic-thread",messages:S.messages});else y1.info("Sending empty messages for continued thread without stored messages",{threadId:E}),P.next({type:"historic-thread",messages:[]})});else y1.info("Sending empty messages for new thread initialization",{threadId:E}),P.next({type:"historic-thread",messages:[]});return Ns6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await B2(g)}async function Ns6(A){try{let Q=await q4A("0.0.1751515778-gc465ed");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await U4A(Q.latestVersion),A.next({type:"update-result",success:!0,version:Q.latestVersion})}catch(B){y1.info("Update failed",B),A.next({type:"update-result",success:!1,version:Q.latestVersion})}},100);else y1.info("No update available")}catch(Q){y1.debug("Update check failed",Q)}}var S51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();F2();yq();function E4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
7329
7329
  `)}return(z)=>{let Z=new C8;if(!J)throw new Error("JSONL UI requires piped input (non-interactive mode)");return y1.debug("setting up JSONL UI"),z.pipe(Qi({onSubscribe:()=>{D({type:"initial",threadID:B}),Bj().then(()=>{Z.next({type:"initialized"})})},onUnsubscribe:()=>{y1.debug("JSONL UI stopped")}})).pipe(KZ(()=>{Z.complete()})).pipe(zT(d3("JSONL",(X,K)=>{if(y1.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:W}=w;return{type:H,text:W}}else if(w.type==="image"){let{type:H,source:W}=w;return{type:H,source:W}}else if(w.type==="tool_result"){let{type:H,toolUseID:W,run:M,userInput:I}=w;return{type:H,toolUseID:W,run:M,userInput:I}}else if(w.type==="thinking"){let{type:H,thinking:W}=w;return{type:H,thinking:W}}else if(w.type==="redacted_thinking"){let{type:H,data:W}=w;return{type:H,data:W}}else if(w.type==="tool_use"){let{type:H,id:W,name:M,input:I}=w,N={type:H,id:W,name:M};if(I!==void 0)N.input=I;return N}else if(w.type==="server_tool_use"){let{type:H,id:W,name:M,input:I}=w;return{type:H,id:W,name:M,input:I}}else if(w.type==="web_search_tool_result"){let{type:H,content:W}=w;return{type:H,content:W}}else if(w.type==="summary"){let{type:H,summary:W}=w;return{type:H,summary:W}}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:W,content:M,meta:I}=H,N={role:W,content:G(M),meta:I};Y.push([w,N])}else if(H.role==="assistant"){let{role:W,content:M,state:I}=H,N={role:W,content:G(M),state:I};Y.push([w,N])}else if(H.role==="info"){let{role:W,content:M}=H,I={role:W,content:G(M)};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 W={type:w.type,id:w.id,name:w.name,input:{}},M={type:H.type,toolUseID:H.toolUseID,run:q(D5(H.run))};F.push([W,M])}else y1.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 y1.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===s4&&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)=>{y1.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 ff}from"node:child_process";function kf(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")ff("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")ff("powershell [console]::beep(800,200)");else if(process.platform==="linux")ff("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="requires-user-input"){if(process.platform==="darwin")ff("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")ff("powershell [console]::beep(1000,300)");else if(process.platform==="linux")ff("paplay /usr/share/sounds/freedesktop/stereo/dialog-information.oga || beep -f 1000 -l 100")}}catch(Q){y1.error(`Failed to play notification sound (${A}):`,Q)}}F2();y2();import{mkdir as w4A,readFile as H4A,writeFile as df1,open as Cs6}from"node:fs/promises";import{homedir as Vs6}from"node:os";import Nd from"node:path";var Os6=Nd.join(Mf||Nd.join(Vs6(),".local/share"),"amp"),Rs6=Nd.join(Os6,"history.jsonl"),Ls6=1000;class Cd{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(A){this.historyFile=A?.historyFile||Rs6,this.maxSize=A?.maxSize||Ls6,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)this.history=await this.readHistoryFromDisk(),this.loaded=!0}async readHistoryFromDisk(){try{let A=await H4A(this.historyFile,"utf-8");if(!A.trim())return[];return this.parseJsonlContent(A)}catch(A){if(A.code!=="ENOENT")return y1.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 H4A(Q,"utf-8");if(B.trim()){let J=JSON.parse(B);y1.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(`
7330
7330
  `),B=[];for(let J of Q)if(J.trim())try{let D=JSON.parse(J);if(typeof D==="string")B.push(D);else y1.warn("Skipping non-string entry in history",{line:J,type:typeof D})}catch(D){y1.warn("Skipping invalid JSONL line in history",{line:J})}return y1.info("Loaded history from JSONL file",{file:this.historyFile,size:B.length}),B}async writeHistoryToDisk(A){await w4A(Nd.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
7331
7331
  `)+`
@@ -7453,7 +7453,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
7453
7453
  `),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(`
7454
7454
  `),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=GQA(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=qQA(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(y1.info("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("")+`
7455
7455
  `+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){y1.error("Failed to submit message",u)}finally{w(!1)}};return fA(y6,{flexDirection:"column",width:"100%",flexGrow:1,flexShrink:0,ref:Z,children:W.map((b,u)=>fA(y6,{flexShrink:0,flexDirection:"row",children:fA(y6,{flexGrow:1,flexShrink:0,width:"100%",children:u===X.virtualLine?T9(Gy1,{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 J12(A,Q){let B=A.split(`
7456
- `),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(/ +$/,""),W=g6.default(K),M=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+M.length}),q=G+W.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let W=0;W<H.length;W+=Q){let M=H.slice(W,W+Q).join("");J.push({type:Y?"start":"continuation",content:M,originalLine:D,start:G+W,end:G+W+g6.default(M).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 u71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=u71.useState(0);if(nW((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)}),u71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return T9(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:T9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function D12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var UQA=10;function z12({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=xd(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(Fy1,{children:z.text})},Z);return null})})}function Z12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=X12(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 X12(A){if(A.name===s4){let Q=A.input;return"Run "+pl.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return pl.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 G12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return T9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:T9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:T9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function FQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function EQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=ef(),[K]=t3.useState(()=>new C8);t3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=t3.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=(W)=>{q((M)=>{if(M.type!=="confirming"||!M.currentConfirmation)return M;let I=M.currentConfirmation,N=M.confirmationQueue.slice(1),V=W===null?"no":W;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{...M,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...M,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};t3.useEffect(()=>{let W=A.subscribe((M)=>{switch(M.type){case"state":{switch(M.state.type){case"shutting-down":q({...G,type:"exiting"}),Bj().then(()=>{z.exit()});break;case"idle":if(D)kf("idle");q((I)=>({...I,agentState:M.state}));break;default:q((I)=>({...I,agentState:M.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...M.blocks],V=FQA(N),_=_i({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:M.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:M.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(M.toolUse.name===UQ)return{...I,activeTools:N};if(M.status==="completed"||M.status==="error"||M.status==="cancelled")N.delete(M.toolUse.id);else{let V=M.subthreadID;N.set(M.toolUse.id,{toolUse:M.toolUse,status:M.status,startTime:M.startTime,endTime:M.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(M.subThreadID,{subThreadID:M.subThreadID,agentNumber:M.agentNumber,taskDescription:M.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(M.subThreadID);if(V)N.set(M.subThreadID,{...V,agentState:M.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)kf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,M.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:M.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:M.title}));break}default:y1.info("unhandled ui output",M);break}});return()=>{W.unsubscribe()}},[A,z]);let F=async(W,M)=>{let I=await D12(J,W);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:M}))},E=()=>{q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(W)=>{if(W!==null)K.next(W),q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};t3.useEffect(()=>{let W=null,M=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),W=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA)};return process.stdout.on("resize",M),()=>{if(W)clearTimeout(W);process.stdout.off("resize",M)}},[]),nW((W,M)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(M.escape)Q.next({type:"interrupt"});else if(M.ctrl&&W.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(M.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}))},UQA);else if(M.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 W=FQA(G.messages);return fA(KQA,{threadName:G.threadTitle,messages:W,onExit:()=>q({...G,type:"running"})})}return T9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(f71,{items:G.messages,children:(W,M)=>fA(y6,{children:fA(q12,{block:W,marginTop:M===0?0:1},M)},M)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(z12,{messages:G.messages,agentState:G.agentState}),fA(s7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(zQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:Z12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:K12(G.currentConfirmation),onSelect:Y})}),T9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(G12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(YQA,{onSubmit:(W)=>{Q.next({type:"message",message:W})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let W=Math.min(10,Math.max(3,Math.floor(X*0.4))),M=G.completions.slice(0,W);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${M.length}${G.completions.length>W?`/${G.completions.length}`:""})`,options:M.map((I)=>({value:I,label:I})),onSelect:w})})})(),T9(y6,{gap:2,children:[T9(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"&&T9(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"})})]})]}),T9(y6,{flexGrow:0,gap:2,children:[fA(U12,{lspState:G.lspState}),G.tokenUsage&&fA(Y12,{tokenUsage:G.tokenUsage})]})]})]})]})}function q12({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(Fy1,{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=xd(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=m71(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 Y12({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 U12({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)=>T9(h6,{color:D,children:[B," ",J]},z))})}global.React=wy1.default;function wQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(EQA,{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 Wy1=Hy1.join(GAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function My1(A){try{await E12(Hy1.dirname(Wy1),{recursive:!0}),await H12(Wy1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function p71(){try{return(await w12(Wy1,"utf-8")).trim()}catch(A){return null}}var W12=[{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(y1).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 M12(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 tZ(Aq.unknownCommand(B),1,Z)}}class WQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=FD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function e3(A,Q){Hd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751500949-g9462de");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=al(),D=kv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=oB1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new WQA,K=kq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await B2(s8);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"]??[];$P1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new N51,await E.start();try{await j9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=P9A(E,process.cwd())}else E=new class extends N51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(Z7.write(`No API key found. Starting login flow...
7456
+ `),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(/ +$/,""),W=g6.default(K),M=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+M.length}),q=G+W.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let W=0;W<H.length;W+=Q){let M=H.slice(W,W+Q).join("");J.push({type:Y?"start":"continuation",content:M,originalLine:D,start:G+W,end:G+W+g6.default(M).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 u71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=u71.useState(0);if(nW((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)}),u71.useEffect(()=>{D(0)},[A]),A.length===0)return null;return T9(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:T9(h6,{bold:Z===J,color:Z===J?"blue":void 0,children:[Z===J?"» ":" ",z.label]})},Z))]})}async function D12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var UQA=10;function z12({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=xd(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(Fy1,{children:z.text})},Z);return null})})}function Z12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=X12(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 X12(A){if(A.name===s4){let Q=A.input;return"Run "+pl.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return pl.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 G12({todos:A}){if(!Array.isArray(A)||A.length===0)return null;return T9(y6,{borderStyle:"round",paddingX:1,flexDirection:"column",flexGrow:1,flexShrink:0,children:[fA(y6,{children:T9(h6,{bold:!0,children:["TODOs (",A.length,")"]})}),A.map((Q,B)=>fA(y6,{gap:1,children:T9(h6,{wrap:"truncate",children:[fA(h6,{children:"• "}),fA(h6,{bold:Q.status==="in-progress",strikethrough:Q.status==="completed",children:Q.content})]})},Q.id))]})}function FQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function EQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=ef(),[K]=t3.useState(()=>new C8);t3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=t3.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=(W)=>{q((M)=>{if(M.type!=="confirming"||!M.currentConfirmation)return M;let I=M.currentConfirmation,N=M.confirmationQueue.slice(1),V=W===null?"no":W;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{...M,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...M,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};t3.useEffect(()=>{let W=A.subscribe((M)=>{switch(M.type){case"state":{switch(M.state.type){case"shutting-down":q({...G,type:"exiting"}),Bj().then(()=>{z.exit()});break;case"idle":if(D)kf("idle");q((I)=>({...I,agentState:M.state}));break;default:q((I)=>({...I,agentState:M.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...M.blocks],V=FQA(N),_=_i({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:M.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:M.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(M.toolUse.name===UQ)return{...I,activeTools:N};if(M.status==="completed"||M.status==="error"||M.status==="cancelled")N.delete(M.toolUse.id);else{let V=M.subthreadID;N.set(M.toolUse.id,{toolUse:M.toolUse,status:M.status,startTime:M.startTime,endTime:M.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(M.subThreadID,{subThreadID:M.subThreadID,agentNumber:M.agentNumber,taskDescription:M.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(M.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(M.subThreadID);if(V)N.set(M.subThreadID,{...V,agentState:M.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)kf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,M.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:M.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:M.title}));break}default:y1.info("unhandled ui output",M);break}});return()=>{W.unsubscribe()}},[A,z]);let F=async(W,M)=>{let I=await D12(J,W);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:M}))},E=()=>{q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(W)=>{if(W!==null)K.next(W),q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};t3.useEffect(()=>{let W=null,M=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),W=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},UQA)};return process.stdout.on("resize",M),()=>{if(W)clearTimeout(W);process.stdout.off("resize",M)}},[]),nW((W,M)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(M.escape)Q.next({type:"interrupt"});else if(M.ctrl&&W.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(M.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}))},UQA);else if(M.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 W=FQA(G.messages);return fA(KQA,{threadName:G.threadTitle,messages:W,onExit:()=>q({...G,type:"running"})})}return T9(y6,{flexDirection:"column",minHeight:"100%",flexGrow:1,height:G.rerendering&&G.messages.length==0?0:"auto",children:[!G.rerendering&&fA(f71,{items:G.messages,children:(W,M)=>fA(y6,{children:fA(q12,{block:W,marginTop:M===0?0:1},M)},M)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(z12,{messages:G.messages,agentState:G.agentState}),fA(s7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(zQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:Z12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:K12(G.currentConfirmation),onSelect:Y})}),T9(y6,{flexDirection:H?"row-reverse":"column",children:[G.todos.length>0&&fA(y6,{flexGrow:0,flexShrink:0,width:H?"auto":"100%",children:fA(G12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(YQA,{onSubmit:(W)=>{Q.next({type:"message",message:W})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let W=Math.min(10,Math.max(3,Math.floor(X*0.4))),M=G.completions.slice(0,W);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${M.length}${G.completions.length>W?`/${G.completions.length}`:""})`,options:M.map((I)=>({value:I,label:I})),onSelect:w})})})(),T9(y6,{gap:2,children:[T9(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"&&T9(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"})})]})]}),T9(y6,{flexGrow:0,gap:2,children:[fA(U12,{lspState:G.lspState}),G.tokenUsage&&fA(Y12,{tokenUsage:G.tokenUsage})]})]})]})]})}function q12({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(Fy1,{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=xd(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=m71(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 Y12({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 U12({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)=>T9(h6,{color:D,children:[B," ",J]},z))})}global.React=wy1.default;function wQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(EQA,{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 Wy1=Hy1.join(GAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function My1(A){try{await E12(Hy1.dirname(Wy1),{recursive:!0}),await H12(Wy1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function p71(){try{return(await w12(Wy1,"utf-8")).trim()}catch(A){return null}}var W12=[{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(y1).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 M12(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 tZ(Aq.unknownCommand(B),1,Z)}}class WQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=FD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function e3(A,Q){Hd({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751515778-gc465ed");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=al(),D=kv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=oB1({storage:D,secretStorage:J,workspaceRoots:FA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new WQA,K=kq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await B2(s8);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"]??[];$P1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new N51,await E.start();try{await j9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=P9A(E,process.cwd())}else E=new class extends N51{async start(){}async query(){return[]}dispose(){}},w={[Symbol.dispose]:()=>{}};if(!await J.get("apiKey",A.ampURL)){if(Z7.write(`No API key found. Starting login flow...
7457
7457
  `),!await I12(A,J))process.exit(1)}let H=cl1(),W=new HG1(H),M=new wG1(H),I=new gF1(W),N=new lf1({configService:Z,threadService:W,toolService:K,systemPromptService:X,threadSummaryService:I,threadHistoryService:M,mcpService:G}),V=void 0;return y1.info("Starting Amp background services"),V=Cn1({threadService:W,threadHistoryService:M,isExtensionDevelopment:!1}),{configService:Z,systemPromptService:X,toolService:K,mcpService:G,threadService:W,threadHistoryService:M,summaryService:I,threadSyncService:V,threadStorage:H,secretStorage:J,settingsStorage:D,fileWatcher:w,fuzzyServer:E,subthreadTracker:N}}async function I12(A,Q){if(A.isInteractiveMode){if(await fE("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return Z7.write(`Login cancelled. Run the command again to retry.
7458
7458
  `),!1}return await MQA(A,Q)}async function MQA(A,Q){let B=F12(32).toString("hex"),J=await o9A(A.ampURL,B);Z7.write(`If your browser doesn't open automatically, visit:
7459
7459
 
@@ -7468,8 +7468,8 @@ ${A.printer.print(J,{foreground:"blue",style:"bold"})}
7468
7468
  Login successful! You can now use the Amp CLI.
7469
7469
  `),!0}catch(D){return L8.write(`
7470
7470
  Login failed: ${D instanceof Error?D.message:String(D)}
7471
- `),!1}}var N12=new Set(["fuzzy-server"]);function C12(A){let Q=new h41().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)vC(),process.exit(0);let X=Z.originalError??Z;Wf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.1751500949-g9462de ${A.printer.print("(released 2025-07-03T00:11:17.602Z)",{foreground:"gray"})}
7472
- `);else Z7.write(`0.0.1751500949-g9462de (released 2025-07-03T00:11:17.602Z)
7471
+ `),!1}}var N12=new Set(["fuzzy-server"]);function C12(A){let Q=new h41().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)vC(),process.exit(0);let X=Z.originalError??Z;Wf(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.1751515778-gc465ed ${A.printer.print("(released 2025-07-03T04:18:57.338Z)",{foreground:"gray"})}
7472
+ `);else Z7.write(`0.0.1751515778-gc465ed (released 2025-07-03T04:18:57.338Z)
7473
7473
  `);process.exit(0)}),Q.addHelpText("after",(()=>{let Z="";Z+=A.printer.print("Environment variables:",{style:"bold"})+`
7474
7474
 
7475
7475
  `,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.1751500949-g9462de",
3
+ "version": "0.0.1751515778-gc465ed",
4
4
  "description": "CLI for Amp, an agentic coding tool in research preview from Sourcegraph.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {