@sourcegraph/amp 0.0.1751535324-g810c0e → 0.0.1751537861-gbec607
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +4 -4
- package/package.json +1 -1
package/dist/main.js
CHANGED
@@ -7351,7 +7351,7 @@ ${B.join(`
|
|
7351
7351
|
`)}function Ks6(A,Q){if(A.state!=="active")return{type:"idle"};let B=mC(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 L51(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 aZ.getOrCreateForThread({configService:this.dependencies.configService,threadService:this.dependencies.threadService,toolService:this.dependencies.toolService,getThreadEnvironment:Ff,systemPromptService:this.dependencies.systemPromptService,threadSummaryService:this.dependencies.threadSummaryService,createFileSystem:await Md,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 J2(this.dependencies.threadService.observe(A).pipe(s7((G)=>G!==void 0)));if(K){let G=Ks6(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)}}}),$W(this.dependencies.threadService.observe(A).pipe(s7((X)=>X!==void 0))).observable.subscribe((X)=>{if(!X)return;let K=Fz(X,"assistant");if(Oi(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 M=`${A}-${w.id}`,W=z.toolStartTimes?.get(M);if(this.events.next({type:"tool-status",toolUse:w,status:H,startTime:W,endTime:Date.now(),subthreadID:A}),z.toolStartTimes)z.toolStartTimes.delete(M)}}}}let q=Fz(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(`
|
7352
7352
|
|
7353
7353
|
`);this.events.next({type:"subagent-finished",subThreadID:A,agentNumber:z.agentNumber,taskDescription:z.taskDescription||"Task completed",result:F})}if(!z.isCompleted){let F=Pf(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===FQ&&(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=ek(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 J4A(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 D4A="Out of credits";Ez();Jl();wi();Y2();_51();AK();u21();cL();import{readdir as Gs6}from"node:fs/promises";import{homedir as qs6}from"node:os";async function z4A(A,Q){let J=!(await p21(A,Q)).some((z)=>z.type==="project"),D=await Ys6();return{shouldGenerate:J&&D}}async function Ys6(){let A=process.cwd(),Q=qs6();if(A===Q)return!1;try{return(await Gs6(A)).length>0}catch{return!1}}async function Z4A(A){await A.handle({type:"user:message",message:{content:[{type:"text",text:_u0}]}})}y2();function c3(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 K4A}from"node:child_process";import{readlink as Us6,stat as Fs6}from"node:fs/promises";import{dirname as X4A,join as Es6}from"node:path";async function G4A(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 Hs6(){try{let A=process.argv[1]||"";y1.debug("Detecting package manager from script path",{currentScript:A});let Q=A;try{let z=await Us6(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=X4A(X4A(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=Es6(B,z);return y1.debug("Checking for lockfile",{filePath:X}),await Fs6(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 q4A();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 q4A(){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([T51("pnpm"),T51("yarn"),T51("bun"),T51("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 T51(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=K4A("/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 Ms6(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 Y4A(A){let Q=await Hs6();if(!Q)Q=await q4A();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]=Ms6(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=K4A("/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}:
|
7354
|
-
${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function U4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let M=XT(),W=new Set,I=$W(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await J2(I.observable);let _=await Md,T=await aZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Ff,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(UA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=xU(R,j,xU(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 M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(XZ(()=>{b()})).pipe(JT(c3("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>j51.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=mC(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>j51.CRITICAL)K1="critical",X1="final";else if(A1>j51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>j51.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&&W.size===0&&y.thread.messages.length>0){let K1=Pf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Vi(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=mC(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=Pf(y.thread,W,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=mC(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=Fz(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=Fz(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=Vi(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(D4A)){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(J4A(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=mC(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?L51(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=mC(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=Vi(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&&W.size===0&&y.messages.length>0){let A1=Pf({id:E,messages:y.messages},W,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(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"}),aZ.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 aZ.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")aZ.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 Z4A(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 Ws6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await J2(g)}async function Ws6(A){try{let Q=await G4A("0.0.1751535324-g810c0e");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await Y4A(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 j51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();Y2();kq();function F4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
|
7354
|
+
${w}`))}}),q.on("error",(E)=>{z(new Error(`Failed to spawn ${B}: ${E.message}`))})})}async function U4A({threadSyncService:A,configService:Q,threadService:B,threadHistoryService:J,mcpService:D,fileWatcher:z,fuzzyServer:Z,summaryService:X,settingsStorage:K,threadStorage:G,toolService:q,systemPromptService:Y,subthreadTracker:F},{threadID:E,isContinued:w,ui:H}){let M=XT(),W=new Set,I=$W(B.observe(E).pipe(s7((S)=>S!==void 0))),N=new Set,V=new Map;await J2(I.observable);let _=await Md,T=await aZ.getOrCreateForThread({configService:Q,threadService:B,toolService:q,getThreadEnvironment:Ff,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(UA.from($)).pipe(r6((S)=>({type:"ui-input",input:S}))),m=F.events$.pipe(r6((S)=>S)),l=M.status.pipe(r6((S)=>({type:"lsp-status",lspState:S}))),v=xU(R,j,xU(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 M.stopAllServers(),T.dispose(),A)A.dispose();B.dispose(),await D.dispose(),z[Symbol.dispose](),Z.dispose(),$.complete(),g.next()}let u=v.pipe(XZ(()=>{b()})).pipe(JT(c3("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>j51.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=mC(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>j51.CRITICAL)K1="critical",X1="final";else if(A1>j51.WARNING&&S.compactionPromptState==="none")K1="moderate",X1="first";else if(A1>j51.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&&W.size===0&&y.thread.messages.length>0){let K1=Pf(y.thread,W,N);if(K1.blocks.length>0)$.next({type:"messages",blocks:K1.blocks})}let A1=S.tokenUsage;if(y.thread){let K1=Vi(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=mC(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=Pf(y.thread,W,N),N1=X1.blocks;if(K1?.role==="assistant"&&K1.state.type==="streaming"&&X1.blocks.length===0){N1=[{type:"message",data:[y.thread.messages.length-1,K1]}];let U1=mC(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=Fz(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=Fz(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=Vi(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(D4A)){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(J4A(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=mC(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?L51(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=mC(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=Vi(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&&W.size===0&&y.messages.length>0){let A1=Pf({id:E,messages:y.messages},W,N);if(A1.blocks.length>0)$.next({type:"messages",blocks:A1.blocks})}let D1={...S,hasThread:!0};if(D1.hasUI&&D1.hasThread)return z1();return D1}else if(y.type==="subagent-finished")return $.next({type:"subagent-finished",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,result:y.result}),S;else if(y.type==="subagent-cancelled")return $.next({type:"subagent-cancelled",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription}),S;else if(y.type==="subagent-error")return $.next({type:"subagent-error",subThreadID:y.subThreadID,agentNumber:y.agentNumber,taskDescription:y.taskDescription,error:y.error}),S;else if(y.type==="subthread-tool-request"){if(y.tools.length>0){if(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"}),aZ.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 aZ.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")aZ.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 Z4A(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 Ws6(P).catch((S)=>{y1.debug("Update check startup failed",S)}),await J2(g)}async function Ws6(A){try{let Q=await G4A("0.0.1751537861-gbec607");if(Q.hasUpdate&&Q.latestVersion)A.next({type:"update-start-updating"}),setTimeout(async()=>{try{await Y4A(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 j51={WARNING:0.8,SEVERE:0.9,CRITICAL:0.98};y2();AK();Y2();kq();function F4A(A){let{stdout:Q,threadID:B,pipedInput:J}=A;function D(z){Q.write(JSON.stringify(z)+`
|
7355
7355
|
`)}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(ed({onSubscribe:()=>{D({type:"initial",threadID:B}),Aj().then(()=>{Z.next({type:"initialized"})})},onUnsubscribe:()=>{y1.debug("JSONL UI stopped")}})).pipe(XZ(()=>{Z.complete()})).pipe(JT(c3("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:M}=w;return{type:H,text:M}}else if(w.type==="image"){let{type:H,source:M}=w;return{type:H,source:M}}else if(w.type==="tool_result"){let{type:H,toolUseID:M,run:W,userInput:I}=w;return{type:H,toolUseID:M,run:W,userInput:I}}else if(w.type==="thinking"){let{type:H,thinking:M}=w;return{type:H,thinking:M}}else if(w.type==="redacted_thinking"){let{type:H,data:M}=w;return{type:H,data:M}}else if(w.type==="tool_use"){let{type:H,id:M,name:W,input:I}=w,N={type:H,id:M,name:W};if(I!==void 0)N.input=I;return N}else if(w.type==="server_tool_use"){let{type:H,id:M,name:W,input:I}=w;return{type:H,id:M,name:W,input:I}}else if(w.type==="web_search_tool_result"){let{type:H,content:M}=w;return{type:H,content:M}}else if(w.type==="summary"){let{type:H,summary:M}=w;return{type:H,summary:M}}return w})},q=(E)=>{switch(E.status){case"blocked-on-user":case"rejected-by-user":return{status:E.status,toAllow:E.toAllow};case"error":return{status:"error",error:typeof E.error==="object"&&"message"in E.error?E.error:{message:String(E.error)}};case"cancelled":case"in-progress":return{status:E.status,progress:E.progress};case"done":return{status:"done",progress:E.progress,result:E.result,files:E.files};default:return{status:E.status}}},Y=[],F=[];for(let E of K.blocks)if(E.type==="message"){let[w,H]=E.data;if(H.role==="user"){let{role:M,content:W,meta:I}=H,N={role:M,content:G(W),meta:I};Y.push([w,N])}else if(H.role==="assistant"){let{role:M,content:W,state:I}=H,N={role:M,content:G(W),state:I};Y.push([w,N])}else if(H.role==="info"){let{role:M,content:W}=H,I={role:M,content:G(W)};Y.push([w,I])}else Y.push([w,H])}else if(E.type==="toolResult"){let[w,H]=E.data;if(w.input&&H.run!==void 0){let M={type:w.type,id:w.id,name:w.name,input:{}},W={type:H.type,toolUseID:H.toolUseID,run:q(D5(H.run))};F.push([M,W])}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 ${_E}: {"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"})}}),UA.from(Z)}}y2();AK();y2();import{exec as Sf}from"node:child_process";function vf(A="idle"){try{if(A==="idle"){if(process.platform==="darwin")Sf("afplay /System/Library/Sounds/Submarine.aiff");else if(process.platform==="win32")Sf("powershell [console]::beep(800,200)");else if(process.platform==="linux")Sf("paplay /usr/share/sounds/freedesktop/stereo/message.oga || beep")}else if(A==="requires-user-input"){if(process.platform==="darwin")Sf("afplay /System/Library/Sounds/Ping.aiff");else if(process.platform==="win32")Sf("powershell [console]::beep(1000,300)");else if(process.platform==="linux")Sf("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)}}Y2();y2();import{mkdir as E4A,readFile as w4A,writeFile as df1,open as Is6}from"node:fs/promises";import{homedir as Ns6}from"node:os";import Wd from"node:path";var Cs6=Wd.join(wf||Wd.join(Ns6(),".local/share"),"amp"),Vs6=Wd.join(Cs6,"history.jsonl"),Os6=1000;class Id{history=[];index=-1;loaded=!1;historyFile;maxSize;constructor(A){this.historyFile=A?.historyFile||Vs6,this.maxSize=A?.maxSize||Os6,this.ensureLoaded()}async ensureLoaded(){if(!this.loaded)this.history=await this.readHistoryFromDisk(),this.loaded=!0}async readHistoryFromDisk(){try{let A=await w4A(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 w4A(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(`
|
7356
7356
|
`),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 E4A(Wd.dirname(this.historyFile),{recursive:!0});let Q=A.map((B)=>JSON.stringify(B)).join(`
|
7357
7357
|
`)+`
|
@@ -7479,7 +7479,7 @@ Read about how to prevent this error on https://github.com/vadimdemedes/ink/#isr
|
|
7479
7479
|
`),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(`
|
7480
7480
|
`),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=KQA(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=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("")})}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("")+`
|
7481
7481
|
`+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:M.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 Q12(A,Q){let B=A.split(`
|
7482
|
-
`),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var h71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=h71.useState(0);if(iM((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)}),h71.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 B12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var YQA=10;function J12({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=gd(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 D12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=z12(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 z12(A){if(A.name===s4){let Q=A.input;return"Run "+ml.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return ml.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function Z12(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 X12({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 UQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function FQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=sf(),[K]=s3.useState(()=>new C8);s3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=s3.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};s3.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),Aj().then(()=>{z.exit()});break;case"idle":if(D)vf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=UQA(N),_=Ri({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(W.toolUse.name===FQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)vf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:W.title}));break}default:y1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await B12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};s3.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},YQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),iM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},YQA);else if(W.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let M=UQA(G.messages);return fA(XQA,{threadName:G.threadTitle,messages:M,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(v71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(K12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(J12,{messages:G.messages,agentState:G.agentState}),fA(r7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(DQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:D12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:Z12(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(X12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(qQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.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(q12,{lspState:G.lspState}),G.tokenUsage&&fA(G12,{tokenUsage:G.tokenUsage})]})]})]})]})}function K12({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=gd(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=x71(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 G12({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 q12({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 EQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(FQA,{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"})}),UA.from(B)}}var My1=Hy1.join(XAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function Wy1(A){try{await U12(Hy1.dirname(My1),{recursive:!0}),await E12(My1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function m71(){try{return(await F12(My1,"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 ${_E})`},{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 H12(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 oZ(eG.unknownCommand(B),1,Z)}}class HQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=YD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function o3(A,Q){Ed({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751535324-g810c0e");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=dl(),D=fv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=rB1({storage:D,secretStorage:J,workspaceRoots:UA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new HQA,K=fq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await J2(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"]??[];vP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new W51,await E.start();try{await T9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=j9A(E,process.cwd())}else E=new class extends W51{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...
|
7482
|
+
`),J=[],D=0;for(let z of B){let Z=g6.default(z);if(Z.length<=Q)J.push({type:"start",content:z,originalLine:D,start:0,end:Z.length});else{let X=z.match(/\S+| +/g)||[""],K="",G=0,q=0,Y=!0;for(let F of X){let E=/^ +$/.test(F),w=g6.default(F).length;if(g6.default(K).length+w<=Q)K+=F;else{if(K){let H=K.replace(/ +$/,""),M=g6.default(K),W=g6.default(H);J.push({type:Y?"start":"continuation",content:H,originalLine:D,start:G,end:G+W.length}),q=G+M.length,Y=!1}if(E){q+=w,G=q,K="";continue}if(G=q,w>Q){let H=g6.default(F);for(let M=0;M<H.length;M+=Q){let W=H.slice(M,M+Q).join("");J.push({type:Y?"start":"continuation",content:W,originalLine:D,start:G+M,end:G+M+g6.default(W).length}),Y=!1}q+=w,G=q,K=""}else K=F}if(!E||g6.default(K).length>0)q+=w}if(K){let F=g6.default(K);J.push({type:Y?"start":"continuation",content:K,originalLine:D,start:G,end:G+F.length})}}D++}return J}var h71=G6(z4(),1);function Ey1({options:A,onSelect:Q,title:B}){let[J,D]=h71.useState(0);if(iM((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)}),h71.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 B12(A,Q){try{return await A.query(Q)}catch(B){return y1.error("Completion failed",B),[]}}var YQA=10;function J12({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=gd(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 D12(A,Q){let B;switch(A.type){case"tool-use":{if(A.tools.length===1){let J=A.tools[0];if(J?.useBlock)B=z12(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 z12(A){if(A.name===s4){let Q=A.input;return"Run "+ml.print(Q.cmd,{foreground:"green",style:"bold"})+`${Q.cwd?` in ${Q.cwd}`:""}?`}else return ml.print(`Invoke tool ${A.name} with args ${JSON.stringify(A.input)}?`,{foreground:"yellow"})}function Z12(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 X12({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 UQA(A){return A.filter((Q)=>Q.type==="message").map((Q)=>Q.data[1])}function FQA({outputs:A,inputs:Q,history:B,fuzzyServer:J,useNotifications:D}){let z=zy1(),[Z,X]=sf(),[K]=s3.useState(()=>new C8);s3.useEffect(()=>{return()=>{K.complete()}},[K]);let[G,q]=s3.useState({type:"running",agentState:{type:"idle"},tokenUsage:null,lspState:null,todos:[],showCancelled:!1,rerendering:!1,confirmationQueue:[],currentConfirmation:void 0,totalConfirmations:0,threadTitle:"Untitled",messages:[],activeTools:new Map,subagents:new Map,completions:[],selectedCompletionIndex:0,currentMention:void 0}),Y=(M)=>{q((W)=>{if(W.type!=="confirming"||!W.currentConfirmation)return W;let I=W.currentConfirmation,N=W.confirmationQueue.slice(1),V=M===null?"no":M;if(I.type==="tool-use")for(let{useBlock:T,toAllow:R}of I.tools){let j=V==="yes"||V==="always",P=V==="always"&&R?R:[];Q.next({type:"confirmation",allow:j,confirmation:{type:"tool-use",toolUseID:T.id,addToAllowList:P,subthreadID:I.subthreadID}})}else{let T=V==="yes";Q.next({type:"confirmation",allow:T,confirmation:{type:I.type}})}let _=N[0];if(_)return{...W,type:"confirming",currentConfirmation:_,confirmationQueue:N};else return{...W,type:"running",currentConfirmation:void 0,confirmationQueue:N,totalConfirmations:0}})};s3.useEffect(()=>{let M=A.subscribe((W)=>{switch(W.type){case"state":{switch(W.state.type){case"shutting-down":q({...G,type:"exiting"}),Aj().then(()=>{z.exit()});break;case"idle":if(D)vf("idle");q((I)=>({...I,agentState:W.state}));break;default:q((I)=>({...I,agentState:W.state}));break}break}case"messages":{q((I)=>{let N=[...I.messages,...W.blocks],V=UQA(N),_=Ri({messages:V});return{...I,messages:N,todos:Array.isArray(_)?_:[],showCancelled:!1}});break}case"token-usage":{q((I)=>({...I,tokenUsage:W.tokenUsage}));break}case"lsp-status":{q((I)=>({...I,lspState:W.lspState}));break}case"cancelled":{q((I)=>({...I,showCancelled:!0,activeTools:new Map,subagents:new Map}));break}case"tool-status":{q((I)=>{let N=new Map(I.activeTools);if(W.toolUse.name===FQ)return{...I,activeTools:N};if(W.status==="completed"||W.status==="error"||W.status==="cancelled")N.delete(W.toolUse.id);else{let V=W.subthreadID;N.set(W.toolUse.id,{toolUse:W.toolUse,status:W.status,startTime:W.startTime,endTime:W.endTime,subthreadID:V})}return{...I,activeTools:N}});break}case"subthread-messages":break;case"subagent-started":{q((I)=>({...I,subagents:new Map(I.subagents).set(W.subThreadID,{subThreadID:W.subThreadID,agentNumber:W.agentNumber,taskDescription:W.taskDescription,status:"running",startTime:Date.now()})}));break}case"subagent-finished":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-cancelled":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-error":{q((I)=>{let N=new Map(I.subagents);return N.delete(W.subThreadID),{...I,subagents:N}});break}case"subagent-status":{q((I)=>{let N=new Map(I.subagents),V=N.get(W.subThreadID);if(V)N.set(W.subThreadID,{...V,agentState:W.agentState});return{...I,subagents:N}});break}case"confirm":{if(D)vf("requires-user-input");q((I)=>{let N=[...I.confirmationQueue,W.confirmation];if(I.type==="running"&&N.length===1)return{...I,type:"confirming",currentConfirmation:W.confirmation,confirmationQueue:N,totalConfirmations:N.length};else return{...I,confirmationQueue:N,totalConfirmations:Math.max(I.totalConfirmations,N.length)}});break}case"thread-title":{q((I)=>({...I,threadTitle:W.title}));break}default:y1.info("unhandled ui output",W);break}});return()=>{M.unsubscribe()}},[A,z]);let F=async(M,W)=>{let I=await B12(J,M);q((N)=>({...N,completions:I,selectedCompletionIndex:0,currentMention:W}))},E=()=>{q((M)=>({...M,completions:[],selectedCompletionIndex:0,currentMention:void 0}))},w=(M)=>{if(M!==null)K.next(M),q((W)=>({...W,completions:[],selectedCompletionIndex:0,currentMention:void 0}));else E()};s3.useEffect(()=>{let M=null,W=()=>{q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),M=setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},YQA)};return process.stdout.on("resize",W),()=>{if(M)clearTimeout(M);process.stdout.off("resize",W)}},[]),iM((M,W)=>{if(G.type==="expanded-view")return;if(G.type==="confirming")return;if(W.escape)Q.next({type:"interrupt"});else if(W.ctrl&&M.toLowerCase()==="r")q({...G,type:"expanded-view"});else if(W.ctrlL)q((I)=>({...I,rerendering:!0})),process.stdout.write("\x1B[2J"),process.stdout.write("\x1B[3J"),process.stdout.write("\x1B[H"),setTimeout(()=>{q((I)=>({...I,rerendering:!1}))},YQA);else if(W.ctrlC)if(G.type==="confirming-exit")Q.next({type:"exit"});else q({...G,type:"confirming-exit"}),setTimeout(()=>{q({...G,type:"running"})},1000)});let H=Z>100;if(G.type==="expanded-view"){let M=UQA(G.messages);return fA(XQA,{threadName:G.threadTitle,messages:M,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(v71,{items:G.messages,children:(M,W)=>fA(y6,{children:fA(K12,{block:M,marginTop:W===0?0:1},W)},W)}),G.showCancelled&&fA(y6,{marginTop:1,children:fA(h6,{color:"gray",children:"Cancelled"})}),G.type!=="exiting"&&T9(y6,{flexDirection:"column",marginTop:1,children:[fA(J12,{messages:G.messages,agentState:G.agentState}),fA(r7A,{agentState:G.agentState,activeTools:G.activeTools,subagents:G.subagents}),fA(DQA,{activeTools:G.activeTools,subagents:G.subagents,messages:G.messages}),G.type==="confirming"&&G.currentConfirmation&&fA(y6,{marginBottom:1,children:fA(Ey1,{title:D12(G.currentConfirmation,{current:G.totalConfirmations-G.confirmationQueue.length,total:G.totalConfirmations}),options:Z12(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(X12,{todos:G.todos})}),fA(y6,{flexGrow:1,borderStyle:"round",paddingX:1,children:fA(qQA,{onSubmit:(M)=>{Q.next({type:"message",message:M})},history:B,disabled:G.type==="confirming",onCompletionRequest:F,onCompletionCancel:E,selectedCompletions:K})})]}),G.completions.length>0&&(()=>{let M=Math.min(10,Math.max(3,Math.floor(X*0.4))),W=G.completions.slice(0,M);return fA(y6,{marginBottom:1,children:fA(Ey1,{title:`File mentions (${W.length}${G.completions.length>M?`/${G.completions.length}`:""})`,options:W.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(q12,{lspState:G.lspState}),G.tokenUsage&&fA(G12,{tokenUsage:G.tokenUsage})]})]})]})]})}function K12({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=gd(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=x71(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 G12({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 q12({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 EQA(A){return JA.level=1,(Q)=>{let B=new C8;return Dy1(wy1.default.createElement(FQA,{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"})}),UA.from(B)}}var My1=Hy1.join(XAA||Hy1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");async function Wy1(A){try{await U12(Hy1.dirname(My1),{recursive:!0}),await E12(My1,A,"utf-8")}catch(Q){y1.debug("Failed to save last thread ID",Q)}}async function m71(){try{return(await F12(My1,"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 ${_E})`},{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 H12(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 oZ(eG.unknownCommand(B),1,Z)}}class HQA{async environment(){let A=process.cwd(),Q=j8.file(A),B=YD1(null),J=await Hn1(Q,B,{workingDirectory:Q});return{workspacePaths:[A],workingDirectory:A,rootDirectoryListing:J}}}async function o3(A,Q){Ed({logLevel:Q.logLevel||process.env.AMP_LOG_LEVEL,logFile:Q.logFile||process.env.AMP_LOG_FILE}),um1("0.0.1751537861-gbec607");let B=Q.settingsFile??process.env.AMP_SETTINGS_FILE;y1.info("Using settings file",{settingsFile:B});let J=dl(),D=fv1({settingsFile:B}),z=process.env.AMP_API_KEY;if(z)await J.set("apiKey",z,A.ampURL);let Z=rB1({storage:D,secretStorage:J,workspaceRoots:UA.of([j8.file(process.cwd())]),defaultAmpURL:A.ampURL}),X=new HQA,K=fq(),G=fl1({configService:Z,toolService:K});try{await G.initialized}catch(_){y1.warn("Failed to wait for MCP servers, continuing anyway:",_)}let q=await J2(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"]??[];vP1(K,!1,Y,F);let E,w;if(A.isInteractiveMode){E=new W51,await E.start();try{await T9A(E,process.cwd())}catch(_){y1.error("Failed to index files for fuzzy completion",_)}w=j9A(E,process.cwd())}else E=new class extends W51{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...
|
7483
7483
|
`),!await M12(A,J))process.exit(1)}let H=cl1(),M=new EG1(H),W=new FG1(H),I=new fF1(M),N=new lf1({configService:Z,threadService:M,toolService:K,systemPromptService:X,threadSummaryService:I,threadHistoryService:W,mcpService:G}),V=void 0;return y1.info("Starting Amp background services"),V=Cn1({threadService:M,threadHistoryService:W,isExtensionDevelopment:!1}),{configService:Z,systemPromptService:X,toolService:K,mcpService:G,threadService:M,threadHistoryService:W,summaryService:I,threadSyncService:V,threadStorage:H,secretStorage:J,settingsStorage:D,fileWatcher:w,fuzzyServer:E,subthreadTracker:N}}async function M12(A,Q){if(A.isInteractiveMode){if(await vE("Would you like to log in to Amp?",["(y)es","(n)o"])!="y")return Z7.write(`Login cancelled. Run the command again to retry.
|
7484
7484
|
`),!1}return await MQA(A,Q)}async function MQA(A,Q){let B=Y12(32).toString("hex"),J=await s9A(A.ampURL,B);Z7.write(`If your browser doesn't open automatically, visit:
|
7485
7485
|
|
@@ -7494,8 +7494,8 @@ ${A.printer.print(J,{foreground:"blue",style:"bold"})}
|
|
7494
7494
|
Login successful! You can now use the Amp CLI.
|
7495
7495
|
`),!0}catch(D){return L8.write(`
|
7496
7496
|
Login failed: ${D instanceof Error?D.message:String(D)}
|
7497
|
-
`),!1}}var W12=new Set(["fuzzy-server"]);function I12(A){let Q=new b41().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)PC(),process.exit(0);let X=Z.originalError??Z;Ef(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.
|
7498
|
-
`);else Z7.write(`0.0.
|
7497
|
+
`),!1}}var W12=new Set(["fuzzy-server"]);function I12(A){let Q=new b41().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)PC(),process.exit(0);let X=Z.originalError??Z;Ef(A,X)}),Q.option("-V, --version","output the version number",()=>{if(A.isTTY)Z7.write(`0.0.1751537861-gbec607 ${A.printer.print("(released 2025-07-03T10:24:39.072Z)",{foreground:"gray"})}
|
7498
|
+
`);else Z7.write(`0.0.1751537861-gbec607 (released 2025-07-03T10:24:39.072Z)
|
7499
7499
|
`);process.exit(0)}),Q.addHelpText("after",(()=>{let Z="";Z+=A.printer.print("Environment variables:",{style:"bold"})+`
|
7500
7500
|
|
7501
7501
|
`,Z+=" "+A.printer.print("AMP_API_KEY",{foreground:"green"})+` API key for Amp (see https://ampcode.com/settings)
|
package/package.json
CHANGED