@sourcegraph/amp 0.0.1777875280-g2566d7 → 0.0.1777879744-g2d678a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4563,7 +4563,7 @@ ${$}`}function st(A){let Q=A.lastIndexOf("/");return Q===-1?A:A.slice(Q+1)}funct
4563
4563
  ${Q.join(`
4564
4564
  `)}`:void 0}}function Gp5(A){let Q=[],B=new Set,$=A.split(`
4565
4565
  `);for(let J=0;J<$.length;J++){let Z=$[J].match(/^\*\*\* (?:Add|Delete|Update) File: (.+)$/);if(!Z)continue;let X=Z[1],F=$[J+1]?.match(/^\*\*\* Move to: (.+)$/);if(F)X=F[1];if(B.has(X))continue;B.add(X),Q.push(X)}return Q}function o2(A){if(A.status!=="error"||!A.error)return;if(typeof A.error==="object"&&"message"in A.error){let Q=A.error.message;if(typeof Q==="string"&&Q.trim())return Q}return String(A.error)}function Vp5(A,Q){if(A==="find_thread"){let B=typeof Q.query==="string"?Q.query.trim():void 0;return{kind:"search",title:B?`Searched threads: ${B}`:"Searched threads",icon:"search"}}if(A==="read_thread"){let B=typeof Q.threadID==="string"?Q.threadID.trim():void 0,$=typeof Q.goal==="string"?Q.goal.trim():void 0;return{kind:"thread",title:$?`Read thread: ${$}`:B?`Read thread ${B}`:"Read thread",icon:"threads"}}if(A==="slack_read"){let B=typeof Q.type==="string"?Q.type:void 0,$=typeof Q.query==="string"?Q.query.trim():void 0,J=$?`: ${$}`:"";if(B==="users")return{kind:"search",title:`Slack searched users${J}`,icon:"slack"};if(B==="channels")return{kind:"search",title:`Slack searched channels${J}`,icon:"slack"};if(B==="messages")return{kind:"read",title:`Slack read messages${J}`,icon:"slack"};if(B==="thread")return{kind:"read",title:"Slack read thread",icon:"slack"};return{kind:"read",title:$?`Slack read: ${$}`:"Slack read",icon:"slack"}}if(A==="docs_list"){let B=uG(Q);return{kind:"list",title:B?`Listed docs: ${B}`:"Listed docs",icon:"docs"}}if(A==="docs_read"){let B=uG(Q);return{kind:"read",title:B?`Read docs: ${B}`:"Read docs",icon:"docs"}}if(A==="github_repo_ci_status"){let B=uG(Q);return{kind:"read",title:B?`Read CI status: ${B}`:"Read CI status",icon:"github"}}if(A==="web_search"){let B=uG(Q);return{kind:"search",title:B?`Searched web: ${B}`:"Searched web",icon:"web"}}if(A==="read_web_page"){let B=uG(Q);return{kind:"web-page",title:B?`Read web page: ${B}`:"Read web page",icon:"web"}}if(A==="search_github"||A==="commit_search"||A==="glob_github"){let B=uG(Q);return{kind:"search",title:B?`Searched GitHub: ${B}`:"Searched GitHub",icon:"github"}}if(A==="list_directory_github"||A==="list_repositories"){let B=uG(Q);return{kind:"list",title:B?`Listed GitHub content: ${B}`:"Listed GitHub content",icon:"github"}}if(A==="read_github"||A==="diff"){let B=uG(Q);return{kind:"read",title:B?`Read GitHub content: ${B}`:"Read GitHub content",icon:"github"}}return}function SU0(A,Q){if(A==="Read"){let J=Up5(Q);if(J)return J}if(A==="read_thread"){let J=typeof Q.goal==="string"?Q.goal.trim():void 0;if(J)return`Read thread: ${J}`;let Y=typeof Q.threadID==="string"?Q.threadID.trim():void 0;return Y?`Read thread ${Y}`:"Read thread"}if(A==="find_thread"){let J=typeof Q.query==="string"?Q.query.trim():void 0;return J?`Searched threads: ${J}`:"Searched threads"}if(A==="skill")return`Read skill ${Q.name}`;if(A==="file_tree")return Kp5(Q);if(A==="web_search"){let J=io4(Q);return J?`Web Search ${J}`:"Web Search"}if(A==="read_web_page"){let J=lo4(Q);return J?`Read ${J}`:"Read"}if(A.toLowerCase()==="Grep".toLowerCase())return Hp5(Q);let B=uG(Q);if(!B)return A;let $=B.includes("/")?vY(B):B;return`${A} ${$}`}function Up5(A){let Q=typeof A.path==="string"?A.path.trim():void 0,B=Ep5(A.read_range);if(!Q)return B?`Read ${B}`:void 0;let $=vY(Q);return B?`Read ${$} ${B}`:`Read ${$}`}function Kp5(A){let Q=typeof A.path==="string"?A.path.trim():void 0;if(!Q)return"List";let B=Q==="/"?Q:Q.replace(/\/+$/,"");return`List ${B.includes("/")?vY(B)||B:B}`}function Ep5(A){if(!Array.isArray(A)||A.length!==2)return;let[Q,B]=A;if(typeof Q!=="number"||typeof B!=="number"||!Number.isInteger(Q)||!Number.isInteger(B))return;if(Q<1||B===-1||B<Q)return;if(Q===B)return`L${Q}`;return`L${Q}-${B}`}function Hp5(A){let Q=A.path?.trim(),B=A.pattern?.trim();if(Q&&B)return`Grep ${Q} "${B}"`;if(B)return`Grep "${B}"`;if(Q)return`Grep ${Q}`;return"Grep"}function uG(A){for(let Q of["path","filePattern","pattern","query","url","objective","description","prompt"])if(typeof A[Q]==="string"&&A[Q].trim())return A[Q].trim();return}function lo4(A){if(typeof A.url!=="string")return;return A.url.trim()||void 0}function io4(A){let Q=typeof A.query==="string"?A.query:void 0,B=typeof A.objective==="string"?A.objective:void 0;return(Q??B)?.trim()||void 0}function Wp5(A){let Q=A.replace(/\/+$/,""),B=Q.lastIndexOf("/");return(B===-1?Q:Q.slice(B+1)).replace(/\.md$/i,"")||A}function zp5(A,Q){let B=iJ(Q.result)?Q.result:void 0,$=iJ(B?.check)?B.check:void 0;return typeof $?.name==="string"?$.name:Wp5(A)}function qp5(A){if(A.status!=="done")return;let Q=iJ(A.result)?A.result:void 0;return Array.isArray(Q?.issues)?Q.issues.length:void 0}function Np5(A){let Q=Object.entries(A).filter(([,B])=>B!==void 0&&B!==null&&B!=="");if(Q.length===0)return;return Q.map(([B,$])=>{let J=typeof $==="string"?$:JSON.stringify($);return`${B}: ${J}`}).join(`
4566
- `)}function Oo4(A){return A==="in-progress"||A==="queued"}function jo4(A,Q){let B=[...A],$=new Set(B.map((J)=>`${J.kind}:${J.title}`));for(let J of no4(Q)){let Y=`${J.kind}:${J.title}`;if($.has(Y))continue;$.add(Y),B.push(J)}return B}function no4(A){return Ip5(A).map((Q)=>({kind:"read",title:`Read ${OJ(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function Ip5(A){if(A.status!=="done"||!iJ(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap((B)=>{if(!iJ(B)||typeof B.uri!=="string"||typeof B.lineCount!=="number"||!Number.isFinite(B.lineCount))return[];return[{uri:B.uri,lineCount:B.lineCount,...typeof B.content==="string"?{content:B.content}:{}}]})}function wp5(A){let Q="result"in A&&iJ(A.result)?A.result:void 0,B=go4("progress"in A?A.progress:void 0),$=iJ(B)?B:void 0;return{main:(iJ(Q?.main)?Q.main:void 0)??(iJ($?.main)?$.main:void 0),checks:(iJ(Q?.checks)?Q.checks:void 0)??(iJ($?.checks)?$.checks:void 0)}}function Cp5(A,Q){let B=[],$=new Set,J=(G)=>{let V=`${G.kind}:${G.title}`;if($.has(V))return;$.add(V),B.push(G)},{main:Y,checks:Z}=wp5(A);if(A.status==="queued")J({kind:"explore",title:"Code review queued"});if(A.status==="error"){let G=o2(A)??"Unknown error";J({kind:"explore",title:`Code review failed: ${G}`})}let X=0,F=0;for(let[G,V]of Object.entries(Z??{})){if(!iJ(V))continue;F+=1;let U=zp5(G,V);if(V.status==="done"){X+=1;let K=qp5(V);if(K===void 0)J({kind:"explore",title:`Check ${U}: complete`});else if(K===0)J({kind:"explore",title:`Check ${U}: ok`});else J({kind:"explore",title:`Check ${U}: ${K} ${W4(K,"issue")} found`});continue}if(V.status==="error"){X+=1;let K=typeof V.error==="string"&&V.error.trim()?V.error.trim():"Unknown error";J({kind:"explore",title:`Check ${U}: error (${K})`});continue}if(V.status==="in-progress"){let K=typeof V.message==="string"&&V.message.trim()?V.message.trim():"Running check...";J({kind:"explore",title:`Check ${U}: ${K}`})}}if(Y?.status==="done"&&F>0&&X<F)J({kind:"explore",title:"Main review complete, running checks..."});if(A.status==="done")J({kind:"explore",title:"Code review complete"});if(B.length===0)J({kind:"explore",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let D=Q.thinking==="low"?"quick code review":"code review";return{actions:B,summary:F>0?`${X}/${F} checks · ${D}`:D}}function Ro4(A,Q=""){let B=0,$=0,J=new Map;for(let Z of A){if(Z.icon==="docs"&&(Z.title.startsWith("Read ")||Z.title.startsWith("Load "))){B++;continue}if(Z.title.startsWith("Read skill ")){$++;continue}J.set(Z.kind,(J.get(Z.kind)??0)+1)}let Y=[];for(let[Z,X,F]of[["read","file",void 0],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["explore","exploration",void 0],["list","list",void 0]]){let D=Z==="guidance"?B:Z==="skill"?$:J.get(Z);if(!D)continue;Y.push(`${D} ${W4(D,X,F)}`)}if(Y.length>0)return Y.join(", ");return Q}function Mp5(A){if(A.kind==="search"&&Lp5(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return VD0(A)}function Lp5(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function iJ(A){return typeof A==="object"&&A!==null}class kU0{originalGuidanceFiles=new Map;toolOrder=new Map;nextToolOrder=0;firstToolForGuidanceFile=new Map;recordToolOrder(A){if(!this.toolOrder.has(A))this.toolOrder.set(A,++this.nextToolOrder)}applyToolResult(A,Q){let B=this.originalGuidanceFiles.get(A)??[],$=new Set(Q.map((X)=>X.uri)),J=new Set;for(let X of B){if($.has(X.uri))continue;if(this.firstToolForGuidanceFile.get(X.uri)!==A)continue;this.firstToolForGuidanceFile.delete(X.uri);let F=this.findEarlierToolListing(X.uri,A);if(F!==void 0)this.firstToolForGuidanceFile.set(X.uri,F),J.add(F)}if(Q.length>0)this.originalGuidanceFiles.set(A,Q);else this.originalGuidanceFiles.delete(A);let Y=this.toolOrder.get(A)??Number.POSITIVE_INFINITY,Z=[];for(let X of Q){let F=this.firstToolForGuidanceFile.get(X.uri);if(F===void 0||F===A){this.firstToolForGuidanceFile.set(X.uri,A),Z.push(X);continue}let D=this.toolOrder.get(F)??Number.POSITIVE_INFINITY;if(Y<D)this.firstToolForGuidanceFile.set(X.uri,A),J.add(F),Z.push(X)}return J.delete(A),{myDedupedFiles:Z,needsRebuild:J}}dedupedFilesFor(A){return(this.originalGuidanceFiles.get(A)??[]).filter((B)=>this.firstToolForGuidanceFile.get(B.uri)===A)}cleanupRemovedTools(A){for(let Q of this.toolOrder.keys())if(!A.has(Q))this.toolOrder.delete(Q);return this.cleanupRemovedToolResults(A)}cleanupRemovedToolResults(A){for(let $ of this.originalGuidanceFiles.keys())if(!A.has($))this.originalGuidanceFiles.delete($);let Q=[];for(let[$,J]of this.firstToolForGuidanceFile)if(!A.has(J))Q.push($);let B=new Set;for(let $ of Q){this.firstToolForGuidanceFile.delete($);let J=this.findEarlierToolListing($,void 0);if(J!==void 0)this.firstToolForGuidanceFile.set($,J),B.add(J)}return B}findEarlierToolListing(A,Q){let B=Number.POSITIVE_INFINITY,$;for(let[J,Y]of this.originalGuidanceFiles){if(J===Q)continue;if(!Y.some((X)=>X.uri===A))continue;let Z=this.toolOrder.get(J)??Number.POSITIVE_INFINITY;if(Z<B)B=Z,$=J}return $}}g5();YQ();function v51(A){let Q=A.replace(/-/g,"");if(Q.length!==32)throw Error(`Invalid UUID hex length: ${Q.length}`);let B=BigInt("0x"+Q),$="";while(B>0n)$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(B%62n)]+$,B=B/62n;return $.padStart(22,"0")}F8();by();H4();If0();YQ();var O8=k.string().min(1),bw=O8.brand(),x51=k.string().regex(/^[0-9A-Za-z]{22}$/),Op5=k.templateLiteral([k.string().regex(/^[0-9a-f]{8}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{12}$/)]),tt=k.templateLiteral(["T-",Op5]),jp5=k.enum(["fork","handoff","mention"]),Rp5=k.enum(["parent","child"]),ao4=k.object({threadID:tt,type:jp5,role:Rp5,messageIndex:k.number().int().nonnegative().optional(),blockIndex:k.number().int().nonnegative().optional(),createdAt:k.number().int().nonnegative(),comment:k.string().optional()}),Z5=k.templateLiteral(["M-",x51]);function vU0(){return`M-${v51(Yv())}`}var S3=k.templateLiteral(["TU-",x51]);var oo4=k.templateLiteral(["E-",x51]);function ro4(){return`E-${v51(Yv())}`}var Pp5=k.looseObject({type:k.literal("object"),properties:k.record(k.string(),k.unknown()),required:k.array(k.string()).optional(),additionalProperties:k.boolean().optional()}),_p5=k.union([k.literal("builtin"),k.object({toolbox:O8}).strict(),k.object({mcp:O8,target:k.enum(["global","workspace","flag","default"]).optional()}).strict(),k.object({plugin:O8}).strict(),k.object({remote:O8}).strict()]),Tp5=k.object({serial:k.boolean().optional(),deferred:k.boolean().optional(),skillNames:k.array(O8).optional()}),so4=k.looseObject({name:O8,description:k.string(),inputSchema:Pp5,source:_p5,meta:Tp5.optional()}),as3=k.object({id:O8,category:O8,title:O8,description:k.string().optional(),pluginName:O8}),yU0=k.strictObject({"agent.skipTitleGenerationIfMessageContains":k.array(k.string()).optional(),"anthropic.thinking.enabled":k.boolean().optional(),"anthropic.interleavedThinking.enabled":k.boolean().optional(),"anthropic.temperature":k.number().optional(),"anthropic.speed":k.enum(["standard","fast"]).optional(),"anthropic.provider":k.enum(["anthropic","vertex"]).optional(),"openai.speed":k.enum(["standard","fast"]).optional(),"painter.model":k.enum(["gemini-3-pro-image","gpt-image-2"]).optional(),"reasoning.effort":k.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),"internal.compactionThresholdPercent":k.number().min(0).max(100).optional(),"internal.model":k.union([k.string(),k.record(k.string(),k.string())]).optional(),"internal.oracleReasoningEffort":k.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":k.enum(["minimal","low","medium","high"]).optional(),"tools.disable":k.array(k.string()).optional(),"tools.enable":k.array(k.string()).optional()}),to4=k.object({workspaceId:k.string(),workingDirectory:k.string(),environment:k.object({os:k.enum(["darwin","linux","windows"]),hasDocker:k.boolean().optional(),hasBrowser:k.boolean().optional()}).strict(),tags:k.array(k.string())}).strict(),eo4=k.enum(["sandbox","local-client"]),et=k.any().and(k.object({status:k.string()})),Ar4=k.discriminatedUnion("type",[k.object({type:k.literal("delta"),blocks:k.array(k.unknown()).optional(),state:k.enum(["start","generating","tool_use","complete","error","aborted"])}),k.object({type:k.literal("snapshot"),value:k.unknown()})]),gK=O8,Qr4=30000,Ju=ND,Sp5=k.enum(["file","directory"]),kp5=k.object({mtimeMs:k.number().nonnegative().optional()}),Ae=k.tuple([k.string(),Sp5,kp5.nullish()]),vp5=k.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),uw=k.object({code:vp5,message:k.string()}),yp5=k.object({ok:k.literal(!0),entries:k.array(Ae)}),xp5=k.object({ok:k.literal(!1),error:uw}),os3=k.discriminatedUnion("ok",[yp5,xp5]),fp5=k.object({ok:k.literal(!0),contentBase64:k.string()}),bp5=k.object({ok:k.literal(!1),error:uw}),rs3=k.discriminatedUnion("ok",[fp5,bp5]),up5=O8,f51=k.object({key:O8,dataType:up5,contentBase64:k.string()}),b51=f51.extend({toolCallId:S3.optional(),updatedAt:k.string()}),u51=k.looseObject({uri:ND,content:k.string().optional(),lineCount:k.int().optional(),hash:k.string().optional()}),hp5=k.enum(HU4),Br4=k.object({path:ND,error:k.string(),hint:k.string().optional()}),$r4=k.object({uri:ND,hash:k.string(),lineCount:k.int().optional()}),Jr4=k.object({name:O8,description:k.string(),baseDir:ND,frontmatter:k.object({name:O8,description:k.string()}).catchall(k.unknown()),files:k.array(k.string()).optional(),source:hp5.optional()}),h51=k.object({type:k.literal("text"),text:k.string(),hidden:k.boolean().optional()}),Yr4=k.looseObject({type:k.literal("image"),source:k.discriminatedUnion("type",[k.object({type:k.literal("base64"),mediaType:k.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:k.string()}),k.object({type:k.literal("url"),url:k.string()})]),sourcePath:k.string()}),Qe=k.array(k.discriminatedUnion("type",[h51,Yr4])),$u=k.record(k.string(),k.unknown()),Zr4=k.object({type:k.literal("tool_use"),id:k.string().min(1),name:k.string().min(1),normalizedName:k.string().optional(),metadata:k.record(k.string(),k.unknown()).optional()}),gp5=Zr4.extend({complete:k.literal(!0),input:$u,normalizedInput:$u.optional()}),mp5=Zr4.extend({complete:k.literal(!1),input:$u,inputIncomplete:$u,inputPartialJSON:k.object({json:k.string()}),normalizedInput:$u.optional()}),pp5=k.object({accepted:k.boolean(),askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}),dp5=k.object({type:k.literal("tool_result"),toolUseID:k.string().min(1),run:et,userInput:pp5.optional()}),cp5=k.object({type:k.literal("thinking"),thinking:k.string(),signature:k.string()}),lp5=k.object({type:k.literal("redacted_thinking"),data:k.string()}),ip5=k.object({type:k.literal("server_tool_use"),id:k.string().min(1),name:k.string().min(1),input:$u}),np5=k.object({type:k.literal("manual_bash_invocation"),args:k.object({cmd:k.string(),args:k.array(k.string()).readonly().optional(),cwd:k.string().optional()}),toolRun:et,hidden:k.boolean().optional()}),g51=k.object({sentAt:k.number().int().nonnegative().optional(),fromAggman:k.boolean().optional(),fromExecutorThreadID:tt.optional()}),ap5=k.union([h51,Yr4,dp5]),op5=k.union([h51,cp5,lp5,gp5,mp5,ip5]),m51=k.array(ap5),p51=k.array(op5),rp5=k.array(np5),y51=k.looseObject({line:k.number().int(),column:k.number().int()}),sp5=k.looseObject({start:y51,end:y51}),tp5=k.looseObject({name:k.string(),repositoryURL:k.string()}),ep5=k.looseObject({currentURL:k.string(),availableProjects:k.array(tp5).optional()}),d51=k.looseObject({currentlyVisibleFiles:k.array(ND),runningTerminalCommands:k.array(k.string()).optional(),activeEditor:k.any().optional(),cursorLocation:y51.optional(),cursorLocationLine:k.string().optional(),selectionRange:sp5.optional(),aggmanContext:ep5.optional()}),PP=k.custom((A)=>typeof A==="string"&&N3(A)!==void 0),Ad5=k.object({threadId:tt,role:k.literal("user"),content:m51,agentMode:PP.optional(),meta:g51.optional(),userState:d51.optional(),readAt:k.string().nullable().optional(),messageId:Z5,createdAt:k.string().optional()}),c51=k.object({model:k.string().optional(),maxInputTokens:k.number(),inputTokens:k.number(),outputTokens:k.number(),cacheCreationInputTokens:k.number().nullable(),cacheReadInputTokens:k.number().nullable(),totalInputTokens:k.number(),thinkingBudget:k.number().optional(),timestamp:k.string().optional()}),Qd5=k.union([k.object({type:k.literal("complete")}),k.object({type:k.literal("cancelled")})]),Bd5=k.object({threadId:tt,role:k.literal("assistant"),content:p51,state:Qd5.optional(),usage:c51.optional(),readAt:k.string().nullable().optional(),messageId:Z5,createdAt:k.string().optional()}),$d5=k.object({threadId:tt,role:k.literal("info"),content:rp5,messageId:Z5,createdAt:k.string().optional()}),l51=k.discriminatedUnion("role",[Ad5,Bd5,$d5]),Be=k.object({workspaceRoot:ND.optional(),workingDirectory:ND.optional(),rootDirectoryListing:k.string().nullable().optional(),trees:k.array(k.any()).optional(),platform:k.any().optional(),tags:k.array(k.string()).optional(),git:k.object({branch:k.string().optional()}).optional(),updatedAt:k.string().optional()}),Jd5=k.object({added:k.number().int().nonnegative(),deleted:k.number().int().nonnegative(),changed:k.number().int().nonnegative()}),Yd5=k.object({path:k.string(),previousPath:k.string().optional(),changeType:k.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:k.boolean(),diff:k.string(),fullFileDiff:k.string().optional(),oldContent:k.string().optional(),newContent:k.string().optional(),diffStat:Jd5}),Zd5=k.object({hash:k.string(),shortHash:k.string(),subject:k.string()}),Xr4=k.object({provider:k.literal("git"),capturedAt:k.number(),available:k.boolean(),repositoryRoot:k.string().nullable(),repositoryName:k.string().nullable(),branch:k.string().nullable(),head:k.string().nullable(),baseRef:k.string().nullable().optional(),baseRefHead:k.string().nullable().optional(),aheadCount:k.number().int().nonnegative().optional(),behindCount:k.number().int().nonnegative().optional(),aheadCommits:k.array(Zd5).optional(),diffHash:k.string().optional(),files:k.array(Yd5),unavailableReason:k.string().optional(),unchanged:k.boolean().optional()}),xU0=k.object({id:k.string(),toolCallId:S3,toolName:k.string(),args:k.record(k.string(),k.unknown()),reason:k.string().optional(),toAllow:k.array(k.string()).optional(),context:k.enum(["thread","subagent"]),subagentToolName:k.string().optional(),parentToolCallId:S3.optional(),timestamp:k.number(),matchedRule:k.object({tool:k.string(),action:k.string(),matches:k.record(k.string(),k.unknown()).optional()}).optional(),ruleSource:k.enum(["user","built-in"]).optional()}),Xd5=k.object({type:k.literal("request"),id:O8,method:O8,params:k.unknown()}),Fd5=k.object({type:k.literal("response"),id:O8,result:k.unknown().optional(),error:k.string().optional()}),Dd5=k.object({type:k.literal("event"),event:O8,data:k.unknown(),span:k.string().optional()}),fU0=k.discriminatedUnion("type",[Xd5,Fd5,Dd5]);var Gd5=k.object({type:k.literal("executor_connect"),clientId:bw,capabilities:to4,executorType:eo4.optional()}),Vd5=k.object({type:k.literal("client_update_thread_settings"),settings:yU0}),Ud5=k.object({type:k.literal("executor_tools_register"),tools:k.array(so4)}),Kd5=k.object({type:k.literal("executor_tools_unregister"),toolNames:k.array(O8)}),Ed5=k.object({type:k.literal("executor_tools_bootstrap_complete"),ok:k.boolean(),error:k.string().optional()}),Hd5=k.object({type:k.literal("executor_tool_lease_ack"),toolCallId:S3}),i51=k.object({type:k.literal("tool_progress"),toolCallId:S3,progress:k.union([Ar4,k.unknown()]).optional(),parentToolCallId:S3.optional()}),Wd5=k.object({type:k.literal("executor_tool_result"),toolCallId:S3,run:et}),zd5=k.object({type:k.literal("executor_guidance_snapshot"),snapshotId:O8,files:k.array(u51),isLast:k.boolean(),userConfigDir:k.any().optional()}),qd5=k.object({type:k.literal("executor_guidance_discovery"),toolCallId:S3,files:k.array(u51),isLast:k.boolean()}),Nd5=k.object({type:k.literal("executor_skill_snapshot"),snapshotId:O8,skills:k.array(Jr4),isLast:k.boolean(),errors:k.array(Br4).optional()}),Id5=k.object({type:k.literal("executor_environment_snapshot"),environment:Be}),wd5=k.object({type:k.literal("executor_environment_update"),environment:Be}),Cd5=k.object({type:k.literal("executor_artifact_upsert"),artifact:f51,toolCallId:S3.optional()}),Md5=k.object({type:k.literal("executor_artifact_delete"),key:O8}),Ld5=k.object({type:k.literal("executor_tool_approval_request"),approval:xU0}),Od5=k.object({type:k.literal("executor_plugin_message"),message:fU0}),jd5=k.object({type:k.literal("client_append_user_msg"),content:Qe,userState:d51.optional(),agentMode:PP.optional(),messageId:Z5,steer:k.boolean().optional()}),Rd5=k.object({type:k.literal("client_remove_queued_msg"),queuedMessageId:Z5}),Pd5=k.object({type:k.literal("client_steer_queued_msg"),queuedMessageId:Z5}),_d5=k.object({type:k.literal("client_edit_message"),messageId:Z5,editId:oo4,content:Qe,agentMode:PP.optional()}),Td5=k.object({type:k.literal("client_mark_message_read"),messageId:Z5}),Sd5=k.object({type:k.literal("client_mark_message_unread"),messageId:Z5}),kd5=k.object({type:k.literal("client_set_thread_title"),title:k.string().trim().min(1).max(256)}),vd5=k.object({auth:k.string().min(1),p256dh:k.string().min(1)}),yd5=k.object({endpoint:k.string().url(),keys:vd5}),xd5=k.object({type:k.literal("client_upsert_notification_subscription"),subscription:yd5,threadURL:k.string().min(1)}),fd5=k.object({type:k.literal("client_filesystem_read_directory"),requestId:gK,uri:Ju}),bd5=k.object({type:k.literal("client_filesystem_read_file"),requestId:gK,uri:Ju}),ud5=k.object({type:k.literal("executor_filesystem_read_directory_result"),requestId:gK,ok:k.boolean(),entries:k.array(Ae).optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:k.ZodIssueCode.custom,message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:k.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),hd5=k.object({type:k.literal("executor_filesystem_read_file_result"),requestId:gK,ok:k.boolean(),contentBase64:k.string().optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:k.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:k.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),gd5=k.object({type:k.literal("client_resume"),version:k.number()}),md5=k.object({type:k.literal("client_retry")}),pd5=k.object({type:k.literal("client_dismiss_active_error"),seq:k.number().optional()}),dd5=k.object({type:k.literal("client_cancel")}),cd5=k.object({type:k.literal("client_append_manual_bash_invocation"),args:k.object({cmd:k.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:k.array(k.string()).optional(),cwd:k.string().optional()}),run:et,hidden:k.boolean().optional()}),ld5=k.object({type:k.literal("client_tool_approval_response"),toolCallId:S3,accepted:k.boolean(),input:k.object({askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}).optional()}),id5=k.object({type:k.literal("client_spawn_executor"),requestId:k.string().optional(),repositoryURL:k.string().optional(),projectID:k.uuid().optional(),additionalRepositories:k.array(k.object({name:k.string(),url:k.string()})).optional()}),Fr4=k.discriminatedUnion("type",[Gd5,Vd5,Ud5,Kd5,Ed5,Hd5,i51,Wd5,zd5,qd5,Nd5,Id5,wd5,Cd5,Md5,Ld5,Od5,jd5,Rd5,Pd5,_d5,Td5,Sd5,kd5,xd5,fd5,bd5,ud5,hd5,gd5,md5,pd5,dd5,cd5,ld5,id5]);YQ();var bU0=(A)=>k.codec(k.string(),A,{decode:(Q,B)=>{try{return JSON.parse(Q)}catch($){return B.issues.push({code:"invalid_format",format:"json",input:Q,message:$.message}),k.NEVER}},encode:(Q)=>JSON.stringify(Q)});YQ();YQ();var n51=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],$t3=new Set(n51);var nd5=["working","streaming","tool_use","running_tools"],ad5=new Set(nd5);function w$(A){if(typeof A!=="string")return!1;return ad5.has(A)}function $e(A){return typeof A==="object"&&A!==null}function od5(A){return $e(A)&&A.type==="text"&&typeof A.text==="string"}function a51(A){if(!A)return;let Q=A.filter(od5).map((B)=>B.text).join("");return Q.length>0?Q:void 0}function o51(A){if(typeof A==="string")return A;if(Array.isArray(A))return a51(A);if(!$e(A))return;for(let Q of["output","displayMessage","message","reason"]){let B=A[Q];if(typeof B==="string")return B}for(let Q of["result","error","value"])if(Q in A){let B=o51(A[Q]);if(B!==void 0)return B}return}function Dr4(A,Q){if(typeof A==="string")return A+Q;if(Array.isArray(A)){if(!A.every((B)=>$e(B)&&typeof B.type==="string"))return;return[...A,{type:"text",text:Q}]}if(!$e(A))return;for(let B of["output","displayMessage","message","reason"]){let $=A[B];if(typeof $==="string")return{...A,[B]:$+Q}}if("value"in A){let B=Dr4(A.value,Q);if(B!==void 0)return{...A,value:B}}return}function rd5(A){return $e(A)&&typeof A.status==="string"}function sd5(A,Q){return{type:"delta",...A?{blocks:[{type:"text",text:A}]}:{},state:Q}}function td5(A){if(!A)return;if(A.type==="snapshot")return o51(A.value);return a51(A.blocks)}function Yu(A,Q){if(A&&typeof A==="object"&&"type"in A){let $=A;if($.type==="delta"||$.type==="snapshot")return $}if(Q==="snapshot")return{type:"snapshot",value:A};let B=typeof A==="string"?A:A!==void 0?JSON.stringify(A):"";return{type:"delta",blocks:B?[{type:"text",text:B}]:void 0,state:"generating"}}function Gr4(A,Q){if(Q.type!=="snapshot"||rd5(Q.value))return Q;let B=td5(A),$=o51(Q.value);if(B===void 0||$===void 0)return Q;if(!$.startsWith(B))return Q;return sd5($.slice(B.length),"generating")}function uU0(A,Q){let B=A===void 0?void 0:Yu(A,"snapshot"),$=Yu(Q,"snapshot");if($.type==="snapshot")return $;if(!B)return $;let J=a51($.blocks);if(J===void 0)return B;if(B.type==="snapshot"){let Z=Dr4(B.value,J);if(Z!==void 0)return{type:"snapshot",value:Z}}return{type:"delta",blocks:[...B.type==="delta"?B.blocks??[]:Array.isArray(B.value)?B.value:[],...$.blocks??[]],state:$.state}}var ed5=k.enum(n51),Ac5=k.enum(["start","generating","tool_use","complete","error","aborted"]),Qc5=k.object({message:k.string(),code:k.string().optional(),stack:k.string().optional(),retryAt:k.number().optional(),attempt:k.number().optional()}),Bc5=k.object({userId:k.string(),name:k.string(),avatarURL:k.string().optional()}),$c5=k.enum(["starting","running","failed"]),Jc5=k.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),Yc5=k.enum(["pending","ready","failed"]).nullable(),Zc5=k.enum(["allocating_environment","configuring_workspace","starting_headless"]).nullable(),Xc5=k.enum(["idle","creating","recovering"]),Fc5=k.enum(["unknown","running","paused","missing"]),Dc5=k.enum(["spawn_requested","spawn_rejected","environment_recovering","waiting_for_executor_connect","executor_connected","executor_disconnected","connect_timeout","executor_connect_rejected","spawn_failed","restart_failed","environment_missing"]),Gc5=k.object({environmentId:k.string().nullable().optional(),stage:Jc5.optional(),setupState:Yc5.optional(),setupPhase:Zc5.optional(),operation:Xc5.optional(),providerState:Fc5.optional(),restartAttempts:k.number().optional()}),Vc5=k.object({reasonCode:Dc5.optional(),executionEnvironment:Gc5.optional()}),Uc5=k.object({cutMessageId:Z5,createdAt:k.string()}),Vr4=k.object({steer:k.boolean(),queuedMessage:k.object({role:k.literal("user"),messageId:Z5,content:Qe,userState:k.any().optional(),meta:g51.optional(),createdAt:k.string().optional()})}),Kc5=k.object({type:k.literal("agent_state"),state:ed5,messageId:Z5.optional(),agentMode:PP.optional()}),Ec5=k.object({type:k.literal("inference_tools"),messageId:Z5,agentMode:PP,tools:k.array(O8),parentToolCallId:S3.optional()}),Hc5=k.object({type:k.literal("thread_settings"),settings:yU0}),Wc5=k.object({type:k.literal("error"),message:k.string(),code:k.enum(["ACCESS_DENIED","ACTOR_STOPPING","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),zc5=k.object({type:k.literal("error_set"),seq:k.number(),error:Qc5}),qc5=k.object({type:k.literal("error_cleared"),seq:k.number()}),Nc5=k.object({type:k.literal("cancelled"),seq:k.number(),messageId:Z5.optional()}),Ic5=k.object({type:k.literal("retry_scheduled"),retryAt:k.number(),attempt:k.number(),maxAttempts:k.number(),reason:k.string()}),wc5=k.object({type:k.literal("retry_started")}),Cc5=k.object({type:k.literal("retry_cancelled")}),Mc5=k.object({type:k.literal("executor_connected"),executorId:bw,registeredToolCount:k.number(),guidanceInventory:k.array($r4),resumeBootstrap:k.boolean().optional(),rejectedTools:k.array(k.object({name:k.string(),reason:k.string()})).optional()}),Lc5=k.object({type:k.literal("tool_lease"),toolCallId:S3,toolName:k.string(),args:k.unknown(),messageId:Z5,parentToolCallId:S3.optional()}),Oc5=k.object({type:k.literal("executor_filesystem_read_directory"),requestId:gK,uri:Ju}),jc5=k.object({type:k.literal("executor_filesystem_read_file"),requestId:gK,uri:Ju}),Rc5=k.object({type:k.literal("client_filesystem_read_directory_result"),requestId:gK,ok:k.boolean(),entries:k.array(Ae).optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:"custom",message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:"custom",message:"entries must not be present when ok is false"})}),Pc5=k.object({type:k.literal("client_filesystem_read_file_result"),requestId:gK,ok:k.boolean(),contentBase64:k.string().optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:"custom",message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:"custom",message:"contentBase64 must not be present when ok is false"})}),_c5=k.object({type:k.literal("tool_approval_queue"),approvals:k.array(xU0)}),Tc5=k.object({type:k.literal("executor_tool_lease_revoked"),toolCallId:S3,reason:k.enum(["executor_disconnected","reassigned","user_canceled"])}),Sc5=k.object({type:k.literal("executor_tool_result_ack"),toolCallId:S3}),kc5=k.object({type:k.literal("plugin_message"),message:fU0}),vc5=k.object({type:k.literal("executor_tool_approval_response"),toolCallId:S3,accepted:k.boolean(),input:k.object({askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}).optional()}),yc5=k.object({type:k.literal("executor_error"),message:k.string(),toolCallId:S3.optional(),code:k.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),xc5=k.object({type:k.literal("delta"),messageId:Z5,role:k.literal("assistant"),blocks:p51.optional(),blockIndex:k.number().int().nonnegative().optional(),state:Ac5,usage:c51.optional(),parentToolCallId:S3.optional()}),fc5=k.object({type:k.literal("delta"),messageId:Z5,role:k.literal("user"),blocks:m51.optional(),state:k.literal("complete"),parentToolCallId:S3.optional()}),bc5=k.discriminatedUnion("role",[xc5,fc5]),uc5=k.object({type:k.literal("queued_messages"),messages:k.array(Vr4)}),hc5=k.object({type:k.literal("queued_message_added"),message:Vr4,seq:k.number()}),gc5=k.object({type:k.literal("queued_message_removed"),queuedMessageId:Z5,seq:k.number()}),mc5=k.object({type:k.literal("message_added"),message:l51,seq:k.number(),parentToolUseId:S3.optional()}),pc5=k.object({type:k.literal("message_updated"),message:l51,seq:k.number()}),dc5=k.object({type:k.literal("edit_rejected"),editId:k.string(),message:k.string()}),cc5=k.object({type:k.literal("thread_truncated"),seq:k.number(),truncateFromMessage:Z5}),lc5=k.object({type:k.literal("observers"),count:k.number(),observers:k.array(Bc5),hasExecutor:k.boolean().optional()}),ic5=k.object({type:k.literal("executor_status"),spawnId:k.string().optional(),status:$c5,message:k.string().optional(),executorId:k.string().optional(),details:Vc5.optional()}),nc5=k.object({type:k.literal("environment_update"),environment:Be}),ac5=k.object({type:k.literal("artifacts_snapshot"),artifacts:k.array(b51)}),oc5=k.object({type:k.literal("artifact_upserted"),artifact:b51}),rc5=k.object({type:k.literal("artifact_deleted"),key:O8}),sc5=k.object({type:k.literal("thread_title"),title:k.string().nullable()}),tc5=k.object({type:k.literal("thread_status"),status:k.union([k.literal("merging"),k.literal("merged"),k.null()])}),ec5=k.object({type:k.literal("thread_relationships"),seq:k.number(),relationships:k.array(ao4)}),Al5=k.object({type:k.literal("compaction_started")}),Ql5=k.object({type:k.literal("compaction_complete"),cutMessageId:Z5}),Bl5=k.object({type:k.literal("compaction_records"),records:k.array(Uc5)}),hU0=k.discriminatedUnion("type",[Kc5,Ec5,Hc5,Wc5,zc5,qc5,Nc5,Ic5,wc5,Cc5,Mc5,Lc5,Oc5,jc5,Rc5,Pc5,_c5,Tc5,Sc5,kc5,vc5,i51,yc5,bc5,cc5,uc5,hc5,gc5,mc5,pc5,dc5,lc5,ic5,nc5,ac5,oc5,rc5,sc5,tc5,ec5,Al5,Ql5,Bl5]);var Ur4=bU0(Fr4),$l5=k.union([hU0,k.array(hU0)]),Kr4=bU0(hU0),Er4=bU0($l5);H4();function Hr4(A,Q={}){let $=(Q.mode??"lenient")==="strict";if(!Array.isArray(A))return $?null:[];let J=[];for(let Y of A){if(typeof Y!=="object"||Y===null){if($)return null;continue}let Z=Y;if(typeof Z.uri!=="string"||Z.uri.length===0){if($)return null;continue}let X;try{X=o1(J1.parse(Z.uri))}catch{if($)return null;continue}let F={uri:X};if(typeof Z.content==="string")F.content=Z.content;if(typeof Z.lineCount==="number"&&Number.isFinite(Z.lineCount))F.lineCount=Z.lineCount;if(typeof Z.hash==="string")F.hash=Z.hash;J.push(F)}return J}var Wr4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function r51(A,Q){if(A.length<=Q)return A;return`${A.slice(0,Q)}...<truncated>`}function Jl5(A){return A.replace(/\s+/g," ").trim()}function Yl5(A){if(!A||typeof A!=="object")return[];let Q=A.issues;return Array.isArray(Q)?Q.slice(0,5):[]}function Zl5(A){if(A===void 0)return null;if(typeof A==="string")return JSON.stringify(A);if(typeof A==="number"||typeof A==="boolean"||A===null)return JSON.stringify(A);try{return r51(JSON.stringify(A),120)}catch{return r51(String(A),120)}}function zr4(A){if(!Array.isArray(A)||A.length===0)return null;let Q=A.map((B)=>typeof B==="number"?`[${B}]`:String(B)).join(".").replace(/\.\[/g,"[");return Q.length>0?Q:null}function Xl5(A){if(!A||typeof A!=="object")return null;let Q=A,B=typeof Q.message==="string"?Q.message:null,$=typeof Q.note==="string"?Q.note:null,J=zr4(Q.path);if(J&&B&&B!=="Invalid input")return`${J}: ${B}`;if(J&&$)return`${J}: ${$}`;if(J&&B)return`invalid value at ${J}`;return $??B}function qr4(A){for(let Q of A){let B=Xl5(Q);if(B)return B}return null}function Fl5(A){return A.some((Q)=>{if(!Q||typeof Q!=="object")return!1;let B=Q;return B.code==="invalid_union"&&(B.note==="No matching discriminator"||B.discriminator==="type"||zr4(B.path)==="type")})}function Dl5(A,Q){let B=qr4(Q);if(A&&B)return`type ${JSON.stringify(A)} failed validation: ${B}`;if(A)return`type ${JSON.stringify(A)} failed validation`;if(B)return`message payload failed validation: ${B}`;return"message payload failed validation"}function Nr4(A,Q,B){let $=Yl5(Q),J=(()=>{let D=Jl5(A);if(D.length===0)return null;return r51(D,B?.payloadPreviewMaxChars??1200)})(),Y;try{Y=JSON.parse(A)}catch{let D=qr4($);return{failureType:"invalid_json",summary:D?`malformed JSON: ${D}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:J,issues:$}}if(!Y||typeof Y!=="object"||Array.isArray(Y))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:J,issues:$};let Z=Y;if(!Object.hasOwn(Z,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:J,issues:$};let X=Z.type,F=Zl5(X);if(typeof X!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:J,issues:$};if(Fl5($))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(X)} (likely protocol version mismatch)`,messageType:X,typePreview:F,payloadPreview:J,issues:$};return{failureType:"invalid_shape",summary:Dl5(X,$),messageType:X,typePreview:F,payloadPreview:J,issues:$}}function s51(A){let Q=Number.isFinite(A)?A:0;function B(J=Q){if(Number.isFinite(J))Q=J;return Q}function $(J){if(!Number.isFinite(J)||J<1)return Q;return Q=Math.max(Q,J),Q}return{getVersion:()=>Q,reset:B,advanceFromSeq:$}}function wr4(A,Q,B){if(Gl5(Q))return A;let $;switch(Q.type){case"message_added":$=Vl5(A,Q);break;case"message_updated":$=Ul5(A,Q);break;case"delta":$=Kl5(A,Q,B);break;case"tool_progress":$=El5(A,Q,B);break;case"thread_truncated":$=Hl5(A,Q);break}return Ml5($,Q,B)}function Gl5(A){if(A.type==="message_added")return A.parentToolUseId!==void 0;if(A.type==="delta"||A.type==="tool_progress")return A.parentToolCallId!==void 0;return!1}function Vl5(A,Q){let B=Sl5(A,vl5(Q.message)),$=Zu(B,Q.message.messageId),J=B.slice();if($>=0)return J[$]=Q.message,J;return J.push(Q.message),J}function Ul5(A,Q){let B=Zu(A,Q.message.messageId),$=A.slice();if(B>=0)return $[B]=Q.message,$;return $.push(Q.message),$}function Kl5(A,Q,B){let $=Q.role==="assistant"&&Q.state==="aborted"?Cl5(A,Q.messageId):A;if(!Q.blocks||Q.blocks.length===0)return $.slice();if(Q.role==="assistant")return Wl5($,Q,B);return zl5($,{...Q,blocks:Q.blocks},B)}function El5(A,Q,B){let $=Tl5(Q.progress);if($!==void 0&&$!=="in-progress")return A.slice();if(Je(A,Q.toolCallId,(G)=>G.run.status==="done"||G.run.status==="error"||G.run.status==="cancelled"||G.run.status==="rejected-by-user"))return A.slice();let Y=Je(A,Q.toolCallId),Z=Y&&"progress"in Y.block.run?Y.block.run.progress:void 0,X=Q.progress===void 0?Z:uU0(Z,Q.progress),F=X===void 0?{status:"in-progress"}:{status:"in-progress",progress:X},D=Y?.block.userInput===void 0?{type:"tool_result",toolUseID:Q.toolCallId,run:F}:{type:"tool_result",toolUseID:Q.toolCallId,run:F,userInput:Y.block.userInput};if(Y)return e51(A,Y,D);return[...A,{threadId:B.threadId,messageId:Mr4(Q.toolCallId),role:"user",content:[D]}]}function Hl5(A,Q){let B=Zu(A,Q.truncateFromMessage);return B>=0?A.slice(0,B):A.slice()}function Wl5(A,Q,B){let $=Zu(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="assistant"?J.content:[],Z=ql5(Y,Q.blocks,Q.blockIndex),X=J?.role==="assistant"?{...J,content:Z}:{threadId:B.threadId,messageId:Q.messageId,role:"assistant",content:Z};if(Q.usage!==void 0)X.usage=Q.usage;if(Q.state==="aborted")X.state={type:"cancelled"};else if(Q.state==="complete"||Q.state==="tool_use")X.state={type:"complete"};return t51(A,$,X)}function zl5(A,Q,B){let $=Zu(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="user"?J.content:[],Z=wl5(Y,Q.blocks),X=J?.role==="user"?{...J,content:Z}:{threadId:B.threadId,messageId:Q.messageId,role:"user",content:Z};return t51(A,$,X)}function ql5(A,Q,B){let $=[...A];for(let[J,Y]of Q.entries()){let Z=B+J;Nl5($,Z);let X=$[Z];if(Il5(X))$[Z]=Y;else if(X?.type==="text"&&Y.type==="text")$[Z]={...X,text:X.text+Y.text};else if(X?.type==="thinking"&&Y.type==="thinking")$[Z]={...X,thinking:X.thinking+Y.thinking};else $[Z]=Y}return $}function Nl5(A,Q){while(A.length<Q)A.push({type:"text",text:"",hidden:!0})}function Il5(A){return A?.type==="text"&&A.hidden===!0&&A.text===""}function wl5(A,Q){let B=[...A];for(let $ of Q){let J=B.length-1,Y=B[J];if(Y?.type==="text"&&$.type==="text")B[J]={...Y,text:Y.text+$.text};else B.push($)}return B}function t51(A,Q,B){let $=A.slice();if(Q>=0)return $[Q]=B,$;return $.push(B),$}function Cl5(A,Q){return A.filter((B)=>B.messageId!==Q)}function Zu(A,Q){return A.findIndex((B)=>B.messageId===Q)}function Je(A,Q,B=()=>!0){for(let[$,J]of A.entries()){if(J.role!=="user")continue;for(let[Y,Z]of J.content.entries())if(Z.type==="tool_result"&&Z.toolUseID===Q&&B(Z))return{messageIndex:$,blockIndex:Y,message:J,block:Z}}return}function e51(A,Q,B){let $=Q.message.content.slice();return $[Q.blockIndex]=B,t51(A,Q.messageIndex,{...Q.message,content:$})}function Ml5(A,Q,B){let $=B.guidanceDedup;if(!$)return A.slice();Ll5($,Q);let J=A.slice();for(let Z of jl5(J,Q)){let X=Je(J,Z.block.toolUseID)??Z,{myDedupedFiles:F,needsRebuild:D}=$.applyToolResult(X.block.toolUseID,wd0(X.block));J=e51(J,X,Cr4(X.block,F));for(let G of D)J=Ir4(J,$,G)}let Y=$.cleanupRemovedToolResults(Rl5(J));for(let Z of Y)J=Ir4(J,$,Z);return J}function Ll5(A,Q){if(Q.type==="message_added"||Q.type==="message_updated"){Ol5(A,Q.message);return}if(Q.type!=="delta"||Q.role!=="assistant"||!Q.blocks)return;for(let B of Q.blocks)if(B.type==="tool_use")A.recordToolOrder(B.id)}function Ol5(A,Q){if(Q.role!=="assistant")return;for(let B of Q.content)if(B.type==="tool_use")A.recordToolOrder(B.id)}function jl5(A,Q){if(Q.type==="message_added"||Q.type==="message_updated"){let B=Zu(A,Q.message.messageId),$=B>=0?A[B]:void 0;if($?.role!=="user")return[];return $.content.flatMap((J,Y)=>J.type==="tool_result"?[{messageIndex:B,blockIndex:Y,message:$,block:J}]:[])}if(Q.type!=="delta"||Q.role!=="user"||!Q.blocks)return[];return Q.blocks.flatMap((B)=>{if(B.type!=="tool_result")return[];let $=Je(A,B.toolUseID);return $?[$]:[]})}function Ir4(A,Q,B){let $=Je(A,B);if(!$)return A.slice();return e51(A,$,Cr4($.block,Q.dedupedFilesFor(B)))}function Cr4(A,Q){if(A.run.status!=="done")return A;let B=A.run.result;if(!B||typeof B!=="object"||Array.isArray(B))return A;let{discoveredGuidanceFiles:$,...J}=B,Y=J;if(Q.length>0)Y={...J,discoveredGuidanceFiles:[...Q]};return{...A,run:{...A.run,result:Y}}}function Rl5(A){let Q=new Set;for(let B of A){if(B.role!=="user")continue;for(let $ of B.content)if($.type==="tool_result")Q.add($.toolUseID)}return Q}var Pl5=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function _l5(A){return typeof A==="string"&&Pl5.includes(A)}function Tl5(A){if(A===void 0||typeof A!=="object"||A===null)return;let Q=A;if(Q.type!=="snapshot")return;let B=Q.value;if(typeof B!=="object"||B===null)return;let $=B.status;return _l5($)?$:void 0}function Sl5(A,Q){if(Q.size===0)return A;return A.filter((B)=>!kl5(B,Q))}function kl5(A,Q){if(A.role!=="user"||A.content.length!==1)return!1;let B=A.content[0];return B?.type==="tool_result"&&Q.has(B.toolUseID)&&A.messageId===Mr4(B.toolUseID)}function vl5(A){let Q=new Set;if(A.role!=="user")return Q;for(let B of A.content)if(B.type==="tool_result")Q.add(B.toolUseID);return Q}function Mr4(A){return`M-${A.replace(/^TU-/,"")}`}class A81{guidance=new kU0;inProgressMessageID=null;threadMessages=[];messageSeq=new Map;messageOrder=new Map;nextMessageOrder=0;threadID;constructor(A){this.threadID=A}setThreadID(A){this.threadID=A}getThreadID(){return this.threadID}reset(A){if(A!==void 0)this.threadID=A;this.guidance=new kU0,this.threadMessages=[],this.messageSeq.clear(),this.messageOrder.clear(),this.nextMessageOrder=0,this.inProgressMessageID=null}apply(A){let Q=this.threadMessages;if(A.type==="delta"&&A.parentToolCallId===void 0&&A.state==="aborted"){if(this.applyThreadMessageEvent(A),this.inProgressMessageID===A.messageId)this.inProgressMessageID=null;return this.threadMessages!==Q}let B=yl5(A);if(B!==void 0)this.updateInProgressMessage(B);if(this.applyThreadMessageEvent(A),A.type==="delta"&&(A.state==="complete"||A.state==="tool_use"))this.inProgressMessageID=null;return this.threadMessages!==Q}messages(){return this.threadMessages}sortedMessages(){return this.sortThreadMessages(this.threadMessages)}applyThreadMessageEvent(A){this.recordMessageOrder(A);let Q=A.type==="thread_truncated"?this.sortThreadMessages(this.threadMessages):this.threadMessages;this.threadMessages=wr4(Q,A,{threadId:this.threadID,guidanceDedup:this.guidance}),this.pruneMessageOrder()}recordMessageOrder(A){if(A.type==="message_added"){this.recordMessage(A.message.messageId,A.seq);return}if(A.type==="message_updated"){this.recordMessage(A.message.messageId,this.messageSeq.has(A.message.messageId)?void 0:A.seq);return}if(A.type==="delta"){this.recordMessage(A.messageId);return}if(A.type==="tool_progress")this.recordMessage(xl5(A.toolCallId))}recordMessage(A,Q){if(!this.messageOrder.has(A))this.messageOrder.set(A,this.nextMessageOrder),this.nextMessageOrder+=1;if(Q!==void 0)this.messageSeq.set(A,Q)}sortThreadMessages(A){return A.slice().sort((Q,B)=>{let $=this.messageSeq.get(Q.messageId),J=this.messageSeq.get(B.messageId),Y=$!==void 0&&J!==void 0?$-J:this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId);if(Y!==0)return Y;return this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId)})}messageSortOrder(A){return this.messageOrder.get(A)??Number.MAX_SAFE_INTEGER}pruneMessageOrder(){let A=new Set(this.threadMessages.map((Q)=>Q.messageId));for(let Q of this.messageSeq.keys())if(!A.has(Q))this.messageSeq.delete(Q);for(let Q of this.messageOrder.keys())if(!A.has(Q))this.messageOrder.delete(Q);if(this.inProgressMessageID!==null&&!A.has(this.inProgressMessageID))this.inProgressMessageID=null}updateInProgressMessage(A){if(this.inProgressMessageID===A)return;if(this.inProgressMessageID!==null)this.markMessageNotInProgress(this.inProgressMessageID);this.inProgressMessageID=A}markMessageNotInProgress(A){this.threadMessages=this.threadMessages.map((Q)=>{if(Q.messageId!==A||Q.role!=="assistant"||Q.state!==void 0)return Q;return{...Q,state:{type:"complete"}}})}}function yl5(A){if(A.type==="message_added"&&A.parentToolUseId===void 0)return A.message.messageId;if(A.type==="delta"&&A.parentToolCallId===void 0)return A.messageId;return}function xl5(A){return`M-${A.replace(/^TU-/,"")}`}AA();function Lr4(A,Q){if(A.role==="assistant")return{role:"assistant",content:A.content,state:A.state?.type==="cancelled"?{type:"cancelled"}:{type:"complete",stopReason:null},usage:A.usage,messageId:Q,protocolMessageID:A.messageId,readAt:A.readAt};if(A.role==="info")return{role:"info",content:A.content,messageId:Q,protocolMessageID:A.messageId};return{role:"user",content:A.content,meta:s90(A.meta),userState:A.userState,readAt:A.readAt,messageId:Q,protocolMessageID:A.messageId}}class gU0{accumulator;currentVersion=0;constructor(A){this.accumulator=new A81(A)}get version(){return this.currentVersion}setThreadID(A){this.accumulator.setThreadID(A)}reset(A){let Q=this.accumulator.sortedMessages().length;return this.accumulator.reset(A),this.currentVersion+=1,{changed:Q>0,previousMessageCount:Q,nextMessageCount:0,changedIndices:bl5(Q,0),version:this.currentVersion}}apply(A){if(A.type==="message_added"&&A.parentToolUseId===void 0||A.type==="message_updated")this.setThreadID(A.message.threadId);let Q=this.accumulator.sortedMessages();if(!this.accumulator.apply(A))return{changed:!1,previousMessageCount:Q.length,nextMessageCount:Q.length,changedIndices:[],version:this.currentVersion};let $=this.accumulator.sortedMessages();return this.currentVersion+=1,{changed:!0,previousMessageCount:Q.length,nextMessageCount:$.length,changedIndices:fl5(Q,$),version:this.currentVersion}}protocolMessages(){return this.accumulator.sortedMessages()}coreMessages(){return this.accumulator.sortedMessages().map((A,Q)=>Lr4(A,Q))}buildTranscriptEntries(A={}){return _o4(this.protocolMessages(),{threadID:this.accumulator.getThreadID(),...A})}}function fl5(A,Q){let B=Math.max(A.length,Q.length),$=[];for(let J=0;J<B;J+=1)if(A[J]!==Q[J])$.push(J);return $}function bl5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}function mU0(A,Q={}){let B=!1,$=!1;return A.connectionChanges().subscribe({next:(J)=>{let Y=J.state==="connected";if(Y&&!B){if($)try{A.resumeFromVersion(A.getResumeVersion())}catch(Z){Q.onError?.({threadID:A.getThreadId(),error:Z})}$=!0}B=Y}})}XY0();j1();var Q81=Number.MAX_SAFE_INTEGER;class B81{callbacks;agentLoopState=null;pending=new Map;constructor(A){this.callbacks=A}setAgentLoopState(A){this.agentLoopState=A}emitOptimisticUserMessage(A){if(this.pending.has(A.messageId))return;let Q=this.nextEventType();this.pending.set(A.messageId,Q),this.dispatchOptimistic(Q,A)}emitOptimisticQueuedUserMessage(A){if(this.pending.has(A.messageId))return;this.pending.set(A.messageId,"queued_message_added"),this.dispatchOptimistic("queued_message_added",A)}reconcileMessageAdded(A){let Q=A.message.messageId;if(this.pending.get(Q)==="queued_message_added")this.emitQueuedMessages({type:"queued_message_removed",queuedMessageId:Q,seq:Q81});this.pending.delete(Q),this.emitMessageAdded(A)}reconcileQueuedMessageAdded(A){let Q=A.message.queuedMessage.messageId,B=this.pending.get(Q);if(B==="queued_message_added")return;if(B==="message_added")this.pending.set(Q,"queued_message_added");this.emitQueuedMessages(A)}reconcileQueuedMessagesSnapshot(A){let Q=new Set;for(let B of A.messages)Q.add(B.queuedMessage.messageId);for(let B of Q)if(this.pending.get(B)==="message_added")this.pending.set(B,"queued_message_added");for(let[B,$]of this.pending)if($==="queued_message_added"&&!Q.has(B))return;this.emitQueuedMessages(A)}reconcileQueuedMessageRemoved(A){this.pending.delete(A.queuedMessageId),this.emitQueuedMessages(A)}reset(){this.agentLoopState=null,this.pending.clear()}nextEventType(){if(this.agentLoopState===null||this.agentLoopState==="idle")return"message_added";return"queued_message_added"}dispatchOptimistic(A,Q){if(A==="message_added"){this.emitMessageAdded({type:"message_added",message:{role:"user",messageId:Q.messageId,content:Q.content,agentMode:Q.agentMode,threadId:this.callbacks.getThreadID()??"T-00000000-0000-0000-0000-000000000000"},seq:Q81});return}this.emitQueuedMessages({type:"queued_message_added",message:{steer:!1,queuedMessage:{role:"user",messageId:Q.messageId,content:Q.content,userState:Q.userState}},seq:Q81})}emitMessageAdded(A){this.callbacks.observerCallbacks((Q)=>{Q.onMessageAdded?.(A)})}emitQueuedMessages(A){this.callbacks.observerCallbacks((Q)=>{Q.onQueuedMessages?.(A)})}}class $81{options;queue=[];active=null;retryTimer=null;constructor(A){this.options=A}send(A){this.queue.push({message:A,sent:!1}),this.pump()}retry(){this.clearRetryTimer(),this.pump({forceActiveRetry:!0})}handleServerMessage(A){if(!this.active||!this.active.sent||this.active.message.type!=="client_append_user_msg")return;if(!hl5(this.active.message,A))return;this.clearRetryTimer(),this.active=null,this.pump()}reset(){this.clearRetryTimer(),this.queue.length=0,this.active=null}pump(A){if(this.active){if(!this.active.sent||A?.forceActiveRetry)this.tryActive();return}let Q=this.queue.shift();if(!Q)return;this.active=Q,this.tryActive()}tryActive(){let A=this.active;if(!A||A.sent&&A.message.type!=="client_append_user_msg")return;if(!this.options.trySend(A.message)){this.scheduleRetry();return}if(A.sent=!0,A.message.type!=="client_append_user_msg"){this.clearRetryTimer(),this.active=null,this.pump();return}this.scheduleRetry()}scheduleRetry(){if(this.retryTimer!==null)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.pump({forceActiveRetry:!0})},1000),ul5(this.retryTimer)}clearRetryTimer(){if(this.retryTimer===null)return;clearTimeout(this.retryTimer),this.retryTimer=null}}function ul5(A){if(typeof A!=="object"||A===null||!("unref"in A))return;let Q=A.unref;if(typeof Q==="function")Q.call(A)}function hl5(A,Q){switch(Q.type){case"message_added":return Q.message.messageId===A.messageId;case"queued_message_added":return Q.message.queuedMessage.messageId===A.messageId;case"queued_messages":return gl5(Q.messages,A.messageId);default:return!1}}function gl5(A,Q){return A.some((B)=>B.queuedMessage.messageId===Q)}i0();j1();var ml5=1000,pl5=30000,dl5=124,cl5=30000,ll5=15000,il5=1000,nl5=200,al5=30000,Or4=["online","focus","pageshow","keydown","pointerdown"],jr4=["visibilitychange"];function Y81(){return globalThis}function Pr4(A){if(!A||typeof A!=="object")return null;let Q=A;if(typeof Q.addEventListener!=="function"||typeof Q.removeEventListener!=="function")return null;return Q}function Rr4(){return Pr4(Y81().window)}function J81(){let A=Y81().document;if(!Pr4(A))return null;return A}function ol5(){let A=Y81().navigator;if(!A||typeof A!=="object")return null;return A}function rl5(A){if(!A)return"none";let Q=[A.type];if(A.code!==void 0)Q.push(`code=${A.code}`);if(A.reason!==void 0)Q.push(`reason=${A.reason}`);if(A.error!==void 0)Q.push(`error=${A.error}`);return Q.join(" ")}class Z81{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;latencyTimeoutIDs=new Set;disposed=!1;lastServerFrameAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new D4({state:"disconnected",role:null,clientId:null});lifecycleEventSubject=new D4([]);config;threadIDSubject=new D4(null);_currentThreadID=null;log=new yY;get currentThreadID(){return this._currentThreadID}set currentThreadID(A){if(A!==null&&A!==this._currentThreadID)this._currentThreadID=A,this.log=FO(A),this.threadIDSubject.next(A);else this._currentThreadID=A}constructor(A){this.config={threadId:A.threadId,webSocketProvider:A.webSocketProvider,reconnectDelayMs:A.reconnectDelayMs??ml5,maxReconnectDelayMs:A.maxReconnectDelayMs??pl5,maxReconnectAttempts:A.maxReconnectAttempts??dl5,pingIntervalMs:A.pingIntervalMs??cl5,connectTimeoutMs:A.connectTimeoutMs??ll5,webSocketLatencyMs:A.webSocketLatencyMs??(()=>0)},this.currentThreadID=A.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(A){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||A<=0)return Promise.resolve(!1);return new Promise((Q)=>{let B=!1,$=null,J=null,Y=(Z)=>{if(B)return;if(B=!0,$)clearTimeout($),$=null;J?.unsubscribe(),J=null,Q(Z)};$=setTimeout(()=>{Y(!1)},A),J=this.connectionSubject.subscribe({next:(Z)=>{if(Z.state==="connected")Y(!0)},error:()=>{Y(!1)},complete:()=>{Y(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(A,Q){let B={id:++this.lifecycleEventID,at:Date.now(),type:A,...Q?{details:Q}:{}},$=nl5,J=this.lifecycleEvents.slice(-($-1));this.lifecycleEvents=[...J,B],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(A){if(this.disposed)throw new T3("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",A.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Q,threadId:B}=await this.config.webSocketProvider();this.currentThreadID=B;try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastServerFrameAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Q){let B=Q instanceof Error?Q.message:String(Q);if(this.recordLifecycleEvent("connect_failed",`mode=${A.fromReconnect?"reconnect":"initial"} error=${B}`),!A.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:B},this.scheduleReconnect();throw Q}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let A=this.ws;if(A){if(this.ws=null,this.intentionallyClosedSockets.add(A),A.readyState===WebSocket.OPEN)A.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(A){if(this.disposed)return;let Q=this.ws;if(!Q&&this.connectionInfo.state!=="connected")return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${A}`),this.clearWebSocketLatencyTimeouts(),this.reconnectCause={type:"error",at:Date.now(),error:A},this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),Q&&(Q.readyState===WebSocket.OPEN||Q.readyState===WebSocket.CONNECTING))Q.close(4000,A);this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}retryConnect(A){if(this.disposed)return;if(this.recordLifecycleEvent("reconnect_attempts_reset",`reason=${A}`),this.reconnectAttempts=0,this.cancelReconnectAttemptsReset(),this.reconnectTimeoutID)return;this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}async disconnectAndWait(A){let Q=this.ws;if(!Q||Q.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let B=this.waitForSocketClose(Q,A?.waitForCloseTimeoutMs??il5);return this.disconnect(),B}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(A){if(!this.hasOpenSocket())throw new T3("WebSocket is not connected");let Q=this.ws;if(!Q)throw new T3("WebSocket is not connected");this.runAfterWebSocketLatency(()=>{if(Q!==this.ws||Q.readyState!==WebSocket.OPEN)return;Q.send(A)}),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}runAfterWebSocketLatency(A){let Q=this.config.webSocketLatencyMs();if(!Number.isFinite(Q)||Q<=0){A();return}let B=setTimeout(()=>{this.latencyTimeoutIDs.delete(B),A()},Q);this.latencyTimeoutIDs.add(B)}clearWebSocketLatencyTimeouts(){for(let A of this.latencyTimeoutIDs)clearTimeout(A);this.latencyTimeoutIDs.clear()}waitForSocketClose(A,Q){return new Promise((B)=>{let $=!1,J=null,Y=(X)=>{if($)return;if($=!0,J)clearTimeout(J);A.removeEventListener("close",Z),B(X)},Z=(X)=>{let F=X;Y({status:F.code===1000?"server_acknowledged":"timeout",...typeof F.code==="number"?{closeCode:F.code}:{},...typeof F.reason==="string"?{closeReason:F.reason}:{}})};if(J=setTimeout(()=>{Y({status:"timeout"})},Q),A.addEventListener("close",Z),A.readyState===WebSocket.CLOSED)Y({status:"timeout"})})}updateConnectionState(A){let Q={...this.connectionInfo};if(A==="disconnected"||A==="reconnecting"){let $={state:A,role:null,clientId:null};if(this.reconnectCause)$.reconnectCause=this.reconnectCause;this.connectionInfo=$}else if(this.connectionInfo.state=A,A==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let B={...this.connectionInfo};this.connectionSubject.next(B),this.log.info("[thread-client] Transport connection state changed",{previousState:Q.state,nextState:B.state,previousRole:Q.role,nextRole:B.role,clientId:B.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${A} cause=${rl5(this.reconnectCause)}`)}onRawMessage(A){}onMaxReconnectExceeded(A){}async waitForOpen(A){if(A.readyState===WebSocket.OPEN)return;return new Promise((Q,B)=>{let $=setTimeout(()=>{J(),this.updateConnectionState("disconnected");try{if(A.readyState===WebSocket.CONNECTING)A.close()}catch{}B(new T3(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),J=()=>{clearTimeout($),A.removeEventListener("open",Y),A.removeEventListener("error",Z),A.removeEventListener("close",X)},Y=()=>{J(),Q()},Z=(F)=>{J(),this.updateConnectionState("disconnected");let D="message"in F?F.message:("error"in F)&&F.error instanceof Error?F.error.message:F.type;B(new T3(`WebSocket connection failed: ${D}`))},X=(F)=>{J(),this.updateConnectionState("disconnected"),B(new T3(`WebSocket closed during connect: code=${F.code} reason=${F.reason||"none"}`))};if(A.addEventListener("open",Y),A.addEventListener("error",Z),A.addEventListener("close",X),A.readyState===WebSocket.OPEN)return Y();if(A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)return X({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(A){A.addEventListener("message",(Q)=>{let B=Q.data;this.runAfterWebSocketLatency(()=>this.handleWebSocketMessage(A,B))}),A.addEventListener("close",(Q)=>{this.handleClose(A,Q.code,Q.reason)}),A.addEventListener("error",()=>{this.handleError(A)})}handleWebSocketMessage(A,Q){if(A!==this.ws)return;if(this.lastServerFrameAt=Date.now(),this.startPingIntervalOnce(),typeof Q==="string"){if(Q==="pong")return;this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}handleClose(A,Q,B){let $=this.intentionallyClosedSockets.has(A);if($)this.intentionallyClosedSockets.delete(A);if(this.log.info("[thread-client] Transport socket close observed",{code:Q,reason:B||void 0,intentional:$,isCurrentSocket:A===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Q} reason=${B||"none"} intentional=${$}`),A!==this.ws)return;if(this.ws=null,this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!$){let J=this.reconnectCause,Y=J?.type==="ping_timeout"&&Q===4000&&!B?{...J,at:Date.now(),code:Q}:{type:"close",at:Date.now(),code:Q,...B?{reason:B}:{}};this.reconnectCause=Y,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(A){if(A!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(A){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!A?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Q=A?.immediate?0:this.getReconnectDelayMs();this.log.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Q),immediate:A?.immediate===!0,bypassActivityGate:A?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Q)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((B)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:B instanceof Error?B.message:String(B)},!this.disposed)this.scheduleReconnect()})},Q)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let A=Math.min(this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),this.config.maxReconnectDelayMs),Q=0.8+Math.random()*0.4;return A*Q}shouldWaitForReconnectActivity(){let A=Rr4(),Q=J81();if(!A&&!Q)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let A=ol5();if(typeof A?.onLine!=="boolean")return!1;return A.onLine===!1}isDocumentHidden(){let A=J81();if(!A)return!1;return A.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let A=Rr4(),Q=J81();if(!A&&!Q)return;let B=()=>{this.handleReconnectActivity()};for(let $ of Or4)A?.addEventListener($,B);for(let $ of jr4)Q?.addEventListener($,B);this.reconnectActivityCleanup=()=>{for(let $ of Or4)A?.removeEventListener($,B);for(let $ of jr4)Q?.removeEventListener($,B)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},al5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let A=Date.now();this.pingIntervalID=setInterval(()=>{let Q=Date.now(),B=Q-A;if(A=Q,B>this.config.pingIntervalMs*3){this.lastServerFrameAt=Q;return}if(this.hasOpenSocket()){let $=Q-this.lastServerFrameAt,J=this.config.pingIntervalMs*2;if($>J){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${$} thresholdMs=${J}`);let Y=`No server frame received for ${$}ms (threshold ${J}ms)`;this.reconnectCause={type:"ping_timeout",at:Q,code:4000,reason:"Pong timeout",error:Y},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}YQ();var _r4="dtw-parse-error",gt3=k.object({kind:k.literal(_r4),failureType:k.enum(Wr4).nullable().optional(),source:k.string().nullable().optional(),direction:k.string().nullable().optional(),stage:k.string().nullable().optional(),summary:k.string().nullable().optional(),messageType:k.string().nullable().optional(),typePreview:k.string().nullable().optional(),payloadPreview:k.string().nullable().optional(),issues:k.array(k.unknown()).optional()}).passthrough(),mt3=k.object({source:k.string(),direction:k.string(),stage:k.string(),summary:k.string().nullable().optional(),messageType:k.string().nullable().optional(),payloadPreview:k.string().nullable().optional(),issues:k.array(k.unknown()).optional()}).passthrough();function sl5(A){return{kind:_r4,failureType:A.failureType??null,source:A.source??null,direction:A.direction??null,stage:A.stage??null,summary:A.summary??null,messageType:A.messageType??null,typePreview:A.typePreview??null,payloadPreview:A.payloadPreview??null,issues:A.issues??[]}}function tl5(A){let Q=sl5(A);return JSON.stringify(Q)}function Tr4(A,Q){let B=Nr4(A,Q);return tl5({failureType:B.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:B.summary,messageType:B.messageType,typePreview:B.typePreview,payloadPreview:B.payloadPreview,issues:B.issues})}var el5=3000,Ai5=30000,Qi5=5;function Sr4(A){if(A instanceof a2)return A;if(A instanceof Error){let Q=A.message||"Unknown thread-client connection error";return new a2(Q,A)}if(typeof A==="string"&&A.length>0)return new a2(A,A);return new a2("Unknown thread-client connection error",A)}function Bi5(A){let Q=atob(A),B=new Uint8Array(Q.length);for(let $=0;$<Q.length;$++)B[$]=Q.charCodeAt($);return B}function $i5(A){return{type:"error",message:`Failed to send user message: ${A}`,code:"MESSAGE_ERROR"}}class mK extends Z81{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outbox;optimisticUserMessages;pendingCancelAgentLoop=!1;pendingDismissActiveError=null;fileSystemRequestCounter=0;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=s51(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new D4(null);threadIDSubscription;constructor(A){super(A.transport);if(this.threadHistoryLoader=A.threadHistoryLoader,this.outbox=new $81({trySend:(Q)=>this.trySendOutboxMessage(Q)}),this.optimisticUserMessages=new B81({getThreadID:()=>this.getThreadId(),observerCallbacks:(Q)=>this.dispatchObserverCallbacks(Q)}),this.threadIDSubscription=this.threadIDSubject.subscribe((Q)=>{if(Q!==null)this.dispatchObserverCallbacks((B)=>{B.onThreadId?.(Q)})}),A.observerCallbacks)this.setObserverCallbacks(A.observerCallbacks);if(A.executorCallbacks)this.setExecutorCallbacks(A.executorCallbacks)}setObserverCallbacks(A){if(this.observerCallbacks&&this.observerCallbacks!==A)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===A)return;if(this.observerCallbacks=A,this.pendingObserverDispatches.length===0)return;for(let Q of this.pendingObserverDispatches)Q(A);this.pendingObserverDispatches.length=0}setExecutorCallbacks(A){if(this.executorCallbacks&&this.executorCallbacks!==A)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===A)return;if(this.executorCallbacks=A,this.pendingExecutorDispatches.length===0)return;for(let Q of this.pendingExecutorDispatches)Q(A);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(A){throw Sr4(A)}}async ensureConnected(A){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(A);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(A){let Q=A?.baseDelayMs??el5,B=A?.maxDelayMs??Ai5,$=A?.maxAttempts??Qi5;if(A?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let J=0;J<$;J++){try{await this.connect()}catch(F){let D=Sr4(F);if(this.getConnectionInfo().state!=="reconnecting")throw D;A?.onRetryableConnectError?.(D)}let Y=A?.waitForConnectedTimeoutMs??Math.min(Q*2**J,B);if(await this.waitForConnected(Y))return!0;let X=J+1<$?Math.min(Q*2**(J+1),B):null;A?.onAttemptTimeout?.({attempt:J+1,maxAttempts:$,nextDelayMs:X})}return!1}async loadThreadHistory(A){let Q=await this.threadHistoryLoader(A);if(!Q)return null;let B=Q.title;if(B!==void 0)this.dispatchObserverCallbacks(($)=>{$.onThreadTitle?.({type:"thread_title",title:B})});for(let[$,J]of Q.messages.entries())this.dispatchObserverCallbacks((Y)=>{Y.onMessageAdded?.({type:"message_added",message:J,seq:$})});return Q}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(A,Q,B){let $=B?.messageId??vU0(),J={type:"client_append_user_msg",content:nX(A),agentMode:Q,messageId:$,steer:B?.steer,userState:B?.userState};return this.dispatchObserverCallbacks((Y)=>{Y.onUserMessageSendPending?.($,Date.now())}),this.optimisticUserMessages.emitOptimisticUserMessage(J),this.outbox.send(J),this.retryConnectIfTerminallyDisconnected("user message sent"),$}retryConnectIfTerminallyDisconnected(A){if(this.getConnectionInfo().state!=="disconnected")return;this.retryConnect(A)}removeQueuedMessage(A){this.dispatchObserverCallbacks((Q)=>{Q.onUserActionMessageDeliveryStatusChanged?.(A,"buffered",Date.now())}),this.outbox.send({type:"client_remove_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message remove requested")}steerQueuedMessage(A){this.outbox.send({type:"client_steer_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message steer requested")}editUserMessage(A,Q,B,$){this.outbox.send({type:"client_edit_message",messageId:A,editId:B,content:nX(Q),agentMode:$}),this.retryConnectIfTerminallyDisconnected("user message edit requested")}markMessageRead(A){this.send({type:"client_mark_message_read",messageId:A})}markMessageUnread(A){this.send({type:"client_mark_message_unread",messageId:A})}setThreadTitle(A){this.send({type:"client_set_thread_title",title:A})}upsertNotificationSubscription(A,Q){this.send({type:"client_upsert_notification_subscription",subscription:A,threadURL:Q})}readDirectory(A){return this.requestReadDirectory(A)}readFile(A){return this.requestReadFile(A)}resumeFromVersion(A){this.send({type:"client_resume",version:A}),this.resumeCursor.reset(A)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(A){let Q=A===void 0?{}:{seq:A};if(!this.hasOpenSocket()){this.pendingDismissActiveError=Q;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Q})}cancelAgentLoop(){if(!this.hasOpenSocket()){this.pendingCancelAgentLoop=!0;return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(A){this.send({type:"client_append_manual_bash_invocation",args:nX(A.args),run:nX(A.run),hidden:A.hidden})}resolveToolApproval(A,Q,B){this.send({type:"client_tool_approval_response",toolCallId:A,accepted:Q,input:B})}requestExecutorSpawn(A,Q){this.send({type:"client_spawn_executor",requestId:A,repositoryURL:Q?.repositoryURL,projectID:Q?.projectID,additionalRepositories:Q?.additionalRepositories})}executePluginCommand(A,Q,B,$){this.sendPluginMessage({type:"request",id:A,method:"command.execute",params:{pluginName:Q,commandId:B,threadID:$}})}executorHandshake(A,Q,B){if(this.disposed)throw new T3("Transport is disposed");if(!this.hasOpenSocket()){if(this.getConnectionInfo().state==="connected")this.forceReconnect("executor handshake attempted without open socket");throw new T3("WebSocket is not connected. Call connect() first.")}let $=performance.now(),J=60000,Y={clientId:A,executorType:B?.executorType,timeoutMs:J};return this.log.info("[thread-client] Starting executor handshake",{...Y,connectionState:this.getConnectionInfo().state}),new Promise((Z,X)=>{let F=!1,D=null,G=null,V=()=>Math.round(performance.now()-$),U=(W,z,q)=>{let N=this.getConnectionInfo();this.log.error(W,{...Y,durationMs:V(),connectionState:N.state,role:N.role,reconnectCauseType:N.reconnectCause?.type,reconnectCode:N.reconnectCause?.code,reconnectReason:N.reconnectCause?.reason,error:z,...q})},K=(W)=>{this.log.info("[thread-client] Executor handshake completed",{...Y,durationMs:V(),executorId:W.executorId,registeredToolCount:W.registeredToolCount,resumeBootstrap:W.resumeBootstrap}),H(()=>Z(W))},E=(W)=>{let z=Error(W.message);U("[thread-client] Executor handshake rejected by server",z,{code:W.code}),H(()=>X(z))},H=(W)=>{if(F)return;if(F=!0,D)clearTimeout(D),D=null;this.executorConnectedListeners.delete(K),this.executorErrorListeners.delete(E),G?.unsubscribe(),W()};this.executorConnectedListeners.add(K),this.executorErrorListeners.add(E),G=this.connectionChanges().subscribe({next:(W)=>{if(W.state==="connected")return;let z=new T3(W.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");U("[thread-client] Executor handshake interrupted",z),H(()=>X(z))}}),this.send({type:"executor_connect",clientId:A,capabilities:Q,executorType:B?.executorType}),D=setTimeout(()=>{let W=Error("Executor connect timeout");U("[thread-client] Executor handshake timed out",W),H(()=>X(W))},J)})}ackToolLease(A){this.send({type:"executor_tool_lease_ack",toolCallId:A})}sendToolProgress(A,Q){let B=Yu(Q,"snapshot");this.send({type:"tool_progress",toolCallId:A,progress:B})}sendExecutorToolResult(A,Q){this.send({type:"executor_tool_result",toolCallId:A,run:Q})}sendExecutorFileSystemReadDirectoryResult(A,Q){this.send({type:"executor_filesystem_read_directory_result",requestId:A,...Q})}sendExecutorFileSystemReadFileResult(A,Q){this.send({type:"executor_filesystem_read_file_result",requestId:A,...Q})}sendExecutorToolApprovalRequest(A){this.send({type:"executor_tool_approval_request",approval:A})}sendPluginMessage(A){this.send({type:"executor_plugin_message",message:A})}sendExecutorGuidanceSnapshot(A){this.send({type:"executor_guidance_snapshot",...A})}sendExecutorGuidanceDiscovery(A){this.send({type:"executor_guidance_discovery",...A})}sendExecutorSkillSnapshot(A){this.send({type:"executor_skill_snapshot",...A})}sendClientUpdateThreadSettings(A){if(!this.hasOpenSocket()){this.pendingThreadSettings=A;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch(Q){if(!this.hasOpenSocket()){this.pendingThreadSettings=A;return}throw Q}}registerTools(A){this.send({type:"executor_tools_register",tools:A})}sendExecutorToolsBootstrapComplete(A,Q){this.send({type:"executor_tools_bootstrap_complete",ok:A,error:Q})}sendEnvironmentSnapshot(A){this.send({type:"executor_environment_snapshot",environment:A}),this.environmentSubject.next(A)}sendEnvironmentUpdate(A){this.send({type:"executor_environment_update",environment:A}),this.environmentSubject.next(A)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(A,Q){this.send({type:"executor_artifact_upsert",artifact:A,toolCallId:Q})}sendExecutorArtifactDelete(A){this.send({type:"executor_artifact_delete",key:A})}unregisterTools(A){this.send({type:"executor_tools_unregister",toolNames:A})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outbox.reset(),this.optimisticUserMessages.reset(),this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=s51(0),this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(A){if(super.updateConnectionState(A),A==="connected")this.flushPendingThreadSettings(),this.outbox.retry(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError();if(this.emitConnectionChanged(),A==="reconnecting"||A==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(A){let Q=Er4.safeDecode(A);if(!Q.success){let $=Kr4.safeDecode(A),J=$.success?Q.error:$.error,Y={type:"error",message:Tr4(A,J),code:"PARSE_ERROR"};this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.(Y)});return}let B=Array.isArray(Q.data)?Q.data:[Q.data];for(let $ of B)this.handleServerMessage($)}onMaxReconnectExceeded(A){this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${A} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(A){switch(this.advanceResumeCursor(A),this.reconcileOptimisticUserMessage(A),this.outbox.handleServerMessage(A),A.type){case"agent_state":this.dispatchObserverCallbacks((Q)=>{Q.onAgentState?.(A)});break;case"inference_tools":this.dispatchObserverCallbacks((Q)=>{Q.onInferenceTools?.(A)});break;case"thread_settings":this.dispatchObserverCallbacks((Q)=>{Q.onThreadSettings?.(A)});break;case"error":this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.(A)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Q)=>{Q.onActiveError?.(A)});break;case"cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onCancelled?.(A)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onRetryEvent?.(A)});break;case"delta":this.dispatchObserverCallbacks((Q)=>{Q.onDelta?.(A)});break;case"message_updated":this.dispatchObserverCallbacks((Q)=>{Q.onMessageUpdated?.(A)});break;case"edit_rejected":this.dispatchObserverCallbacks((Q)=>{Q.onEditRejected?.(A)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=A.executorId,this.connectionSubject.next({...this.connectionInfo}),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Q)=>{Q.onExecutorConnected?.(A)});for(let Q of this.executorConnectedListeners)Q(A);break;case"tool_lease":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLease?.(A)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadDirectoryRequest?.(A)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadFileRequest?.(A)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLeaseRevoked?.(A)});break;case"executor_tool_result_ack":this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorToolResultAck?.(A)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Q)=>{Q.onToolApprovalQueue?.(A)});break;case"plugin_message":this.dispatchObserverCallbacks((Q)=>{Q.onPluginMessage?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onPluginMessage?.(A)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorToolApprovalResponse?.(A)});break;case"tool_progress":this.dispatchObserverCallbacks((Q)=>{Q.onToolProgress?.(A)});break;case"executor_error":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorError?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorError?.(A)});for(let Q of this.executorErrorListeners)Q(A);break;case"observers":this.dispatchObserverCallbacks((Q)=>{Q.onObservers?.(A)});break;case"executor_status":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorStatus?.(A)});break;case"environment_update":this.environmentSubject.next(A.environment),this.dispatchObserverCallbacks((Q)=>{Q.onEnvironmentUpdate?.(A)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Q)=>{Q.onArtifactEvent?.(A)});break;case"thread_title":this.dispatchObserverCallbacks((Q)=>{Q.onThreadTitle?.(A)});break;case"thread_relationships":this.dispatchObserverCallbacks((Q)=>{Q.onThreadRelationships?.(A)});break;case"thread_truncated":this.dispatchObserverCallbacks((Q)=>{Q.onTruncate?.(A)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(A);break;case"client_filesystem_read_file_result":this.handleReadFileResult(A);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Q)=>{Q.onCompactionEvent?.(A)});break;case"thread_status":break}}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.hasOpenSocket())return;let A=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch{if(!this.hasOpenSocket())this.pendingThreadSettings=A}}flushPendingCancelAgentLoop(){if(!this.pendingCancelAgentLoop||!this.hasOpenSocket())return;try{this.send({type:"client_cancel"}),this.pendingCancelAgentLoop=!1}catch{if(this.hasOpenSocket())this.pendingCancelAgentLoop=!1}}flushPendingDismissActiveError(){if(!this.pendingDismissActiveError||!this.hasOpenSocket())return;try{this.send({type:"client_dismiss_active_error",...this.pendingDismissActiveError}),this.pendingDismissActiveError=null}catch{if(this.hasOpenSocket())this.pendingDismissActiveError=null}}reconcileOptimisticUserMessage(A){switch(A.type){case"agent_state":this.optimisticUserMessages.setAgentLoopState(A.state);return;case"message_added":this.optimisticUserMessages.reconcileMessageAdded(A);return;case"queued_messages":this.optimisticUserMessages.reconcileQueuedMessagesSnapshot(A);return;case"queued_message_added":this.optimisticUserMessages.reconcileQueuedMessageAdded(A);return;case"queued_message_removed":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;default:return}}trySendOutboxMessage(A){if(!this.hasOpenSocket())return!1;try{return this.send(A),!0}catch(Q){let B=Q instanceof Error?Q.message:String(Q);return this.dispatchObserverCallbacks(($)=>{$.onErrorNotice?.($i5(B))}),!1}}emitConnectionChanged(){let A=this.getConnectionInfo();this.log.info("[thread-client] Emitting connection change callbacks",{state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCode:A.reconnectCause?.code,reconnectReason:A.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Q)=>{Q.onConnectionChange?.(A)}),this.dispatchObserverCallbacks((Q)=>{Q.onConnectionChanged?.(A)})}dispatchObserverCallbacks(A){let Q=this.observerCallbacks;if(!Q){this.pendingObserverDispatches.push(A);return}A(Q)}dispatchExecutorCallbacks(A){let Q=this.executorCallbacks;if(!Q){this.pendingExecutorDispatches.push(A);return}A(Q)}requestReadDirectory(A){let Q=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Q,()=>{this.send({type:"client_filesystem_read_directory",requestId:Q,uri:A})})}requestReadFile(A){let Q=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Q,()=>{this.send({type:"client_filesystem_read_file",requestId:Q,uri:A})})}createPendingReadRequest(A,Q,B){if(!this.hasOpenSocket())return Promise.reject(new T3("WebSocket is not connected"));return new Promise(($,J)=>{let Y=setTimeout(()=>{A.delete(Q),J(new T3(`Filesystem request timed out: ${Q}`))},Qr4);A.set(Q,{resolve:$,reject:J,timeoutID:Y});try{B()}catch(Z){clearTimeout(Y),A.delete(Q),J(Z instanceof Error?Z:Error(String(Z)))}})}nextFileSystemRequestID(A){let Q=this.fileSystemRequestCounter++;return`${A}-${Date.now()}-${Q}`}handleReadDirectoryResult(A){let Q=this.pendingReadDirectoryRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadDirectoryRequests.delete(A.requestId),A.ok&&A.entries){Q.resolve(A.entries);return}if(A.ok){Q.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!A.error){Q.reject(Error("Invalid filesystem read_directory response: missing error"));return}Q.reject(this.createFileSystemError(A.error))}handleReadFileResult(A){let Q=this.pendingReadFileRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadFileRequests.delete(A.requestId),!A.ok&&A.error){Q.reject(this.createFileSystemError(A.error));return}if(!A.ok){Q.reject(Error("Invalid filesystem read_file response: missing error"));return}if(A.contentBase64===void 0){Q.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Q.resolve(Bi5(A.contentBase64))}catch{Q.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(A){return Error(`Filesystem error (${A.code}): ${A.message}`)}rejectPendingFileSystemRequests(A){for(let[Q,B]of this.pendingReadDirectoryRequests)clearTimeout(B.timeoutID),B.reject(new T3(A)),this.pendingReadDirectoryRequests.delete(Q);for(let[Q,B]of this.pendingReadFileRequests)clearTimeout(B.timeoutID),B.reject(new T3(A)),this.pendingReadFileRequests.delete(Q)}advanceResumeCursor(A){if(!("seq"in A)||!Number.isFinite(A.seq))return;this.resumeCursor.advanceFromSeq(A.seq)}send(A){try{this.sendRaw(Ur4.encode(A))}catch(Q){let B=Q instanceof Error?Q.message:String(Q);throw new T3(`Failed to encode thread-protocol message "${A.type}": ${B}`,Q)}}}j1();function X81(A){return{...A,pendingRemoval:!0}}function kr4(A,Q){if(Q.find(($)=>$.queuedMessage.messageId===A.queuedMessage.messageId)?.pendingRemoval!==!0)return A;return X81(A)}function vr4(A,Q,B){if(Q.type==="queued_messages")return Q.messages.map(($)=>kr4($,A));if(Q.type==="queued_message_added"){if(A.find((J)=>J.queuedMessage.messageId===Q.message.queuedMessage.messageId)&&B.dedupeAdded)return[...A];return[...A,kr4(Q.message,A)]}if(!A.some(($)=>$.queuedMessage.messageId===Q.queuedMessageId))return[...A];return A.filter(($)=>$.queuedMessage.messageId!==Q.queuedMessageId)}var yr4={state:"disconnected",role:null,clientId:null};function xr4(A){return[...A].sort((Q,B)=>Q.key.localeCompare(B.key))}function Ji5(A,Q){let B=A.findIndex((J)=>J.key===Q.key);if(B===-1)return xr4([...A,Q]);let $=[...A];return $[B]=Q,$}class pU0{connectionInfo;agentLoopState;pendingSend=new D4(!1);queuedMessages=new D4([]);pendingApprovals=new D4([]);lastError=new D4(null);activeError=new D4(null);cancelledMessageId=new D4(null);retryState=new D4(null);executorError=new D4(null);observers=new D4(null);executorStatus=new D4(null);environment=new D4(null);compactionState=new D4("idle");compactionRecords=new D4([]);artifacts=new D4([]);threadSettings;threadTitle=new D4(void 0);threadId=new D4(null);messageAddedEvents=new r4;messageUpdatedEvents=new r4;deltaEvents=new r4;toolProgressEvents=new r4;truncateEvents=new r4;pluginMessages=new r4;now;dedupeQueuedMessageAdds;compactionRecordsState;constructor(A={}){this.connectionInfo=new D4(A.initialConnectionInfo??yr4),this.agentLoopState=new D4(A.initialAgentLoopState??"idle"),this.threadSettings=new D4(A.initialThreadSettings??null),this.dedupeQueuedMessageAdds=A.dedupeQueuedMessageAdds??!0,this.compactionRecordsState=A.compactionRecordsState??null,this.now=A.now??(()=>new Date().toISOString())}callbacks(){return this}onConnectionChanged(A){this.connectionInfo.next(A)}onAgentState(A){if(w$(A.state))this.pendingSend.next(!1);this.agentLoopState.next(A.state)}onUserMessageSendPending(A,Q){this.pendingSend.next(!0)}onThreadSettings(A){this.threadSettings.next(A.settings)}onMessageAdded(A){this.messageAddedEvents.next(A)}onMessageUpdated(A){this.messageUpdatedEvents.next(A)}onDelta(A){this.deltaEvents.next(A)}onToolProgress(A){this.toolProgressEvents.next(A)}onTruncate(A){this.truncateEvents.next(A)}onPluginMessage(A){this.pluginMessages.next(A)}onQueuedMessages(A){this.queuedMessages.next(vr4(this.queuedMessages.getValue(),A,{dedupeAdded:this.dedupeQueuedMessageAdds}))}onUserActionMessageDeliveryStatusChanged(A,Q,B){if(Q!=="buffered")return;let $=this.queuedMessages.getValue(),J=$.findIndex((X)=>X.queuedMessage.messageId===A);if(J===-1)return;let Y=$[J];if(!Y)return;let Z=[...$];Z[J]=X81(Y),this.queuedMessages.next(Z)}onToolApprovalQueue(A){this.pendingApprovals.next(A.approvals)}onErrorNotice(A){this.clearPendingSendIfIdle(),this.lastError.next(A)}onActiveError(A){if(A.type==="error_set")this.clearPendingSendIfIdle();this.cancelledMessageId.next(null),this.activeError.next(A.type==="error_set"?A.error:null)}onCancelled(A){this.cancelledMessageId.next(A.messageId??null),this.activeError.next(null)}onExecutorError(A){this.executorError.next(A)}onRetryEvent(A){this.retryState.next(A)}onObservers(A){this.observers.next({count:A.count,observers:A.observers,hasExecutor:A.hasExecutor??!1})}onExecutorStatus(A){if(this.executorStatus.next(A),A.status==="running")this.executorError.next(null)}onEnvironmentUpdate(A){this.environment.next(A.environment)}onArtifactEvent(A){let Q=this.artifacts.getValue();switch(A.type){case"artifacts_snapshot":this.artifacts.next(xr4(A.artifacts));return;case"artifact_upserted":this.artifacts.next(Ji5(Q,A.artifact));return;case"artifact_deleted":this.artifacts.next(Q.filter((B)=>B.key!==A.key));return}}onCompactionEvent(A){if(A.type==="compaction_started"){this.compactionState.next("compacting");return}if(A.type==="compaction_complete"){this.compactionState.next("idle"),this.addCompactionRecord({cutMessageId:A.cutMessageId,createdAt:this.now()});return}if(this.compactionRecords.next(A.records),this.compactionRecordsState!==null)this.compactionState.next(this.compactionRecordsState)}onThreadTitle(A){this.threadTitle.next(A.title||void 0)}onThreadId(A){this.threadId.next(A)}resetRuntimeState(){this.connectionInfo.next(yr4),this.agentLoopState.next("idle"),this.pendingSend.next(!1),this.queuedMessages.next([]),this.pendingApprovals.next([]),this.activeError.next(null),this.executorError.next(null),this.cancelledMessageId.next(null),this.retryState.next(null),this.observers.next(null),this.executorStatus.next(null),this.environment.next(null),this.compactionState.next("idle"),this.artifacts.next([])}dispose(){this.connectionInfo.complete(),this.agentLoopState.complete(),this.pendingSend.complete(),this.queuedMessages.complete(),this.pendingApprovals.complete(),this.lastError.complete(),this.activeError.complete(),this.cancelledMessageId.complete(),this.retryState.complete(),this.executorError.complete(),this.observers.complete(),this.executorStatus.complete(),this.environment.complete(),this.compactionState.complete(),this.compactionRecords.complete(),this.artifacts.complete(),this.threadSettings.complete(),this.threadTitle.complete(),this.threadId.complete(),this.messageAddedEvents.complete(),this.messageUpdatedEvents.complete(),this.deltaEvents.complete(),this.toolProgressEvents.complete(),this.truncateEvents.complete(),this.pluginMessages.complete()}addCompactionRecord(A){let Q=this.compactionRecords.getValue();if(Q.some((B)=>B.cutMessageId===A.cutMessageId))return;this.compactionRecords.next([...Q,A])}clearPendingSendIfIdle(){if(this.pendingSend.getValue()&&!w$(this.agentLoopState.getValue()))this.pendingSend.next(!1)}}i0();function dU0(A){let{client:Q,observer:B,toolService:$,callbacks:J}=A,Y=new Set,Z=[],X=!1,F=!1,D=null,G=!1,V=[],U=setInterval(()=>{},1000),E=Qu(()=>{if(G)return;j.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{Q.cancelAgentLoop()}catch(W){j.warn("Failed to cancel remote agent loop on signal",{error:W})}J.onSignal()});return E.install(),V.push(B.activeError$.subscribe((W)=>{if(!W)return;J.onError(W.message)})),V.push(B.errorNotice$.subscribe((W)=>{J.onError(W)})),V.push($.pendingApprovals$.subscribe((W)=>{Z=W})),V.push(B.agentState$.subscribe((W)=>{D=W.state;let z=w$(W.state);if(z&&W.messageId)Y.add(W.messageId);if(z){X=!0,F=!0;return}if(F=!1,!X)return;J.onTransitionToIdle(Z)})),V.push(B.messageAdded$.subscribe((W)=>{J.onMessageAdded(W)})),{currentTurnAssistantIds:Y,pendingApprovals:()=>Z,agentStarted:()=>X,agentActive:()=>F,agentIdle:()=>D==="idle",dispose:()=>{if(G)return;G=!0,E.remove(),clearInterval(U);for(let W of V)W.unsubscribe()}}}import Yi5 from"node:process";var F81=Number(Yi5.env.SIMULATE_LATENCY??0),Zi5=Number.isFinite(F81)&&F81>0?F81:0;function Xu(A,Q){let B=Q;return async()=>{let $=await A(B);return B=$.threadId,$}}function Fu(A){let Q=yK({endpoint:A.rivetEndpoint});return{...A.initialThreadID?{threadId:A.initialThreadID}:{},...A.maxReconnectAttempts!==void 0?{maxReconnectAttempts:A.maxReconnectAttempts}:{},pingIntervalMs:A.pingIntervalMs??5000,webSocketLatencyMs:()=>Zi5,webSocketProvider:async()=>{let B=await A.credentialsProvider({forceRefresh:!0});return{webSocket:await Q.threadActor.getOrCreate([B.threadId],{params:{wsToken:B.wsToken},createWithInput:{threadId:B.threadId,threadVersion:B.threadVersion,ownerUserId:B.ownerUserId,...B.agentMode?{agentMode:B.agentMode}:{}}}).webSocket("/"),threadId:B.threadId}}}}AA();function cU0(A){let Q=A.agentMode||dc(A);if(!Q)throw Error("agent mode could not be determined from thread");return{version:A.v,title:A.title??null,messages:A.messages.map((B)=>ur4(A,B)),agentMode:Q,needsImport:!Fi5(A)}}function br4(A){let Q=A.agentMode||dc(A);if(!Q)throw Error("agent mode could not be determined from thread");return{id:A.id,v:A.v,...A.title?{title:A.title}:{},messages:A.messages.map((B)=>Xi5(A,B)),agentMode:Q,...A.meta?{meta:A.meta}:{}}}function Xi5(A,Q){let{threadId:B,...$}=ur4(A,Q);return $}function Fi5(A){if(!A.meta||typeof A.meta!=="object")return!1;return A.meta.usesThreadActors===!0}function ur4(A,Q){let B=Di5(Q);switch(Q.role){case"user":return{threadId:A.id,role:"user",content:[...Q.content],meta:s90(Q.meta),userState:Gi5(Q.userState),readAt:Q.readAt,messageId:B};case"assistant":return{threadId:A.id,role:"assistant",content:[...Q.content],state:Q.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Q.usage,readAt:Q.readAt,messageId:B};case"info":return{threadId:A.id,role:"info",content:Q.content.filter(Vi5),messageId:B}}}function Di5(A){let Q=fr4(A.protocolMessageID);if(Q)return Q;let B=A.messageId;if(typeof B==="string"){let $=fr4(B);if($)return $}return vU0()}function fr4(A){if(!A)return null;let Q=Z5.safeParse(A);return Q.success?Q.data:null}function Gi5(A){if(!A)return;return{...A,currentlyVisibleFiles:[...A.currentlyVisibleFiles],runningTerminalCommands:A.runningTerminalCommands?[...A.runningTerminalCommands]:void 0,aggmanContext:A.aggmanContext?{...A.aggmanContext,availableProjects:A.aggmanContext.availableProjects?A.aggmanContext.availableProjects.map((Q)=>({...Q})):void 0,recentUnreadThreads:A.aggmanContext.recentUnreadThreads?A.aggmanContext.recentUnreadThreads.map((Q)=>({...Q})):void 0}:void 0}}function Vi5(A){return A.type==="manual_bash_invocation"}eQ();H4();import Ye from"node:path";class _P extends Error{code;constructor(A,Q){super(Q);this.code=A;this.name="ExecutorFileSystemPathError"}}function gr4(A,Q){let B=J1.parse(A);if(B.scheme!=="file")throw new _P("INVALID_URI","Only file:// URIs are supported");if(!B.path.startsWith("/"))throw new _P("INVALID_URI","File URI path must be absolute");if(B.path.split("/").some((F)=>F===".."))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");let J=Ye.posix.normalize(B.path).replace(/^\/+/u,"");if(J===".."||J.startsWith("../"))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");let Y=Ye.resolve(Q),Z=J.length>0?Ye.resolve(Y,J):Y,X=Ye.relative(Y,Z);if(X.startsWith("..")||Ye.isAbsolute(X))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");return Z}async function hw(A,Q){try{let B=gr4(Q,A.workspaceRoot),$=await A.fileSystem.readdir(J1.file(B));return{ok:!0,entries:await Promise.all($.map(async(Y)=>{let Z=Y.isDirectory?"directory":"file",X=Z==="file"?await Ui5(A.fileSystem,Y.uri):void 0;return[K1.basename(Y.uri),Z,X]}))}}catch(B){return{ok:!1,error:pr4(B,"read_directory")}}}async function Ui5(A,Q){try{let B=await A.getMtime(Q);if(!Number.isFinite(B)||B<0)return;return{mtimeMs:B}}catch{return}}async function mr4(A,Q){try{let B=gr4(Q,A.workspaceRoot),$=await A.fileSystem.readBinaryFile(J1.file(B));return{ok:!0,contentBase64:Buffer.from($).toString("base64")}}catch(B){return{ok:!1,error:pr4(B,"read_file")}}}function pr4(A,Q){if(A instanceof _P)return{code:A.code,message:A.message};if(d3(A))return{code:"NOT_FOUND",message:"File or directory not found"};if(lU0(A,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(lU0(A,"ENOTDIR"))return{code:Q==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Q==="read_directory"?"Expected a directory":hr4(A)};if(lU0(A,"EACCES")||lU0(A,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:hr4(A)}}function lU0(A,Q){if(!(A instanceof Error))return!1;return"code"in A&&A.code===Q}function hr4(A){if(A instanceof Error)return A.message;return String(A)}i0();g5();XY0();AA();H4();j1();i0();function iU0(A){return(Q)=>{let B=Q.message;if(B.type!=="request")return;Ki5(A.pluginService,B.method,B.params).then(($)=>A.sendPluginMessage(dr4(B.id,$))).catch(($)=>{j.debug("Plugin hook dispatcher request failed",{method:B.method,id:B.id,error:$}),A.sendPluginMessage(dr4(B.id,void 0,$ instanceof Error?$.message:String($)))})}}function dr4(A,Q,B){if(B!==void 0)return{type:"response",id:A,error:B};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}async function Ki5(A,Q,B){switch(Q){case"agent.start":{let{event:$}=B;return await A.event.agentStart($)}case"agent.end":{let{event:$}=B;return await A.event.agentEnd($)}case"command.execute":{let{pluginName:$,commandId:J,threadID:Y}=B;return await A.commands.execute($,J,Y?{threadID:Y}:void 0),{ok:!0}}default:throw Error(`Unknown plugin hook method: ${Q}`)}}import{exec as Ei5}from"node:child_process";import{promisify as Hi5}from"node:util";TU();AA();H4();var Wi5=Hi5(Ei5);async function cr4(A){let Q=await bW(),B=W7(A)?A:G9(),$=await oD({filesystem:e5},Q,B),J=await zi5($.workingDirectory??$.workspaceRoot);return{...Q,...$,...J?{git:{branch:J}}:{},updatedAt:new Date().toISOString()}}async function zi5(A){if(!A)return;let Q;try{Q=J1.parse(A).fsPath}catch{return}try{let{stdout:B}=await Wi5("git symbolic-ref --quiet --short HEAD",{cwd:Q});return B.trim()||void 0}catch{return}}function qi5(A){return new TextEncoder().encode(JSON.stringify(A)).length}function Du(A,Q,B){if(A.length===0)return[];let $=[],J=[];for(let Y of A){let Z=[...J,Y],X=qi5(B(Z));if(J.length>0&&X>Q){$.push(J),J=[Y];continue}J=Z}if(J.length>0)$.push(J);return $}var ir4=1048576;function lr4(A){let Q=new Map;for(let B of A)Q.set(B.name,{schema:B,serializedSchema:JSON.stringify(B)});return Q}function Ni5(A){let Q={...A.executionProfile?.serial!==void 0?{serial:A.executionProfile.serial}:{},...A.meta?.deferred!==void 0?{deferred:A.meta.deferred}:{},...A.meta?.skillNames!==void 0?{skillNames:[...A.meta.skillNames]}:{}};return Object.keys(Q).length>0?Q:void 0}function Ii5(A){return{name:A.name,description:A.description??"",inputSchema:{type:"object",properties:A.inputSchema.properties??{},required:A.inputSchema.required,additionalProperties:A.inputSchema.additionalProperties},source:A.source,meta:Ni5(A)}}function nU0(A){return A.map((Q)=>Ii5(Q.spec))}function nr4(A,Q){let B=lr4(A),$=lr4(Q);return{toolsToRegister:Q.filter((J)=>{let Y=B.get(J.name),Z=$.get(J.name);return Y?.serializedSchema!==Z?.serializedSchema}),toolNamesToUnregister:[...B.keys()].filter((J)=>!$.has(J))}}function ar4(A,Q=ir4){return Du(A,Q,(B)=>({type:"executor_tools_register",tools:B}))}function or4(A,Q=ir4){return Du(A,Q,(B)=>({type:"executor_tools_unregister",toolNames:B}))}import{execFile as Oi5}from"node:child_process";import{createHash as ji5}from"node:crypto";import{readFile as Ri5,stat as Pi5}from"node:fs/promises";import{basename as _i5,join as Ti5}from"node:path";import $s4 from"node:process";import{promisify as Si5}from"node:util";async function rr4(A,Q,B){let $=[];for(let J=0;J<A.length;J+=Q){let Y=A.slice(J,J+Q);$.push(...await Promise.all(Y.map(B)))}return $}var sr4=2097152,gw="(Content omitted — git status artifact exceeds size limit)";function wi5(A){return(A.fullFileDiff?.length??0)+(A.oldContent?.length??0)+(A.newContent?.length??0)}function Ci5(A){let Q=!1;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==A.diff)A.fullFileDiff=A.diff,Q=!0;if(A.oldContent!==void 0&&A.oldContent!==gw)A.oldContent=gw,Q=!0;if(A.newContent!==void 0&&A.newContent!==gw)A.newContent=gw,Q=!0;return Q}function Mi5(A){let Q=!1;if(A.oldContent!==void 0)A.oldContent=void 0,Q=!0;if(A.newContent!==void 0)A.newContent=void 0,Q=!0;if(A.fullFileDiff!==void 0)A.fullFileDiff=void 0,Q=!0;return Q}function Li5(A){let Q=!1;if(A.diff!==gw)A.diff=gw,Q=!0;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==gw)A.fullFileDiff=gw,Q=!0;return Q}function Gu(A){let Q=Buffer.from(JSON.stringify(A),"utf8").toString("base64"),B=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:Yx,dataType:"application/json",contentBase64:Q}})).length;return{contentBase64:Q,messageSizeBytes:B}}function tr4(A,Q){let B={...A,aheadCommits:[...A.aheadCommits],files:A.files.map((Z)=>({...Z}))},$=Gu(B);if($.messageSizeBytes<=Q)return $.contentBase64;let J=B.files.map((Z,X)=>({index:X,weight:wi5(Z)})).filter((Z)=>Z.weight>0).sort((Z,X)=>X.weight-Z.weight);for(let{index:Z}of J){let X=B.files[Z];if(!X||!Ci5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}for(let{index:Z}of J){let X=B.files[Z];if(!X||!Mi5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}let Y=B.files.map((Z,X)=>({index:X,weight:Z.diff.length+(Z.fullFileDiff?.length??0)})).filter((Z)=>Z.weight>0).sort((Z,X)=>X.weight-Z.weight);for(let{index:Z}of Y){let X=B.files[Z];if(!X||!Li5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}if(B.aheadCommits.length>0){if(B.aheadCommits=[],$=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}while(B.files.length>0)if(B.files.pop(),$=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64;return $.contentBase64}var ki5=Si5(Oi5),Uu=20971520,vi5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],aU0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],yi5=999999,er4="refs/remotes/origin/",xi5=20,fi5=10;function oU0(A){return A.replace(/\n+$/,"")}var D81=$s4.platform==="win32"?"NUL":"/dev/null";function bi5(A=$s4.env,Q={}){let{isolateGitConfig:B=!0}=Q,$={...A};if(B){for(let J of Object.keys($))if(vi5.includes(J)||J.startsWith("GIT_CONFIG_KEY_")||J.startsWith("GIT_CONFIG_VALUE_"))delete $[J];$.GIT_CONFIG_NOSYSTEM="1",$.GIT_CONFIG_SYSTEM=D81,$.GIT_CONFIG_GLOBAL=D81}return $}function As4(A,Q){return{provider:"git",capturedAt:A,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Q}}function ui5(A){return A instanceof Error}async function Vu(A,Q,B={}){try{let{stdout:$}=await ki5("git",Q,{cwd:A,env:bi5(),maxBuffer:B.maxBufferBytes??Uu});return $}catch($){if(B?.allowExitCodeOne&&ui5($)&&($.code===1||$.code==="1")&&typeof $.stdout==="string")return $.stdout;throw $}}async function Qz(A,Q){try{return await Vu(A,Q)}catch{return null}}function hi5(A){if(A==="??")return"untracked";let Q=A[0]??" ",B=A[1]??" ";if(Q==="U"||B==="U"||A==="AA"||A==="DD")return"unmerged";if(Q==="R"||B==="R")return"renamed";if(Q==="C"||B==="C")return"copied";if(Q==="A"||B==="A")return"added";if(Q==="D"||B==="D")return"deleted";if(Q==="T"||B==="T")return"type_changed";return"modified"}function G81(A){let Q=[],B=A.split("\x00");for(let $=0;$<B.length;$++){let J=B[$];if(!J||J.length<4)continue;let Y=J.slice(0,2),Z=J.slice(3);if(!Z)continue;let X=hi5(Y);if(X==="renamed"||X==="copied"){let F=B[$+1];if(F){Q.push({path:Z,previousPath:F,changeType:X}),$+=1;continue}}Q.push({path:Z,changeType:X})}return Q.sort(($,J)=>$.path.localeCompare(J.path))}function gi5(A){let Q=0,B=0,$=0,J=0,Y=0,Z=()=>{if(J===0&&Y===0)return;$+=Math.min(J,Y),J=0,Y=0};for(let X of A.split(`
4566
+ `)}function Oo4(A){return A==="in-progress"||A==="queued"}function jo4(A,Q){let B=[...A],$=new Set(B.map((J)=>`${J.kind}:${J.title}`));for(let J of no4(Q)){let Y=`${J.kind}:${J.title}`;if($.has(Y))continue;$.add(Y),B.push(J)}return B}function no4(A){return Ip5(A).map((Q)=>({kind:"read",title:`Read ${OJ(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function Ip5(A){if(A.status!=="done"||!iJ(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap((B)=>{if(!iJ(B)||typeof B.uri!=="string"||typeof B.lineCount!=="number"||!Number.isFinite(B.lineCount))return[];return[{uri:B.uri,lineCount:B.lineCount,...typeof B.content==="string"?{content:B.content}:{}}]})}function wp5(A){let Q="result"in A&&iJ(A.result)?A.result:void 0,B=go4("progress"in A?A.progress:void 0),$=iJ(B)?B:void 0;return{main:(iJ(Q?.main)?Q.main:void 0)??(iJ($?.main)?$.main:void 0),checks:(iJ(Q?.checks)?Q.checks:void 0)??(iJ($?.checks)?$.checks:void 0)}}function Cp5(A,Q){let B=[],$=new Set,J=(G)=>{let V=`${G.kind}:${G.title}`;if($.has(V))return;$.add(V),B.push(G)},{main:Y,checks:Z}=wp5(A);if(A.status==="queued")J({kind:"explore",title:"Code review queued"});if(A.status==="error"){let G=o2(A)??"Unknown error";J({kind:"explore",title:`Code review failed: ${G}`})}let X=0,F=0;for(let[G,V]of Object.entries(Z??{})){if(!iJ(V))continue;F+=1;let U=zp5(G,V);if(V.status==="done"){X+=1;let K=qp5(V);if(K===void 0)J({kind:"explore",title:`Check ${U}: complete`});else if(K===0)J({kind:"explore",title:`Check ${U}: ok`});else J({kind:"explore",title:`Check ${U}: ${K} ${W4(K,"issue")} found`});continue}if(V.status==="error"){X+=1;let K=typeof V.error==="string"&&V.error.trim()?V.error.trim():"Unknown error";J({kind:"explore",title:`Check ${U}: error (${K})`});continue}if(V.status==="in-progress"){let K=typeof V.message==="string"&&V.message.trim()?V.message.trim():"Running check...";J({kind:"explore",title:`Check ${U}: ${K}`})}}if(Y?.status==="done"&&F>0&&X<F)J({kind:"explore",title:"Main review complete, running checks..."});if(A.status==="done")J({kind:"explore",title:"Code review complete"});if(B.length===0)J({kind:"explore",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let D=Q.thinking==="low"?"quick code review":"code review";return{actions:B,summary:F>0?`${X}/${F} checks · ${D}`:D}}function Ro4(A,Q=""){let B=0,$=0,J=new Map;for(let Z of A){if(Z.icon==="docs"&&(Z.title.startsWith("Read ")||Z.title.startsWith("Load "))){B++;continue}if(Z.title.startsWith("Read skill ")){$++;continue}J.set(Z.kind,(J.get(Z.kind)??0)+1)}let Y=[];for(let[Z,X,F]of[["read","file",void 0],["web-page","web page","web pages"],["thread","thread",void 0],["skill","skill",void 0],["guidance","guidance file","guidance files"],["search","search","searches"],["web","web search","web searches"],["explore","exploration",void 0],["list","list",void 0]]){let D=Z==="guidance"?B:Z==="skill"?$:J.get(Z);if(!D)continue;Y.push(`${D} ${W4(D,X,F)}`)}if(Y.length>0)return Y.join(", ");return Q}function Mp5(A){if(A.kind==="search"&&Lp5(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return VD0(A)}function Lp5(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function iJ(A){return typeof A==="object"&&A!==null}class kU0{originalGuidanceFiles=new Map;toolOrder=new Map;nextToolOrder=0;firstToolForGuidanceFile=new Map;recordToolOrder(A){if(!this.toolOrder.has(A))this.toolOrder.set(A,++this.nextToolOrder)}applyToolResult(A,Q){let B=this.originalGuidanceFiles.get(A)??[],$=new Set(Q.map((X)=>X.uri)),J=new Set;for(let X of B){if($.has(X.uri))continue;if(this.firstToolForGuidanceFile.get(X.uri)!==A)continue;this.firstToolForGuidanceFile.delete(X.uri);let F=this.findEarlierToolListing(X.uri,A);if(F!==void 0)this.firstToolForGuidanceFile.set(X.uri,F),J.add(F)}if(Q.length>0)this.originalGuidanceFiles.set(A,Q);else this.originalGuidanceFiles.delete(A);let Y=this.toolOrder.get(A)??Number.POSITIVE_INFINITY,Z=[];for(let X of Q){let F=this.firstToolForGuidanceFile.get(X.uri);if(F===void 0||F===A){this.firstToolForGuidanceFile.set(X.uri,A),Z.push(X);continue}let D=this.toolOrder.get(F)??Number.POSITIVE_INFINITY;if(Y<D)this.firstToolForGuidanceFile.set(X.uri,A),J.add(F),Z.push(X)}return J.delete(A),{myDedupedFiles:Z,needsRebuild:J}}dedupedFilesFor(A){return(this.originalGuidanceFiles.get(A)??[]).filter((B)=>this.firstToolForGuidanceFile.get(B.uri)===A)}cleanupRemovedTools(A){for(let Q of this.toolOrder.keys())if(!A.has(Q))this.toolOrder.delete(Q);return this.cleanupRemovedToolResults(A)}cleanupRemovedToolResults(A){for(let $ of this.originalGuidanceFiles.keys())if(!A.has($))this.originalGuidanceFiles.delete($);let Q=[];for(let[$,J]of this.firstToolForGuidanceFile)if(!A.has(J))Q.push($);let B=new Set;for(let $ of Q){this.firstToolForGuidanceFile.delete($);let J=this.findEarlierToolListing($,void 0);if(J!==void 0)this.firstToolForGuidanceFile.set($,J),B.add(J)}return B}findEarlierToolListing(A,Q){let B=Number.POSITIVE_INFINITY,$;for(let[J,Y]of this.originalGuidanceFiles){if(J===Q)continue;if(!Y.some((X)=>X.uri===A))continue;let Z=this.toolOrder.get(J)??Number.POSITIVE_INFINITY;if(Z<B)B=Z,$=J}return $}}g5();YQ();function v51(A){let Q=A.replace(/-/g,"");if(Q.length!==32)throw Error(`Invalid UUID hex length: ${Q.length}`);let B=BigInt("0x"+Q),$="";while(B>0n)$="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(B%62n)]+$,B=B/62n;return $.padStart(22,"0")}F8();by();H4();If0();YQ();var O8=k.string().min(1),bw=O8.brand(),x51=k.string().regex(/^[0-9A-Za-z]{22}$/),Op5=k.templateLiteral([k.string().regex(/^[0-9a-f]{8}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{4}$/),"-",k.string().regex(/^[0-9a-f]{12}$/)]),tt=k.templateLiteral(["T-",Op5]),jp5=k.enum(["fork","handoff","mention"]),Rp5=k.enum(["parent","child"]),ao4=k.object({threadID:tt,type:jp5,role:Rp5,messageIndex:k.number().int().nonnegative().optional(),blockIndex:k.number().int().nonnegative().optional(),createdAt:k.number().int().nonnegative(),comment:k.string().optional()}),Z5=k.templateLiteral(["M-",x51]);function vU0(){return`M-${v51(Yv())}`}var S3=k.templateLiteral(["TU-",x51]);var oo4=k.templateLiteral(["E-",x51]);function ro4(){return`E-${v51(Yv())}`}var Pp5=k.looseObject({type:k.literal("object"),properties:k.record(k.string(),k.unknown()),required:k.array(k.string()).optional(),additionalProperties:k.boolean().optional()}),_p5=k.union([k.literal("builtin"),k.object({toolbox:O8}).strict(),k.object({mcp:O8,target:k.enum(["global","workspace","flag","default"]).optional()}).strict(),k.object({plugin:O8}).strict(),k.object({remote:O8}).strict()]),Tp5=k.object({serial:k.boolean().optional(),deferred:k.boolean().optional(),skillNames:k.array(O8).optional()}),so4=k.looseObject({name:O8,description:k.string(),inputSchema:Pp5,source:_p5,meta:Tp5.optional()}),as3=k.object({id:O8,category:O8,title:O8,description:k.string().optional(),pluginName:O8}),yU0=k.strictObject({"agent.skipTitleGenerationIfMessageContains":k.array(k.string()).optional(),"anthropic.thinking.enabled":k.boolean().optional(),"anthropic.interleavedThinking.enabled":k.boolean().optional(),"anthropic.temperature":k.number().optional(),"anthropic.speed":k.enum(["standard","fast"]).optional(),"anthropic.provider":k.enum(["anthropic","vertex"]).optional(),"openai.speed":k.enum(["standard","fast"]).optional(),"painter.model":k.enum(["gemini-3-pro-image","gpt-image-2"]).optional(),"reasoning.effort":k.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),"internal.compactionThresholdPercent":k.number().min(0).max(100).optional(),"internal.model":k.union([k.string(),k.record(k.string(),k.string())]).optional(),"internal.oracleReasoningEffort":k.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":k.enum(["minimal","low","medium","high"]).optional(),"tools.disable":k.array(k.string()).optional(),"tools.enable":k.array(k.string()).optional()}),to4=k.object({workspaceId:k.string(),workingDirectory:k.string(),environment:k.object({os:k.enum(["darwin","linux","windows"]),hasDocker:k.boolean().optional(),hasBrowser:k.boolean().optional()}).strict(),tags:k.array(k.string())}).strict(),eo4=k.enum(["sandbox","local-client"]),et=k.any().and(k.object({status:k.string()})),Ar4=k.discriminatedUnion("type",[k.object({type:k.literal("delta"),blocks:k.array(k.unknown()).optional(),state:k.enum(["start","generating","tool_use","complete","error","aborted"])}),k.object({type:k.literal("snapshot"),value:k.unknown()})]),gK=O8,Qr4=30000,Ju=ND,Sp5=k.enum(["file","directory"]),kp5=k.object({mtimeMs:k.number().nonnegative().optional()}),Ae=k.tuple([k.string(),Sp5,kp5.nullish()]),vp5=k.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),uw=k.object({code:vp5,message:k.string()}),yp5=k.object({ok:k.literal(!0),entries:k.array(Ae)}),xp5=k.object({ok:k.literal(!1),error:uw}),os3=k.discriminatedUnion("ok",[yp5,xp5]),fp5=k.object({ok:k.literal(!0),contentBase64:k.string()}),bp5=k.object({ok:k.literal(!1),error:uw}),rs3=k.discriminatedUnion("ok",[fp5,bp5]),up5=O8,f51=k.object({key:O8,dataType:up5,contentBase64:k.string()}),b51=f51.extend({toolCallId:S3.optional(),updatedAt:k.string()}),u51=k.looseObject({uri:ND,content:k.string().optional(),lineCount:k.int().optional(),hash:k.string().optional()}),hp5=k.enum(HU4),Br4=k.object({path:ND,error:k.string(),hint:k.string().optional()}),$r4=k.object({uri:ND,hash:k.string(),lineCount:k.int().optional()}),Jr4=k.object({name:O8,description:k.string(),baseDir:ND,frontmatter:k.object({name:O8,description:k.string()}).catchall(k.unknown()),files:k.array(k.string()).optional(),source:hp5.optional()}),h51=k.object({type:k.literal("text"),text:k.string(),hidden:k.boolean().optional()}),Yr4=k.looseObject({type:k.literal("image"),source:k.discriminatedUnion("type",[k.object({type:k.literal("base64"),mediaType:k.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:k.string()}),k.object({type:k.literal("url"),url:k.string()})]),sourcePath:k.string()}),Qe=k.array(k.discriminatedUnion("type",[h51,Yr4])),$u=k.record(k.string(),k.unknown()),Zr4=k.object({type:k.literal("tool_use"),id:k.string().min(1),name:k.string().min(1),normalizedName:k.string().optional(),metadata:k.record(k.string(),k.unknown()).optional()}),gp5=Zr4.extend({complete:k.literal(!0),input:$u,normalizedInput:$u.optional()}),mp5=Zr4.extend({complete:k.literal(!1),input:$u,inputIncomplete:$u,inputPartialJSON:k.object({json:k.string()}),normalizedInput:$u.optional()}),pp5=k.object({accepted:k.boolean(),askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}),dp5=k.object({type:k.literal("tool_result"),toolUseID:k.string().min(1),run:et,userInput:pp5.optional()}),cp5=k.object({type:k.literal("thinking"),thinking:k.string(),signature:k.string()}),lp5=k.object({type:k.literal("redacted_thinking"),data:k.string()}),ip5=k.object({type:k.literal("server_tool_use"),id:k.string().min(1),name:k.string().min(1),input:$u}),np5=k.object({type:k.literal("manual_bash_invocation"),args:k.object({cmd:k.string(),args:k.array(k.string()).readonly().optional(),cwd:k.string().optional()}),toolRun:et,hidden:k.boolean().optional()}),g51=k.object({sentAt:k.number().int().nonnegative().optional(),fromAggman:k.boolean().optional(),fromExecutorThreadID:tt.optional()}),ap5=k.union([h51,Yr4,dp5]),op5=k.union([h51,cp5,lp5,gp5,mp5,ip5]),m51=k.array(ap5),p51=k.array(op5),rp5=k.array(np5),y51=k.looseObject({line:k.number().int(),column:k.number().int()}),sp5=k.looseObject({start:y51,end:y51}),tp5=k.looseObject({name:k.string(),repositoryURL:k.string()}),ep5=k.looseObject({currentURL:k.string(),availableProjects:k.array(tp5).optional()}),d51=k.looseObject({currentlyVisibleFiles:k.array(ND),runningTerminalCommands:k.array(k.string()).optional(),activeEditor:k.any().optional(),cursorLocation:y51.optional(),cursorLocationLine:k.string().optional(),selectionRange:sp5.optional(),aggmanContext:ep5.optional()}),PP=k.custom((A)=>typeof A==="string"&&N3(A)!==void 0),Ad5=k.object({threadId:tt,role:k.literal("user"),content:m51,agentMode:PP.optional(),meta:g51.optional(),userState:d51.optional(),readAt:k.string().nullable().optional(),messageId:Z5,createdAt:k.string().optional()}),c51=k.object({model:k.string().optional(),maxInputTokens:k.number(),inputTokens:k.number(),outputTokens:k.number(),cacheCreationInputTokens:k.number().nullable(),cacheReadInputTokens:k.number().nullable(),totalInputTokens:k.number(),thinkingBudget:k.number().optional(),timestamp:k.string().optional()}),Qd5=k.union([k.object({type:k.literal("complete")}),k.object({type:k.literal("cancelled")})]),Bd5=k.object({threadId:tt,role:k.literal("assistant"),content:p51,state:Qd5.optional(),usage:c51.optional(),readAt:k.string().nullable().optional(),messageId:Z5,createdAt:k.string().optional()}),$d5=k.object({threadId:tt,role:k.literal("info"),content:rp5,messageId:Z5,createdAt:k.string().optional()}),l51=k.discriminatedUnion("role",[Ad5,Bd5,$d5]),Be=k.object({workspaceRoot:ND.optional(),workingDirectory:ND.optional(),rootDirectoryListing:k.string().nullable().optional(),trees:k.array(k.any()).optional(),platform:k.any().optional(),tags:k.array(k.string()).optional(),git:k.object({branch:k.string().optional()}).optional(),updatedAt:k.string().optional()}),Jd5=k.object({added:k.number().int().nonnegative(),deleted:k.number().int().nonnegative(),changed:k.number().int().nonnegative()}),Yd5=k.object({path:k.string(),previousPath:k.string().optional(),changeType:k.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:k.boolean(),diff:k.string(),fullFileDiff:k.string().optional(),oldContent:k.string().optional(),newContent:k.string().optional(),diffStat:Jd5}),Zd5=k.object({hash:k.string(),shortHash:k.string(),subject:k.string()}),Xr4=k.object({provider:k.literal("git"),capturedAt:k.number(),available:k.boolean(),repositoryRoot:k.string().nullable(),repositoryName:k.string().nullable(),branch:k.string().nullable(),head:k.string().nullable(),baseRef:k.string().nullable().optional(),baseRefHead:k.string().nullable().optional(),aheadCount:k.number().int().nonnegative().optional(),behindCount:k.number().int().nonnegative().optional(),aheadCommits:k.array(Zd5).optional(),diffHash:k.string().optional(),files:k.array(Yd5),unavailableReason:k.string().optional(),unchanged:k.boolean().optional()}),xU0=k.object({id:k.string(),toolCallId:S3,toolName:k.string(),args:k.record(k.string(),k.unknown()),reason:k.string().optional(),toAllow:k.array(k.string()).optional(),context:k.enum(["thread","subagent"]),subagentToolName:k.string().optional(),parentToolCallId:S3.optional(),timestamp:k.number(),matchedRule:k.object({tool:k.string(),action:k.string(),matches:k.record(k.string(),k.unknown()).optional()}).optional(),ruleSource:k.enum(["user","built-in"]).optional()}),Xd5=k.object({type:k.literal("request"),id:O8,method:O8,params:k.unknown()}),Fd5=k.object({type:k.literal("response"),id:O8,result:k.unknown().optional(),error:k.string().optional()}),Dd5=k.object({type:k.literal("event"),event:O8,data:k.unknown(),span:k.string().optional()}),fU0=k.discriminatedUnion("type",[Xd5,Fd5,Dd5]);var Gd5=k.object({type:k.literal("executor_connect"),clientId:bw,capabilities:to4,executorType:eo4.optional()}),Vd5=k.object({type:k.literal("client_update_thread_settings"),settings:yU0}),Ud5=k.object({type:k.literal("executor_tools_register"),tools:k.array(so4)}),Kd5=k.object({type:k.literal("executor_tools_unregister"),toolNames:k.array(O8)}),Ed5=k.object({type:k.literal("executor_tools_bootstrap_complete"),ok:k.boolean(),error:k.string().optional()}),Hd5=k.object({type:k.literal("executor_tool_lease_ack"),toolCallId:S3}),i51=k.object({type:k.literal("tool_progress"),toolCallId:S3,progress:k.union([Ar4,k.unknown()]).optional(),parentToolCallId:S3.optional()}),Wd5=k.object({type:k.literal("executor_tool_result"),toolCallId:S3,run:et}),zd5=k.object({type:k.literal("executor_guidance_snapshot"),snapshotId:O8,files:k.array(u51),isLast:k.boolean(),userConfigDir:k.any().optional()}),qd5=k.object({type:k.literal("executor_guidance_discovery"),toolCallId:S3,files:k.array(u51),isLast:k.boolean()}),Nd5=k.object({type:k.literal("executor_skill_snapshot"),snapshotId:O8,skills:k.array(Jr4),isLast:k.boolean(),errors:k.array(Br4).optional()}),Id5=k.object({type:k.literal("executor_environment_snapshot"),environment:Be}),wd5=k.object({type:k.literal("executor_environment_update"),environment:Be}),Cd5=k.object({type:k.literal("executor_artifact_upsert"),artifact:f51,toolCallId:S3.optional()}),Md5=k.object({type:k.literal("executor_artifact_delete"),key:O8}),Ld5=k.object({type:k.literal("executor_tool_approval_request"),approval:xU0}),Od5=k.object({type:k.literal("executor_plugin_message"),message:fU0}),jd5=k.object({type:k.literal("client_append_user_msg"),content:Qe,userState:d51.optional(),agentMode:PP.optional(),messageId:Z5,steer:k.boolean().optional()}),Rd5=k.object({type:k.literal("client_remove_queued_msg"),queuedMessageId:Z5}),Pd5=k.object({type:k.literal("client_steer_queued_msg"),queuedMessageId:Z5}),_d5=k.object({type:k.literal("client_edit_message"),messageId:Z5,editId:oo4,content:Qe,agentMode:PP.optional()}),Td5=k.object({type:k.literal("client_mark_message_read"),messageId:Z5}),Sd5=k.object({type:k.literal("client_mark_message_unread"),messageId:Z5}),kd5=k.object({type:k.literal("client_set_thread_title"),title:k.string().trim().min(1).max(256)}),vd5=k.object({auth:k.string().min(1),p256dh:k.string().min(1)}),yd5=k.object({endpoint:k.string().url(),keys:vd5}),xd5=k.object({type:k.literal("client_upsert_notification_subscription"),subscription:yd5,threadURL:k.string().min(1)}),fd5=k.object({type:k.literal("client_filesystem_read_directory"),requestId:gK,uri:Ju}),bd5=k.object({type:k.literal("client_filesystem_read_file"),requestId:gK,uri:Ju}),ud5=k.object({type:k.literal("executor_filesystem_read_directory_result"),requestId:gK,ok:k.boolean(),entries:k.array(Ae).optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:k.ZodIssueCode.custom,message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:k.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),hd5=k.object({type:k.literal("executor_filesystem_read_file_result"),requestId:gK,ok:k.boolean(),contentBase64:k.string().optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:k.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:k.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:k.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),gd5=k.object({type:k.literal("client_resume"),version:k.number()}),md5=k.object({type:k.literal("client_retry")}),pd5=k.object({type:k.literal("client_dismiss_active_error"),seq:k.number().optional()}),dd5=k.object({type:k.literal("client_cancel")}),cd5=k.object({type:k.literal("client_append_manual_bash_invocation"),args:k.object({cmd:k.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:k.array(k.string()).optional(),cwd:k.string().optional()}),run:et,hidden:k.boolean().optional()}),ld5=k.object({type:k.literal("client_tool_approval_response"),toolCallId:S3,accepted:k.boolean(),input:k.object({askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}).optional()}),id5=k.object({type:k.literal("client_spawn_executor"),requestId:k.string().optional(),repositoryURL:k.string().optional(),projectID:k.uuid().optional(),additionalRepositories:k.array(k.object({name:k.string(),url:k.string()})).optional()}),Fr4=k.discriminatedUnion("type",[Gd5,Vd5,Ud5,Kd5,Ed5,Hd5,i51,Wd5,zd5,qd5,Nd5,Id5,wd5,Cd5,Md5,Ld5,Od5,jd5,Rd5,Pd5,_d5,Td5,Sd5,kd5,xd5,fd5,bd5,ud5,hd5,gd5,md5,pd5,dd5,cd5,ld5,id5]);YQ();var bU0=(A)=>k.codec(k.string(),A,{decode:(Q,B)=>{try{return JSON.parse(Q)}catch($){return B.issues.push({code:"invalid_format",format:"json",input:Q,message:$.message}),k.NEVER}},encode:(Q)=>JSON.stringify(Q)});YQ();YQ();var n51=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],$t3=new Set(n51);var nd5=["working","streaming","tool_use","running_tools"],ad5=new Set(nd5);function w$(A){if(typeof A!=="string")return!1;return ad5.has(A)}function $e(A){return typeof A==="object"&&A!==null}function od5(A){return $e(A)&&A.type==="text"&&typeof A.text==="string"}function a51(A){if(!A)return;let Q=A.filter(od5).map((B)=>B.text).join("");return Q.length>0?Q:void 0}function o51(A){if(typeof A==="string")return A;if(Array.isArray(A))return a51(A);if(!$e(A))return;for(let Q of["output","displayMessage","message","reason"]){let B=A[Q];if(typeof B==="string")return B}for(let Q of["result","error","value"])if(Q in A){let B=o51(A[Q]);if(B!==void 0)return B}return}function Dr4(A,Q){if(typeof A==="string")return A+Q;if(Array.isArray(A)){if(!A.every((B)=>$e(B)&&typeof B.type==="string"))return;return[...A,{type:"text",text:Q}]}if(!$e(A))return;for(let B of["output","displayMessage","message","reason"]){let $=A[B];if(typeof $==="string")return{...A,[B]:$+Q}}if("value"in A){let B=Dr4(A.value,Q);if(B!==void 0)return{...A,value:B}}return}function rd5(A){return $e(A)&&typeof A.status==="string"}function sd5(A,Q){return{type:"delta",...A?{blocks:[{type:"text",text:A}]}:{},state:Q}}function td5(A){if(!A)return;if(A.type==="snapshot")return o51(A.value);return a51(A.blocks)}function Yu(A,Q){if(A&&typeof A==="object"&&"type"in A){let $=A;if($.type==="delta"||$.type==="snapshot")return $}if(Q==="snapshot")return{type:"snapshot",value:A};let B=typeof A==="string"?A:A!==void 0?JSON.stringify(A):"";return{type:"delta",blocks:B?[{type:"text",text:B}]:void 0,state:"generating"}}function Gr4(A,Q){if(Q.type!=="snapshot"||rd5(Q.value))return Q;let B=td5(A),$=o51(Q.value);if(B===void 0||$===void 0)return Q;if(!$.startsWith(B))return Q;return sd5($.slice(B.length),"generating")}function uU0(A,Q){let B=A===void 0?void 0:Yu(A,"snapshot"),$=Yu(Q,"snapshot");if($.type==="snapshot")return $;if(!B)return $;let J=a51($.blocks);if(J===void 0)return B;if(B.type==="snapshot"){let Z=Dr4(B.value,J);if(Z!==void 0)return{type:"snapshot",value:Z}}return{type:"delta",blocks:[...B.type==="delta"?B.blocks??[]:Array.isArray(B.value)?B.value:[],...$.blocks??[]],state:$.state}}var ed5=k.enum(n51),Ac5=k.enum(["start","generating","tool_use","complete","error","aborted"]),Qc5=k.object({message:k.string(),code:k.string().optional(),stack:k.string().optional(),retryAt:k.number().optional(),attempt:k.number().optional()}),Bc5=k.object({userId:k.string(),name:k.string(),avatarURL:k.string().optional()}),$c5=k.enum(["starting","running","failed"]),Jc5=k.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),Yc5=k.enum(["pending","ready","failed"]).nullable(),Zc5=k.enum(["allocating_environment","configuring_workspace","starting_headless"]).nullable(),Xc5=k.enum(["idle","creating","recovering"]),Fc5=k.enum(["unknown","running","paused","missing"]),Dc5=k.enum(["spawn_requested","spawn_rejected","environment_recovering","waiting_for_executor_connect","executor_connected","executor_disconnected","connect_timeout","executor_connect_rejected","spawn_failed","restart_failed","environment_missing"]),Gc5=k.object({environmentId:k.string().nullable().optional(),stage:Jc5.optional(),setupState:Yc5.optional(),setupPhase:Zc5.optional(),operation:Xc5.optional(),providerState:Fc5.optional(),restartAttempts:k.number().optional()}),Vc5=k.object({reasonCode:Dc5.optional(),executionEnvironment:Gc5.optional()}),Uc5=k.object({cutMessageId:Z5,createdAt:k.string()}),Vr4=k.object({steer:k.boolean(),queuedMessage:k.object({role:k.literal("user"),messageId:Z5,content:Qe,userState:k.any().optional(),meta:g51.optional(),createdAt:k.string().optional()})}),Kc5=k.object({type:k.literal("agent_state"),state:ed5,messageId:Z5.optional(),agentMode:PP.optional()}),Ec5=k.object({type:k.literal("inference_tools"),messageId:Z5,agentMode:PP,tools:k.array(O8),parentToolCallId:S3.optional()}),Hc5=k.object({type:k.literal("thread_settings"),settings:yU0}),Wc5=k.object({type:k.literal("error"),message:k.string(),code:k.enum(["ACCESS_DENIED","ACTOR_STOPPING","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),zc5=k.object({type:k.literal("error_set"),seq:k.number(),error:Qc5}),qc5=k.object({type:k.literal("error_cleared"),seq:k.number()}),Nc5=k.object({type:k.literal("cancelled"),seq:k.number(),messageId:Z5.optional()}),Ic5=k.object({type:k.literal("retry_scheduled"),retryAt:k.number(),attempt:k.number(),maxAttempts:k.number(),reason:k.string()}),wc5=k.object({type:k.literal("retry_started")}),Cc5=k.object({type:k.literal("retry_cancelled")}),Mc5=k.object({type:k.literal("executor_connected"),executorId:bw,registeredToolCount:k.number(),guidanceInventory:k.array($r4),resumeBootstrap:k.boolean().optional(),rejectedTools:k.array(k.object({name:k.string(),reason:k.string()})).optional()}),Lc5=k.object({type:k.literal("tool_lease"),toolCallId:S3,toolName:k.string(),args:k.unknown(),messageId:Z5,parentToolCallId:S3.optional()}),Oc5=k.object({type:k.literal("executor_filesystem_read_directory"),requestId:gK,uri:Ju}),jc5=k.object({type:k.literal("executor_filesystem_read_file"),requestId:gK,uri:Ju}),Rc5=k.object({type:k.literal("client_filesystem_read_directory_result"),requestId:gK,ok:k.boolean(),entries:k.array(Ae).optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:"custom",message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:"custom",message:"entries must not be present when ok is false"})}),Pc5=k.object({type:k.literal("client_filesystem_read_file_result"),requestId:gK,ok:k.boolean(),contentBase64:k.string().optional(),error:uw.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:"custom",message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:"custom",message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:"custom",message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:"custom",message:"contentBase64 must not be present when ok is false"})}),_c5=k.object({type:k.literal("tool_approval_queue"),approvals:k.array(xU0)}),Tc5=k.object({type:k.literal("executor_tool_lease_revoked"),toolCallId:S3,reason:k.enum(["executor_disconnected","reassigned","user_canceled"])}),Sc5=k.object({type:k.literal("executor_tool_result_ack"),toolCallId:S3}),kc5=k.object({type:k.literal("plugin_message"),message:fU0}),vc5=k.object({type:k.literal("executor_tool_approval_response"),toolCallId:S3,accepted:k.boolean(),input:k.object({askAnswers:k.record(k.string(),k.string()).optional(),denyFeedback:k.string().optional()}).optional()}),yc5=k.object({type:k.literal("executor_error"),message:k.string(),toolCallId:S3.optional(),code:k.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),xc5=k.object({type:k.literal("delta"),messageId:Z5,role:k.literal("assistant"),blocks:p51.optional(),blockIndex:k.number().int().nonnegative().optional(),state:Ac5,usage:c51.optional(),parentToolCallId:S3.optional()}),fc5=k.object({type:k.literal("delta"),messageId:Z5,role:k.literal("user"),blocks:m51.optional(),state:k.literal("complete"),parentToolCallId:S3.optional()}),bc5=k.discriminatedUnion("role",[xc5,fc5]),uc5=k.object({type:k.literal("queued_messages"),messages:k.array(Vr4)}),hc5=k.object({type:k.literal("queued_message_added"),message:Vr4,seq:k.number()}),gc5=k.object({type:k.literal("queued_message_removed"),queuedMessageId:Z5,seq:k.number()}),mc5=k.object({type:k.literal("message_added"),message:l51,seq:k.number(),parentToolUseId:S3.optional()}),pc5=k.object({type:k.literal("message_updated"),message:l51,seq:k.number()}),dc5=k.object({type:k.literal("edit_rejected"),editId:k.string(),message:k.string()}),cc5=k.object({type:k.literal("thread_truncated"),seq:k.number(),truncateFromMessage:Z5}),lc5=k.object({type:k.literal("observers"),count:k.number(),observers:k.array(Bc5),hasExecutor:k.boolean().optional()}),ic5=k.object({type:k.literal("executor_status"),spawnId:k.string().optional(),status:$c5,message:k.string().optional(),executorId:k.string().optional(),details:Vc5.optional()}),nc5=k.object({type:k.literal("environment_update"),environment:Be}),ac5=k.object({type:k.literal("artifacts_snapshot"),artifacts:k.array(b51)}),oc5=k.object({type:k.literal("artifact_upserted"),artifact:b51}),rc5=k.object({type:k.literal("artifact_deleted"),key:O8}),sc5=k.object({type:k.literal("thread_title"),title:k.string().nullable()}),tc5=k.object({type:k.literal("thread_status"),status:k.union([k.literal("merging"),k.literal("merged"),k.null()])}),ec5=k.object({type:k.literal("thread_relationships"),seq:k.number(),relationships:k.array(ao4)}),Al5=k.object({type:k.literal("compaction_started")}),Ql5=k.object({type:k.literal("compaction_complete"),cutMessageId:Z5}),Bl5=k.object({type:k.literal("compaction_records"),records:k.array(Uc5)}),hU0=k.discriminatedUnion("type",[Kc5,Ec5,Hc5,Wc5,zc5,qc5,Nc5,Ic5,wc5,Cc5,Mc5,Lc5,Oc5,jc5,Rc5,Pc5,_c5,Tc5,Sc5,kc5,vc5,i51,yc5,bc5,cc5,uc5,hc5,gc5,mc5,pc5,dc5,lc5,ic5,nc5,ac5,oc5,rc5,sc5,tc5,ec5,Al5,Ql5,Bl5]);var Ur4=bU0(Fr4),$l5=k.union([hU0,k.array(hU0)]),Kr4=bU0(hU0),Er4=bU0($l5);H4();function Hr4(A,Q={}){let $=(Q.mode??"lenient")==="strict";if(!Array.isArray(A))return $?null:[];let J=[];for(let Y of A){if(typeof Y!=="object"||Y===null){if($)return null;continue}let Z=Y;if(typeof Z.uri!=="string"||Z.uri.length===0){if($)return null;continue}let X;try{X=o1(J1.parse(Z.uri))}catch{if($)return null;continue}let F={uri:X};if(typeof Z.content==="string")F.content=Z.content;if(typeof Z.lineCount==="number"&&Number.isFinite(Z.lineCount))F.lineCount=Z.lineCount;if(typeof Z.hash==="string")F.hash=Z.hash;J.push(F)}return J}var Wr4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function r51(A,Q){if(A.length<=Q)return A;return`${A.slice(0,Q)}...<truncated>`}function Jl5(A){return A.replace(/\s+/g," ").trim()}function Yl5(A){if(!A||typeof A!=="object")return[];let Q=A.issues;return Array.isArray(Q)?Q.slice(0,5):[]}function Zl5(A){if(A===void 0)return null;if(typeof A==="string")return JSON.stringify(A);if(typeof A==="number"||typeof A==="boolean"||A===null)return JSON.stringify(A);try{return r51(JSON.stringify(A),120)}catch{return r51(String(A),120)}}function zr4(A){if(!Array.isArray(A)||A.length===0)return null;let Q=A.map((B)=>typeof B==="number"?`[${B}]`:String(B)).join(".").replace(/\.\[/g,"[");return Q.length>0?Q:null}function Xl5(A){if(!A||typeof A!=="object")return null;let Q=A,B=typeof Q.message==="string"?Q.message:null,$=typeof Q.note==="string"?Q.note:null,J=zr4(Q.path);if(J&&B&&B!=="Invalid input")return`${J}: ${B}`;if(J&&$)return`${J}: ${$}`;if(J&&B)return`invalid value at ${J}`;return $??B}function qr4(A){for(let Q of A){let B=Xl5(Q);if(B)return B}return null}function Fl5(A){return A.some((Q)=>{if(!Q||typeof Q!=="object")return!1;let B=Q;return B.code==="invalid_union"&&(B.note==="No matching discriminator"||B.discriminator==="type"||zr4(B.path)==="type")})}function Dl5(A,Q){let B=qr4(Q);if(A&&B)return`type ${JSON.stringify(A)} failed validation: ${B}`;if(A)return`type ${JSON.stringify(A)} failed validation`;if(B)return`message payload failed validation: ${B}`;return"message payload failed validation"}function Nr4(A,Q,B){let $=Yl5(Q),J=(()=>{let D=Jl5(A);if(D.length===0)return null;return r51(D,B?.payloadPreviewMaxChars??1200)})(),Y;try{Y=JSON.parse(A)}catch{let D=qr4($);return{failureType:"invalid_json",summary:D?`malformed JSON: ${D}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:J,issues:$}}if(!Y||typeof Y!=="object"||Array.isArray(Y))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:J,issues:$};let Z=Y;if(!Object.hasOwn(Z,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:J,issues:$};let X=Z.type,F=Zl5(X);if(typeof X!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:J,issues:$};if(Fl5($))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(X)} (likely protocol version mismatch)`,messageType:X,typePreview:F,payloadPreview:J,issues:$};return{failureType:"invalid_shape",summary:Dl5(X,$),messageType:X,typePreview:F,payloadPreview:J,issues:$}}function s51(A){let Q=Number.isFinite(A)?A:0;function B(J=Q){if(Number.isFinite(J))Q=J;return Q}function $(J){if(!Number.isFinite(J)||J<1)return Q;return Q=Math.max(Q,J),Q}return{getVersion:()=>Q,reset:B,advanceFromSeq:$}}function wr4(A,Q,B){if(Gl5(Q))return A;let $;switch(Q.type){case"message_added":$=Vl5(A,Q);break;case"message_updated":$=Ul5(A,Q);break;case"delta":$=Kl5(A,Q,B);break;case"tool_progress":$=El5(A,Q,B);break;case"thread_truncated":$=Hl5(A,Q);break}return Ml5($,Q,B)}function Gl5(A){if(A.type==="message_added")return A.parentToolUseId!==void 0;if(A.type==="delta"||A.type==="tool_progress")return A.parentToolCallId!==void 0;return!1}function Vl5(A,Q){let B=Sl5(A,vl5(Q.message)),$=Zu(B,Q.message.messageId),J=B.slice();if($>=0)return J[$]=Q.message,J;return J.push(Q.message),J}function Ul5(A,Q){let B=Zu(A,Q.message.messageId),$=A.slice();if(B>=0)return $[B]=Q.message,$;return $.push(Q.message),$}function Kl5(A,Q,B){let $=Q.role==="assistant"&&Q.state==="aborted"?Cl5(A,Q.messageId):A;if(!Q.blocks||Q.blocks.length===0)return $.slice();if(Q.role==="assistant")return Wl5($,Q,B);return zl5($,{...Q,blocks:Q.blocks},B)}function El5(A,Q,B){let $=Tl5(Q.progress);if($!==void 0&&$!=="in-progress")return A.slice();if(Je(A,Q.toolCallId,(G)=>G.run.status==="done"||G.run.status==="error"||G.run.status==="cancelled"||G.run.status==="rejected-by-user"))return A.slice();let Y=Je(A,Q.toolCallId),Z=Y&&"progress"in Y.block.run?Y.block.run.progress:void 0,X=Q.progress===void 0?Z:uU0(Z,Q.progress),F=X===void 0?{status:"in-progress"}:{status:"in-progress",progress:X},D=Y?.block.userInput===void 0?{type:"tool_result",toolUseID:Q.toolCallId,run:F}:{type:"tool_result",toolUseID:Q.toolCallId,run:F,userInput:Y.block.userInput};if(Y)return e51(A,Y,D);return[...A,{threadId:B.threadId,messageId:Mr4(Q.toolCallId),role:"user",content:[D]}]}function Hl5(A,Q){let B=Zu(A,Q.truncateFromMessage);return B>=0?A.slice(0,B):A.slice()}function Wl5(A,Q,B){let $=Zu(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="assistant"?J.content:[],Z=ql5(Y,Q.blocks,Q.blockIndex),X=J?.role==="assistant"?{...J,content:Z}:{threadId:B.threadId,messageId:Q.messageId,role:"assistant",content:Z};if(Q.usage!==void 0)X.usage=Q.usage;if(Q.state==="aborted")X.state={type:"cancelled"};else if(Q.state==="complete"||Q.state==="tool_use")X.state={type:"complete"};return t51(A,$,X)}function zl5(A,Q,B){let $=Zu(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="user"?J.content:[],Z=wl5(Y,Q.blocks),X=J?.role==="user"?{...J,content:Z}:{threadId:B.threadId,messageId:Q.messageId,role:"user",content:Z};return t51(A,$,X)}function ql5(A,Q,B){let $=[...A];for(let[J,Y]of Q.entries()){let Z=B+J;Nl5($,Z);let X=$[Z];if(Il5(X))$[Z]=Y;else if(X?.type==="text"&&Y.type==="text")$[Z]={...X,text:X.text+Y.text};else if(X?.type==="thinking"&&Y.type==="thinking")$[Z]={...X,thinking:X.thinking+Y.thinking};else $[Z]=Y}return $}function Nl5(A,Q){while(A.length<Q)A.push({type:"text",text:"",hidden:!0})}function Il5(A){return A?.type==="text"&&A.hidden===!0&&A.text===""}function wl5(A,Q){let B=[...A];for(let $ of Q){let J=B.length-1,Y=B[J];if(Y?.type==="text"&&$.type==="text")B[J]={...Y,text:Y.text+$.text};else B.push($)}return B}function t51(A,Q,B){let $=A.slice();if(Q>=0)return $[Q]=B,$;return $.push(B),$}function Cl5(A,Q){return A.filter((B)=>B.messageId!==Q)}function Zu(A,Q){return A.findIndex((B)=>B.messageId===Q)}function Je(A,Q,B=()=>!0){for(let[$,J]of A.entries()){if(J.role!=="user")continue;for(let[Y,Z]of J.content.entries())if(Z.type==="tool_result"&&Z.toolUseID===Q&&B(Z))return{messageIndex:$,blockIndex:Y,message:J,block:Z}}return}function e51(A,Q,B){let $=Q.message.content.slice();return $[Q.blockIndex]=B,t51(A,Q.messageIndex,{...Q.message,content:$})}function Ml5(A,Q,B){let $=B.guidanceDedup;if(!$)return A.slice();Ll5($,Q);let J=A.slice();for(let Z of jl5(J,Q)){let X=Je(J,Z.block.toolUseID)??Z,{myDedupedFiles:F,needsRebuild:D}=$.applyToolResult(X.block.toolUseID,wd0(X.block));J=e51(J,X,Cr4(X.block,F));for(let G of D)J=Ir4(J,$,G)}let Y=$.cleanupRemovedToolResults(Rl5(J));for(let Z of Y)J=Ir4(J,$,Z);return J}function Ll5(A,Q){if(Q.type==="message_added"||Q.type==="message_updated"){Ol5(A,Q.message);return}if(Q.type!=="delta"||Q.role!=="assistant"||!Q.blocks)return;for(let B of Q.blocks)if(B.type==="tool_use")A.recordToolOrder(B.id)}function Ol5(A,Q){if(Q.role!=="assistant")return;for(let B of Q.content)if(B.type==="tool_use")A.recordToolOrder(B.id)}function jl5(A,Q){if(Q.type==="message_added"||Q.type==="message_updated"){let B=Zu(A,Q.message.messageId),$=B>=0?A[B]:void 0;if($?.role!=="user")return[];return $.content.flatMap((J,Y)=>J.type==="tool_result"?[{messageIndex:B,blockIndex:Y,message:$,block:J}]:[])}if(Q.type!=="delta"||Q.role!=="user"||!Q.blocks)return[];return Q.blocks.flatMap((B)=>{if(B.type!=="tool_result")return[];let $=Je(A,B.toolUseID);return $?[$]:[]})}function Ir4(A,Q,B){let $=Je(A,B);if(!$)return A.slice();return e51(A,$,Cr4($.block,Q.dedupedFilesFor(B)))}function Cr4(A,Q){if(A.run.status!=="done")return A;let B=A.run.result;if(!B||typeof B!=="object"||Array.isArray(B))return A;let{discoveredGuidanceFiles:$,...J}=B,Y=J;if(Q.length>0)Y={...J,discoveredGuidanceFiles:[...Q]};return{...A,run:{...A.run,result:Y}}}function Rl5(A){let Q=new Set;for(let B of A){if(B.role!=="user")continue;for(let $ of B.content)if($.type==="tool_result")Q.add($.toolUseID)}return Q}var Pl5=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function _l5(A){return typeof A==="string"&&Pl5.includes(A)}function Tl5(A){if(A===void 0||typeof A!=="object"||A===null)return;let Q=A;if(Q.type!=="snapshot")return;let B=Q.value;if(typeof B!=="object"||B===null)return;let $=B.status;return _l5($)?$:void 0}function Sl5(A,Q){if(Q.size===0)return A;return A.filter((B)=>!kl5(B,Q))}function kl5(A,Q){if(A.role!=="user"||A.content.length!==1)return!1;let B=A.content[0];return B?.type==="tool_result"&&Q.has(B.toolUseID)&&A.messageId===Mr4(B.toolUseID)}function vl5(A){let Q=new Set;if(A.role!=="user")return Q;for(let B of A.content)if(B.type==="tool_result")Q.add(B.toolUseID);return Q}function Mr4(A){return`M-${A.replace(/^TU-/,"")}`}class A81{guidance=new kU0;inProgressMessageID=null;threadMessages=[];messageSeq=new Map;messageOrder=new Map;nextMessageOrder=0;threadID;constructor(A){this.threadID=A}setThreadID(A){this.threadID=A}getThreadID(){return this.threadID}reset(A){if(A!==void 0)this.threadID=A;this.guidance=new kU0,this.threadMessages=[],this.messageSeq.clear(),this.messageOrder.clear(),this.nextMessageOrder=0,this.inProgressMessageID=null}apply(A){let Q=this.threadMessages;if(A.type==="delta"&&A.parentToolCallId===void 0&&A.state==="aborted"){if(this.applyThreadMessageEvent(A),this.inProgressMessageID===A.messageId)this.inProgressMessageID=null;return this.threadMessages!==Q}let B=yl5(A);if(B!==void 0)this.updateInProgressMessage(B);if(this.applyThreadMessageEvent(A),A.type==="delta"&&(A.state==="complete"||A.state==="tool_use"))this.inProgressMessageID=null;return this.threadMessages!==Q}messages(){return this.threadMessages}sortedMessages(){return this.sortThreadMessages(this.threadMessages)}applyThreadMessageEvent(A){this.recordMessageOrder(A);let Q=A.type==="thread_truncated"?this.sortThreadMessages(this.threadMessages):this.threadMessages;this.threadMessages=wr4(Q,A,{threadId:this.threadID,guidanceDedup:this.guidance}),this.pruneMessageOrder()}recordMessageOrder(A){if(A.type==="message_added"){this.recordMessage(A.message.messageId,A.seq);return}if(A.type==="message_updated"){this.recordMessage(A.message.messageId,this.messageSeq.has(A.message.messageId)?void 0:A.seq);return}if(A.type==="delta"){this.recordMessage(A.messageId);return}if(A.type==="tool_progress")this.recordMessage(xl5(A.toolCallId))}recordMessage(A,Q){if(!this.messageOrder.has(A))this.messageOrder.set(A,this.nextMessageOrder),this.nextMessageOrder+=1;if(Q!==void 0)this.messageSeq.set(A,Q)}sortThreadMessages(A){return A.slice().sort((Q,B)=>{let $=this.messageSeq.get(Q.messageId),J=this.messageSeq.get(B.messageId),Y=$!==void 0&&J!==void 0?$-J:this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId);if(Y!==0)return Y;return this.messageSortOrder(Q.messageId)-this.messageSortOrder(B.messageId)})}messageSortOrder(A){return this.messageOrder.get(A)??Number.MAX_SAFE_INTEGER}pruneMessageOrder(){let A=new Set(this.threadMessages.map((Q)=>Q.messageId));for(let Q of this.messageSeq.keys())if(!A.has(Q))this.messageSeq.delete(Q);for(let Q of this.messageOrder.keys())if(!A.has(Q))this.messageOrder.delete(Q);if(this.inProgressMessageID!==null&&!A.has(this.inProgressMessageID))this.inProgressMessageID=null}updateInProgressMessage(A){if(this.inProgressMessageID===A)return;if(this.inProgressMessageID!==null)this.markMessageNotInProgress(this.inProgressMessageID);this.inProgressMessageID=A}markMessageNotInProgress(A){this.threadMessages=this.threadMessages.map((Q)=>{if(Q.messageId!==A||Q.role!=="assistant"||Q.state!==void 0)return Q;return{...Q,state:{type:"complete"}}})}}function yl5(A){if(A.type==="message_added"&&A.parentToolUseId===void 0)return A.message.messageId;if(A.type==="delta"&&A.parentToolCallId===void 0)return A.messageId;return}function xl5(A){return`M-${A.replace(/^TU-/,"")}`}AA();function Lr4(A,Q){if(A.role==="assistant")return{role:"assistant",content:A.content,state:A.state?.type==="cancelled"?{type:"cancelled"}:{type:"complete",stopReason:null},usage:A.usage,messageId:Q,protocolMessageID:A.messageId,readAt:A.readAt};if(A.role==="info")return{role:"info",content:A.content,messageId:Q,protocolMessageID:A.messageId};return{role:"user",content:A.content,meta:s90(A.meta),userState:A.userState,readAt:A.readAt,messageId:Q,protocolMessageID:A.messageId}}class gU0{accumulator;currentVersion=0;constructor(A){this.accumulator=new A81(A)}get version(){return this.currentVersion}setThreadID(A){this.accumulator.setThreadID(A)}reset(A){let Q=this.accumulator.sortedMessages().length;return this.accumulator.reset(A),this.currentVersion+=1,{changed:Q>0,previousMessageCount:Q,nextMessageCount:0,changedIndices:bl5(Q,0),version:this.currentVersion}}apply(A){if(A.type==="message_added"&&A.parentToolUseId===void 0||A.type==="message_updated")this.setThreadID(A.message.threadId);let Q=this.accumulator.sortedMessages();if(!this.accumulator.apply(A))return{changed:!1,previousMessageCount:Q.length,nextMessageCount:Q.length,changedIndices:[],version:this.currentVersion};let $=this.accumulator.sortedMessages();return this.currentVersion+=1,{changed:!0,previousMessageCount:Q.length,nextMessageCount:$.length,changedIndices:fl5(Q,$),version:this.currentVersion}}protocolMessages(){return this.accumulator.sortedMessages()}coreMessages(){return this.accumulator.sortedMessages().map((A,Q)=>Lr4(A,Q))}buildTranscriptEntries(A={}){return _o4(this.protocolMessages(),{threadID:this.accumulator.getThreadID(),...A})}}function fl5(A,Q){let B=Math.max(A.length,Q.length),$=[];for(let J=0;J<B;J+=1)if(A[J]!==Q[J])$.push(J);return $}function bl5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}function mU0(A,Q={}){let B=!1,$=!1;return A.connectionChanges().subscribe({next:(J)=>{let Y=J.state==="connected";if(Y&&!B){if($)try{A.resumeFromVersion(A.getResumeVersion())}catch(Z){Q.onError?.({threadID:A.getThreadId(),error:Z})}$=!0}B=Y}})}XY0();j1();var Q81=Number.MAX_SAFE_INTEGER;class B81{callbacks;agentLoopState=null;pending=new Map;constructor(A){this.callbacks=A}setAgentLoopState(A){this.agentLoopState=A}emitOptimisticUserMessage(A){if(this.pending.has(A.messageId))return;let Q=this.nextEventType();this.pending.set(A.messageId,Q),this.dispatchOptimistic(Q,A)}emitOptimisticQueuedUserMessage(A){if(this.pending.has(A.messageId))return;this.pending.set(A.messageId,"queued_message_added"),this.dispatchOptimistic("queued_message_added",A)}reconcileMessageAdded(A){let Q=A.message.messageId;if(this.pending.get(Q)==="queued_message_added")this.emitQueuedMessages({type:"queued_message_removed",queuedMessageId:Q,seq:Q81});this.pending.delete(Q),this.emitMessageAdded(A)}reconcileQueuedMessageAdded(A){let Q=A.message.queuedMessage.messageId,B=this.pending.get(Q);if(B==="queued_message_added")return;if(B==="message_added")this.pending.set(Q,"queued_message_added");this.emitQueuedMessages(A)}reconcileQueuedMessagesSnapshot(A){let Q=new Set;for(let B of A.messages)Q.add(B.queuedMessage.messageId);for(let B of Q)if(this.pending.get(B)==="message_added")this.pending.set(B,"queued_message_added");for(let[B,$]of this.pending)if($==="queued_message_added"&&!Q.has(B))return;this.emitQueuedMessages(A)}reconcileQueuedMessageRemoved(A){this.pending.delete(A.queuedMessageId),this.emitQueuedMessages(A)}reset(){this.agentLoopState=null,this.pending.clear()}nextEventType(){if(this.agentLoopState===null||this.agentLoopState==="idle")return"message_added";return"queued_message_added"}dispatchOptimistic(A,Q){if(A==="message_added"){this.emitMessageAdded({type:"message_added",message:{role:"user",messageId:Q.messageId,content:Q.content,agentMode:Q.agentMode,threadId:this.callbacks.getThreadID()??"T-00000000-0000-0000-0000-000000000000"},seq:Q81});return}this.emitQueuedMessages({type:"queued_message_added",message:{steer:!1,queuedMessage:{role:"user",messageId:Q.messageId,content:Q.content,userState:Q.userState}},seq:Q81})}emitMessageAdded(A){this.callbacks.observerCallbacks((Q)=>{Q.onMessageAdded?.(A)})}emitQueuedMessages(A){this.callbacks.observerCallbacks((Q)=>{Q.onQueuedMessages?.(A)})}}class $81{options;queue=[];active=null;retryTimer=null;constructor(A){this.options=A}send(A){this.queue.push({message:A,sent:!1}),this.pump()}retry(){this.clearRetryTimer(),this.pump({forceActiveRetry:!0})}handleServerMessage(A){if(!this.active||!this.active.sent||this.active.message.type!=="client_append_user_msg")return;if(!hl5(this.active.message,A))return;this.clearRetryTimer(),this.active=null,this.pump()}reset(){this.clearRetryTimer(),this.queue.length=0,this.active=null}pump(A){if(this.active){if(!this.active.sent||A?.forceActiveRetry)this.tryActive();return}let Q=this.queue.shift();if(!Q)return;this.active=Q,this.tryActive()}tryActive(){let A=this.active;if(!A||A.sent&&A.message.type!=="client_append_user_msg")return;if(!this.options.trySend(A.message)){this.scheduleRetry();return}if(A.sent=!0,A.message.type!=="client_append_user_msg"){this.clearRetryTimer(),this.active=null,this.pump();return}this.scheduleRetry()}scheduleRetry(){if(this.retryTimer!==null)return;this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.pump({forceActiveRetry:!0})},1000),ul5(this.retryTimer)}clearRetryTimer(){if(this.retryTimer===null)return;clearTimeout(this.retryTimer),this.retryTimer=null}}function ul5(A){if(typeof A!=="object"||A===null||!("unref"in A))return;let Q=A.unref;if(typeof Q==="function")Q.call(A)}function hl5(A,Q){switch(Q.type){case"message_added":return Q.message.messageId===A.messageId;case"queued_message_added":return Q.message.queuedMessage.messageId===A.messageId;case"queued_messages":return gl5(Q.messages,A.messageId);default:return!1}}function gl5(A,Q){return A.some((B)=>B.queuedMessage.messageId===Q)}i0();j1();var ml5=1000,pl5=30000,dl5=124,cl5=30000,ll5=15000,il5=1000,nl5=200,al5=30000,Or4=["online","focus","pageshow","keydown","pointerdown"],jr4=["visibilitychange"];function Y81(){return globalThis}function Pr4(A){if(!A||typeof A!=="object")return null;let Q=A;if(typeof Q.addEventListener!=="function"||typeof Q.removeEventListener!=="function")return null;return Q}function Rr4(){return Pr4(Y81().window)}function J81(){let A=Y81().document;if(!Pr4(A))return null;return A}function ol5(){let A=Y81().navigator;if(!A||typeof A!=="object")return null;return A}function rl5(A){if(!A)return"none";let Q=[A.type];if(A.code!==void 0)Q.push(`code=${A.code}`);if(A.reason!==void 0)Q.push(`reason=${A.reason}`);if(A.error!==void 0)Q.push(`error=${A.error}`);return Q.join(" ")}class Z81{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;latencyTimeoutIDs=new Set;disposed=!1;lastServerFrameAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new D4({state:"disconnected",role:null,clientId:null});lifecycleEventSubject=new D4([]);config;threadIDSubject=new D4(null);_currentThreadID=null;log=new yY;get currentThreadID(){return this._currentThreadID}set currentThreadID(A){if(A!==null&&A!==this._currentThreadID)this._currentThreadID=A,this.log=FO(A),this.threadIDSubject.next(A);else this._currentThreadID=A}constructor(A){this.config={threadId:A.threadId,webSocketProvider:A.webSocketProvider,reconnectDelayMs:A.reconnectDelayMs??ml5,maxReconnectDelayMs:A.maxReconnectDelayMs??pl5,maxReconnectAttempts:A.maxReconnectAttempts??dl5,pingIntervalMs:A.pingIntervalMs??cl5,connectTimeoutMs:A.connectTimeoutMs??ll5,webSocketLatencyMs:A.webSocketLatencyMs??(()=>0)},this.currentThreadID=A.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(A){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||A<=0)return Promise.resolve(!1);return new Promise((Q)=>{let B=!1,$=null,J=null,Y=(Z)=>{if(B)return;if(B=!0,$)clearTimeout($),$=null;J?.unsubscribe(),J=null,Q(Z)};$=setTimeout(()=>{Y(!1)},A),J=this.connectionSubject.subscribe({next:(Z)=>{if(Z.state==="connected")Y(!0)},error:()=>{Y(!1)},complete:()=>{Y(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(A,Q){let B={id:++this.lifecycleEventID,at:Date.now(),type:A,...Q?{details:Q}:{}},$=nl5,J=this.lifecycleEvents.slice(-($-1));this.lifecycleEvents=[...J,B],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(A){if(this.disposed)throw new T3("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",A.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Q,threadId:B}=await this.config.webSocketProvider();this.currentThreadID=B;try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastServerFrameAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Q){let B=Q instanceof Error?Q.message:String(Q);if(this.recordLifecycleEvent("connect_failed",`mode=${A.fromReconnect?"reconnect":"initial"} error=${B}`),!A.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:B},this.scheduleReconnect();throw Q}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let A=this.ws;if(A){if(this.ws=null,this.intentionallyClosedSockets.add(A),A.readyState===WebSocket.OPEN)A.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(A){if(this.disposed)return;let Q=this.ws;if(!Q&&this.connectionInfo.state!=="connected")return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${A}`),this.clearWebSocketLatencyTimeouts(),this.reconnectCause={type:"error",at:Date.now(),error:A},this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),Q&&(Q.readyState===WebSocket.OPEN||Q.readyState===WebSocket.CONNECTING))Q.close(4000,A);this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}retryConnect(A){if(this.disposed)return;if(this.recordLifecycleEvent("reconnect_attempts_reset",`reason=${A}`),this.reconnectAttempts=0,this.cancelReconnectAttemptsReset(),this.reconnectTimeoutID)return;this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}async disconnectAndWait(A){let Q=this.ws;if(!Q||Q.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let B=this.waitForSocketClose(Q,A?.waitForCloseTimeoutMs??il5);return this.disconnect(),B}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(A){if(!this.hasOpenSocket())throw new T3("WebSocket is not connected");let Q=this.ws;if(!Q)throw new T3("WebSocket is not connected");this.runAfterWebSocketLatency(()=>{if(Q!==this.ws||Q.readyState!==WebSocket.OPEN)return;Q.send(A)}),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}runAfterWebSocketLatency(A){let Q=this.config.webSocketLatencyMs();if(!Number.isFinite(Q)||Q<=0){A();return}let B=setTimeout(()=>{this.latencyTimeoutIDs.delete(B),A()},Q);this.latencyTimeoutIDs.add(B)}clearWebSocketLatencyTimeouts(){for(let A of this.latencyTimeoutIDs)clearTimeout(A);this.latencyTimeoutIDs.clear()}waitForSocketClose(A,Q){return new Promise((B)=>{let $=!1,J=null,Y=(X)=>{if($)return;if($=!0,J)clearTimeout(J);A.removeEventListener("close",Z),B(X)},Z=(X)=>{let F=X;Y({status:F.code===1000?"server_acknowledged":"timeout",...typeof F.code==="number"?{closeCode:F.code}:{},...typeof F.reason==="string"?{closeReason:F.reason}:{}})};if(J=setTimeout(()=>{Y({status:"timeout"})},Q),A.addEventListener("close",Z),A.readyState===WebSocket.CLOSED)Y({status:"timeout"})})}updateConnectionState(A){let Q={...this.connectionInfo};if(A==="disconnected"||A==="reconnecting"){let $={state:A,role:null,clientId:null};if(this.reconnectCause)$.reconnectCause=this.reconnectCause;this.connectionInfo=$}else if(this.connectionInfo.state=A,A==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let B={...this.connectionInfo};this.connectionSubject.next(B),this.log.info("[thread-client] Transport connection state changed",{previousState:Q.state,nextState:B.state,previousRole:Q.role,nextRole:B.role,clientId:B.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${A} cause=${rl5(this.reconnectCause)}`)}onRawMessage(A){}onMaxReconnectExceeded(A){}async waitForOpen(A){if(A.readyState===WebSocket.OPEN)return;return new Promise((Q,B)=>{let $=setTimeout(()=>{J(),this.updateConnectionState("disconnected");try{if(A.readyState===WebSocket.CONNECTING)A.close()}catch{}B(new T3(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),J=()=>{clearTimeout($),A.removeEventListener("open",Y),A.removeEventListener("error",Z),A.removeEventListener("close",X)},Y=()=>{J(),Q()},Z=(F)=>{J(),this.updateConnectionState("disconnected");let D="message"in F?F.message:("error"in F)&&F.error instanceof Error?F.error.message:F.type;B(new T3(`WebSocket connection failed: ${D}`))},X=(F)=>{J(),this.updateConnectionState("disconnected"),B(new T3(`WebSocket closed during connect: code=${F.code} reason=${F.reason||"none"}`))};if(A.addEventListener("open",Y),A.addEventListener("error",Z),A.addEventListener("close",X),A.readyState===WebSocket.OPEN)return Y();if(A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)return X({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(A){A.addEventListener("message",(Q)=>{let B=Q.data;this.runAfterWebSocketLatency(()=>this.handleWebSocketMessage(A,B))}),A.addEventListener("close",(Q)=>{this.handleClose(A,Q.code,Q.reason)}),A.addEventListener("error",()=>{this.handleError(A)})}handleWebSocketMessage(A,Q){if(A!==this.ws)return;if(this.lastServerFrameAt=Date.now(),this.startPingIntervalOnce(),typeof Q==="string"){if(Q==="pong")return;this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}handleClose(A,Q,B){let $=this.intentionallyClosedSockets.has(A);if($)this.intentionallyClosedSockets.delete(A);if(this.log.info("[thread-client] Transport socket close observed",{code:Q,reason:B||void 0,intentional:$,isCurrentSocket:A===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Q} reason=${B||"none"} intentional=${$}`),A!==this.ws)return;if(this.ws=null,this.clearWebSocketLatencyTimeouts(),this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!$){let J=this.reconnectCause,Y=J?.type==="ping_timeout"&&Q===4000&&!B?{...J,at:Date.now(),code:Q}:{type:"close",at:Date.now(),code:Q,...B?{reason:B}:{}};this.reconnectCause=Y,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(A){if(A!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(A){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!A?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Q=A?.immediate?0:this.getReconnectDelayMs();this.log.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Q),immediate:A?.immediate===!0,bypassActivityGate:A?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Q)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((B)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:B instanceof Error?B.message:String(B)},!this.disposed)this.scheduleReconnect()})},Q)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let A=Math.min(this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),this.config.maxReconnectDelayMs),Q=0.8+Math.random()*0.4;return A*Q}shouldWaitForReconnectActivity(){let A=Rr4(),Q=J81();if(!A&&!Q)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let A=ol5();if(typeof A?.onLine!=="boolean")return!1;return A.onLine===!1}isDocumentHidden(){let A=J81();if(!A)return!1;return A.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let A=Rr4(),Q=J81();if(!A&&!Q)return;let B=()=>{this.handleReconnectActivity()};for(let $ of Or4)A?.addEventListener($,B);for(let $ of jr4)Q?.addEventListener($,B);this.reconnectActivityCleanup=()=>{for(let $ of Or4)A?.removeEventListener($,B);for(let $ of jr4)Q?.removeEventListener($,B)}}stopWaitingForReconnectActivity(){this.reconnectActivityCleanup?.(),this.reconnectActivityCleanup=null}handleReconnectActivity(){if(this.disposed||this.ws){this.stopWaitingForReconnectActivity();return}if(this.shouldWaitForReconnectActivity())return;this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_activity_detected"),this.scheduleReconnect({immediate:!0,bypassActivityGate:!0})}scheduleReconnectAttemptsReset(){this.cancelReconnectAttemptsReset(),this.reconnectResetTimeoutID=setTimeout(()=>{this.reconnectResetTimeoutID=null,this.reconnectAttempts=0},al5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let A=Date.now();this.pingIntervalID=setInterval(()=>{let Q=Date.now(),B=Q-A;if(A=Q,B>this.config.pingIntervalMs*3){this.lastServerFrameAt=Q;return}if(this.hasOpenSocket()){let $=Q-this.lastServerFrameAt,J=this.config.pingIntervalMs*2;if($>J){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${$} thresholdMs=${J}`);let Y=`No server frame received for ${$}ms (threshold ${J}ms)`;this.reconnectCause={type:"ping_timeout",at:Q,code:4000,reason:"Pong timeout",error:Y},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}YQ();var _r4="dtw-parse-error",gt3=k.object({kind:k.literal(_r4),failureType:k.enum(Wr4).nullable().optional(),source:k.string().nullable().optional(),direction:k.string().nullable().optional(),stage:k.string().nullable().optional(),summary:k.string().nullable().optional(),messageType:k.string().nullable().optional(),typePreview:k.string().nullable().optional(),payloadPreview:k.string().nullable().optional(),issues:k.array(k.unknown()).optional()}).passthrough(),mt3=k.object({source:k.string(),direction:k.string(),stage:k.string(),summary:k.string().nullable().optional(),messageType:k.string().nullable().optional(),payloadPreview:k.string().nullable().optional(),issues:k.array(k.unknown()).optional()}).passthrough();function sl5(A){return{kind:_r4,failureType:A.failureType??null,source:A.source??null,direction:A.direction??null,stage:A.stage??null,summary:A.summary??null,messageType:A.messageType??null,typePreview:A.typePreview??null,payloadPreview:A.payloadPreview??null,issues:A.issues??[]}}function tl5(A){let Q=sl5(A);return JSON.stringify(Q)}function Tr4(A,Q){let B=Nr4(A,Q);return tl5({failureType:B.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:B.summary,messageType:B.messageType,typePreview:B.typePreview,payloadPreview:B.payloadPreview,issues:B.issues})}var el5=3000,Ai5=30000,Qi5=5;function Sr4(A){if(A instanceof a2)return A;if(A instanceof Error){let Q=A.message||"Unknown thread-client connection error";return new a2(Q,A)}if(typeof A==="string"&&A.length>0)return new a2(A,A);return new a2("Unknown thread-client connection error",A)}function Bi5(A){let Q=atob(A),B=new Uint8Array(Q.length);for(let $=0;$<Q.length;$++)B[$]=Q.charCodeAt($);return B}function $i5(A){return{type:"error",message:`Failed to send user message: ${A}`,code:"MESSAGE_ERROR"}}class mK extends Z81{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outbox;optimisticUserMessages;pendingCancelAgentLoop=!1;pendingDismissActiveError=null;fileSystemRequestCounter=0;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=s51(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new D4(null);threadIDSubscription;constructor(A){super(A.transport);if(this.threadHistoryLoader=A.threadHistoryLoader,this.outbox=new $81({trySend:(Q)=>this.trySendOutboxMessage(Q)}),this.optimisticUserMessages=new B81({getThreadID:()=>this.getThreadId(),observerCallbacks:(Q)=>this.dispatchObserverCallbacks(Q)}),this.threadIDSubscription=this.threadIDSubject.subscribe((Q)=>{if(Q!==null)this.dispatchObserverCallbacks((B)=>{B.onThreadId?.(Q)})}),A.observerCallbacks)this.setObserverCallbacks(A.observerCallbacks);if(A.executorCallbacks)this.setExecutorCallbacks(A.executorCallbacks)}setObserverCallbacks(A){if(this.observerCallbacks&&this.observerCallbacks!==A)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===A)return;if(this.observerCallbacks=A,this.pendingObserverDispatches.length===0)return;for(let Q of this.pendingObserverDispatches)Q(A);this.pendingObserverDispatches.length=0}setExecutorCallbacks(A){if(this.executorCallbacks&&this.executorCallbacks!==A)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===A)return;if(this.executorCallbacks=A,this.pendingExecutorDispatches.length===0)return;for(let Q of this.pendingExecutorDispatches)Q(A);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(A){throw Sr4(A)}}async ensureConnected(A){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(A);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(A){let Q=A?.baseDelayMs??el5,B=A?.maxDelayMs??Ai5,$=A?.maxAttempts??Qi5;if(A?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let J=0;J<$;J++){try{await this.connect()}catch(F){let D=Sr4(F);if(this.getConnectionInfo().state!=="reconnecting")throw D;A?.onRetryableConnectError?.(D)}let Y=A?.waitForConnectedTimeoutMs??Math.min(Q*2**J,B);if(await this.waitForConnected(Y))return!0;let X=J+1<$?Math.min(Q*2**(J+1),B):null;A?.onAttemptTimeout?.({attempt:J+1,maxAttempts:$,nextDelayMs:X})}return!1}async loadThreadHistory(A){let Q=await this.threadHistoryLoader(A);if(!Q)return null;let B=Q.title;if(B!==void 0)this.dispatchObserverCallbacks(($)=>{$.onThreadTitle?.({type:"thread_title",title:B})});for(let[$,J]of Q.messages.entries())this.dispatchObserverCallbacks((Y)=>{Y.onMessageAdded?.({type:"message_added",message:J,seq:$})});return Q}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(A,Q,B){let $=B?.messageId??vU0(),J={type:"client_append_user_msg",content:nX(A),agentMode:Q,messageId:$,steer:B?.steer,userState:B?.userState};return this.dispatchObserverCallbacks((Y)=>{Y.onUserMessageSendPending?.($,Date.now())}),this.optimisticUserMessages.emitOptimisticUserMessage(J),this.outbox.send(J),this.retryConnectIfTerminallyDisconnected("user message sent"),$}retryConnectIfTerminallyDisconnected(A){if(this.getConnectionInfo().state!=="disconnected")return;this.retryConnect(A)}removeQueuedMessage(A){this.dispatchObserverCallbacks((Q)=>{Q.onUserActionMessageDeliveryStatusChanged?.(A,"buffered",Date.now())}),this.outbox.send({type:"client_remove_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message remove requested")}steerQueuedMessage(A){this.outbox.send({type:"client_steer_queued_msg",queuedMessageId:A}),this.retryConnectIfTerminallyDisconnected("queued message steer requested")}editUserMessage(A,Q,B,$){this.outbox.send({type:"client_edit_message",messageId:A,editId:B,content:nX(Q),agentMode:$}),this.retryConnectIfTerminallyDisconnected("user message edit requested")}markMessageRead(A){this.send({type:"client_mark_message_read",messageId:A})}markMessageUnread(A){this.send({type:"client_mark_message_unread",messageId:A})}setThreadTitle(A){this.send({type:"client_set_thread_title",title:A})}upsertNotificationSubscription(A,Q){this.send({type:"client_upsert_notification_subscription",subscription:A,threadURL:Q})}readDirectory(A){return this.requestReadDirectory(A)}readFile(A){return this.requestReadFile(A)}resumeFromVersion(A){this.send({type:"client_resume",version:A}),this.resumeCursor.reset(A)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(A){let Q=A===void 0?{}:{seq:A};if(!this.hasOpenSocket()){this.pendingDismissActiveError=Q;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Q})}cancelAgentLoop(){if(!this.hasOpenSocket()){this.pendingCancelAgentLoop=!0;return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(A){this.send({type:"client_append_manual_bash_invocation",args:nX(A.args),run:nX(A.run),hidden:A.hidden})}resolveToolApproval(A,Q,B){this.send({type:"client_tool_approval_response",toolCallId:A,accepted:Q,input:B})}requestExecutorSpawn(A,Q){this.send({type:"client_spawn_executor",requestId:A,repositoryURL:Q?.repositoryURL,projectID:Q?.projectID,additionalRepositories:Q?.additionalRepositories})}executePluginCommand(A,Q,B,$){this.sendPluginMessage({type:"request",id:A,method:"command.execute",params:{pluginName:Q,commandId:B,threadID:$}})}executorHandshake(A,Q,B){if(this.disposed)throw new T3("Transport is disposed");if(!this.hasOpenSocket()){if(this.getConnectionInfo().state==="connected")this.forceReconnect("executor handshake attempted without open socket");throw new T3("WebSocket is not connected. Call connect() first.")}let $=performance.now(),J=60000,Y={clientId:A,executorType:B?.executorType,timeoutMs:J};return this.log.info("[thread-client] Starting executor handshake",{...Y,connectionState:this.getConnectionInfo().state}),new Promise((Z,X)=>{let F=!1,D=null,G=null,V=()=>Math.round(performance.now()-$),U=(W,z,q)=>{let N=this.getConnectionInfo();this.log.error(W,{...Y,durationMs:V(),connectionState:N.state,role:N.role,reconnectCauseType:N.reconnectCause?.type,reconnectCode:N.reconnectCause?.code,reconnectReason:N.reconnectCause?.reason,error:z,...q})},K=(W)=>{this.log.info("[thread-client] Executor handshake completed",{...Y,durationMs:V(),executorId:W.executorId,registeredToolCount:W.registeredToolCount,resumeBootstrap:W.resumeBootstrap}),H(()=>Z(W))},E=(W)=>{let z=Error(W.message);U("[thread-client] Executor handshake rejected by server",z,{code:W.code}),H(()=>X(z))},H=(W)=>{if(F)return;if(F=!0,D)clearTimeout(D),D=null;this.executorConnectedListeners.delete(K),this.executorErrorListeners.delete(E),G?.unsubscribe(),W()};this.executorConnectedListeners.add(K),this.executorErrorListeners.add(E),G=this.connectionChanges().subscribe({next:(W)=>{if(W.state==="connected")return;let z=new T3(W.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");U("[thread-client] Executor handshake interrupted",z),H(()=>X(z))}}),this.send({type:"executor_connect",clientId:A,capabilities:Q,executorType:B?.executorType}),D=setTimeout(()=>{let W=Error("Executor connect timeout");U("[thread-client] Executor handshake timed out",W),H(()=>X(W))},J)})}ackToolLease(A){this.send({type:"executor_tool_lease_ack",toolCallId:A})}sendToolProgress(A,Q){let B=Yu(Q,"snapshot");this.send({type:"tool_progress",toolCallId:A,progress:B})}sendExecutorToolResult(A,Q){this.send({type:"executor_tool_result",toolCallId:A,run:Q})}sendExecutorFileSystemReadDirectoryResult(A,Q){this.send({type:"executor_filesystem_read_directory_result",requestId:A,...Q})}sendExecutorFileSystemReadFileResult(A,Q){this.send({type:"executor_filesystem_read_file_result",requestId:A,...Q})}sendExecutorToolApprovalRequest(A){this.send({type:"executor_tool_approval_request",approval:A})}sendPluginMessage(A){this.send({type:"executor_plugin_message",message:A})}sendExecutorGuidanceSnapshot(A){this.send({type:"executor_guidance_snapshot",...A})}sendExecutorGuidanceDiscovery(A){this.send({type:"executor_guidance_discovery",...A})}sendExecutorSkillSnapshot(A){this.send({type:"executor_skill_snapshot",...A})}sendClientUpdateThreadSettings(A){if(!this.hasOpenSocket()){this.pendingThreadSettings=A;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch(Q){if(!this.hasOpenSocket()){this.pendingThreadSettings=A;return}throw Q}}registerTools(A){this.send({type:"executor_tools_register",tools:A})}sendExecutorToolsBootstrapComplete(A,Q){this.send({type:"executor_tools_bootstrap_complete",ok:A,error:Q})}sendEnvironmentSnapshot(A){this.send({type:"executor_environment_snapshot",environment:A}),this.environmentSubject.next(A)}sendEnvironmentUpdate(A){this.send({type:"executor_environment_update",environment:A}),this.environmentSubject.next(A)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(A,Q){this.send({type:"executor_artifact_upsert",artifact:A,toolCallId:Q})}sendExecutorArtifactDelete(A){this.send({type:"executor_artifact_delete",key:A})}unregisterTools(A){this.send({type:"executor_tools_unregister",toolNames:A})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outbox.reset(),this.optimisticUserMessages.reset(),this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=s51(0),this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(A){if(super.updateConnectionState(A),A==="connected")this.flushPendingThreadSettings(),this.outbox.retry(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError();if(this.emitConnectionChanged(),A==="reconnecting"||A==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(A){let Q=Er4.safeDecode(A);if(!Q.success){let $=Kr4.safeDecode(A),J=$.success?Q.error:$.error,Y={type:"error",message:Tr4(A,J),code:"PARSE_ERROR"};this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.(Y)});return}let B=Array.isArray(Q.data)?Q.data:[Q.data];for(let $ of B)this.handleServerMessage($)}onMaxReconnectExceeded(A){this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${A} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(A){switch(this.advanceResumeCursor(A),this.reconcileOptimisticUserMessage(A),this.outbox.handleServerMessage(A),A.type){case"agent_state":this.dispatchObserverCallbacks((Q)=>{Q.onAgentState?.(A)});break;case"inference_tools":this.dispatchObserverCallbacks((Q)=>{Q.onInferenceTools?.(A)});break;case"thread_settings":this.dispatchObserverCallbacks((Q)=>{Q.onThreadSettings?.(A)});break;case"error":this.dispatchObserverCallbacks((Q)=>{Q.onErrorNotice?.(A)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Q)=>{Q.onActiveError?.(A)});break;case"cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onCancelled?.(A)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Q)=>{Q.onRetryEvent?.(A)});break;case"delta":this.dispatchObserverCallbacks((Q)=>{Q.onDelta?.(A)});break;case"message_updated":this.dispatchObserverCallbacks((Q)=>{Q.onMessageUpdated?.(A)});break;case"edit_rejected":this.dispatchObserverCallbacks((Q)=>{Q.onEditRejected?.(A)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=A.executorId,this.connectionSubject.next({...this.connectionInfo}),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Q)=>{Q.onExecutorConnected?.(A)});for(let Q of this.executorConnectedListeners)Q(A);break;case"tool_lease":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLease?.(A)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadDirectoryRequest?.(A)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Q)=>{Q.onFileSystemReadFileRequest?.(A)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Q)=>{Q.onToolLeaseRevoked?.(A)});break;case"executor_tool_result_ack":this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorToolResultAck?.(A)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Q)=>{Q.onToolApprovalQueue?.(A)});break;case"plugin_message":this.dispatchObserverCallbacks((Q)=>{Q.onPluginMessage?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onPluginMessage?.(A)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorToolApprovalResponse?.(A)});break;case"tool_progress":this.dispatchObserverCallbacks((Q)=>{Q.onToolProgress?.(A)});break;case"executor_error":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorError?.(A)}),this.dispatchExecutorCallbacks((Q)=>{Q.onExecutorError?.(A)});for(let Q of this.executorErrorListeners)Q(A);break;case"observers":this.dispatchObserverCallbacks((Q)=>{Q.onObservers?.(A)});break;case"executor_status":this.dispatchObserverCallbacks((Q)=>{Q.onExecutorStatus?.(A)});break;case"environment_update":this.environmentSubject.next(A.environment),this.dispatchObserverCallbacks((Q)=>{Q.onEnvironmentUpdate?.(A)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Q)=>{Q.onArtifactEvent?.(A)});break;case"thread_title":this.dispatchObserverCallbacks((Q)=>{Q.onThreadTitle?.(A)});break;case"thread_relationships":this.dispatchObserverCallbacks((Q)=>{Q.onThreadRelationships?.(A)});break;case"thread_truncated":this.dispatchObserverCallbacks((Q)=>{Q.onTruncate?.(A)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(A);break;case"client_filesystem_read_file_result":this.handleReadFileResult(A);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Q)=>{Q.onCompactionEvent?.(A)});break;case"thread_status":break}}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.hasOpenSocket())return;let A=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:A})}catch{if(!this.hasOpenSocket())this.pendingThreadSettings=A}}flushPendingCancelAgentLoop(){if(!this.pendingCancelAgentLoop||!this.hasOpenSocket())return;try{this.send({type:"client_cancel"}),this.pendingCancelAgentLoop=!1}catch{if(this.hasOpenSocket())this.pendingCancelAgentLoop=!1}}flushPendingDismissActiveError(){if(!this.pendingDismissActiveError||!this.hasOpenSocket())return;try{this.send({type:"client_dismiss_active_error",...this.pendingDismissActiveError}),this.pendingDismissActiveError=null}catch{if(this.hasOpenSocket())this.pendingDismissActiveError=null}}reconcileOptimisticUserMessage(A){switch(A.type){case"agent_state":this.optimisticUserMessages.setAgentLoopState(A.state);return;case"message_added":this.optimisticUserMessages.reconcileMessageAdded(A);return;case"queued_messages":this.optimisticUserMessages.reconcileQueuedMessagesSnapshot(A);return;case"queued_message_added":this.optimisticUserMessages.reconcileQueuedMessageAdded(A);return;case"queued_message_removed":this.optimisticUserMessages.reconcileQueuedMessageRemoved(A);return;default:return}}trySendOutboxMessage(A){if(!this.hasOpenSocket())return!1;try{return this.send(A),!0}catch(Q){let B=Q instanceof Error?Q.message:String(Q);return this.dispatchObserverCallbacks(($)=>{$.onErrorNotice?.($i5(B))}),!1}}emitConnectionChanged(){let A=this.getConnectionInfo();this.log.info("[thread-client] Emitting connection change callbacks",{state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCode:A.reconnectCause?.code,reconnectReason:A.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Q)=>{Q.onConnectionChange?.(A)}),this.dispatchObserverCallbacks((Q)=>{Q.onConnectionChanged?.(A)})}dispatchObserverCallbacks(A){let Q=this.observerCallbacks;if(!Q){this.pendingObserverDispatches.push(A);return}A(Q)}dispatchExecutorCallbacks(A){let Q=this.executorCallbacks;if(!Q){this.pendingExecutorDispatches.push(A);return}A(Q)}requestReadDirectory(A){let Q=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Q,()=>{this.send({type:"client_filesystem_read_directory",requestId:Q,uri:A})})}requestReadFile(A){let Q=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Q,()=>{this.send({type:"client_filesystem_read_file",requestId:Q,uri:A})})}createPendingReadRequest(A,Q,B){if(!this.hasOpenSocket())return Promise.reject(new T3("WebSocket is not connected"));return new Promise(($,J)=>{let Y=setTimeout(()=>{A.delete(Q),J(new T3(`Filesystem request timed out: ${Q}`))},Qr4);A.set(Q,{resolve:$,reject:J,timeoutID:Y});try{B()}catch(Z){clearTimeout(Y),A.delete(Q),J(Z instanceof Error?Z:Error(String(Z)))}})}nextFileSystemRequestID(A){let Q=this.fileSystemRequestCounter++;return`${A}-${Date.now()}-${Q}`}handleReadDirectoryResult(A){let Q=this.pendingReadDirectoryRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadDirectoryRequests.delete(A.requestId),A.ok&&A.entries){Q.resolve(A.entries);return}if(A.ok){Q.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!A.error){Q.reject(Error("Invalid filesystem read_directory response: missing error"));return}Q.reject(this.createFileSystemError(A.error))}handleReadFileResult(A){let Q=this.pendingReadFileRequests.get(A.requestId);if(!Q)return;if(clearTimeout(Q.timeoutID),this.pendingReadFileRequests.delete(A.requestId),!A.ok&&A.error){Q.reject(this.createFileSystemError(A.error));return}if(!A.ok){Q.reject(Error("Invalid filesystem read_file response: missing error"));return}if(A.contentBase64===void 0){Q.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Q.resolve(Bi5(A.contentBase64))}catch{Q.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(A){return Error(`Filesystem error (${A.code}): ${A.message}`)}rejectPendingFileSystemRequests(A){for(let[Q,B]of this.pendingReadDirectoryRequests)clearTimeout(B.timeoutID),B.reject(new T3(A)),this.pendingReadDirectoryRequests.delete(Q);for(let[Q,B]of this.pendingReadFileRequests)clearTimeout(B.timeoutID),B.reject(new T3(A)),this.pendingReadFileRequests.delete(Q)}advanceResumeCursor(A){if(!("seq"in A)||!Number.isFinite(A.seq))return;this.resumeCursor.advanceFromSeq(A.seq)}send(A){try{this.sendRaw(Ur4.encode(A))}catch(Q){let B=Q instanceof Error?Q.message:String(Q);throw new T3(`Failed to encode thread-protocol message "${A.type}": ${B}`,Q)}}}j1();function X81(A){return{...A,pendingRemoval:!0}}function kr4(A,Q){if(Q.find(($)=>$.queuedMessage.messageId===A.queuedMessage.messageId)?.pendingRemoval!==!0)return A;return X81(A)}function vr4(A,Q,B){if(Q.type==="queued_messages")return Q.messages.map(($)=>kr4($,A));if(Q.type==="queued_message_added"){if(A.find((J)=>J.queuedMessage.messageId===Q.message.queuedMessage.messageId)&&B.dedupeAdded)return[...A];return[...A,kr4(Q.message,A)]}if(!A.some(($)=>$.queuedMessage.messageId===Q.queuedMessageId))return[...A];return A.filter(($)=>$.queuedMessage.messageId!==Q.queuedMessageId)}var yr4={state:"disconnected",role:null,clientId:null};function xr4(A){return[...A].sort((Q,B)=>Q.key.localeCompare(B.key))}function Ji5(A,Q){let B=A.findIndex((J)=>J.key===Q.key);if(B===-1)return xr4([...A,Q]);let $=[...A];return $[B]=Q,$}class pU0{connectionInfo;agentLoopState;pendingSend=new D4(!1);queuedMessages=new D4([]);pendingApprovals=new D4([]);lastError=new D4(null);activeError=new D4(null);cancelledMessageId=new D4(null);retryState=new D4(null);executorError=new D4(null);observers=new D4(null);executorStatus=new D4(null);environment=new D4(null);compactionState=new D4("idle");compactionRecords=new D4([]);artifacts=new D4([]);threadSettings;threadTitle=new D4(void 0);threadId=new D4(null);messageAddedEvents=new r4;messageUpdatedEvents=new r4;deltaEvents=new r4;toolProgressEvents=new r4;truncateEvents=new r4;pluginMessages=new r4;now;dedupeQueuedMessageAdds;compactionRecordsState;constructor(A={}){this.connectionInfo=new D4(A.initialConnectionInfo??yr4),this.agentLoopState=new D4(A.initialAgentLoopState??"idle"),this.threadSettings=new D4(A.initialThreadSettings??null),this.dedupeQueuedMessageAdds=A.dedupeQueuedMessageAdds??!0,this.compactionRecordsState=A.compactionRecordsState??null,this.now=A.now??(()=>new Date().toISOString())}callbacks(){return this}onConnectionChanged(A){this.connectionInfo.next(A)}onAgentState(A){if(w$(A.state))this.pendingSend.next(!1);this.agentLoopState.next(A.state)}onUserMessageSendPending(A,Q){this.pendingSend.next(!0)}onThreadSettings(A){this.threadSettings.next(A.settings)}onMessageAdded(A){this.messageAddedEvents.next(A)}onMessageUpdated(A){this.messageUpdatedEvents.next(A)}onDelta(A){this.deltaEvents.next(A)}onToolProgress(A){this.toolProgressEvents.next(A)}onTruncate(A){this.truncateEvents.next(A)}onPluginMessage(A){this.pluginMessages.next(A)}onQueuedMessages(A){this.queuedMessages.next(vr4(this.queuedMessages.getValue(),A,{dedupeAdded:this.dedupeQueuedMessageAdds}))}onUserActionMessageDeliveryStatusChanged(A,Q,B){if(Q!=="buffered")return;let $=this.queuedMessages.getValue(),J=$.findIndex((X)=>X.queuedMessage.messageId===A);if(J===-1)return;let Y=$[J];if(!Y)return;let Z=[...$];Z[J]=X81(Y),this.queuedMessages.next(Z)}onToolApprovalQueue(A){this.pendingApprovals.next(A.approvals)}onErrorNotice(A){this.clearPendingSendIfIdle(),this.lastError.next(A)}onActiveError(A){if(A.type==="error_set")this.clearPendingSendIfIdle();this.cancelledMessageId.next(null),this.activeError.next(A.type==="error_set"?A.error:null)}onCancelled(A){this.cancelledMessageId.next(A.messageId??null),this.activeError.next(null)}onExecutorError(A){this.executorError.next(A)}onRetryEvent(A){this.retryState.next(A)}onObservers(A){this.observers.next({count:A.count,observers:A.observers,hasExecutor:A.hasExecutor??!1})}onExecutorStatus(A){if(this.executorStatus.next(A),A.status==="running")this.executorError.next(null)}onEnvironmentUpdate(A){this.environment.next(A.environment)}onArtifactEvent(A){let Q=this.artifacts.getValue();switch(A.type){case"artifacts_snapshot":this.artifacts.next(xr4(A.artifacts));return;case"artifact_upserted":this.artifacts.next(Ji5(Q,A.artifact));return;case"artifact_deleted":this.artifacts.next(Q.filter((B)=>B.key!==A.key));return}}onCompactionEvent(A){if(A.type==="compaction_started"){this.compactionState.next("compacting");return}if(A.type==="compaction_complete"){this.compactionState.next("idle"),this.addCompactionRecord({cutMessageId:A.cutMessageId,createdAt:this.now()});return}if(this.compactionRecords.next(A.records),this.compactionRecordsState!==null)this.compactionState.next(this.compactionRecordsState)}onThreadTitle(A){this.threadTitle.next(A.title||void 0)}onThreadId(A){this.threadId.next(A)}resetRuntimeState(){this.connectionInfo.next(yr4),this.agentLoopState.next("idle"),this.pendingSend.next(!1),this.queuedMessages.next([]),this.pendingApprovals.next([]),this.activeError.next(null),this.executorError.next(null),this.cancelledMessageId.next(null),this.retryState.next(null),this.observers.next(null),this.executorStatus.next(null),this.environment.next(null),this.compactionState.next("idle"),this.artifacts.next([])}dispose(){this.connectionInfo.complete(),this.agentLoopState.complete(),this.pendingSend.complete(),this.queuedMessages.complete(),this.pendingApprovals.complete(),this.lastError.complete(),this.activeError.complete(),this.cancelledMessageId.complete(),this.retryState.complete(),this.executorError.complete(),this.observers.complete(),this.executorStatus.complete(),this.environment.complete(),this.compactionState.complete(),this.compactionRecords.complete(),this.artifacts.complete(),this.threadSettings.complete(),this.threadTitle.complete(),this.threadId.complete(),this.messageAddedEvents.complete(),this.messageUpdatedEvents.complete(),this.deltaEvents.complete(),this.toolProgressEvents.complete(),this.truncateEvents.complete(),this.pluginMessages.complete()}addCompactionRecord(A){let Q=this.compactionRecords.getValue();if(Q.some((B)=>B.cutMessageId===A.cutMessageId))return;this.compactionRecords.next([...Q,A])}clearPendingSendIfIdle(){if(this.pendingSend.getValue()&&!w$(this.agentLoopState.getValue()))this.pendingSend.next(!1)}}i0();function dU0(A){let{client:Q,observer:B,toolService:$,callbacks:J}=A,Y=new Set,Z=[],X=!1,F=!1,D=null,G=!1,V=[],U=setInterval(()=>{},1000),E=Qu(()=>{if(G)return;j.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{Q.cancelAgentLoop()}catch(W){j.warn("Failed to cancel remote agent loop on signal",{error:W})}J.onSignal()});return E.install(),V.push(B.activeError$.subscribe((W)=>{if(!W)return;J.onError(W.message)})),V.push(B.errorNotice$.subscribe((W)=>{J.onError(W)})),V.push($.pendingApprovals$.subscribe((W)=>{Z=W})),V.push(B.agentState$.subscribe((W)=>{D=W.state;let z=w$(W.state);if(z&&W.messageId)Y.add(W.messageId);if(z){X=!0,F=!0;return}if(F=!1,!X)return;J.onTransitionToIdle(Z)})),V.push(B.messageAdded$.subscribe((W)=>{J.onMessageAdded(W)})),{currentTurnAssistantIds:Y,pendingApprovals:()=>Z,agentStarted:()=>X,agentActive:()=>F,agentIdle:()=>D==="idle",dispose:()=>{if(G)return;G=!0,E.remove(),clearInterval(U);for(let W of V)W.unsubscribe()}}}import Yi5 from"node:process";var F81=Number(Yi5.env.SIMULATE_LATENCY??0),Zi5=Number.isFinite(F81)&&F81>0?F81:0;function Xu(A,Q){let B=Q;return async()=>{let $=await A(B);return B=$.threadId,$}}function Fu(A){let Q=yK({endpoint:A.rivetEndpoint});return{...A.initialThreadID?{threadId:A.initialThreadID}:{},...A.maxReconnectAttempts!==void 0?{maxReconnectAttempts:A.maxReconnectAttempts}:{},pingIntervalMs:A.pingIntervalMs??5000,webSocketLatencyMs:()=>Zi5,webSocketProvider:async()=>{let B=await A.credentialsProvider({forceRefresh:!0});return{webSocket:await Q.threadActor.getOrCreate([B.threadId],{params:{wsToken:B.wsToken},createWithInput:{threadId:B.threadId,threadVersion:B.threadVersion,ownerUserId:B.ownerUserId,...B.agentMode?{agentMode:B.agentMode}:{}}}).webSocket("/"),threadId:B.threadId}}}}AA();function cU0(A){let Q=A.agentMode||dc(A);if(!Q)throw Error("agent mode could not be determined from thread");return{version:A.v,title:A.title??null,messages:A.messages.map((B)=>ur4(A,B)),agentMode:Q,needsImport:!Fi5(A)}}function br4(A){let Q=A.agentMode||dc(A);if(!Q)throw Error("agent mode could not be determined from thread");return{id:A.id,v:A.v,...A.title?{title:A.title}:{},messages:A.messages.map((B)=>Xi5(A,B)),agentMode:Q,...A.meta?{meta:A.meta}:{}}}function Xi5(A,Q){let{threadId:B,...$}=ur4(A,Q);return $}function Fi5(A){if(!A.meta||typeof A.meta!=="object")return!1;return A.meta.usesThreadActors===!0}function ur4(A,Q){let B=Di5(Q);switch(Q.role){case"user":return{threadId:A.id,role:"user",content:[...Q.content],meta:s90(Q.meta),userState:Gi5(Q.userState),readAt:Q.readAt,messageId:B};case"assistant":return{threadId:A.id,role:"assistant",content:[...Q.content],state:Q.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Q.usage,readAt:Q.readAt,messageId:B};case"info":return{threadId:A.id,role:"info",content:Q.content.filter(Vi5),messageId:B}}}function Di5(A){let Q=fr4(A.protocolMessageID);if(Q)return Q;let B=A.messageId;if(typeof B==="string"){let $=fr4(B);if($)return $}return vU0()}function fr4(A){if(!A)return null;let Q=Z5.safeParse(A);return Q.success?Q.data:null}function Gi5(A){if(!A)return;return{...A,currentlyVisibleFiles:[...A.currentlyVisibleFiles],runningTerminalCommands:A.runningTerminalCommands?[...A.runningTerminalCommands]:void 0,aggmanContext:A.aggmanContext?{...A.aggmanContext,availableProjects:A.aggmanContext.availableProjects?A.aggmanContext.availableProjects.map((Q)=>({...Q})):void 0,recentUnreadThreads:A.aggmanContext.recentUnreadThreads?A.aggmanContext.recentUnreadThreads.map((Q)=>({...Q})):void 0}:void 0}}function Vi5(A){return A.type==="manual_bash_invocation"}eQ();H4();import Ye from"node:path";class _P extends Error{code;constructor(A,Q){super(Q);this.code=A;this.name="ExecutorFileSystemPathError"}}function gr4(A,Q){let B=J1.parse(A);if(B.scheme!=="file")throw new _P("INVALID_URI","Only file:// URIs are supported");if(!B.path.startsWith("/"))throw new _P("INVALID_URI","File URI path must be absolute");if(B.path.split("/").some((F)=>F===".."))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");let J=Ye.posix.normalize(B.path).replace(/^\/+/u,"");if(J===".."||J.startsWith("../"))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");let Y=Ye.resolve(Q),Z=J.length>0?Ye.resolve(Y,J):Y,X=Ye.relative(Y,Z);if(X.startsWith("..")||Ye.isAbsolute(X))throw new _P("ACCESS_DENIED","File URI resolves outside workspace root");return Z}async function hw(A,Q){try{let B=gr4(Q,A.workspaceRoot),$=await A.fileSystem.readdir(J1.file(B));return{ok:!0,entries:await Promise.all($.map(async(Y)=>{let Z=Y.isDirectory?"directory":"file",X=Z==="file"?await Ui5(A.fileSystem,Y.uri):void 0;return[K1.basename(Y.uri),Z,X]}))}}catch(B){return{ok:!1,error:pr4(B,"read_directory")}}}async function Ui5(A,Q){try{let B=await A.getMtime(Q);if(!Number.isFinite(B)||B<0)return;return{mtimeMs:B}}catch{return}}async function mr4(A,Q){try{let B=gr4(Q,A.workspaceRoot),$=await A.fileSystem.readBinaryFile(J1.file(B));return{ok:!0,contentBase64:Buffer.from($).toString("base64")}}catch(B){return{ok:!1,error:pr4(B,"read_file")}}}function pr4(A,Q){if(A instanceof _P)return{code:A.code,message:A.message};if(d3(A))return{code:"NOT_FOUND",message:"File or directory not found"};if(lU0(A,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(lU0(A,"ENOTDIR"))return{code:Q==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Q==="read_directory"?"Expected a directory":hr4(A)};if(lU0(A,"EACCES")||lU0(A,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:hr4(A)}}function lU0(A,Q){if(!(A instanceof Error))return!1;return"code"in A&&A.code===Q}function hr4(A){if(A instanceof Error)return A.message;return String(A)}i0();g5();XY0();AA();H4();j1();i0();function iU0(A){return(Q)=>{let B=Q.message;if(B.type!=="request")return;let $=Date.now();j.info("Plugin hook dispatcher request received",{method:B.method,id:B.id}),Ki5(A.pluginService,B.method,B.params).then((J)=>{j.info("Plugin hook dispatcher request completed",{method:B.method,id:B.id,durationMs:Date.now()-$}),A.sendPluginMessage(dr4(B.id,J))}).catch((J)=>{j.warn("Plugin hook dispatcher request failed",{method:B.method,id:B.id,durationMs:Date.now()-$,error:J}),A.sendPluginMessage(dr4(B.id,void 0,J instanceof Error?J.message:String(J)))})}}function dr4(A,Q,B){if(B!==void 0)return{type:"response",id:A,error:B};if(Q===void 0)return{type:"response",id:A};return{type:"response",id:A,result:Q}}async function Ki5(A,Q,B){switch(Q){case"agent.start":{let{event:$}=B;return await A.event.agentStart($)}case"agent.end":{let{event:$}=B;return await A.event.agentEnd($)}case"command.execute":{let{pluginName:$,commandId:J,threadID:Y}=B;return await A.commands.execute($,J,Y?{threadID:Y}:void 0),{ok:!0}}default:throw Error(`Unknown plugin hook method: ${Q}`)}}import{exec as Ei5}from"node:child_process";import{promisify as Hi5}from"node:util";TU();AA();H4();var Wi5=Hi5(Ei5);async function cr4(A){let Q=await bW(),B=W7(A)?A:G9(),$=await oD({filesystem:e5},Q,B),J=await zi5($.workingDirectory??$.workspaceRoot);return{...Q,...$,...J?{git:{branch:J}}:{},updatedAt:new Date().toISOString()}}async function zi5(A){if(!A)return;let Q;try{Q=J1.parse(A).fsPath}catch{return}try{let{stdout:B}=await Wi5("git symbolic-ref --quiet --short HEAD",{cwd:Q});return B.trim()||void 0}catch{return}}function qi5(A){return new TextEncoder().encode(JSON.stringify(A)).length}function Du(A,Q,B){if(A.length===0)return[];let $=[],J=[];for(let Y of A){let Z=[...J,Y],X=qi5(B(Z));if(J.length>0&&X>Q){$.push(J),J=[Y];continue}J=Z}if(J.length>0)$.push(J);return $}var ir4=1048576;function lr4(A){let Q=new Map;for(let B of A)Q.set(B.name,{schema:B,serializedSchema:JSON.stringify(B)});return Q}function Ni5(A){let Q={...A.executionProfile?.serial!==void 0?{serial:A.executionProfile.serial}:{},...A.meta?.deferred!==void 0?{deferred:A.meta.deferred}:{},...A.meta?.skillNames!==void 0?{skillNames:[...A.meta.skillNames]}:{}};return Object.keys(Q).length>0?Q:void 0}function Ii5(A){return{name:A.name,description:A.description??"",inputSchema:{type:"object",properties:A.inputSchema.properties??{},required:A.inputSchema.required,additionalProperties:A.inputSchema.additionalProperties},source:A.source,meta:Ni5(A)}}function nU0(A){return A.map((Q)=>Ii5(Q.spec))}function nr4(A,Q){let B=lr4(A),$=lr4(Q);return{toolsToRegister:Q.filter((J)=>{let Y=B.get(J.name),Z=$.get(J.name);return Y?.serializedSchema!==Z?.serializedSchema}),toolNamesToUnregister:[...B.keys()].filter((J)=>!$.has(J))}}function ar4(A,Q=ir4){return Du(A,Q,(B)=>({type:"executor_tools_register",tools:B}))}function or4(A,Q=ir4){return Du(A,Q,(B)=>({type:"executor_tools_unregister",toolNames:B}))}import{execFile as Oi5}from"node:child_process";import{createHash as ji5}from"node:crypto";import{readFile as Ri5,stat as Pi5}from"node:fs/promises";import{basename as _i5,join as Ti5}from"node:path";import $s4 from"node:process";import{promisify as Si5}from"node:util";async function rr4(A,Q,B){let $=[];for(let J=0;J<A.length;J+=Q){let Y=A.slice(J,J+Q);$.push(...await Promise.all(Y.map(B)))}return $}var sr4=2097152,gw="(Content omitted — git status artifact exceeds size limit)";function wi5(A){return(A.fullFileDiff?.length??0)+(A.oldContent?.length??0)+(A.newContent?.length??0)}function Ci5(A){let Q=!1;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==A.diff)A.fullFileDiff=A.diff,Q=!0;if(A.oldContent!==void 0&&A.oldContent!==gw)A.oldContent=gw,Q=!0;if(A.newContent!==void 0&&A.newContent!==gw)A.newContent=gw,Q=!0;return Q}function Mi5(A){let Q=!1;if(A.oldContent!==void 0)A.oldContent=void 0,Q=!0;if(A.newContent!==void 0)A.newContent=void 0,Q=!0;if(A.fullFileDiff!==void 0)A.fullFileDiff=void 0,Q=!0;return Q}function Li5(A){let Q=!1;if(A.diff!==gw)A.diff=gw,Q=!0;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==gw)A.fullFileDiff=gw,Q=!0;return Q}function Gu(A){let Q=Buffer.from(JSON.stringify(A),"utf8").toString("base64"),B=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:Yx,dataType:"application/json",contentBase64:Q}})).length;return{contentBase64:Q,messageSizeBytes:B}}function tr4(A,Q){let B={...A,aheadCommits:[...A.aheadCommits],files:A.files.map((Z)=>({...Z}))},$=Gu(B);if($.messageSizeBytes<=Q)return $.contentBase64;let J=B.files.map((Z,X)=>({index:X,weight:wi5(Z)})).filter((Z)=>Z.weight>0).sort((Z,X)=>X.weight-Z.weight);for(let{index:Z}of J){let X=B.files[Z];if(!X||!Ci5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}for(let{index:Z}of J){let X=B.files[Z];if(!X||!Mi5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}let Y=B.files.map((Z,X)=>({index:X,weight:Z.diff.length+(Z.fullFileDiff?.length??0)})).filter((Z)=>Z.weight>0).sort((Z,X)=>X.weight-Z.weight);for(let{index:Z}of Y){let X=B.files[Z];if(!X||!Li5(X))continue;if($=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}if(B.aheadCommits.length>0){if(B.aheadCommits=[],$=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64}while(B.files.length>0)if(B.files.pop(),$=Gu(B),$.messageSizeBytes<=Q)return $.contentBase64;return $.contentBase64}var ki5=Si5(Oi5),Uu=20971520,vi5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],aU0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],yi5=999999,er4="refs/remotes/origin/",xi5=20,fi5=10;function oU0(A){return A.replace(/\n+$/,"")}var D81=$s4.platform==="win32"?"NUL":"/dev/null";function bi5(A=$s4.env,Q={}){let{isolateGitConfig:B=!0}=Q,$={...A};if(B){for(let J of Object.keys($))if(vi5.includes(J)||J.startsWith("GIT_CONFIG_KEY_")||J.startsWith("GIT_CONFIG_VALUE_"))delete $[J];$.GIT_CONFIG_NOSYSTEM="1",$.GIT_CONFIG_SYSTEM=D81,$.GIT_CONFIG_GLOBAL=D81}return $}function As4(A,Q){return{provider:"git",capturedAt:A,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Q}}function ui5(A){return A instanceof Error}async function Vu(A,Q,B={}){try{let{stdout:$}=await ki5("git",Q,{cwd:A,env:bi5(),maxBuffer:B.maxBufferBytes??Uu});return $}catch($){if(B?.allowExitCodeOne&&ui5($)&&($.code===1||$.code==="1")&&typeof $.stdout==="string")return $.stdout;throw $}}async function Qz(A,Q){try{return await Vu(A,Q)}catch{return null}}function hi5(A){if(A==="??")return"untracked";let Q=A[0]??" ",B=A[1]??" ";if(Q==="U"||B==="U"||A==="AA"||A==="DD")return"unmerged";if(Q==="R"||B==="R")return"renamed";if(Q==="C"||B==="C")return"copied";if(Q==="A"||B==="A")return"added";if(Q==="D"||B==="D")return"deleted";if(Q==="T"||B==="T")return"type_changed";return"modified"}function G81(A){let Q=[],B=A.split("\x00");for(let $=0;$<B.length;$++){let J=B[$];if(!J||J.length<4)continue;let Y=J.slice(0,2),Z=J.slice(3);if(!Z)continue;let X=hi5(Y);if(X==="renamed"||X==="copied"){let F=B[$+1];if(F){Q.push({path:Z,previousPath:F,changeType:X}),$+=1;continue}}Q.push({path:Z,changeType:X})}return Q.sort(($,J)=>$.path.localeCompare(J.path))}function gi5(A){let Q=0,B=0,$=0,J=0,Y=0,Z=()=>{if(J===0&&Y===0)return;$+=Math.min(J,Y),J=0,Y=0};for(let X of A.split(`
4567
4567
  `)){if(X.startsWith("+")&&!X.startsWith("+++")){Q+=1,J+=1;continue}if(X.startsWith("-")&&!X.startsWith("---")){B+=1,Y+=1;continue}Z()}return Z(),{added:Q,deleted:B,changed:$}}function mi5(A){let Q=ji5("sha256");for(let B of A)Q.update(B.path),Q.update("\x00"),Q.update(B.diff),Q.update("\x00");return Q.digest("hex")}async function Qs4(A,Q,B,$,J=Uu){let Y=$!==void 0?[`--unified=${$}`]:[];if(B)return Vu(A,[...aU0,...Y,"HEAD","--",Q],{maxBufferBytes:J});let[Z,X]=await Promise.all([Vu(A,[...aU0,...Y,"--cached","--",Q],{maxBufferBytes:J}).catch(()=>""),Vu(A,[...aU0,...Y,"--",Q],{maxBufferBytes:J}).catch(()=>"")]);return[oU0(Z),oU0(X)].filter(Boolean).join(`
4568
4568
  `)}async function pi5(A,Q,B=Uu){return Vu(A,[...aU0,"--no-index","--",D81,Q],{allowExitCodeOne:!0,maxBufferBytes:B})}async function di5(A,Q,B,$=Uu){let J=B??"HEAD";try{return await Vu(A,["show",`${J}:${Q}`],{maxBufferBytes:$})}catch{return}}async function ci5(A,Q,B=Uu){try{let $=Ti5(A,Q);if((await Pi5($)).size>B)return;return await Ri5($,"utf-8")}catch{return}}function Bs4(A){let Q=Number.parseInt(A.trim(),10);if(!Number.isFinite(Q))return null;return Q}async function li5(A){let Q=(await Qz(A,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Q?.startsWith(er4))return null;let B=Q.slice(er4.length);if(!B)return null;let $=`origin/${B}`,Y=(await Qz(A,["rev-parse","--verify","--quiet",`${$}^{commit}`]))?.trim();if(!Y)return null;return{baseRef:B,comparisonRef:$,baseRefHead:Y}}function ii5(A){let Q=A.split("\x00"),B=[];for(let $=0;$+1<Q.length;$+=2){let J=Q[$],Y=Q[$+1]??"";if(!J)continue;B.push({hash:J,shortHash:J.slice(0,12),subject:Y})}return B}async function ni5(A,Q){let B=await Qz(A,["log","-z",`--max-count=${xi5}`,"--format=%H%x00%s",`${Q}..HEAD`]);if(!B)return[];return ii5(B)}async function ai5(A,Q){if(!Q)return null;let B=await li5(A);if(!B)return null;let $=await Qz(A,["rev-list","--count",`${B.comparisonRef}..HEAD`]);if(!$)return null;let J=await Qz(A,["rev-list","--count",`HEAD..${B.comparisonRef}`]);if(!J)return null;let Y=Bs4($);if(Y===null)return null;let Z=Bs4(J);if(Z===null)return null;return{baseRef:B.baseRef,comparisonRef:B.comparisonRef,baseRefHead:B.baseRefHead,aheadCount:Y,behindCount:Z}}async function rU0(A,Q={}){let{maxDiffBufferBytes:B=Uu}=Q,$=Date.now(),J=await Qz(A,["rev-parse","--show-toplevel"]);if(!J)return As4($,"not a git repository");let Y=J.trim(),Z=_i5(Y),[X,F,D]=await Promise.all([Qz(Y,["rev-parse","--verify","HEAD"]),Qz(Y,["symbolic-ref","--short","HEAD"]),Qz(Y,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(D===null)return As4($,"failed to read git status");let G=X?.trim()||null,V=F?.trim()||null,U=G81(D),K=await ai5(Y,G),E=K?.aheadCount&&K.aheadCount>0?await ni5(Y,K.comparisonRef):[],H=await rr4(U,fi5,async(W)=>{let z=oU0(W.changeType==="untracked"?await pi5(Y,W.path,B).catch(()=>""):await Qs4(Y,W.path,G,void 0,B).catch(()=>"")),q=oU0(W.changeType==="modified"?await Qs4(Y,W.path,G,yi5,B).catch(()=>""):z),N=W.changeType!=="added"&&W.changeType!=="untracked"?await di5(Y,W.previousPath??W.path,G,B):void 0,I=W.changeType!=="deleted"?await ci5(Y,W.path,B):void 0;return{path:W.path,previousPath:W.previousPath,changeType:W.changeType,created:W.changeType==="added"||W.changeType==="untracked",diff:z,fullFileDiff:q,oldContent:N,newContent:I,diffStat:gi5(z)}});return{provider:"git",capturedAt:$,available:!0,repositoryRoot:Y,repositoryName:Z,branch:V,head:G,diffHash:mi5(H),baseRef:K?.baseRef??null,baseRefHead:K?.baseRefHead??null,aheadCount:K?.aheadCount??0,behindCount:K?.behindCount,aheadCommits:E,files:H}}function oi5(A){return{provider:A.provider,capturedAt:A.capturedAt,available:A.available,repositoryRoot:A.repositoryRoot,repositoryName:A.repositoryName,branch:A.branch,head:A.head,diffHash:A.diffHash,baseRef:A.baseRef??null,baseRefHead:A.baseRefHead??null,aheadCount:A.aheadCount??0,behindCount:A.behindCount,...A.unavailableReason!==void 0?{unavailableReason:A.unavailableReason}:{},aheadCommits:A.aheadCommits??[],files:A.files.map((Q)=>({path:Q.path,previousPath:Q.previousPath,changeType:Q.changeType,created:Q.created,diff:Q.diff,fullFileDiff:Q.fullFileDiff,oldContent:Q.oldContent,newContent:Q.newContent,diffStat:Q.diffStat}))}}function V81(A){let Q=tr4(oi5(A),sr4);return{key:Yx,dataType:"application/json",contentBase64:Q}}import{createHash as ri5}from"node:crypto";function U81(A){return ri5("sha256").update(A).digest("hex")}class Ze{entries=new Map;initialized=!1;static key(A,Q){return`${A}\x00${Q}`}replace(A){this.entries.clear();for(let Q of A)this.entries.set(Ze.key(Q.uri,Q.hash),Q);this.initialized=!0}clear(){this.entries.clear(),this.initialized=!1}has(A,Q){if(!this.initialized||typeof Q!=="string"||Q.length===0)return!1;return this.entries.has(Ze.key(A,Q))}isInitialized(){return this.initialized}}function K81(A,Q){return A.map((B)=>{if(typeof B.hash==="string"&&Q.has(B.uri,B.hash)){let $={uri:B.uri,hash:B.hash};if(typeof B.lineCount==="number")$.lineCount=B.lineCount;return $}return B})}var Js4=1048576;function Ys4(A,Q,B,$=Js4){return Du(A,$,(J)=>({type:"executor_guidance_snapshot",snapshotId:Q,files:J,isLast:!1,userConfigDir:B}))}function Zs4(A,Q,B=Js4){return Du(A,B,($)=>({type:"executor_guidance_discovery",toolCallId:Q,files:$,isLast:!1}))}var Ku={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function sU0(A,Q){if(A>=Q.maxAttempts)return null;let B=Math.max(1,A);return Math.min(Q.baseDelayMs*2**(B-1),Q.maxDelayMs)}function si5(A){return typeof A==="object"&&A!==null&&"output"in A&&A.output===""}function ti5(){let A=()=>{return},Q=()=>{return};return{promise:new Promise(($,J)=>{A=$,Q=J}),resolve:A,reject:Q}}function ei5(A){if(A==="darwin")return"darwin";if(A==="win32")return"windows";return"linux"}function Xs4(A){let Q=A.previouslyAdvertisedTools??[],{toolsToRegister:B,toolNamesToUnregister:$}=nr4(Q,A.nextTools),J=A.forceRegisterAll?[...A.nextTools]:B;for(let Y of ar4(J))A.logMessage?.("SEND",{type:"executor_tools_register",tools:Y.map((Z)=>Z.name)}),A.transport.registerTools(Y);for(let Y of or4($))A.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:Y}),A.transport.unregisterTools(Y);return[...A.nextTools]}async function An5(A){let{transport:Q,threadId:B,configService:$,skillService:J,logMessage:Y}=A,Z=A.fileSystem??e5,X=performance.now(),F={clientID:A.executorClientID,threadID:B,executorType:A.executorType,allowResumeBootstrap:A.allowResumeBootstrap===!0},D={},G="executorHandshake",V=!1,U=performance.now(),K=(W)=>{D[`${W}Ms`]=Math.round(performance.now()-U)};j.info("[executor] Starting executor bootstrap",F);let E={workspaceId:A.workspaceRoot,workingDirectory:A.workspaceRoot,environment:{os:ei5(process.platform)},tags:[]};Y?.("SEND",{type:"executor_connect",clientId:A.executorClientID,capabilities:E,executorType:A.executorType}),G="executorHandshake",U=performance.now();let H=await Q.executorHandshake(A.executorClientID,E,{executorType:A.executorType});K(G),Y?.("RECV",H),A.guidanceContentCache?.replace(H.guidanceInventory),V=A.allowResumeBootstrap===!0&&H.resumeBootstrap===!0;try{if(!V){A.onBootstrapProgress?.("environment"),G="buildEnvironmentSnapshot",U=performance.now();let N=await cr4(B);K(G),Y?.("SEND",{type:"executor_environment_snapshot",environment:N}),Q.sendEnvironmentSnapshot(N);let w={trees:N.workspaceRoot?[{uri:N.workspaceRoot}]:[],platform:N.platform,tags:N.tags};if(A.onBootstrapProgress?.("guidance"),G="sendGuidanceSnapshot",U=performance.now(),await Qn5(Q,Z,$,w,Y,A.guidanceContentCache),K(G),A.onBootstrapProgress?.("skills"),G="sendSkillSnapshot",U=performance.now(),await Bn5(Q,J,Y),K(G),A.sendGitSnapshot!==!1){A.onBootstrapProgress?.("git");try{G="sendGitSnapshot",U=performance.now();let C=await rU0(A.workspaceRoot);Y?.("SEND",{type:"executor_artifact_upsert",available:C.available,fileCount:C.files.length,branch:C.branch,head:C.head}),Q.sendExecutorArtifactUpsert(V81(C)),K(G)}catch{}}}A.onBootstrapProgress?.("tools"),G="initialToolDiscovery",U=performance.now(),await A.initialToolDiscovery,K(G),G="loadToolStatuses",U=performance.now();let W=await y1(A.toolService.tools);K(G);let z=nU0(W);G="syncExecutorToolRegistrations",U=performance.now();let q=Xs4({transport:Q,nextTools:z,previouslyAdvertisedTools:A.previouslyAdvertisedTools,forceRegisterAll:!V,logMessage:Y});return K(G),Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Q.sendExecutorToolsBootstrapComplete(!0),j.info("[executor] Executor bootstrap completed",{...F,resumeBootstrap:V,toolCount:z.length,advertisedToolCount:q.length,totalMs:Math.round(performance.now()-X),...D}),{advertisedTools:q}}catch(W){let z=W instanceof Error?W.message:String(W);throw Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:z}),Q.sendExecutorToolsBootstrapComplete(!1,z),j.error("[executor] Executor bootstrap failed",{...F,currentPhase:G,resumeBootstrap:V,totalMs:Math.round(performance.now()-X),...D,error:W}),W}}async function Qn5(A,Q,B,$,J,Y){let X=(await oN({filesystem:Q,configService:B,threadService:{observe:()=>g0.of({id:G9(),created:Date.now(),v:0,messages:[],env:{initial:$}})}},{messages:[],env:{initial:$}})).map((U)=>({uri:U.uri,content:U.content,lineCount:U.content.split(`
4569
4569
  `).length,hash:U81(U.content)})),F=Y?K81(X,Y):X,D=crypto.randomUUID(),G=B.userConfigDir?o1(B.userConfigDir):void 0;if(F.length===0){J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:0,withContent:[],contentOmitted:[],isLast:!0}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:[],isLast:!0,userConfigDir:G});return}let V=Ys4(F,D,G);for(let U=0;U<V.length;U++){let K=V[U];if(!K)continue;let E=U===V.length-1,H=K.filter((z)=>z.content!==void 0).map((z)=>z.uri),W=K.filter((z)=>z.content===void 0).map((z)=>z.uri);J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:K.length,withContent:H,contentOmitted:W,isLast:E}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:K,isLast:E,userConfigDir:G})}}async function Bn5(A,Q,B){let[$,J]=await Promise.all([Q.getSkills(),Q.getSkillErrors()]),Y=crypto.randomUUID(),Z=20,X=$.map((D)=>({name:D.name,description:D.description,baseDir:D.baseDir,frontmatter:D.frontmatter,files:D.files,source:D.source})),F=J.map((D)=>({path:D.path,error:D.error,...D.hint?{hint:D.hint}:{}}));if(X.length===0){B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:0,errorCount:F.length,isLast:!0}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:[],isLast:!0,errors:F});return}for(let D=0;D<X.length;D+=20){let G=X.slice(D,D+20),V=D+20>=X.length;B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:G.length,...V?{errorCount:F.length}:{},isLast:V}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:G,isLast:V,...V?{errors:F}:{}})}}class Fs4{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(A){this.options=A;this.baseDelayMs=A.baseDelayMs??Ku.baseDelayMs,this.maxDelayMs=A.maxDelayMs??Ku.maxDelayMs,this.maxAttempts=A.maxAttempts??Ku.maxAttempts,this.pollDelayMs=A.pollDelayMs??30000}ensureHandshake(A){return this.tryHandshake(A)}ensureReady(A){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=ti5();this.tryHandshake("connect");let Q=this.readyWaiter.promise;if(!A?.timeoutMs)return Q;let B=A.timeoutMessage??`Timed out waiting for handshake after ${A.timeoutMs}ms`;return this.withTimeout(Q,A.timeoutMs,B)}handleConnectionChange(A){this.lastInfo=A;let Q=A.state!=="connected"?"reset_disconnected":A.role==="executor"?"mark_ready":"ensure_handshake";if(j.info("[executor] Handshake manager handling connection change",{action:Q,state:A.state,role:A.role,clientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,attempt:this.attempt,hasInFlightHandshake:this.inFlight!==null,hasRetryTimer:this.retryTimer!==null}),A.state!=="connected"){this.reset("disconnected");return}if(A.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let A=this.readyWaiter;if(!A)return;this.readyWaiter=null,A.resolve()}rejectReadyWaiter(A){let Q=this.readyWaiter;if(!Q)return;this.readyWaiter=null,Q.reject(A)}reset(A){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}async withTimeout(A,Q,B){let $=null;try{return await Promise.race([A,new Promise((J,Y)=>{$=setTimeout(()=>{Y(Error(B))},Q)})])}finally{if($)clearTimeout($)}}tryHandshake(A){if(this.disposed)return j.info("[executor] Handshake manager ignored trigger while disposed",{trigger:A}),this.inFlight;if(this.inFlight)return j.info("[executor] Handshake manager reused in-flight handshake",{trigger:A,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role}),this.inFlight;let Q=this.generation;j.info("[executor] Handshake manager starting handshake",{trigger:A,generation:Q,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role});let B=this.options.handshake(A);return this.inFlight=B,B.then(()=>{if(this.disposed||Q!==this.generation)return;j.info("[executor] Handshake manager handshake succeeded",{trigger:A,generation:Q}),this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch(($)=>{if(this.disposed||Q!==this.generation)return;this.scheduleRetry(A,$)}).finally(()=>{if(this.inFlight===B)this.inFlight=null}),B}scheduleRetry(A,Q){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let B=sU0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),$=B===null;if($)j.error("[executor] Handshake manager exhausted fast retries",{trigger:A,attempt:this.attempt,maxAttempts:this.maxAttempts,pollDelayMs:this.pollDelayMs,error:Q}),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Q}),this.rejectReadyWaiter(Q instanceof Error?Q:Error("Executor handshake failed and exhausted retries")),this.options.forceReconnect?.("executor handshake exhausted");let J=B??this.pollDelayMs;this.clearRetryTimer(),j.info("[executor] Handshake manager scheduled retry",{trigger:A,attempt:this.attempt,delayMs:J,state:this.lastInfo.state,role:this.lastInfo.role,mode:$?"poll":"fast",error:Q instanceof Error?Q.message:String(Q)}),this.options.onError?.({trigger:A,attempt:this.attempt,delayMs:J,error:Q}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},J)}}class Ds4{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(A){this.options=A;this.clientID=A.clientID,this.transport=A.transport}async handleToolLease(A){if(this.disposing)return;let{toolCallId:Q,toolName:B}=A;if(this.activeTools.has(Q)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Q,toolName:B});return}let $=this.pendingTerminalResults.get(Q);if($){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Q,toolName:B}),this.sendPendingTerminalResult(Q,$,"flush");return}let J=Date.now();this.options.log.info(`${this.clientID} executing tool: ${B}`,{toolCallId:Q}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Q}),this.transport.ackToolLease(Q);let Y=new AbortController,Z={subscription:{unsubscribe:()=>{}},abortController:Y,needsProgressSnapshot:!1};this.activeTools.set(Q,Z);let X=()=>{this.activeTools.delete(Q)};try{let F=A;if(this.options.requestPluginToolCall&&this.options.threadID){let V=await this.requestPluginToolCall(A);if(Y.signal.aborted){X();return}if("shortCircuitRun"in V){this.prepareAndSendToolResult(A,V.shortCircuitRun,Z);return}F=V.lease}let D=await this.options.invokeTool(F);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Q,toolName:B,elapsedMs:Date.now()-J});let G=D.subscribe({next:(V)=>{if(Y.signal.aborted)return;let U=V.status==="in-progress"?V.progress??V.result:void 0,K=U!==void 0?nX(U):void 0;if(K!==void 0&&!si5(K)){let E=Yu(K,"snapshot"),H=uU0(Z.progress,E),W=Z.needsProgressSnapshot&&H.type==="snapshot"?H:Gr4(Z.sentProgress,H);if(Z.progress=H,this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Q,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Q,W),{toolCallId:Q}))Z.sentProgress=H,Z.needsProgressSnapshot=!1;else Z.needsProgressSnapshot=!0}if(C8(V.status))G.unsubscribe(),this.prepareAndSendToolResult(F,V,Z);if(V.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Q,toolName:B})},error:(V)=>{if(Y.signal.aborted){X();return}this.options.log.error(`${this.clientID} tool execution failed: ${B}`,V);let U={status:"error",error:{message:V instanceof Error?V.message:"Unknown error"}};this.prepareAndSendToolResult(F,U,Z)}});Z.subscription=G}catch(F){this.options.log.error(`${this.clientID} tool execution setup failed: ${B}`,F);let D={status:"error",error:{message:F instanceof Error?F.message:String(F)}};this.prepareAndSendToolResult(A,D,Z)}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[A,Q]of this.pendingTerminalResults)this.sendPendingTerminalResult(A,Q,"flush")}markActiveProgressSnapshotsRequired(){for(let A of this.activeTools.values())A.needsProgressSnapshot=!0}handleToolRevocation(A){if(this.disposing)return;let{toolCallId:Q,reason:B}=A;this.options.log.info(`${this.clientID} lease revoked: ${Q}`,{reason:B});let $=this.activeTools.get(Q);if($)$.abortController.abort(),$.subscription.unsubscribe(),this.activeTools.delete(Q);this.sentApprovalRequests.delete(Q)}triggerGitStatus(A){this.queueGitStatusSnapshot(A)}dispose(){this.disposing=!0;for(let[,A]of this.activeTools)A.abortController.abort(),A.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}async prepareAndSendToolResult(A,Q,B){try{let $=this.toToolRun(Q);if(this.options.requestPluginToolResult&&this.options.threadID)$=await this.requestPluginToolResult(A,$);if(this.disposing||B.abortController.signal.aborted||this.activeTools.get(A.toolCallId)!==B)return;this.sendToolResult(A.toolCallId,$)}catch($){this.options.log.error(`${this.clientID} failed to prepare tool result`,$)}finally{if(this.activeTools.get(A.toolCallId)===B)this.activeTools.delete(A.toolCallId)}}sendToolResult(A,Q){let B=Date.now(),$=nX(Q),{run:J,files:Y}=this.extractGuidanceFromRun($),Z=this.prepareGuidanceDiscoveryBatches(A,Y),X={run:J,guidanceBatches:Z};this.pendingTerminalResults.set(A,X),this.sendPendingTerminalResult(A,X,"live",{guidanceFileCount:Y.length,elapsedMs:Date.now()-B}),this.sentApprovalRequests.delete(A),this.queueGitStatusSnapshot(A)}sendPendingTerminalResult(A,Q,B,$){if(!this.sendGuidanceDiscoveryBatches(A,Q.guidanceBatches))return!1;return this.sendTerminalResult(A,Q.run,B,$)}async requestPluginToolCall(A){let Q=this.options.threadID,B=this.options.requestPluginToolCall;if(!Q||!B)return{lease:A};let $={thread:{id:Q},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A)};try{let J=await B($);switch(J.action){case"allow":return{lease:A};case"modify":return{lease:{...A,args:J.input}};case"reject-and-continue":return{shortCircuitRun:{status:"done",result:`Tool rejected by plugin: ${J.message}`}};case"synthesize":return{shortCircuitRun:{status:"done",result:J.result.output}};case"error":return{shortCircuitRun:{status:"error",error:{message:`Plugin error: ${J.message}`,displayMessage:J.message}}}}}catch(J){return this.options.log.error(`${this.clientID} plugin tool.call failed`,J),{shortCircuitRun:{status:"error",error:{message:J instanceof Error?J.message:String(J)}}}}}async requestPluginToolResult(A,Q){let B=this.options.threadID,$=this.options.requestPluginToolResult;if(!B||!$||Q.status!=="done"&&Q.status!=="error"&&Q.status!=="cancelled")return Q;let J={thread:{id:B},toolUseID:A.toolCallId,tool:A.toolName,input:this.getLeaseArgs(A),status:Q.status,error:Q.status==="error"?Q.error?.message:void 0,output:Q.status==="done"?Q.result:void 0};try{let Y=await $(J);if(!Y)return Q;switch(Y.status){case"done":return{status:"done",result:Y.output??(Q.status==="done"?Q.result:""),progress:Q.progress,trackFiles:Q.status==="done"?Q.trackFiles:void 0};case"error":return{status:"error",progress:Q.progress,error:{message:Y.error??(Q.status==="error"?Q.error?.message??"Tool execution failed":"Tool execution failed")}};case"cancelled":return{status:"cancelled",progress:Q.progress,reason:Y.error??(Q.status==="cancelled"?Q.reason:void 0)}}}catch(Y){this.options.log.error(`${this.clientID} plugin tool.result failed`,Y)}return Q}getLeaseArgs(A){if(typeof A.args==="object"&&A.args!==null&&!Array.isArray(A.args))return A.args;return{}}sendTerminalResult(A,Q,B,$){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:A,run:Q});let J=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(A,Q),{toolCallId:A,source:B});return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:A,status:Q.status,sent:J,source:B,...$}),J}ackTerminalResult(A){if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result acknowledged`,{toolCallId:A.toolCallId})}handleExecutorError(A){if(A.code!=="LEASE_NOT_FOUND"||A.toolCallId===void 0)return;if(this.pendingTerminalResults.delete(A.toolCallId))this.options.log.info(`${this.clientID} executor_tool_result rejected`,{toolCallId:A.toolCallId,code:A.code})}prepareGuidanceDiscoveryBatches(A,Q){let B=Q.map((Y)=>{if(typeof Y.hash==="string"||typeof Y.content!=="string")return Y;return{...Y,hash:U81(Y.content)}}),$=this.options.guidanceContentCache,J=$?K81(B,$):B;return this.options.batchGuidanceFiles(J,A)}sendGuidanceDiscoveryBatches(A,Q){for(let B=0;B<Q.length;B++){let $=Q[B];if(!$)continue;let J=B===Q.length-1,Y=$.filter((X)=>X.content!==void 0).map((X)=>X.uri),Z=$.filter((X)=>X.content===void 0).map((X)=>X.uri);if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:A,fileCount:$.length,withContent:Y,contentOmitted:Z,isLast:J}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:A,files:$,isLast:J}),{toolCallId:A,isLast:J,fileCount:$.length,withContent:Y,contentOmitted:Z}))return!1}return!0}queueGitStatusSnapshot(A){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,A)this.gitStatusQueue.queuedToolCallId=A;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(A).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Q=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Q)})}async sendGitStatusSnapshot(A){try{if(!this.options.captureGitStatus)return;let Q=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Q.available,fileCount:Q.files.length,toolCallId:A,branch:Q.branch,head:Q.head}),this.transport.sendExecutorArtifactUpsert(V81(Q),A)}catch(Q){this.options.log.error("Failed to send git status snapshot",Q)}}toToolRun(A){switch(A.status){case"done":return{status:"done",result:A.result,progress:A.progress,trackFiles:A.trackFiles?[...A.trackFiles]:void 0};case"error":return{status:"error",error:{message:A.error?this.options.renderToolRunError(A.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:A.reason};case"cancelled":return{status:"cancelled",reason:A.reason};default:return{status:"error",error:{message:`Unexpected status: ${A.status}`}}}}extractGuidanceFromRun(A){if(A.status!=="done")return{run:A,files:[]};if(!A.result||typeof A.result!=="object"||Array.isArray(A.result))return{run:A,files:[]};let Q=A.result;if(!("discoveredGuidanceFiles"in Q))return{run:A,files:[]};let B=Hr4(Q.discoveredGuidanceFiles),{discoveredGuidanceFiles:$,...J}=Q;return{run:{...A,result:J},files:B}}sendTransportMessage(A,Q,B){try{return Q(),!0}catch($){if($ instanceof T3)return this.options.log.info(`${this.clientID} dropped ${A} while reconnecting`,{messageType:A,...B}),this.options.onTransportSendFailure?.(this.clientID,A,$,B),!1;return this.options.log.error(`${this.clientID} failed to send ${A}`,$),!1}}}class TP{options;toolRunner;sentApprovalRequests;handshakeManager;runtimeLog;guidanceContentCache=new Ze;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(A){this.options=A;this.runtimeLog=this.options.log??{info:(Q,B)=>j.info(`[executor] ${Q}`,{...B,threadID:this.options.threadID}),error:(Q,B)=>j.error(`[executor] ${Q}`,{error:B,threadID:this.options.threadID}),wsMessage:(Q,B,$)=>{j.info("[executor] websocket message",{direction:Q,clientID:B,threadID:this.options.threadID,...typeof $==="object"&&$!==null?$:{message:$}})}},this.handshakeManager=new Fs4({handshake:(Q)=>this.bootstrapExecutor({executorType:this.options.executorType,trigger:Q,suppressConnectLog:!0}),forceReconnect:(Q)=>this.options.transport.forceReconnect(Q),...this.options.handshakeManagerOptions}),this.toolRunner=new Ds4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,threadID:this.options.threadID,invokeTool:(Q)=>this.invokeTool(Q),requestPluginToolCall:this.options.requestPluginToolCall,requestPluginToolResult:this.options.requestPluginToolResult,captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Q)=>[Q]),guidanceContentCache:this.guidanceContentCache,renderToolRunError:this.options.renderToolRunError??((Q)=>Q?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests}ensureHandshake(A){return this.handshakeManager.ensureHandshake(A)}ensureReady(A){return this.handshakeManager.ensureReady(A)}syncExecutorToolRegistrations(A,Q){let B=this.options.transport.getConnectionInfo();if(B.state!=="connected"||B.role!=="executor")return;this.advertisedExecutorTools=Xs4({transport:this.options.transport,nextTools:A,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:Q?.logMessage})}handleConnectionChange(A){if(this.runtimeLog.info(`${this.options.clientID} handling connection change`,{state:A.state,role:A.role,transportClientId:A.clientId,reconnectCauseType:A.reconnectCause?.type,reconnectCauseCode:A.reconnectCause?.code,reconnectCauseReason:A.reconnectCause?.reason,hasCompletedBootstrap:this.hasCompletedBootstrap,executorCallbacksAttached:this.executorCallbacksAttached}),A.state!=="connected"||A.role!=="executor")this.toolRunner.markActiveProgressSnapshotsRequired();if(A.state!=="connected"&&A.role==="executor")this.guidanceContentCache.clear();this.handshakeManager.handleConnectionChange(A)}onToolLeaseMessage(A){this.handleToolLease(A)}onToolLeaseRevokedMessage(A){this.handleToolLeaseRevoked(A)}onExecutorFileSystemReadDirectoryRequestMessage(A){this.handleExecutorFileSystemReadDirectoryRequest(A)}onExecutorFileSystemReadFileRequestMessage(A){this.handleExecutorFileSystemReadFileRequest(A)}attachTransportExecutorCallbacks(A){if(!this.options.transport.setExecutorCallbacks){this.executorCallbacksAttached=!0;return}let Q=A?.includeConnectionChanges??!1,B=this.getInboundExecutorHandlers(),$={onToolLease:(J)=>{this.runtimeLog.info("onToolLease",{data:J}),B.onToolLease(J)},onToolLeaseRevoked:(J)=>{this.runtimeLog.info("onToolLeaseRevoked",{data:J}),B.onToolLeaseRevoked(J)},onExecutorToolResultAck:(J)=>{this.runtimeLog.info("onExecutorToolResultAck",{data:J}),this.toolRunner.ackTerminalResult(J)},onExecutorError:(J)=>{this.runtimeLog.info("onExecutorError",{data:J}),this.toolRunner.handleExecutorError(J)},onFileSystemReadFileRequest:(J)=>{this.runtimeLog.info("onFileSystemReadFileRequest",{data:J}),B.onFileSystemReadFileRequest(J)}};if(Q)$.onConnectionChange=(J)=>{this.runtimeLog.info("onConnectionChange",{data:J}),this.handleConnectionChange(J)};if(B.onFileSystemReadDirectoryRequest){let J=B.onFileSystemReadDirectoryRequest;$.onFileSystemReadDirectoryRequest=(Y)=>{this.runtimeLog.info("onFileSystemReadDirectoryRequest",{data:Y}),J(Y)}}if(this.options.pluginService){let J=iU0({pluginService:this.options.pluginService,sendPluginMessage:(Y)=>this.options.transport.sendPluginMessage(Y)});$.onPluginMessage=(Y)=>{this.runtimeLog.info("onPluginMessage",{data:Y}),J(Y)}}this.options.transport.setExecutorCallbacks($),this.executorCallbacksAttached=!0}advertisePluginReadinessIfEnabled(){if(!this.options.pluginService)return;try{this.options.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(A){this.runtimeLog.error("failed to advertise plugin readiness",A)}}dispose(){this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.executorCallbacksAttached=!1}async invokeTool(A){return this.options.invokeTool(A)}async bootstrapExecutor(A){await this.connectAsExecutor(A.executorType??this.options.executorType,A.workspaceRoot??this.options.workspaceRoot??"",A.threadID??this.options.threadID,A.trigger,A.suppressConnectLog)}async connectAsExecutor(A,Q,B,$,J=!1){if(!J)j.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:Y}=await An5({transport:this.options.transport,executorClientID:this.options.clientID,workspaceRoot:Q,threadId:B,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:A,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools,allowResumeBootstrap:this.hasCompletedBootstrap,onBootstrapProgress:this.options.onBootstrapProgress,guidanceContentCache:this.guidanceContentCache});if(this.advertisedExecutorTools=Y,this.hasCompletedBootstrap=!0,this.toolRunner.flushBufferedTerminalResults(),this.advertisePluginReadinessIfEnabled(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess($)}catch(Y){throw j.error(`executor ${this.options.clientID} bootstrap failed`,Y),Y}}getInboundExecutorHandlers(){let A={onToolLease:(Q)=>{this.handleToolLease(Q)},onToolLeaseRevoked:(Q)=>{this.handleToolLeaseRevoked(Q)},onFileSystemReadFileRequest:(Q)=>{this.handleExecutorFileSystemReadFileRequest(Q)}};if(this.options.handleExecutorFileSystemReadDirectoryRequest||this.options.readFileSystemDirectory)A.onFileSystemReadDirectoryRequest=(Q)=>{this.handleExecutorFileSystemReadDirectoryRequest(Q)};return A}maybeLogInboundExecutorMessage(A){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,A)}handleToolLease(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolLease(A)}handleToolLeaseRevoked(A){this.maybeLogInboundExecutorMessage(A),this.toolRunner.handleToolRevocation(A)}async handleExecutorFileSystemReadDirectoryRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(A);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Q=await this.options.readFileSystemDirectory(A);this.options.transport.sendExecutorFileSystemReadDirectoryResult(A.requestId,Q)}handleExecutorFileSystemReadFileRequest(A){if(this.maybeLogInboundExecutorMessage(A),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(A);return}throw Error("Method not implemented.")}}KQ();async function jZ(A,Q,B,$={}){let J={...A?{threadId:A}:{},...$.repositoryURL?{repositoryURL:$.repositoryURL}:{},...!A&&$.executorType?{executorType:$.executorType}:{},...$.agentMode?{agentMode:$.agentMode}:{},...$.relationship?{relationship:$.relationship}:{},...$.usesThreadActors?{usesThreadActors:!0}:{}};if(!A&&$.threadMeta)J.threadMeta=$.threadMeta;let Y=await I7("/api/thread-actors",$n5({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),signal:$.signal},B),Q);if(!Y.ok)throw Error(`Failed to create thread-actors thread: ${Y.status} ${await Y.text()}`);let Z=await Y.json();if(!Z.threadId||!Z.wsToken)throw Error("Thread actors thread creation response missing threadId or wsToken");if(!Z.ownerUserId||typeof Z.threadVersion!=="number")throw Error("Thread actors thread creation response missing ownerUserId or threadVersion");return{threadId:Z.threadId,wsToken:Z.wsToken,usesDtw:Z.usesDtw??!0,usesThreadActors:Z.usesThreadActors??!1,executorType:Z.executorType??null,ownerUserId:Z.ownerUserId,threadVersion:Z.threadVersion,...Z.agentMode?{agentMode:Z.agentMode}:{}}}function $n5(A,Q){if(!Q)return A;return{...A,headers:{...A?.headers,Authorization:`Bearer ${Q}`}}}i0();AA();j1();function Gs4(A){let{message:Q,sessionId:B,streamJsonThinking:$,currentTurnAssistantIds:J,currentTurnToolUseIds:Y}=A;if(!J.has(Q.messageId))return null;if(!Q.state)return null;if(Q.content.length===0)return null;let Z=Qo4(Q,B,null,{includeThinking:$});for(let X of Q.content)if(X.type==="tool_use")Y.add(X.id);return Z}function Vs4(A){let{message:Q,sessionId:B,currentTurnToolUseIds:$}=A,J=Q.content.some((Z)=>Z.type==="tool_result"),Y=Q.content.some((Z)=>Z.type==="tool_result"&&$.has(Z.toolUseID));if(J&&!Y)return null;return Bo4(Q,B,null)}function Us4(A){return A.inputDone&&A.assistantDone&&A.idleSinceLastSend&&A.agentIdle}var Ks4=1048576;async function Es4(A){let{client:Q,observer:B,dependencies:$,threadID:J,userInput:Y,stdinInput:Z,agentMode:X,reasoningEffort:F,streamJsonThinking:D,streamJsonInput:G,stdin:V}=A;if(Z&&Z.length>Ks4)throw Error(`Stdin input too large: ${Z.length} bytes (max ${Ks4})`);let U=J,K=Date.now(),E=X??"smart",H=Zn5($),W=null,z=()=>{return W??=Yn5($,E),W},q=!1,N=!1,I=0,w="",C=!1,O=!0,P=new Set;return new Promise((S,_)=>{let f=[],h="pending",b=null,y=null,u=PU0(async(U0)=>{try{await U0()}catch(z0){j.error("stream-json-actors emit failed",{error:z0})}}),p=async(U0)=>{if(h==="emitted")return;let z0=await H;await Xn5({sessionId:U,tools:U0,mcpServers:z0,agentMode:E,reasoningEffort:F}),h="emitted";let A0=f.splice(0);for(let J0 of A0)await PF(J0)},d=(U0)=>{if(h!=="pending")return;h="queued",b=U0,u(async()=>{await p(U0)})},g=(U0)=>{if(h!=="emitted"){f.push(U0);return}u(async()=>{await PF(U0)})},n=async()=>{if(h==="emitted")return;await p(b??await z())},c=Jn5({onSuccess:async()=>{await u(async()=>{await n(),await Fn5({sessionId:U,startTime:K,numTurns:I,result:w})}),S({threadID:J,outcome:"success"})},onError:async(U0)=>{await u(async()=>{await n(),await Dn5({sessionId:U,startTime:K,numTurns:I,error:U0})}),S({threadID:J,outcome:"error"})},onFatal:(U0)=>_(U0),cleanup:()=>{if(N)return;N=!0,y?.unsubscribe(),B0.dispose()},isComplete:()=>N}),B0=dU0({client:Q,observer:B,toolService:$.toolService,callbacks:{onError:(U0)=>{c.error(U0)},onTransitionToIdle:(U0)=>{if(U0.length>0){Gn5({client:Q,approvals:U0,complete:c});return}if(B0.agentIdle())O=!0;O0()},onMessageAdded:(U0)=>{if(U0.parentToolUseId)return;let z0=U0.message;if(z0.role==="assistant"){let A0=Gs4({message:z0,sessionId:U,streamJsonThinking:D,currentTurnAssistantIds:B0.currentTurnAssistantIds,currentTurnToolUseIds:P});if(!A0)return;if(g(A0),I++,A0.message.stop_reason==="end_turn")w=I3(z0.content),C=!0,O0()}else if(z0.role==="user"){let A0=Vs4({message:z0,sessionId:U,currentTurnToolUseIds:P});if(!A0)return;g(A0)}},onSignal:()=>{c.error("User cancelled (SIGINT/SIGTERM)")}}});y=B.inferenceTools$.subscribe((U0)=>{if(U0.parentToolCallId)return;d(U0.tools)});let O0=()=>{if(N)return;if(Us4({inputDone:q,assistantDone:C,idleSinceLastSend:O,agentIdle:B0.agentIdle()}))c.success()},l=(U0,z0)=>{O=!1,Q.sendUserMessage(U0,E,z0)};if(G){(async()=>{try{for await(let U0 of _U0(V)){if(N)break;l(U0.contentBlocks,Vn5(U0))}q=!0,O0()}catch(U0){c.error(hK(U0))}})();return}let Q0=[{type:"text",text:Y}];if(Z)Q0.unshift({type:"text",text:`Input received on stdin:
@@ -4736,12 +4736,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
4736
4736
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))H+=`
4737
4737
 
4738
4738
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4739
- npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();xI();async function NK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=_e(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],H=F.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(H)K=Math.floor((W-new Date(H).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var $r5="https://static.ampcode.com/cli/cli-version.txt";async function IK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${$r5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=_e(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Jr5=604800000;function Ee4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Jr5)return{ageMs:B};return null}function _e(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function e81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as Yr5,realpath as Zr5}from"node:fs/promises";import{homedir as Xr5}from"node:os";import{dirname as He4,join as A31}from"node:path";async function We4(A){switch(A){case"binary":case"brew":return Fr5(Oe());case"npm":case"pnpm":case"yarn":case"bun":return Dr5();case"bootstrap":return Gr5()}}async function Fr5(A){let Q=await gG(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Dr5(){try{let A=process.argv[1];if(!A)return null;let Q=await Zr5(A),B=He4(He4(Q));return await ze4(A31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Gr5(){try{let A=process.env.AMP_HOME??A31(Xr5(),".amp");return await ze4(A31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ze4(A){let Q=await Yr5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Vr5=3600000,Ur5=5000;function Q31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Vr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new yY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Kr5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Ur5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let H=Math.min(K,E);await oU(H),E-=H}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function Kr5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await zK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await IK0(A);else{let V=await fP();F=await NK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await We4(Z);if(V&&_e(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,_e(A,V)<0){let U=await $z(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Oe()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await Pe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await $z(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}xI();import{stderr as mG}from"node:process";function qe4(A){let Q=new Zw().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await m81($.force||!1,$.verbose||!1,"0.0.1777875280-g2566d7"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Zw("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await Hr5($.targetVersion)});A.addCommand(B)}function Er5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4739
+ npm install -g @sourcegraph/amp`;F(Error(H))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}i0();i0();xI();async function NK0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=_e(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],H=F.time[D],W=Date.now();if(E)U=Math.floor((W-new Date(E).getTime())/3600000);if(H)K=Math.floor((W-new Date(H).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var $r5="https://static.ampcode.com/cli/cli-version.txt";async function IK0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${$r5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=_e(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var Jr5=604800000;function Ee4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>Jr5)return{ageMs:B};return null}function _e(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function e81(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?rU(B):void 0;return{sha:$,age:J}}catch{return null}}j1();i0();import{readFile as Yr5,realpath as Zr5}from"node:fs/promises";import{homedir as Xr5}from"node:os";import{dirname as He4,join as A31}from"node:path";async function We4(A){switch(A){case"binary":case"brew":return Fr5(Oe());case"npm":case"pnpm":case"yarn":case"bun":return Dr5();case"bootstrap":return Gr5()}}async function Fr5(A){let Q=await gG(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function Dr5(){try{let A=process.argv[1];if(!A)return null;let Q=await Zr5(A),B=He4(He4(Q));return await ze4(A31(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Gr5(){try{let A=process.env.AMP_HOME??A31(Xr5(),".amp");return await ze4(A31(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function ze4(A){let Q=await Yr5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var Vr5=3600000,Ur5=5000;function Q31(A,Q,B={}){let $=new r4,J=$.pipe($6({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Vr5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new yY().scoped("update");if(Y>0){if(await oU(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await Kr5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await oU(Ur5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let H=Math.min(K,E);await oU(H),E-=H}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function Kr5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await zK0(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await IK0(A);else{let V=await fP();F=await NK0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await We4(Z);if(V&&_e(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,_e(A,V)<0){let U=await $z(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==Oe()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await Pe(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await $z(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}xI();import{stderr as mG}from"node:process";function qe4(A){let Q=new Zw().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async($)=>{await m81($.force||!1,$.verbose||!1,"0.0.1777879744-g2d678a"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new Zw("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await Hr5($.targetVersion)});A.addCommand(B)}function Er5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4740
4740
  `),$=!1,B=0}function Y(Z){if(!Q)return;let X=Z.padEnd(B," ");A.write(`\r${X}`),$=!0,B=X.length}return{flushProgressLine:J,renderProgress:Y}}async function Hr5(A){let B=process.platform==="win32"&&xP()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=Er5(mG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")mG.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4741
4741
 
4742
4742
  `));try{if(!A){mG.write(o0.blue(`Checking for updates...
4743
- `));let X=!1,F;if(xP()){let D=await IK0("0.0.1777875280-g2566d7");X=D.hasUpdate,F=D.latestVersion}else{let D=await fP(),G=await NK0("0.0.1777875280-g2566d7",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=e81("0.0.1777875280-g2566d7"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-04T06:18:29.836Z"))} ago`;mG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1777875280-g2566d7"} (${G})
4744
- `));let V=await $z("0.0.1777875280-g2566d7",B);if(V.warning)mG.write(`
4743
+ `));let X=!1,F;if(xP()){let D=await IK0("0.0.1777879744-g2d678a");X=D.hasUpdate,F=D.latestVersion}else{let D=await fP(),G=await NK0("0.0.1777879744-g2d678a",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=e81("0.0.1777879744-g2d678a"),G=D?.age?`released ${D.age} ago`:`built ${rU(new Date("2026-05-04T07:32:44.192Z"))} ago`;mG.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1777879744-g2d678a"} (${G})
4744
+ `));let V=await $z("0.0.1777879744-g2d678a",B);if(V.warning)mG.write(`
4745
4745
  `+o0.yellow(V.warning)+`
4746
4746
  `);process.exit(0)}if(!F)mG.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}mG.write(o0.blue(`Updating to version ${A}...
4747
4747
  `)),await Pe(A,void 0,(X)=>{$(),mG.write(o0.dim(`Running: ${X}
@@ -5286,7 +5286,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let B0=G.text.replace(/`([^`]+)`/g,"$1")+`
5286
5286
  * MIT Licence
5287
5287
  */var Sh=9000000000000000,xC=1e9,Y$1="0123456789abcdef",HW0="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",WW0="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Z$1={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Sh,maxE:Sh,crypto:!1},VBA,wz,Q6=!0,qW0="[DecimalError] ",yC=qW0+"Invalid argument: ",UBA=qW0+"Precision limit exceeded",KBA=qW0+"crypto unavailable",EBA="[object Decimal]",_B=Math.floor,X7=Math.pow,tY8=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,eY8=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,AZ8=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,HBA=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,QV=1e7,gA=7,QZ8=9007199254740991,BZ8=HW0.length-1,X$1=WW0.length-1,c1={toStringTag:EBA};c1.absoluteValue=c1.abs=function(){var A=new this.constructor(this);if(A.s<0)A.s=1;return qA(A)};c1.ceil=function(){return qA(new this.constructor(this),this.e+1,2)};c1.clampedTo=c1.clamp=function(A,Q){var B,$=this,J=$.constructor;if(A=new J(A),Q=new J(Q),!A.s||!Q.s)return new J(NaN);if(A.gt(Q))throw Error(yC+Q);return B=$.cmp(A),B<0?A:$.cmp(Q)>0?Q:new J($)};c1.comparedTo=c1.cmp=function(A){var Q,B,$,J,Y=this,Z=Y.d,X=(A=new Y.constructor(A)).d,F=Y.s,D=A.s;if(!Z||!X)return!F||!D?NaN:F!==D?F:Z===X?0:!Z^F<0?1:-1;if(!Z[0]||!X[0])return Z[0]?F:X[0]?-D:0;if(F!==D)return F;if(Y.e!==A.e)return Y.e>A.e^F<0?1:-1;$=Z.length,J=X.length;for(Q=0,B=$<J?$:J;Q<B;++Q)if(Z[Q]!==X[Q])return Z[Q]>X[Q]^F<0?1:-1;return $===J?0:$>J^F<0?1:-1};c1.cosine=c1.cos=function(){var A,Q,B=this,$=B.constructor;if(!B.d)return new $(NaN);if(!B.d[0])return new $(1);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+gA,$.rounding=1,B=$Z8($,IBA($,B)),$.precision=A,$.rounding=Q,qA(wz==2||wz==3?B.neg():B,A,Q,!0)};c1.cubeRoot=c1.cbrt=function(){var A,Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor;if(!G.isFinite()||G.isZero())return new V(G);if(Q6=!1,Y=G.s*X7(G.s*G,0.3333333333333333),!Y||Math.abs(Y)==1/0){if(B=yQ(G.d),A=G.e,Y=(A-B.length+1)%3)B+=Y==1||Y==-2?"0":"00";if(Y=X7(B,0.3333333333333333),A=_B((A+1)/3)-(A%3==(A<0?-1:2)),Y==1/0)B="5e"+A;else B=Y.toExponential(),B=B.slice(0,B.indexOf("e")+1)+A;$=new V(B),$.s=G.s}else $=new V(Y.toString());Z=(A=V.precision)+3;for(;;)if(X=$,F=X.times(X).times(X),D=F.plus(G),$=u8(D.plus(G).times(X),D.plus(F),Z+2,1),yQ(X.d).slice(0,Z)===(B=yQ($.d)).slice(0,Z))if(B=B.slice(Z-3,Z+1),B=="9999"||!J&&B=="4999"){if(!J){if(qA(X,A+1,0),X.times(X).times(X).eq(G)){$=X;break}}Z+=4,J=1}else{if(!+B||!+B.slice(1)&&B.charAt(0)=="5")qA($,A+1,1),Q=!$.times($).times($).eq(G);break}return Q6=!0,qA($,A,V.rounding,Q)};c1.decimalPlaces=c1.dp=function(){var A,Q=this.d,B=NaN;if(Q){if(A=Q.length-1,B=(A-_B(this.e/gA))*gA,A=Q[A],A)for(;A%10==0;A/=10)B--;if(B<0)B=0}return B};c1.dividedBy=c1.div=function(A){return u8(this,new this.constructor(A))};c1.dividedToIntegerBy=c1.divToInt=function(A){var Q=this,B=Q.constructor;return qA(u8(Q,new B(A),0,1,1),B.precision,B.rounding)};c1.equals=c1.eq=function(A){return this.cmp(A)===0};c1.floor=function(){return qA(new this.constructor(this),this.e+1,3)};c1.greaterThan=c1.gt=function(A){return this.cmp(A)>0};c1.greaterThanOrEqualTo=c1.gte=function(A){var Q=this.cmp(A);return Q==1||Q===0};c1.hyperbolicCosine=c1.cosh=function(){var A,Q,B,$,J,Y=this,Z=Y.constructor,X=new Z(1);if(!Y.isFinite())return new Z(Y.s?1/0:NaN);if(Y.isZero())return X;if(B=Z.precision,$=Z.rounding,Z.precision=B+Math.max(Y.e,Y.sd())+4,Z.rounding=1,J=Y.d.length,J<32)A=Math.ceil(J/3),Q=(1/IW0(4,A)).toString();else A=16,Q="2.3283064365386962890625e-10";Y=kh(Z,1,Y.times(Q),new Z(1),!0);var F,D=A,G=new Z(8);for(;D--;)F=Y.times(Y),Y=X.minus(F.times(G.minus(F.times(G))));return qA(Y,Z.precision=B,Z.rounding=$,!0)};c1.hyperbolicSine=c1.sinh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite()||J.isZero())return new Y(J);if(Q=Y.precision,B=Y.rounding,Y.precision=Q+Math.max(J.e,J.sd())+4,Y.rounding=1,$=J.d.length,$<3)J=kh(Y,2,J,J,!0);else{A=1.4*Math.sqrt($),A=A>16?16:A|0,J=J.times(1/IW0(5,A)),J=kh(Y,2,J,J,!0);var Z,X=new Y(5),F=new Y(16),D=new Y(20);for(;A--;)Z=J.times(J),J=J.times(X.plus(Z.times(F.times(Z).plus(D))))}return Y.precision=Q,Y.rounding=B,qA(J,Q,B,!0)};c1.hyperbolicTangent=c1.tanh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(B.s);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+7,$.rounding=1,u8(B.sinh(),B.cosh(),$.precision=A,$.rounding=Q)};c1.inverseCosine=c1.acos=function(){var A=this,Q=A.constructor,B=A.abs().cmp(1),$=Q.precision,J=Q.rounding;if(B!==-1)return B===0?A.isNeg()?DE(Q,$,J):new Q(0):new Q(NaN);if(A.isZero())return DE(Q,$+4,J).times(0.5);return Q.precision=$+6,Q.rounding=1,A=new Q(1).minus(A).div(A.plus(1)).sqrt().atan(),Q.precision=$,Q.rounding=J,A.times(2)};c1.inverseHyperbolicCosine=c1.acosh=function(){var A,Q,B=this,$=B.constructor;if(B.lte(1))return new $(B.eq(1)?0:NaN);if(!B.isFinite())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(Math.abs(B.e),B.sd())+4,$.rounding=1,Q6=!1,B=B.times(B).minus(1).sqrt().plus(B),Q6=!0,$.precision=A,$.rounding=Q,B.ln()};c1.inverseHyperbolicSine=c1.asinh=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite()||B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+2*Math.max(Math.abs(B.e),B.sd())+6,$.rounding=1,Q6=!1,B=B.times(B).plus(1).sqrt().plus(B),Q6=!0,$.precision=A,$.rounding=Q,B.ln()};c1.inverseHyperbolicTangent=c1.atanh=function(){var A,Q,B,$,J=this,Y=J.constructor;if(!J.isFinite())return new Y(NaN);if(J.e>=0)return new Y(J.abs().eq(1)?J.s/0:J.isZero()?J:NaN);if(A=Y.precision,Q=Y.rounding,$=J.sd(),Math.max($,A)<2*-J.e-1)return qA(new Y(J),A,Q,!0);return Y.precision=B=$-J.e,J=u8(J.plus(1),new Y(1).minus(J),B+A,1),Y.precision=A+4,Y.rounding=1,J=J.ln(),Y.precision=A,Y.rounding=Q,J.times(0.5)};c1.inverseSine=c1.asin=function(){var A,Q,B,$,J=this,Y=J.constructor;if(J.isZero())return new Y(J);if(Q=J.abs().cmp(1),B=Y.precision,$=Y.rounding,Q!==-1){if(Q===0)return A=DE(Y,B+4,$).times(0.5),A.s=J.s,A;return new Y(NaN)}return Y.precision=B+6,Y.rounding=1,J=J.div(new Y(1).minus(J.times(J)).sqrt().plus(1)).atan(),Y.precision=B,Y.rounding=$,J.times(2)};c1.inverseTangent=c1.atan=function(){var A,Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding;if(!D.isFinite()){if(!D.s)return new G(NaN);if(V+4<=X$1)return Z=DE(G,V+4,U).times(0.5),Z.s=D.s,Z}else if(D.isZero())return new G(D);else if(D.abs().eq(1)&&V+4<=X$1)return Z=DE(G,V+4,U).times(0.25),Z.s=D.s,Z;G.precision=X=V+10,G.rounding=1,B=Math.min(28,X/gA+2|0);for(A=B;A;--A)D=D.div(D.times(D).plus(1).sqrt().plus(1));Q6=!1,Q=Math.ceil(X/gA),$=1,F=D.times(D),Z=new G(D),J=D;for(;A!==-1;)if(J=J.times(F),Y=Z.minus(J.div($+=2)),J=J.times(F),Z=Y.plus(J.div($+=2)),Z.d[Q]!==void 0)for(A=Q;Z.d[A]===Y.d[A]&&A--;);if(B)Z=Z.times(2<<B-1);return Q6=!0,qA(Z,G.precision=V,G.rounding=U,!0)};c1.isFinite=function(){return!!this.d};c1.isInteger=c1.isInt=function(){return!!this.d&&_B(this.e/gA)>this.d.length-2};c1.isNaN=function(){return!this.s};c1.isNegative=c1.isNeg=function(){return this.s<0};c1.isPositive=c1.isPos=function(){return this.s>0};c1.isZero=function(){return!!this.d&&this.d[0]===0};c1.lessThan=c1.lt=function(A){return this.cmp(A)<0};c1.lessThanOrEqualTo=c1.lte=function(A){return this.cmp(A)<1};c1.logarithm=c1.log=function(A){var Q,B,$,J,Y,Z,X,F,D=this,G=D.constructor,V=G.precision,U=G.rounding,K=5;if(A==null)A=new G(10),Q=!0;else{if(A=new G(A),B=A.d,A.s<0||!B||!B[0]||A.eq(1))return new G(NaN);Q=A.eq(10)}if(B=D.d,D.s<0||!B||!B[0]||D.eq(1))return new G(B&&!B[0]?-1/0:D.s!=1?NaN:B?0:1/0);if(Q)if(B.length>1)Y=!0;else{for(J=B[0];J%10===0;)J/=10;Y=J!==1}if(Q6=!1,X=V+K,Z=vC(D,X),$=Q?zW0(G,X+10):vC(A,X),F=u8(Z,$,X,1),O10(F.d,J=V,U))do if(X+=10,Z=vC(D,X),$=Q?zW0(G,X+10):vC(A,X),F=u8(Z,$,X,1),!Y){if(+yQ(F.d).slice(J+1,J+15)+1==100000000000000)F=qA(F,V+1,0);break}while(O10(F.d,J+=10,U));return Q6=!0,qA(F,V,U)};c1.minus=c1.sub=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.constructor;if(A=new E(A),!K.d||!A.d){if(!K.s||!A.s)A=new E(NaN);else if(K.d)A.s=-A.s;else A=new E(A.d||K.s!==A.s?K:NaN);return A}if(K.s!=A.s)return A.s=-A.s,K.plus(A);if(D=K.d,U=A.d,X=E.precision,F=E.rounding,!D[0]||!U[0]){if(U[0])A.s=-A.s;else if(D[0])A=new E(K);else return new E(F===3?-0:0);return Q6?qA(A,X,F):A}if(B=_B(A.e/gA),G=_B(K.e/gA),D=D.slice(),Y=G-B,Y){if(V=Y<0,V)Q=D,Y=-Y,Z=U.length;else Q=U,B=G,Z=D.length;if($=Math.max(Math.ceil(X/gA),Z)+2,Y>$)Y=$,Q.length=1;Q.reverse();for($=Y;$--;)Q.push(0);Q.reverse()}else{if($=D.length,Z=U.length,V=$<Z,V)Z=$;for($=0;$<Z;$++)if(D[$]!=U[$]){V=D[$]<U[$];break}Y=0}if(V)Q=D,D=U,U=Q,A.s=-A.s;Z=D.length;for($=U.length-Z;$>0;--$)D[Z++]=0;for($=U.length;$>Y;){if(D[--$]<U[$]){for(J=$;J&&D[--J]===0;)D[J]=QV-1;--D[J],D[$]+=QV}D[$]-=U[$]}for(;D[--Z]===0;)D.pop();for(;D[0]===0;D.shift())--B;if(!D[0])return new E(F===3?-0:0);return A.d=D,A.e=NW0(D,B),Q6?qA(A,X,F):A};c1.modulo=c1.mod=function(A){var Q,B=this,$=B.constructor;if(A=new $(A),!B.d||!A.s||A.d&&!A.d[0])return new $(NaN);if(!A.d||B.d&&!B.d[0])return qA(new $(B),$.precision,$.rounding);if(Q6=!1,$.modulo==9)Q=u8(B,A.abs(),0,3,1),Q.s*=A.s;else Q=u8(B,A,0,$.modulo,1);return Q=Q.times(A),Q6=!0,B.minus(Q)};c1.naturalExponential=c1.exp=function(){return F$1(this)};c1.naturalLogarithm=c1.ln=function(){return vC(this)};c1.negated=c1.neg=function(){var A=new this.constructor(this);return A.s=-A.s,qA(A)};c1.plus=c1.add=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V=this,U=V.constructor;if(A=new U(A),!V.d||!A.d){if(!V.s||!A.s)A=new U(NaN);else if(!V.d)A=new U(A.d||V.s===A.s?V:NaN);return A}if(V.s!=A.s)return A.s=-A.s,V.minus(A);if(D=V.d,G=A.d,X=U.precision,F=U.rounding,!D[0]||!G[0]){if(!G[0])A=new U(V);return Q6?qA(A,X,F):A}if(Y=_B(V.e/gA),$=_B(A.e/gA),D=D.slice(),J=Y-$,J){if(J<0)B=D,J=-J,Z=G.length;else B=G,$=Y,Z=D.length;if(Y=Math.ceil(X/gA),Z=Y>Z?Y+1:Z+1,J>Z)J=Z,B.length=1;B.reverse();for(;J--;)B.push(0);B.reverse()}if(Z=D.length,J=G.length,Z-J<0)J=Z,B=G,G=D,D=B;for(Q=0;J;)Q=(D[--J]=D[J]+G[J]+Q)/QV|0,D[J]%=QV;if(Q)D.unshift(Q),++$;for(Z=D.length;D[--Z]==0;)D.pop();return A.d=D,A.e=NW0(D,$),Q6?qA(A,X,F):A};c1.precision=c1.sd=function(A){var Q,B=this;if(A!==void 0&&A!==!!A&&A!==1&&A!==0)throw Error(yC+A);if(B.d){if(Q=WBA(B.d),A&&B.e+1>Q)Q=B.e+1}else Q=NaN;return Q};c1.round=function(){var A=this,Q=A.constructor;return qA(new Q(A),A.e+1,Q.rounding)};c1.sine=c1.sin=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+Math.max(B.e,B.sd())+gA,$.rounding=1,B=YZ8($,IBA($,B)),$.precision=A,$.rounding=Q,qA(wz>2?B.neg():B,A,Q,!0)};c1.squareRoot=c1.sqrt=function(){var A,Q,B,$,J,Y,Z=this,X=Z.d,F=Z.e,D=Z.s,G=Z.constructor;if(D!==1||!X||!X[0])return new G(!D||D<0&&(!X||X[0])?NaN:X?Z:1/0);if(Q6=!1,D=Math.sqrt(+Z),D==0||D==1/0){if(Q=yQ(X),(Q.length+F)%2==0)Q+="0";if(D=Math.sqrt(Q),F=_B((F+1)/2)-(F<0||F%2),D==1/0)Q="5e"+F;else Q=D.toExponential(),Q=Q.slice(0,Q.indexOf("e")+1)+F;$=new G(Q)}else $=new G(D.toString());B=(F=G.precision)+3;for(;;)if(Y=$,$=Y.plus(u8(Z,Y,B+2,1)).times(0.5),yQ(Y.d).slice(0,B)===(Q=yQ($.d)).slice(0,B))if(Q=Q.slice(B-3,B+1),Q=="9999"||!J&&Q=="4999"){if(!J){if(qA(Y,F+1,0),Y.times(Y).eq(Z)){$=Y;break}}B+=4,J=1}else{if(!+Q||!+Q.slice(1)&&Q.charAt(0)=="5")qA($,F+1,1),A=!$.times($).eq(Z);break}return Q6=!0,qA($,F,G.rounding,A)};c1.tangent=c1.tan=function(){var A,Q,B=this,$=B.constructor;if(!B.isFinite())return new $(NaN);if(B.isZero())return new $(B);return A=$.precision,Q=$.rounding,$.precision=A+10,$.rounding=1,B=B.sin(),B.s=1,B=u8(B,new $(1).minus(B.times(B)).sqrt(),A+10,0),$.precision=A,$.rounding=Q,qA(wz==2||wz==4?B.neg():B,A,Q,!0)};c1.times=c1.mul=function(A){var Q,B,$,J,Y,Z,X,F,D,G=this,V=G.constructor,U=G.d,K=(A=new V(A)).d;if(A.s*=G.s,!U||!U[0]||!K||!K[0])return new V(!A.s||U&&!U[0]&&!K||K&&!K[0]&&!U?NaN:!U||!K?A.s/0:A.s*0);if(B=_B(G.e/gA)+_B(A.e/gA),F=U.length,D=K.length,F<D)Y=U,U=K,K=Y,Z=F,F=D,D=Z;Y=[],Z=F+D;for($=Z;$--;)Y.push(0);for($=D;--$>=0;){Q=0;for(J=F+$;J>$;)X=Y[J]+K[$]*U[J-$-1]+Q,Y[J--]=X%QV|0,Q=X/QV|0;Y[J]=(Y[J]+Q)%QV|0}for(;!Y[--Z];)Y.pop();if(Q)++B;else Y.shift();return A.d=Y,A.e=NW0(Y,B),Q6?qA(A,V.precision,V.rounding):A};c1.toBinary=function(A,Q){return D$1(this,2,A,Q)};c1.toDecimalPlaces=c1.toDP=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A===void 0)return B;if($Y(A,0,xC),Q===void 0)Q=$.rounding;else $Y(Q,0,8);return qA(B,A+B.e+1,Q)};c1.toExponential=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=GE($,!0);else{if($Y(A,0,xC),Q===void 0)Q=J.rounding;else $Y(Q,0,8);$=qA(new J($),A+1,Q),B=GE($,!0,A+1)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toFixed=function(A,Q){var B,$,J=this,Y=J.constructor;if(A===void 0)B=GE(J);else{if($Y(A,0,xC),Q===void 0)Q=Y.rounding;else $Y(Q,0,8);$=qA(new Y(J),A+J.e+1,Q),B=GE($,!1,A+$.e+1)}return J.isNeg()&&!J.isZero()?"-"+B:B};c1.toFraction=function(A){var Q,B,$,J,Y,Z,X,F,D,G,V,U,K=this,E=K.d,H=K.constructor;if(!E)return new H(K);if(D=B=new H(1),$=F=new H(0),Q=new H($),Y=Q.e=WBA(E)-K.e-1,Z=Y%gA,Q.d[0]=X7(10,Z<0?gA+Z:Z),A==null)A=Y>0?Q:D;else{if(X=new H(A),!X.isInt()||X.lt(D))throw Error(yC+X);A=X.gt(Q)?Y>0?Q:D:X}Q6=!1,X=new H(yQ(E)),G=H.precision,H.precision=Y=E.length*gA*2;for(;;){if(V=u8(X,Q,0,1,1),J=B.plus(V.times($)),J.cmp(A)==1)break;B=$,$=J,J=D,D=F.plus(V.times(J)),F=J,J=Q,Q=X.minus(V.times(J)),X=J}return J=u8(A.minus(B),$,0,1,1),F=F.plus(J.times(D)),B=B.plus(J.times($)),F.s=D.s=K.s,U=u8(D,$,Y,1).minus(K).abs().cmp(u8(F,B,Y,1).minus(K).abs())<1?[D,$]:[F,B],H.precision=G,Q6=!0,U};c1.toHexadecimal=c1.toHex=function(A,Q){return D$1(this,16,A,Q)};c1.toNearest=function(A,Q){var B=this,$=B.constructor;if(B=new $(B),A==null){if(!B.d)return B;A=new $(1),Q=$.rounding}else{if(A=new $(A),Q===void 0)Q=$.rounding;else $Y(Q,0,8);if(!B.d)return A.s?B:A;if(!A.d){if(A.s)A.s=B.s;return A}}if(A.d[0])Q6=!1,B=u8(B,A,0,Q,1).times(A),Q6=!0,qA(B);else A.s=B.s,B=A;return B};c1.toNumber=function(){return+this};c1.toOctal=function(A,Q){return D$1(this,8,A,Q)};c1.toPower=c1.pow=function(A){var Q,B,$,J,Y,Z,X=this,F=X.constructor,D=+(A=new F(A));if(!X.d||!A.d||!X.d[0]||!A.d[0])return new F(X7(+X,D));if(X=new F(X),X.eq(1))return X;if($=F.precision,Y=F.rounding,A.eq(1))return qA(X,$,Y);if(Q=_B(A.e/gA),Q>=A.d.length-1&&(B=D<0?-D:D)<=QZ8)return J=zBA(F,X,B,$),A.s<0?new F(1).div(J):qA(J,$,Y);if(Z=X.s,Z<0){if(Q<A.d.length-1)return new F(NaN);if((A.d[Q]&1)==0)Z=1;if(X.e==0&&X.d[0]==1&&X.d.length==1)return X.s=Z,X}if(B=X7(+X,D),Q=B==0||!isFinite(B)?_B(D*(Math.log("0."+yQ(X.d))/Math.LN10+X.e+1)):new F(B+"").e,Q>F.maxE+1||Q<F.minE-1)return new F(Q>0?Z/0:0);if(Q6=!1,F.rounding=X.s=1,B=Math.min(12,(Q+"").length),J=F$1(A.times(vC(X,$+B)),$),J.d){if(J=qA(J,$+5,1),O10(J.d,$,Y)){if(Q=$+10,J=qA(F$1(A.times(vC(X,Q+B)),Q),Q+5,1),+yQ(J.d).slice($+1,$+15)+1==100000000000000)J=qA(J,$+1,0)}}return J.s=Z,Q6=!0,F.rounding=Y,qA(J,$,Y)};c1.toPrecision=function(A,Q){var B,$=this,J=$.constructor;if(A===void 0)B=GE($,$.e<=J.toExpNeg||$.e>=J.toExpPos);else{if($Y(A,1,xC),Q===void 0)Q=J.rounding;else $Y(Q,0,8);$=qA(new J($),A,Q),B=GE($,A<=$.e||$.e<=J.toExpNeg,A)}return $.isNeg()&&!$.isZero()?"-"+B:B};c1.toSignificantDigits=c1.toSD=function(A,Q){var B=this,$=B.constructor;if(A===void 0)A=$.precision,Q=$.rounding;else if($Y(A,1,xC),Q===void 0)Q=$.rounding;else $Y(Q,0,8);return qA(new $(B),A,Q)};c1.toString=function(){var A=this,Q=A.constructor,B=GE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()&&!A.isZero()?"-"+B:B};c1.truncated=c1.trunc=function(){return qA(new this.constructor(this),this.e+1,1)};c1.valueOf=c1.toJSON=function(){var A=this,Q=A.constructor,B=GE(A,A.e<=Q.toExpNeg||A.e>=Q.toExpPos);return A.isNeg()?"-"+B:B};function yQ(A){var Q,B,$,J=A.length-1,Y="",Z=A[0];if(J>0){Y+=Z;for(Q=1;Q<J;Q++){if($=A[Q]+"",B=gA-$.length,B)Y+=kC(B);Y+=$}if(Z=A[Q],$=Z+"",B=gA-$.length,B)Y+=kC(B)}else if(Z===0)return"0";for(;Z%10===0;)Z/=10;return Y+Z}function $Y(A,Q,B){if(A!==~~A||A<Q||A>B)throw Error(yC+A)}function O10(A,Q,B,$){var J,Y,Z,X;for(Y=A[0];Y>=10;Y/=10)--Q;if(--Q<0)Q+=gA,J=0;else J=Math.ceil((Q+1)/gA),Q%=gA;if(Y=X7(10,gA-Q),X=A[J]%Y|0,$==null)if(Q<3){if(Q==0)X=X/100|0;else if(Q==1)X=X/10|0;Z=B<4&&X==99999||B>3&&X==49999||X==50000||X==0}else Z=(B<4&&X+1==Y||B>3&&X+1==Y/2)&&(A[J+1]/Y/100|0)==X7(10,Q-2)-1||(X==Y/2||X==0)&&(A[J+1]/Y/100|0)==0;else if(Q<4){if(Q==0)X=X/1000|0;else if(Q==1)X=X/100|0;else if(Q==2)X=X/10|0;Z=($||B<4)&&X==9999||!$&&B>3&&X==4999}else Z=(($||B<4)&&X+1==Y||!$&&B>3&&X+1==Y/2)&&(A[J+1]/Y/1000|0)==X7(10,Q-3)-1;return Z}function KW0(A,Q,B){var $,J=[0],Y,Z=0,X=A.length;for(;Z<X;){for(Y=J.length;Y--;)J[Y]*=Q;J[0]+=Y$1.indexOf(A.charAt(Z++));for($=0;$<J.length;$++)if(J[$]>B-1){if(J[$+1]===void 0)J[$+1]=0;J[$+1]+=J[$]/B|0,J[$]%=B}}return J.reverse()}function $Z8(A,Q){var B,$,J;if(Q.isZero())return Q;if($=Q.d.length,$<32)B=Math.ceil($/3),J=(1/IW0(4,B)).toString();else B=16,J="2.3283064365386962890625e-10";A.precision+=B,Q=kh(A,1,Q.times(J),new A(1));for(var Y=B;Y--;){var Z=Q.times(Q);Q=Z.times(Z).minus(Z).times(8).plus(1)}return A.precision-=B,Q}var u8=function(){function A($,J,Y){var Z,X=0,F=$.length;for($=$.slice();F--;)Z=$[F]*J+X,$[F]=Z%Y|0,X=Z/Y|0;if(X)$.unshift(X);return $}function Q($,J,Y,Z){var X,F;if(Y!=Z)F=Y>Z?1:-1;else for(X=F=0;X<Y;X++)if($[X]!=J[X]){F=$[X]>J[X]?1:-1;break}return F}function B($,J,Y,Z){var X=0;for(;Y--;)$[Y]-=X,X=$[Y]<J[Y]?1:0,$[Y]=X*Z+$[Y]-J[Y];for(;!$[0]&&$.length>1;)$.shift()}return function($,J,Y,Z,X,F){var D,G,V,U,K,E,H,W,z,q,N,I,w,C,O,P,S,_,f,h,b=$.constructor,y=$.s==J.s?1:-1,u=$.d,p=J.d;if(!u||!u[0]||!p||!p[0])return new b(!$.s||!J.s||(u?p&&u[0]==p[0]:!p)?NaN:u&&u[0]==0||!p?y*0:y/0);if(F)K=1,G=$.e-J.e;else F=QV,K=gA,G=_B($.e/K)-_B(J.e/K);f=p.length,S=u.length,z=new b(y),q=z.d=[];for(V=0;p[V]==(u[V]||0);V++);if(p[V]>(u[V]||0))G--;if(Y==null)C=Y=b.precision,Z=b.rounding;else if(X)C=Y+($.e-J.e)+1;else C=Y;if(C<0)q.push(1),E=!0;else{if(C=C/K+2|0,V=0,f==1){U=0,p=p[0],C++;for(;(V<S||U)&&C--;V++)O=U*F+(u[V]||0),q[V]=O/p|0,U=O%p|0;E=U||V<S}else{if(U=F/(p[0]+1)|0,U>1)p=A(p,U,F),u=A(u,U,F),f=p.length,S=u.length;P=f,N=u.slice(0,f),I=N.length;for(;I<f;)N[I++]=0;if(h=p.slice(),h.unshift(0),_=p[0],p[1]>=F/2)++_;do{if(U=0,D=Q(p,N,f,I),D<0){if(w=N[0],f!=I)w=w*F+(N[1]||0);if(U=w/_|0,U>1){if(U>=F)U=F-1;if(H=A(p,U,F),W=H.length,I=N.length,D=Q(H,N,W,I),D==1)U--,B(H,f<W?h:p,W,F)}else{if(U==0)D=U=1;H=p.slice()}if(W=H.length,W<I)H.unshift(0);if(B(N,H,I,F),D==-1){if(I=N.length,D=Q(p,N,f,I),D<1)U++,B(N,f<I?h:p,I,F)}I=N.length}else if(D===0)U++,N=[0];if(q[V++]=U,D&&N[0])N[I++]=u[P]||0;else N=[u[P]],I=1}while((P++<S||N[0]!==void 0)&&C--);E=N[0]!==void 0}if(!q[0])q.shift()}if(K==1)z.e=G,VBA=E;else{for(V=1,U=q[0];U>=10;U/=10)V++;z.e=V+G*K-1,qA(z,X?Y+z.e+1:Y,Z,E)}return z}}();function qA(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor;A:if(Q!=null){if(V=A.d,!V)return A;for(J=1,X=V[0];X>=10;X/=10)J++;if(Y=Q-J,Y<0)Y+=gA,Z=Q,G=V[U=0],F=G/X7(10,J-Z-1)%10|0;else if(U=Math.ceil((Y+1)/gA),X=V.length,U>=X)if($){for(;X++<=U;)V.push(0);G=F=0,J=1,Y%=gA,Z=Y-gA+1}else break A;else{G=X=V[U];for(J=1;X>=10;X/=10)J++;Y%=gA,Z=Y-gA+J,F=Z<0?0:G/X7(10,J-Z-1)%10|0}if($=$||Q<0||V[U+1]!==void 0||(Z<0?G:G%X7(10,J-Z-1)),D=B<4?(F||$)&&(B==0||B==(A.s<0?3:2)):F>5||F==5&&(B==4||$||B==6&&(Y>0?Z>0?G/X7(10,J-Z):0:V[U-1])%10&1||B==(A.s<0?8:7)),Q<1||!V[0]){if(V.length=0,D)Q-=A.e+1,V[0]=X7(10,(gA-Q%gA)%gA),A.e=-Q||0;else V[0]=A.e=0;return A}if(Y==0)V.length=U,X=1,U--;else V.length=U+1,X=X7(10,gA-Y),V[U]=Z>0?(G/X7(10,J-Z)%X7(10,Z)|0)*X:0;if(D)for(;;)if(U==0){for(Y=1,Z=V[0];Z>=10;Z/=10)Y++;Z=V[0]+=X;for(X=1;Z>=10;Z/=10)X++;if(Y!=X){if(A.e++,V[0]==QV)V[0]=1}break}else{if(V[U]+=X,V[U]!=QV)break;V[U--]=0,X=1}for(Y=V.length;V[--Y]===0;)V.pop()}if(Q6){if(A.e>K.maxE)A.d=null,A.e=NaN;else if(A.e<K.minE)A.e=0,A.d=[0]}return A}function GE(A,Q,B){if(!A.isFinite())return NBA(A);var $,J=A.e,Y=yQ(A.d),Z=Y.length;if(Q){if(B&&($=B-Z)>0)Y=Y.charAt(0)+"."+Y.slice(1)+kC($);else if(Z>1)Y=Y.charAt(0)+"."+Y.slice(1);Y=Y+(A.e<0?"e":"e+")+A.e}else if(J<0){if(Y="0."+kC(-J-1)+Y,B&&($=B-Z)>0)Y+=kC($)}else if(J>=Z){if(Y+=kC(J+1-Z),B&&($=B-J-1)>0)Y=Y+"."+kC($)}else{if(($=J+1)<Z)Y=Y.slice(0,$)+"."+Y.slice($);if(B&&($=B-Z)>0){if(J+1===Z)Y+=".";Y+=kC($)}}return Y}function NW0(A,Q){var B=A[0];for(Q*=gA;B>=10;B/=10)Q++;return Q}function zW0(A,Q,B){if(Q>BZ8){if(Q6=!0,B)A.precision=B;throw Error(UBA)}return qA(new A(HW0),Q,1,!0)}function DE(A,Q,B){if(Q>X$1)throw Error(UBA);return qA(new A(WW0),Q,B,!0)}function WBA(A){var Q=A.length-1,B=Q*gA+1;if(Q=A[Q],Q){for(;Q%10==0;Q/=10)B--;for(Q=A[0];Q>=10;Q/=10)B++}return B}function kC(A){var Q="";for(;A--;)Q+="0";return Q}function zBA(A,Q,B,$){var J,Y=new A(1),Z=Math.ceil($/gA+4);Q6=!1;for(;;){if(B%2){if(Y=Y.times(Q),DBA(Y.d,Z))J=!0}if(B=_B(B/2),B===0){if(B=Y.d.length-1,J&&Y.d[B]===0)++Y.d[B];break}Q=Q.times(Q),DBA(Q.d,Z)}return Q6=!0,Y}function FBA(A){return A.d[A.d.length-1]&1}function qBA(A,Q,B){var $,J,Y=new A(Q[0]),Z=0;for(;++Z<Q.length;){if(J=new A(Q[Z]),!J.s){Y=J;break}if($=Y.cmp(J),$===B||$===0&&Y.s===B)Y=J}return Y}function F$1(A,Q){var B,$,J,Y,Z,X,F,D=0,G=0,V=0,U=A.constructor,K=U.rounding,E=U.precision;if(!A.d||!A.d[0]||A.e>17)return new U(A.d?!A.d[0]?1:A.s<0?0:1/0:A.s?A.s<0?0:A:NaN);if(Q==null)Q6=!1,F=E;else F=Q;X=new U(0.03125);while(A.e>-2)A=A.times(X),V+=5;$=Math.log(X7(2,V))/Math.LN10*2+5|0,F+=$,B=Y=Z=new U(1),U.precision=F;for(;;){if(Y=qA(Y.times(A),F,1),B=B.times(++G),X=Z.plus(u8(Y,B,F,1)),yQ(X.d).slice(0,F)===yQ(Z.d).slice(0,F)){J=V;while(J--)Z=qA(Z.times(Z),F,1);if(Q==null)if(D<3&&O10(Z.d,F-$,K,D))U.precision=F+=10,B=Y=X=new U(1),G=0,D++;else return qA(Z,U.precision=E,K,Q6=!0);else return U.precision=E,Z}Z=X}}function vC(A,Q){var B,$,J,Y,Z,X,F,D,G,V,U,K=1,E=10,H=A,W=H.d,z=H.constructor,q=z.rounding,N=z.precision;if(H.s<0||!W||!W[0]||!H.e&&W[0]==1&&W.length==1)return new z(W&&!W[0]?-1/0:H.s!=1?NaN:W?0:H);if(Q==null)Q6=!1,G=N;else G=Q;if(z.precision=G+=E,B=yQ(W),$=B.charAt(0),Math.abs(Y=H.e)<1500000000000000){while($<7&&$!=1||$==1&&B.charAt(1)>3)H=H.times(A),B=yQ(H.d),$=B.charAt(0),K++;if(Y=H.e,$>1)H=new z("0."+B),Y++;else H=new z($+"."+B.slice(1))}else return D=zW0(z,G+2,N).times(Y+""),H=vC(new z($+"."+B.slice(1)),G-E).plus(D),z.precision=N,Q==null?qA(H,N,q,Q6=!0):H;V=H,F=Z=H=u8(H.minus(1),H.plus(1),G,1),U=qA(H.times(H),G,1),J=3;for(;;){if(Z=qA(Z.times(U),G,1),D=F.plus(u8(Z,new z(J),G,1)),yQ(D.d).slice(0,G)===yQ(F.d).slice(0,G)){if(F=F.times(2),Y!==0)F=F.plus(zW0(z,G+2,N).times(Y+""));if(F=u8(F,new z(K),G,1),Q==null)if(O10(F.d,G-E,q,X))z.precision=G+=E,D=Z=H=u8(V.minus(1),V.plus(1),G,1),U=qA(H.times(H),G,1),J=X=1;else return qA(F,z.precision=N,q,Q6=!0);else return z.precision=N,F}F=D,J+=2}}function NBA(A){return String(A.s*A.s/0)}function EW0(A,Q){var B,$,J;if((B=Q.indexOf("."))>-1)Q=Q.replace(".","");if(($=Q.search(/e/i))>0){if(B<0)B=$;B+=+Q.slice($+1),Q=Q.substring(0,$)}else if(B<0)B=Q.length;for($=0;Q.charCodeAt($)===48;$++);for(J=Q.length;Q.charCodeAt(J-1)===48;--J);if(Q=Q.slice($,J),Q){if(J-=$,A.e=B=B-$-1,A.d=[],$=(B+1)%gA,B<0)$+=gA;if($<J){if($)A.d.push(+Q.slice(0,$));for(J-=gA;$<J;)A.d.push(+Q.slice($,$+=gA));Q=Q.slice($),$=gA-Q.length}else $-=J;for(;$--;)Q+="0";if(A.d.push(+Q),Q6){if(A.e>A.constructor.maxE)A.d=null,A.e=NaN;else if(A.e<A.constructor.minE)A.e=0,A.d=[0]}}else A.e=0,A.d=[0];return A}function JZ8(A,Q){var B,$,J,Y,Z,X,F,D,G;if(Q.indexOf("_")>-1){if(Q=Q.replace(/(\d)_(?=\d)/g,"$1"),HBA.test(Q))return EW0(A,Q)}else if(Q==="Infinity"||Q==="NaN"){if(!+Q)A.s=NaN;return A.e=NaN,A.d=null,A}if(eY8.test(Q))B=16,Q=Q.toLowerCase();else if(tY8.test(Q))B=2;else if(AZ8.test(Q))B=8;else throw Error(yC+Q);if(Y=Q.search(/p/i),Y>0)F=+Q.slice(Y+1),Q=Q.substring(2,Y);else Q=Q.slice(2);if(Y=Q.indexOf("."),Z=Y>=0,$=A.constructor,Z)Q=Q.replace(".",""),X=Q.length,Y=X-Y,J=zBA($,new $(B),Y,Y*2);D=KW0(Q,B,QV),G=D.length-1;for(Y=G;D[Y]===0;--Y)D.pop();if(Y<0)return new $(A.s*0);if(A.e=NW0(D,G),A.d=D,Q6=!1,Z)A=u8(A,J,X*4);if(F)A=A.times(Math.abs(F)<54?X7(2,F):j10.pow(2,F));return Q6=!0,A}function YZ8(A,Q){var B,$=Q.d.length;if($<3)return Q.isZero()?Q:kh(A,2,Q,Q);B=1.4*Math.sqrt($),B=B>16?16:B|0,Q=Q.times(1/IW0(5,B)),Q=kh(A,2,Q,Q);var J,Y=new A(5),Z=new A(16),X=new A(20);for(;B--;)J=Q.times(Q),Q=Q.times(Y.plus(J.times(Z.times(J).minus(X))));return Q}function kh(A,Q,B,$,J){var Y,Z,X,F,D=1,G=A.precision,V=Math.ceil(G/gA);Q6=!1,F=B.times(B),X=new A($);for(;;){if(Z=u8(X.times(F),new A(Q++*Q++),G,1),X=J?$.plus(Z):$.minus(Z),$=u8(Z.times(F),new A(Q++*Q++),G,1),Z=X.plus($),Z.d[V]!==void 0){for(Y=V;Z.d[Y]===X.d[Y]&&Y--;);if(Y==-1)break}Y=X,X=$,$=Z,Z=Y,D++}return Q6=!0,Z.d.length=V+1,Z}function IW0(A,Q){var B=A;while(--Q)B*=A;return B}function IBA(A,Q){var B,$=Q.s<0,J=DE(A,A.precision,1),Y=J.times(0.5);if(Q=Q.abs(),Q.lte(Y))return wz=$?4:1,Q;if(B=Q.divToInt(J),B.isZero())wz=$?3:2;else{if(Q=Q.minus(B.times(J)),Q.lte(Y))return wz=FBA(B)?$?2:3:$?4:1,Q;wz=FBA(B)?$?1:4:$?3:2}return Q.minus(J).abs()}function D$1(A,Q,B,$){var J,Y,Z,X,F,D,G,V,U,K=A.constructor,E=B!==void 0;if(E)if($Y(B,1,xC),$===void 0)$=K.rounding;else $Y($,0,8);else B=K.precision,$=K.rounding;if(!A.isFinite())G=NBA(A);else{if(G=GE(A),Z=G.indexOf("."),E){if(J=2,Q==16)B=B*4-3;else if(Q==8)B=B*3-2}else J=Q;if(Z>=0)G=G.replace(".",""),U=new K(1),U.e=G.length-Z,U.d=KW0(GE(U),10,J),U.e=U.d.length;V=KW0(G,10,J),Y=F=V.length;for(;V[--F]==0;)V.pop();if(!V[0])G=E?"0p+0":"0";else{if(Z<0)Y--;else A=new K(A),A.d=V,A.e=Y,A=u8(A,U,B,$,0,J),V=A.d,Y=A.e,D=VBA;if(Z=V[B],X=J/2,D=D||V[B+1]!==void 0,D=$<4?(Z!==void 0||D)&&($===0||$===(A.s<0?3:2)):Z>X||Z===X&&($===4||D||$===6&&V[B-1]&1||$===(A.s<0?8:7)),V.length=B,D){for(;++V[--B]>J-1;)if(V[B]=0,!B)++Y,V.unshift(1)}for(F=V.length;!V[F-1];--F);for(Z=0,G="";Z<F;Z++)G+=Y$1.charAt(V[Z]);if(E){if(F>1)if(Q==16||Q==8){Z=Q==16?4:3;for(--F;F%Z;F++)G+="0";V=KW0(G,J,Q);for(F=V.length;!V[F-1];--F);for(Z=1,G="1.";Z<F;Z++)G+=Y$1.charAt(V[Z])}else G=G.charAt(0)+"."+G.slice(1);G=G+(Y<0?"p":"p+")+Y}else if(Y<0){for(;++Y;)G="0"+G;G="0."+G}else if(++Y>F)for(Y-=F;Y--;)G+="0";else if(Y<F)G=G.slice(0,Y)+"."+G.slice(Y)}G=(Q==16?"0x":Q==2?"0b":Q==8?"0o":"")+G}return A.s<0?"-"+G:G}function DBA(A,Q){if(A.length>Q)return A.length=Q,!0}function ZZ8(A){return new this(A).abs()}function XZ8(A){return new this(A).acos()}function FZ8(A){return new this(A).acosh()}function DZ8(A,Q){return new this(A).plus(Q)}function GZ8(A){return new this(A).asin()}function VZ8(A){return new this(A).asinh()}function UZ8(A){return new this(A).atan()}function KZ8(A){return new this(A).atanh()}function EZ8(A,Q){A=new this(A),Q=new this(Q);var B,$=this.precision,J=this.rounding,Y=$+4;if(!A.s||!Q.s)B=new this(NaN);else if(!A.d&&!Q.d)B=DE(this,Y,1).times(Q.s>0?0.25:0.75),B.s=A.s;else if(!Q.d||A.isZero())B=Q.s<0?DE(this,$,J):new this(0),B.s=A.s;else if(!A.d||Q.isZero())B=DE(this,Y,1).times(0.5),B.s=A.s;else if(Q.s<0)this.precision=Y,this.rounding=1,B=this.atan(u8(A,Q,Y,1)),Q=DE(this,Y,1),this.precision=$,this.rounding=J,B=A.s<0?B.minus(Q):B.plus(Q);else B=this.atan(u8(A,Q,Y,1));return B}function HZ8(A){return new this(A).cbrt()}function WZ8(A){return qA(A=new this(A),A.e+1,2)}function zZ8(A,Q,B){return new this(A).clamp(Q,B)}function qZ8(A){if(!A||typeof A!=="object")throw Error(qW0+"Object expected");var Q,B,$,J=A.defaults===!0,Y=["precision",1,xC,"rounding",0,8,"toExpNeg",-Sh,0,"toExpPos",0,Sh,"maxE",0,Sh,"minE",-Sh,0,"modulo",0,9];for(Q=0;Q<Y.length;Q+=3){if(B=Y[Q],J)this[B]=Z$1[B];if(($=A[B])!==void 0)if(_B($)===$&&$>=Y[Q+1]&&$<=Y[Q+2])this[B]=$;else throw Error(yC+B+": "+$)}if(B="crypto",J)this[B]=Z$1[B];if(($=A[B])!==void 0)if($===!0||$===!1||$===0||$===1)if($)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[B]=!0;else throw Error(KBA);else this[B]=!1;else throw Error(yC+B+": "+$);return this}function NZ8(A){return new this(A).cos()}function IZ8(A){return new this(A).cosh()}function wBA(A){var Q,B,$;function J(Y){var Z,X,F,D=this;if(!(D instanceof J))return new J(Y);if(D.constructor=J,GBA(Y)){if(D.s=Y.s,Q6)if(!Y.d||Y.e>J.maxE)D.e=NaN,D.d=null;else if(Y.e<J.minE)D.e=0,D.d=[0];else D.e=Y.e,D.d=Y.d.slice();else D.e=Y.e,D.d=Y.d?Y.d.slice():Y.d;return}if(F=typeof Y,F==="number"){if(Y===0){D.s=1/Y<0?-1:1,D.e=0,D.d=[0];return}if(Y<0)Y=-Y,D.s=-1;else D.s=1;if(Y===~~Y&&Y<1e7){for(Z=0,X=Y;X>=10;X/=10)Z++;if(Q6)if(Z>J.maxE)D.e=NaN,D.d=null;else if(Z<J.minE)D.e=0,D.d=[0];else D.e=Z,D.d=[Y];else D.e=Z,D.d=[Y];return}if(Y*0!==0){if(!Y)D.s=NaN;D.e=NaN,D.d=null;return}return EW0(D,Y.toString())}if(F==="string"){if((X=Y.charCodeAt(0))===45)Y=Y.slice(1),D.s=-1;else{if(X===43)Y=Y.slice(1);D.s=1}return HBA.test(Y)?EW0(D,Y):JZ8(D,Y)}if(F==="bigint"){if(Y<0)Y=-Y,D.s=-1;else D.s=1;return EW0(D,Y.toString())}throw Error(yC+Y)}if(J.prototype=c1,J.ROUND_UP=0,J.ROUND_DOWN=1,J.ROUND_CEIL=2,J.ROUND_FLOOR=3,J.ROUND_HALF_UP=4,J.ROUND_HALF_DOWN=5,J.ROUND_HALF_EVEN=6,J.ROUND_HALF_CEIL=7,J.ROUND_HALF_FLOOR=8,J.EUCLID=9,J.config=J.set=qZ8,J.clone=wBA,J.isDecimal=GBA,J.abs=ZZ8,J.acos=XZ8,J.acosh=FZ8,J.add=DZ8,J.asin=GZ8,J.asinh=VZ8,J.atan=UZ8,J.atanh=KZ8,J.atan2=EZ8,J.cbrt=HZ8,J.ceil=WZ8,J.clamp=zZ8,J.cos=NZ8,J.cosh=IZ8,J.div=wZ8,J.exp=CZ8,J.floor=MZ8,J.hypot=LZ8,J.ln=OZ8,J.log=jZ8,J.log10=PZ8,J.log2=RZ8,J.max=_Z8,J.min=TZ8,J.mod=SZ8,J.mul=kZ8,J.pow=vZ8,J.random=yZ8,J.round=xZ8,J.sign=fZ8,J.sin=bZ8,J.sinh=uZ8,J.sqrt=hZ8,J.sub=gZ8,J.sum=mZ8,J.tan=pZ8,J.tanh=dZ8,J.trunc=cZ8,A===void 0)A={};if(A){if(A.defaults!==!0){$=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"];for(Q=0;Q<$.length;)if(!A.hasOwnProperty(B=$[Q++]))A[B]=this[B]}}return J.config(A),J}function wZ8(A,Q){return new this(A).div(Q)}function CZ8(A){return new this(A).exp()}function MZ8(A){return qA(A=new this(A),A.e+1,3)}function LZ8(){var A,Q,B=new this(0);Q6=!1;for(A=0;A<arguments.length;)if(Q=new this(arguments[A++]),!Q.d){if(Q.s)return Q6=!0,new this(1/0);B=Q}else if(B.d)B=B.plus(Q.times(Q));return Q6=!0,B.sqrt()}function GBA(A){return A instanceof j10||A&&A.toStringTag===EBA||!1}function OZ8(A){return new this(A).ln()}function jZ8(A,Q){return new this(A).log(Q)}function RZ8(A){return new this(A).log(2)}function PZ8(A){return new this(A).log(10)}function _Z8(){return qBA(this,arguments,-1)}function TZ8(){return qBA(this,arguments,1)}function SZ8(A,Q){return new this(A).mod(Q)}function kZ8(A,Q){return new this(A).mul(Q)}function vZ8(A,Q){return new this(A).pow(Q)}function yZ8(A){var Q,B,$,J,Y=0,Z=new this(1),X=[];if(A===void 0)A=this.precision;else $Y(A,1,xC);if($=Math.ceil(A/gA),!this.crypto)for(;Y<$;)X[Y++]=Math.random()*1e7|0;else if(crypto.getRandomValues){Q=crypto.getRandomValues(new Uint32Array($));for(;Y<$;)if(J=Q[Y],J>=4290000000)Q[Y]=crypto.getRandomValues(new Uint32Array(1))[0];else X[Y++]=J%1e7}else if(crypto.randomBytes){Q=crypto.randomBytes($*=4);for(;Y<$;)if(J=Q[Y]+(Q[Y+1]<<8)+(Q[Y+2]<<16)+((Q[Y+3]&127)<<24),J>=2140000000)crypto.randomBytes(4).copy(Q,Y);else X.push(J%1e7),Y+=4;Y=$/4}else throw Error(KBA);if($=X[--Y],A%=gA,$&&A)J=X7(10,gA-A),X[Y]=($/J|0)*J;for(;X[Y]===0;Y--)X.pop();if(Y<0)B=0,X=[0];else{B=-1;for(;X[0]===0;B-=gA)X.shift();for($=1,J=X[0];J>=10;J/=10)$++;if($<gA)B-=gA-$}return Z.e=B,Z.d=X,Z}function xZ8(A){return qA(A=new this(A),A.e+1,this.rounding)}function fZ8(A){return A=new this(A),A.d?A.d[0]?A.s:0*A.s:A.s||NaN}function bZ8(A){return new this(A).sin()}function uZ8(A){return new this(A).sinh()}function hZ8(A){return new this(A).sqrt()}function gZ8(A,Q){return new this(A).sub(Q)}function mZ8(){var A=0,Q=arguments,B=new this(Q[A]);Q6=!1;for(;B.s&&++A<Q.length;)B=B.plus(Q[A]);return Q6=!0,qA(B,this.precision,this.rounding)}function pZ8(A){return new this(A).tan()}function dZ8(A){return new this(A).tanh()}function cZ8(A){return qA(A=new this(A),A.e+1,1)}c1[Symbol.for("nodejs.util.inspect.custom")]=c1.toString;c1[Symbol.toStringTag]="Decimal";var j10=c1.constructor=wBA(Z$1);HW0=new j10(HW0);WW0=new j10(WW0);var G$1=2;function lZ8(A,Q){let B=Q.decimalPlaces==="more-if-tiny"?Math.abs(A)<0.01?G$1+1:G$1:Q.decimalPlaces??G$1,$=Q.intent==="balance"?A<0?"expand":"trunc":"halfExpand";return{decimalPlaces:B,roundingMode:$}}function fC(A,Q){let{decimalPlaces:B,roundingMode:$}=lZ8(A,Q),J=A%1===0&&!Q.alwaysShowCents?A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0,roundingMode:$}):A.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:B,maximumFractionDigits:B,roundingMode:$});return Q.includeCurrencyCode?`${J} USD`:J}function R10(A){if(A>=1e6)return`${Math.round(A/1e6)}M`;if(A>=1000)return`${Math.round(A/1000)}k`;return A.toString()}function iZ8(A){if(!A)return"";let Q=A.split("-");if(Q.length>=2)return Q.slice(0,2).join("-");return A}function CBA(A){let Q=[],B=(A.inputTokens??0)+(A.cacheCreationInputTokens??0),$=A.cacheReadInputTokens??0;if(B>0)Q.push(`${R10(B)} in`);if($>0)Q.push(`${R10($)} cache read`);if(A.outputTokens)Q.push(`${R10(A.outputTokens)} out`);if(A.model)Q.push(iZ8(A.model));if(Q.length>0)return`(${Q.join(", ")})`;return""}function bC(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,X=Y?.paidUSD??0;if(Z===0&&X===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(X===0)J.push(new M(fC(Z,D),new x({color:B.foreground,dim:$}))),J.push(new M(" (free)",new x({color:B.foreground,dim:$})));else if(Z>0)J.push(new M(fC(Z,D),new x({color:B.foreground,dim:$}))),J.push(new M(" (free)",new x({color:B.foreground,dim:$}))),J.push(new M(" + ",new x({color:B.foreground,dim:$}))),J.push(new M(fC(X,D),new x({color:B.foreground,dim:$,bold:!$})));else J.push(new M(fC(X,D),new x({color:B.foreground,dim:$,bold:!$})));return J}class V$1 extends EA{}class U$1 extends EA{}function nZ8(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function aZ8(A,Q){let B=S0.of(Q),{colors:$}=B,J=bC(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new M("Total: ",new x({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new M("Usage information is currently unavailable."));else Y.push(new M("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new M(`
5288
5288
 
5289
- `)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new i({text:new M("",void 0,Y)})}function oZ8(A,Q,B){let $=aZ8(A,Q);if(!A.costBreakdownURL)return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new M4(()=>{return TA.maybeInvoke(Q,new _$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new M4(()=>{return L6(Q,J),"handled"});return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new TA({actions:new Map([[V$1,Y],[U$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new U$1],[g1.key("y"),new V$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function MBA(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await LA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(nZ8(J,Y.error),"error",5000),$();return}Q.push(oZ8(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var rZ8=250,sZ8=2000;class K$1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new OBA}}class OBA extends v0{editorController=new v3;commandPalette=new G00(this);commandRegistry=new kQ1;toastController=new E21;exitHintTimer=new du(this,1000);ideStatus=new r3(this,{});threadNavigationHistory=new jQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await D9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return G9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await H5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await W5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await z5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(d90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new OQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=d4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},rZ8),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<sZ8)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Z9A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>SB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},MBA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new pQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new eB1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{rJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new gQ1({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new bQ1({commands:T$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new nA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new i({text:new M(X21({version:"0.0.1777875280-g2566d7",buildTimestamp:"2026-05-04T06:18:29.836Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{TA.maybeInvoke(Y,new wh)}},...Q,...o2A(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new tB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=Y4.of(A),Z=[new p0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new vQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(SB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new QA({debugLabel:"NeoWelcomeDialogOverlay",child:new $$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new uQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:P10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new hQ1);return new M2({neoContext:this.widget.neoContext,child:new T$({commandRegistry:this.commandRegistry,child:new OC({completionBuilder:this.widget.completionBuilder,child:new e8({controller:this.toastController,child:new TA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new cH0],[g1.ctrl("o"),new lH0],[g1.alt("i"),new nH0],[g1.alt("p"),new JC],[g1.ctrl("t"),new aH0]]),child:new s4({debugLabel:"AppShellFocus",child:new H21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new M4(()=>{if(oJ.hasAnyCopyableSelection())return oJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new M4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new M4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new M4(()=>{let G=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(G),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new M4(()=>{return d4.instance.stop(),"handled"}),Y=new M4((G)=>{if(!G.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(G.text).then(()=>{this.toastController.show(G.successMessage,"success",2000)}).catch((V)=>{j.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Z=new M4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let G=this.activeThreadContext?.client.getThreadId();if(!G)return this.toastController.show("No active thread","error",2000),"handled";return C51(G).then((V)=>{this.toastController.show(ga4(V),"success",2000)}).catch((V)=>{let U=V instanceof Error?V.message:String(V);j.error("Failed to copy thread log",{error:V}),this.toastController.show(`Failed to copy thread log: ${U}`,"error",2000)}),"handled"}),D=new M4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[cH0,A],[Z10,$],[wh,J],[_$,Y],[D10,B],[lH0,Q],[nH0,X],[M_,F],[JC,Z],[aH0,D]])}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=AE0(await ku(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=LBA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(SX(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=LBA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(LC);if(this.exitHintTimer.isActive())A.add(Hh);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),d4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,P10.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?xZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=$D0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=P10.cwd().replace(P10.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";P10.stdout.write(aw(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function LBA(A,Q,B){let $={...A};for(let J of tZ8(Q,B)){if(!SX(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function tZ8(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}AA();function jBA(A,Q,B,$){let J=Fv(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new _Z(G,V),K=new A7(42),E=new sw(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,q0.default(),K);E.layout(L1.tight(G,V)),E.paint(U,0,0);let H=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(H[P].some((S)=>S.char!==" ")){W=P;break}let z=V-1;for(let P=V-1;P>=0;P--)if(H[P].some((S)=>S.char!==" ")){z=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:_,g:f,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${_};${f};${h}m`;let b=gP(_,f,h);return`\x1B[${S?38:48};5;${b}m`}return""}let N=[];if(z>=W)for(let P=W;P<=z;P++){let S="";for(let _=0;_<G;_++){let f=H[P][_],h=f.char,b=q(f.style.fg,!0);S+=b+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=C&&P<C+I)S=N[P-C];let _=" ",f="";if(P>=O&&P<O+D.length)f=D[P-O];B.write(S+_+f+`
5289
+ `)),Y.push(new M("Details: ",new x({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new x({color:B.app.link})));return new i({text:new M("",void 0,Y)})}function oZ8(A,Q,B){let $=aZ8(A,Q);if(!A.costBreakdownURL)return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new M4(()=>{return TA.maybeInvoke(Q,new _$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new M4(()=>{return L6(Q,J),"handled"});return new nA({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new TA({actions:new Map([[V$1,Y],[U$1,Z]]),child:new V8({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[g1.key("o"),new U$1],[g1.key("y"),new V$1]]),child:new s4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function MBA(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await LA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(nZ8(J,Y.error),"error",5000),$();return}Q.push(oZ8(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var rZ8=250,sZ8=2000;class K$1 extends y0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new OBA}}class OBA extends v0{editorController=new v3;commandPalette=new G00(this);commandRegistry=new kQ1;toastController=new E21;exitHintTimer=new du(this,1000);ideStatus=new r3(this,{});threadNavigationHistory=new jQ1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};shareThreadWithSupport=async(A,Q)=>{let B;if(this.activeThreadContext&&this.activeThreadContext.client.getThreadId()===A){let $=this.activeThreadContext.observer.activeError().getValue();if($)B={message:$.message,type:$.code,stack:$.stack,retryAfterSeconds:$.retryAt!==void 0?Math.max(0,Math.ceil(($.retryAt-Date.now())/1000)):void 0}}await D9A({configService:this.widget.configService},A,Q,B)};setThreadVisibility=(A,Q)=>{return G9A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await H5A({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await W5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await z5A({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(M$.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(d90(Q.settings))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new OQ1({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=d4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},rZ8),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<sZ8)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?Z9A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>SB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},MBA({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new pQ1({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new eB1({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await L6(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{rJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new gQ1({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new bQ1({commands:T$.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show neo welcome",description:"Show the Neo welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new nA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new i({text:new M(X21({version:"0.0.1777879744-g2d678a",buildTimestamp:"2026-05-04T07:32:44.192Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:g1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{TA.maybeInvoke(Y,new wh)}},...Q,...o2A(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new tB1({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,shareThreadWithSupport:this.shareThreadWithSupport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=Y4.of(A),Z=[new p0({constraints:L1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new QA({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new vQ1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(SB1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new QA({debugLabel:"NeoWelcomeDialogOverlay",child:new $$1({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new uQ1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:P10.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new hQ1);return new M2({neoContext:this.widget.neoContext,child:new T$({commandRegistry:this.commandRegistry,child:new OC({completionBuilder:this.widget.completionBuilder,child:new e8({controller:this.toastController,child:new TA({actions:this.buildActions(),child:new V8({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[g1.ctrl("c"),new cH0],[g1.ctrl("o"),new lH0],[g1.alt("i"),new nH0],[g1.alt("p"),new JC],[g1.ctrl("t"),new aH0]]),child:new s4({debugLabel:"AppShellFocus",child:new H21({controller:this.toastController,child:new HA({children:Z})})})})})})})})})}buildActions(){let A=new M4(()=>{if(oJ.hasAnyCopyableSelection())return oJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new M4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new M4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new M4(()=>{let G=this.activeThreadContext?.client.getThreadId();return this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(G),this.setState(()=>{this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.writeTerminalTitle(void 0),this.activeThreadContext=null,this.connectingToThreadID=null}),"handled"}),J=new M4(()=>{return d4.instance.stop(),"handled"}),Y=new M4((G)=>{if(!G.text)return"ignored";return d4.instance.tuiInstance.clipboard.writeText(G.text).then(()=>{this.toastController.show(G.successMessage,"success",2000)}).catch((V)=>{j.error("Failed to copy Neo text to clipboard",{error:V}),this.toastController.show(G.failureMessage,"error",2000)}),"handled"}),Z=new M4(()=>{return d4.instance.toggleFrameStatsOverlay(),"handled"}),X=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new M4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let G=this.activeThreadContext?.client.getThreadId();if(!G)return this.toastController.show("No active thread","error",2000),"handled";return C51(G).then((V)=>{this.toastController.show(ga4(V),"success",2000)}).catch((V)=>{let U=V instanceof Error?V.message:String(V);j.error("Failed to copy thread log",{error:V}),this.toastController.show(`Failed to copy thread log: ${U}`,"error",2000)}),"handled"}),D=new M4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[cH0,A],[Z10,$],[wh,J],[_$,Y],[D10,B],[lH0,Q],[nH0,X],[M_,F],[JC,Z],[aH0,D]])}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=AE0(await ku(this.widget.configService),{agentMode:this.widget.neoContext.sessionAgentMode,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext});this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=LBA(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(SX(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=LBA(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(LC);if(this.exitHintTimer.isActive())A.add(Hh);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),d4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null)=>{await this.ensureDraftThreadSettingsInitialized();let $=this.activeThreadContext?.client.getThreadId(),J=A.find((Z)=>Z.type==="text");if(J&&J.type==="text")this.widget.history.add(J.text,P10.cwd()),this.widget.history.reset();let Y=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?xZ(B):void 0);this.sendUserMessage(Y,A,Q),this.threadNavigationHistory.recordNavigation($),this.setActiveClient(Y)};sendUserMessage(A,Q,B){let $=$D0(this.ideStatus.getValue());A.client.sendUserMessage(Q,B,{userState:$})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.writeTerminalTitle(Q)}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}writeTerminalTitle(A){let Q=P10.cwd().replace(P10.env.HOME||"","~"),B=A?`amp - ${A} - ${Q}`:"";P10.stdout.write(aw(B))}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function LBA(A,Q,B){let $={...A};for(let J of tZ8(Q,B)){if(!SX(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function tZ8(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}AA();function jBA(A,Q,B,$){let J=Fv(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new _Z(G,V),K=new A7(42),E=new sw(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,q0.default(),K);E.layout(L1.tight(G,V)),E.paint(U,0,0);let H=U.getBuffer().getCells(),W=0;for(let P=0;P<V;P++)if(H[P].some((S)=>S.char!==" ")){W=P;break}let z=V-1;for(let P=V-1;P>=0;P--)if(H[P].some((S)=>S.char!==" ")){z=P;break}function q(P,S){if(!P)return"";if(P.type==="rgb"){let{r:_,g:f,b:h}=P.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${_};${f};${h}m`;let b=gP(_,f,h);return`\x1B[${S?38:48};5;${b}m`}return""}let N=[];if(z>=W)for(let P=W;P<=z;P++){let S="";for(let _=0;_<G;_++){let f=H[P][_],h=f.char,b=q(f.style.fg,!0);S+=b+h+"\x1B[0m"}N.push(S)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let P=0;P<w;P++){let S=" ".repeat(G);if(P>=C&&P<C+I)S=N[P-C];let _=" ",f="";if(P>=O&&P<O+D.length)f=D[P-O];B.write(S+_+f+`
5290
5290
  `)}if($)B.write(`
5291
5291
  \x1B[90m${$}\x1B[0m
5292
5292
  `)}i0();GE0();var eZ8=2000;function RBA(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<eZ8)return;if(J=U,nP())return;if(XK0())FK0();else Vs(V)},Z=(V)=>{if(!Q||!B)return;if(nP()&&!B00()&&!Mu())return;process.stdout.write(dG(`\x1B]777;notify;Amp;${V}\x1B\\`))},X=null,F=null,D=()=>{X?.unsubscribe(),X=null,F=null};return{attach:(V)=>{D(),X=V.subscribe({next:(U)=>{try{let K=F!==null&&w$(F),E=F==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{F=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}i0();OH();H4();j1();function PBA(A,Q){if(!Q)return A;let B=Q.toLowerCase(),$=[];for(let J of A){let Y=AX8(J,B);if(Y>0)$.push({...J,score:Y})}return $.sort((J,Y)=>{let Z=Y.score-J.score;if(Z!==0)return Z;return A.indexOf(J)-A.indexOf(Y)}),$}function AX8(A,Q){let B=QX8(A,Q),$=BX8(A.message.toLowerCase(),Q);return Math.max(B,$)}function QX8(A,Q){let B=A.hash.toLowerCase(),$=A.shortHash.toLowerCase();if($===Q)return 1000;if($.startsWith(Q))return 900;if(B.startsWith(Q))return 850;if(B.includes(Q)||$.includes(Q))return 400;return 0}function BX8(A,Q){if(A===Q)return 800;if(A.startsWith(Q))return 700;let B=A.indexOf(Q);if(B!==-1)return 600-Math.min(B,500);let $=$X8(A,Q);if($>0)return $;return 0}function $X8(A,Q){let B=0,$=0,J=-1;while(B<A.length&&$<Q.length){if(A[B]===Q[$]){if(J===-1)J=B;$++}B++}if($===Q.length)return 250-Math.min(J,150);return 0}var _BA=":";function k_(A,Q){if(!kP())return;j.debug("[file mention completions]",{event:A,...Q})}function vh(A){return A.length<=80?A:`${A.slice(0,77)}...`}class v_{fuzzyClient;cachedDirtyFiles=[];cachedCommits=[];refreshPromise;refreshCommitsPromise;constructor(A){this.fuzzyClient=A;this.refreshDirtyFilesInBackground(),this.refreshCommitsInBackground()}async buildOptions(A){if(A.trigger==="@"){let Q=A.query;if(Q.toLowerCase().startsWith(_BA)){let Z=Q.slice(_BA.length);return k_("commit_query_detected",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Z.length,queryPreview:vh(Z)}),this.buildCommitOptions(Z)}let $=Q.length===0?18:20,J=await this.buildFileOptions(Q,$),Y=this.appendHintOptions(Q,J);return k_("build_options_completed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:Q.length,queryPreview:vh(Q),maxResults:$,fileOptionCount:J.filter((Z)=>Z.type==="file").length,hintOptionCount:Y.filter((Z)=>Z.type==="hint").length,finalOptionCount:Y.length,firstFilePaths:Y.filter((Z)=>Z.type==="file").slice(0,5).map((Z)=>Z.path)}),Y}return[]}async buildFileOptions(A,Q){try{let B=await this.getOpenFiles(),$=this.cachedDirtyFiles;this.refreshDirtyFilesInBackground();let J=await this.fuzzyClient.queryCompletions(A,Q,B,$),Y=J.map((Z)=>X7A(Z));return k_("file_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),maxResults:Q,openFilesCount:B?.length??0,dirtyFilesCount:$.length,completionItemCount:J.length,fileOptionCount:Y.length,firstPaths:Y.slice(0,5).map((Z)=>Z.path)}),Y}catch(B){return k_("file_options_failed",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),maxResults:Q,error:B instanceof Error?B.message:String(B)}),[]}}async getOpenFiles(){let A=await y1(n8.status);if(!A.connected)return;let Q=[];if(A.openFile)Q.push(J1.parse(A.openFile).fsPath);if(A.visibleFiles)for(let B of A.visibleFiles){let $=J1.parse(B).fsPath;if(!Q.includes($))Q.push($)}if(Q.length===0)return;return Q}refreshDirtyFilesInBackground(){if(this.refreshPromise!==void 0)return;this.refreshPromise=wv4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedDirtyFiles=A}).catch(()=>{}).finally(()=>{this.refreshPromise=void 0})}async buildCommitOptions(A){this.refreshCommitsInBackground();let Q=this.cachedCommits;if(!Q.length)return k_("commit_options_empty_cache",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A)}),[];let B=PBA(Q,A).slice(0,20);return k_("commit_options_built",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,queryPreview:vh(A),commitCacheCount:Q.length,resultCount:B.length,firstCommitHashes:B.slice(0,5).map(($)=>$.shortHash)}),B.map(($)=>({type:"commit",hash:$.hash,shortHash:$.shortHash,message:$.message,relativeDate:$.relativeDate}))}refreshCommitsInBackground(){if(this.refreshCommitsPromise!==void 0)return;this.refreshCommitsPromise=Cv4(this.fuzzyClient.workspaceRoot).then((A)=>{this.cachedCommits=A}).catch(()=>{}).finally(()=>{this.refreshCommitsPromise=void 0})}appendHintOptions(A,Q){if(A.length>0)return Q;let B=[{type:"hint",kind:"commit",message:"mention a commit"},{type:"hint",kind:"thread",message:"mention a thread"}];return k_("hint_options_appended",{workspaceRoot:this.fuzzyClient.workspaceRoot,queryLength:A.length,fileOptionCount:Q.filter(($)=>$.type==="file").length,hintOptionCount:B.length,hintOnly:Q.length===0,firstFilePaths:Q.filter(($)=>$.type==="file").slice(0,5).map(($)=>$.path)}),[...Q,...B]}}var YX8=[{long:"neo",description:"Use the Neo TUI",type:"boolean",default:!1},{long:"url",short:"u",description:"Amp server URL",type:"string",default:""},{long:"dangerously-allow-all",description:"Disable all command confirmation prompts (agent will execute all commands without asking)",type:"boolean",default:!1},{long:"observe",description:"Connect to an existing thread as observer only (no local executor). Accepts a thread ID or thread URL.",type:"string",default:""}],sl2=D4A({name:"amp neo",description:"Start the Neo TUI",options:YX8,positionals:[],action:async({options:A})=>{let Q=TBA(A);if(A.observe){let B=l8(A.observe)??WB(A.observe);await wW0(Q,{initialThreadID:B,observerOnly:!0});return}await wW0(Q)},subcommands:[{name:"threads",alias:"t",description:"List and manage threads",options:[],positionals:[],subcommands:[{name:"continue",alias:"c",description:"Continue an existing thread",options:[],positionals:[{name:"thread-id",description:"Thread ID to continue"}],action:async({globalOptions:A,positionals:Q})=>{let $=TBA(A);if(!Q["thread-id"]){await wW0($,{openThreadPickerOnStart:!0});return}let J=l8(Q["thread-id"]);if(!J)throw"invalid thread ID";await wW0($,{initialThreadID:J})}}]}]});function ZX8(A){if(A)return A;if(process.env.AMP_URL)return process.env.AMP_URL;return x9}function XX8(A){if(process.env.RIVET_PUBLIC_ENDPOINT)return process.env.RIVET_PUBLIC_ENDPOINT;return dJ(A)}var SBA=J1.file(JX8.homedir()),FX8=process.env.XDG_CONFIG_HOME?J1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(SBA,".config");function DX8({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function GX8(A){await kZ((Q)=>$E0(Q,A,"interactive"))}function TBA(A){return{url:A.url,dangerouslyAllowAll:A["dangerously-allow-all"]}}async function wW0(A,Q={}){let{initialThreadID:B,openThreadPickerOnStart:$=!1,observerOnly:J=!1}=Q,Y=ZX8(A.url),Z={dataDir:void 0,getHook:(S,_)=>{if(S==="url")return Promise.resolve(Y);return _()}},X=await KK0(Z),F=BE0(await qe(Z,X)),D=XX8(Y);if(A.dangerouslyAllowAll)sB("dangerouslyAllowAll",!0);let G=await F.get("apiKey",Y);if(!G)throw new F4("API key required. Please run `amp login` first.",1);let V=Jv({storage:X,secretStorage:F,workspaceRoot:g0.of(J1.file(process.cwd())),defaultAmpURL:Y,homeDir:SBA,userConfigDir:FX8}),U=jj(V,{usesThreadActors:!0}),K=bD0({configService:V}),E=new Su({configService:V});E.pluginExecutorKind="local";let H=mi({configService:V,fileSystem:e5,platform:E,internalPlugins:Te,loadGlobalPlugins:Ee(V),pluginFilter:"all"}),W=N$0({pluginService:H,toolService:K.toolService}),z=Qs({configService:V,filesystem:e5,spawn:nf}),q=Bs({toolService:K.toolService,providers:[z]}),N=qJ0({configService:V,filesystem:e5}),I={registerToolsWithToolService:()=>({dispose:()=>{}}),getClient:()=>{return},servers:g0.of([]),getPrompt:async()=>null,searchResources:async()=>[],searchPrompts:()=>g0.of([]),getToolsForServer:async()=>{return}},w=process.cwd(),C=async({uri:S})=>{return hw({fileSystem:e5,workspaceRoot:w},S)},O=new qu(w,{},!0),P=new v_(O);await E$1({ampURL:Y,apiKey:G,rivetEndpoint:D,configService:V,toolService:K.toolService,pluginPlatform:E,pluginService:H,skillService:N,mcpService:I,readFileSystemDirectory:C,completionBuilder:P,workspaceRoot:w,listThreads:()=>U.listThreads(),getThreadFromServer:(S)=>U.getThread(S),toolboxes:z.toolboxes,isInternalUser:!1,settingsFilePath:X.getSettingsFilePath(),dispose:()=>{for(let S of q.values())S.dispose();return z.dispose(),O.dispose(),W.dispose(),K.dispose(),H.dispose()}},{initialThreadID:B,openThreadPickerOnStart:$,observerOnly:J})}async function E$1(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:X,showNeoWelcome:F=!1}=Q,D=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)return null;return cU0(w)},G=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)throw Error(`Thread ${I} not found`);let C=await jZ(I,A.configService,A.apiKey,{usesThreadActors:!0}),S=await yK({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([I],{params:{wsToken:C.wsToken},createWithInput:{threadId:C.threadId,threadVersion:C.threadVersion,ownerUserId:C.ownerUserId,...C.agentMode?{agentMode:C.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:br4(w)})});if(S.ok||S.status===409)return;throw Error(`Thread import failed (${S.status}): ${await S.text()}`)},V=new g31(A.rivetEndpoint,A.apiKey,A.configService,{clientID:bw.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(I)=>A.pluginService.event.toolCall(I),requestPluginToolResult:(I)=>A.pluginService.event.toolResult(I),pluginService:A.pluginService,invokeTool:async(I,w)=>{let C=typeof w.args==="object"&&w.args!==null?w.args:{},O=await mw({toolName:w.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:w.toolCallId,threadID:I});return A.toolService.invokeTool(w.toolName,{args:C},O)},persistLastThreadID:GX8,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await BC(),K=DX8({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?SU(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:rt,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:Y,sessionAgentMode:Z??U.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:U.lastReasoningEffortByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},H=(I,w)=>{return db({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},W=(I,w)=>{return W1A({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=new Z21,q=RBA({configService:A.configService}),N=new Set;try{await $00(new K$1({clientPool:V,analyzeContextForThread:H,listSkillsForThread:W,completionBuilder:A.completionBuilder,history:new Fe,ideManager:z,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{kZ(I1A).catch((w)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:w})})}:void 0,onThreadArchived:(w)=>{N.add(w)}}));let I=V.lastActiveObservingClient;if(I){let{client:w,observer:C}=I,O=w.getThreadId();if(O){let P={id:O,title:C.title().getValue(),agentMode:C.agentMode,archived:N.has(O)},S=`${A.ampURL.replace(/\/$/,"")}/threads/${O}`;jBA(P,S,process.stdout)}}}finally{process.stdout.write(aw("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}yl();EH();async function VX8(A,Q,B){let $=s70(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=$N($.data);if(!J.success){let F=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${F}`)}let Y=await Q.get("permissions",B)??[],X=[$.data[0],...Y];await Q.set("permissions",X,B)}async function kBA(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await VX8(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -6054,7 +6054,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
6054
6054
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new M(G.slice(1,-1),new x({color:$.app.keybind,bold:!0})));else Y.push(new M(G,new x({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new M(`
6055
6055
  `))}return new p0({decoration:{color:B.colorScheme.background,border:e1.all(new A4($.app.keybind,1,"rounded"))},child:new b0({padding:w0.symmetric(0,1),child:new i({text:new M(void 0,void 0,Y)})})})}}class NJ1 extends a3{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=yz0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new zJ1({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function dYA(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let X=B;return X>=0&&X<Y?X:null}case"bar":case"stacked-bar":{let X=Z?e3:0,F=$-X;if(F<=0)return null;let D=Q-X;if(D<0||D>=F)return null;let G=Math.max(1,Math.floor(F/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let X=Z?e3:0,F=$-X;if(F<=0)return null;let D=Math.max(0,Math.min(F-1,Q-X));if(Y===1)return 0;let G=F/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function VK8(A,Q,B,$,J,Y,Z,X){if(J<=0||Q<0||Q>=J)return null;let F=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?e3:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=X>0?Z/X:0,H=Math.round((1-E)*(V-1));return{x:K,y:H}}case"line":case"sparkline":case"stacked-area":{let D=Y?e3:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=X>0?Z/X:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function UK8(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function KK8(A,Q,B,$,J){if(B.length<=1){let X=$(A.value),F=A.meta?` (${A.meta})`:"";return A.label.length+2+X.length+F.length}let Y=A.label.length,Z=0;for(let X of B){let F=X.points[Q];if(!F)continue;Z+=F.value;let D=2+X.name.length+2+$(F.value).length;Y=Math.max(Y,D)}if(J){let X=9+$(Z).length;Y=Math.max(Y,X)}return Y}function EK8(A,Q,B,$,J,Y,Z){let X;try{let E=S1.of(A),H=S0.of(A);X={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:H.app.keybind}}catch{X={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new x({color:X.foreground,bold:!0}),D=new x({color:X.foreground}),G=new x({color:X.foreground,dim:!0}),V=[],U=new x({color:X.foreground,underline:!0}),K=(E,H)=>new M(H,U,void 0,RK0(E),()=>{L6(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new M(Y(Q.value),D));if(Q.meta)V.push(new M(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new M(`${Q.label}
6056
6056
  `,F));let H=0;for(let W=0;W<$.length;W++){let z=$[W],q=z.points[B];if(!q)continue;H+=q.value;let N=z.color??J[W%J.length]??X.foreground;if(V.push(new M("● ",new x({color:N}))),V.push(new M(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(W<$.length-1||E)V.push(new M(`
6057
- `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new p0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new i({text:new M(void 0,void 0,V)})})}i0();S8();EO();f2();F8();oQ();Yr();OX();KQ();K9();Q$();TU();AA();Zx();bk();j1();i0();KQ();class IJ1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777875280-g2566d7"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await n70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class oC extends y0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA extends v0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class lYA extends v0{controller=new v3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new L$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Y1({children:[new p0({decoration:{color:B.background},child:new i({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new p0({padding:w0.symmetric(1,0),child:new i({text:this.widget.props.title?new M(this.widget.props.title,new x({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new x({color:$.keybind}))),V.push(new M(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new M("Esc",new x({color:$.keybind}))),V.push(new M(" to cancel",new x({color:B.foreground,dim:!0})));let U=new p0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new C0({height:1}),D,new H5,U]})})}}class c10 extends y0{props;constructor(A){super();this.props=A}createState(){return new lYA}}Q$();class iYA extends v0{controller=new v3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=C7)return!1;let Q=await uF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=Y4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new BY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=new p0({padding:w0.symmetric(1,0),child:new i({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new x({color:$.keybind})),new M(" again to clear input",new x({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new x({color:B.foreground,dim:!0})),new M("Enter",new x({color:$.keybind})),new M(" to submit, ",new x({color:B.foreground,dim:!0})),new M("Esc",new x({color:$.keybind})),new M(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new C0({height:1}),new T1({child:D}),new C0({height:1}),V];return new p0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class wJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new iYA}}function nYA(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class CJ1 extends M1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>nYA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=S0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(H,W)=>new C0({width:W,child:Y1.end([new i({text:new M(H,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new Y1({children:[new T1({child:new i({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new C0({width:2}),E(nYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}i0();class aYA extends v0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=S0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M("",void 0,[new M("Create new label: ",new x({color:E})),new M(W,new x({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M(D.name,new x({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class MJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new aYA}}class $V extends y0{props;constructor(A){super();this.props=A}createState(){return new oYA}}class oYA extends v0{_spinner=new C6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=e1.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new i({textAlign:"center",text:new M("",void 0,[new M(Y,new x({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new C0({height:2,child:new p0({padding:w0.symmetric(2,0),child:new i({text:new M("",new x({dim:!0}),[new M("Press ",new x({color:B.foreground})),new M("Esc",new x({color:B.info})),new M(" to cancel",new x({color:B.foreground}))])})})}));let D=new p0({decoration:new t4(B.background,J),child:new C0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class KE extends y0{props;constructor(A){super();this.props=A}createState(){return new rYA}}class rYA extends v0{scrollController=new Z6;scrollAreaKey=new q2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof e2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=S0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=cE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.symmetric(1,0),child:new i({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new i({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new s2({child:new p0({padding:w0.symmetric(1,0),child:new Y1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new hA({controller:this.scrollController,autofocus:!0,child:X})}),new C2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:w0.symmetric(1,0),child:new i({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new x({color:Q.colors.foreground,dim:!0})),new M("R",new x({color:Q.app.keybind})),new M(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new M("Esc",new x({color:Q.app.keybind})),new M(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new x({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new x({color:Q.app.keybind}),U=new x({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new i1({onClick:()=>{},child:new C0}),new s4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new p0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new C0({height:1}),F,D]})})})]})})}}S8();class sYA extends y0{props;constructor(A){super();this.props=A}createState(){return new tYA}}class tYA extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new i({text:new M("No plugins found.",new x({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${W4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${X} ${W4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
6057
+ `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(H),D))}return new p0({decoration:{color:X.background,border:e1.all(new A4(X.border,1,"rounded"))},child:new i({text:new M(void 0,void 0,V)})})}i0();S8();EO();f2();F8();oQ();Yr();OX();KQ();K9();Q$();TU();AA();Zx();bk();j1();i0();KQ();class IJ1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1777879744-g2d678a"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await n70(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class oC extends y0{props;constructor(A){super();this.props=A}createState(){return new cYA}}class cYA extends v0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class lYA extends v0{controller=new v3;focusNode=new H6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=e1.all(new A4(B.foreground,1,"solid")),F=new L$({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Y1({children:[new p0({decoration:{color:B.background},child:new i({text:new M(">",new x({color:B.foreground}))})}),new T1({child:F})]}),G=new p0({padding:w0.symmetric(1,0),child:new i({text:this.widget.props.title?new M(this.widget.props.title,new x({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new x({color:$.keybind}))),V.push(new M(" to submit, ",new x({color:B.foreground,dim:!0})));V.push(new M("Esc",new x({color:$.keybind}))),V.push(new M(" to cancel",new x({color:B.foreground,dim:!0})));let U=new p0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:w0.all(1),child:new f0({children:[G,new C0({height:1}),D,new H5,U]})})}}class c10 extends y0{props;constructor(A){super();this.props=A}createState(){return new lYA}}Q$();class iYA extends v0{controller=new v3;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new H6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=C7)return!1;let Q=await uF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,Y=Y4.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new AV({controller:this.controller,triggers:[new BY],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:d4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new s4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new L1({maxHeight:Z}),padding:w0.symmetric(1,0),child:F}),G=new p0({padding:w0.symmetric(1,0),child:new i({text:new M("",void 0,[new M("Command: ",new x({color:B.foreground})),new M(this.widget.props.commandName,new x({color:$.command,bold:!0}))])})}),V=new p0({padding:w0.symmetric(1,0),child:new i({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new x({color:$.keybind})),new M(" again to clear input",new x({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new x({color:B.foreground,dim:!0})),new M("Enter",new x({color:$.keybind})),new M(" to submit, ",new x({color:B.foreground,dim:!0})),new M("Esc",new x({color:$.keybind})),new M(" to clear",new x({color:B.foreground,dim:!0}))])})}),U=[G,new C0({height:1}),new T1({child:D}),new C0({height:1}),V];return new p0({decoration:{border:e1.all(new A4(B.foreground,1,"solid")),color:B.background},padding:w0.all(1),child:new f0({children:U})})}}class wJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new iYA}}function nYA(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class CJ1 extends M1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>nYA(J.pubDate).length));return new t6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=S0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(H,W)=>new C0({width:W,child:Y1.end([new i({text:new M(H,new x({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:w0.symmetric(2,0),child:new Y1({children:[new T1({child:new i({text:new M(J.title,new x({color:U})),overflow:"ellipsis",maxLines:1})}),new C0({width:2}),E(nYA(J.pubDate),B)]})})}})}}class yB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!yB._instance)yB._instance=new yB;return yB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}i0();class aYA extends v0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=S0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new t6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let W=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M("",void 0,[new M("Create new label: ",new x({color:E})),new M(W,new x({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:w0.symmetric(2,0),child:new i({text:new M(D.name,new x({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class MJ1 extends y0{props;constructor(A){super();this.props=A}createState(){return new aYA}}class $V extends y0{props;constructor(A){super();this.props=A}createState(){return new oYA}}class oYA extends v0{_spinner=new C6;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(A){let Q=S0.of(A),{colors:B,app:$}=Q,J=e1.all(new A4(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new i({textAlign:"center",text:new M("",void 0,[new M(Y,new x({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new x({color:B.foreground}))])}),F=[new T1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new C0({height:2,child:new p0({padding:w0.symmetric(2,0),child:new i({text:new M("",new x({dim:!0}),[new M("Press ",new x({color:B.foreground})),new M("Esc",new x({color:B.info})),new M(" to cancel",new x({color:B.foreground}))])})})}));let D=new p0({decoration:new t4(B.background,J),child:new C0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new QA({debugLabel:"LoadingDialog",child:new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class KE extends y0{props;constructor(A){super();this.props=A}createState(){return new rYA}}class rYA extends v0{scrollController=new Z6;scrollAreaKey=new q2("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(A){return A instanceof e2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=S0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=cE0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=e1.all(new A4(Q.colors.border,1,"solid")),Z=new p0({padding:w0.symmetric(1,0),child:new i({text:new M($.title,new x({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new i({text:new M($.description,new x({color:Q.colors.foreground})),selectable:!0}),F=new T1({child:new s2({child:new p0({padding:w0.symmetric(1,0),child:new Y1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new T1({child:new hA({controller:this.scrollController,autofocus:!0,child:X})}),new C2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:w0.symmetric(1,0),child:new i({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new x({color:Q.colors.foreground,dim:!0})),new M("R",new x({color:Q.app.keybind})),new M(" to retry, ",new x({color:Q.colors.foreground,dim:!0})),new M("Esc",new x({color:Q.app.keybind})),new M(" to cancel",new x({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new x({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new x({color:Q.app.keybind}),U=new x({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new x({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new QA({debugLabel:"MessageDialog",child:new HA({fit:"expand",children:[new i1({onClick:()=>{},child:new C0}),new s4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new p0({decoration:{border:Y,color:Q.colors.background},padding:w0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new C0({height:1}),F,D]})})})]})})}}S8();class sYA extends y0{props;constructor(A){super();this.props=A}createState(){return new tYA}}class tYA extends v0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=s3.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=S0.of(A),{app:B}=Q;if(this.plugins.length===0)return new i({text:new M("No plugins found.",new x({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${W4(J,"plugin")} active`,new x({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${X} ${W4(X,"tool")})`,new x({dim:!0})));$.push(new M(`
6058
6058
 
6059
6059
  `));for(let F of this.plugins){let{icon:D,color:G}=this.statusIcon(F.status),V=this.getRelativePath(F.uri.toString());if($.push(new M(`${D} `,new x({color:G}))),$.push(new M(V,new x({bold:!0}))),$.push(new M(` ${F.status}`,new x({dim:!0}))),$.push(new M(`
6060
6060
  `)),F.status==="active"&&F.registeredEvents.length>0)$.push(new M(" Events: ",new x({dim:!0}))),$.push(new M(F.registeredEvents.join(", "),new x({color:B.link}))),$.push(new M(`
@@ -6232,7 +6232,7 @@ ${s.content||""}`:s.content||"",u0=[],E1=s.baseDir.startsWith("file://")?Dq0(s.b
6232
6232
  `)}function yFA(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),X=Z84({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await LA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(o0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(o0.red("Error: ")+F.error.message+`
6233
6233
  `),process.exit(1)}process.stdout.write(await TW8(F.result.displayText)+`
6234
6234
  `),process.exit(0)})}var sI8=R40.join(LX,"logs","headless.log"),RX1=R40.join(Iu,"device-id.json"),tI8=`cli-tui-${XUA(16).toString("hex")}`;async function eI8(){for(let A of qO)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => w4(Cg(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){GY.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
6235
- `)}function Aw8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function J9(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")sB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)sB("internal.model",$w8(Q.model))}function QUA(A){let Q=A.indexOf(":");if(Q===-1)throw new F4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new F4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Qw8(A){if(A===void 0)return;let Q=A.trim();if(n54(Q))return Q;throw new F4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Bw8(A,Q){if(RD(A,Q))return;let B=FJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new F4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function $w8(A){if(!A.includes("="))return QUA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new F4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new F4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new F4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);QUA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new F4("No valid model overrides found in --model flag value.",1);return Q}function Jw8(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function Yw8(A){try{return await FUA(A,"utf-8")}catch{return A}}async function PX1(A,Q,B){let $=Jw8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!Mg(J,b2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new F4("You are not allowed to do this.",1);sB("systemPrompt",await Yw8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Zw8(A){return A!=="pending"}function e_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Xw8(A){let Q=e_(A);if(Q)return Q.id;if(vD(A))throw Error(A.error.message);throw Error("unreachable")}function Fw8(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function Dw8(A){let $=Fw8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new F4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function P40(A,Q){let B=L51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return Dw8(Q);if(B.message!==g7.internalBug)return new F4(B.message,1,B.suggestion);return new F4(A.error.message.replace(/^Error: /,""),1)}var BUA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??_F,description:`Custom settings file path (overrides the default location ${_F})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${rt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:_9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:KO.SMART.key,description:`Set the agent mode (${ZJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(ZJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],$UA=(A)=>("deprecated"in A)&&A.deprecated===!0,Gw8=(A)=>("hidden"in A)&&A.hidden===!0,Vw8=(A)=>("default"in A),Uw8=(A)=>("default"in A)?A.default:void 0;function tq0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=Qw8(Q.effort);if(B!==void 0)Bw8(Q.mode,B);return B}function Kw8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new F4(g7.unknownCommand(B),1,Z)}}async function QN0(A){return{...A,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Dj(A.fileSystem),generateThreadTitle:BH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function DUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eq0=J1.file(rI8.homedir()),_X1=process.env.XDG_CONFIG_HOME?J1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(eq0,".config");function Ew8(A){return Sx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XK0())FK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Tx4();else Vs(Q);let B=nP(),$=B00();if((!B||$||Mu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(dG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(dG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(nP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;p84("0.0.1777875280-g2566d7");let Y=Jv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(J1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:eq0,userConfigDir:_X1});rBA(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let d=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(d),j.info("API key lookup before login",{found:Boolean(d),ampURL:A.ampURL,deferAuth:$}),!d)if($)j.info("No API key found, continuing startup with deferred auth");else{N5.write(`No API key found. Starting login flow...
6235
+ `)}function Aw8(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function J9(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")sB("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")sB("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)sB("internal.model",$w8(Q.model))}function QUA(A){let Q=A.indexOf(":");if(Q===-1)throw new F4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new F4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Qw8(A){if(A===void 0)return;let Q=A.trim();if(n54(Q))return Q;throw new F4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function Bw8(A,Q){if(RD(A,Q))return;let B=FJ(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new F4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function $w8(A){if(!A.includes("="))return QUA(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new F4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new F4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new F4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);QUA(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new F4("No valid model overrides found in --model flag value.",1);return Q}function Jw8(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function Yw8(A){try{return await FUA(A,"utf-8")}catch{return A}}async function PX1(A,Q,B){let $=Jw8(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!Mg(J,b2.HARNESS_SYSTEM_PROMPT)&&!(Y&&ZQ(Y)))throw new F4("You are not allowed to do this.",1);sB("systemPrompt",await Yw8($))}function Mg(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function Zw8(A){return A!=="pending"}function e_(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function Xw8(A){let Q=e_(A);if(Q)return Q.id;if(vD(A))throw Error(A.error.message);throw Error("unreachable")}function Fw8(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function Dw8(A){let $=Fw8(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new F4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function P40(A,Q){let B=L51(Error(A.error.message));if(B.message===g7.networkOffline||B.message===g7.networkTimeout)return Dw8(Q);if(B.message!==g7.internalBug)return new F4(B.message,1,B.suggestion);return new F4(A.error.message.replace(/^Error: /,""),1)}var BUA=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??_F,description:`Custom settings file path (overrides the default location ${_F})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${rt})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:_9(),description:(A)=>A?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(A)=>A?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:KO.SMART.key,description:`Set the agent mode (${ZJ({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(ZJ().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showNeoWelcome",long:"show-neo-welcome",type:"switch",description:"Show the Neo welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],$UA=(A)=>("deprecated"in A)&&A.deprecated===!0,Gw8=(A)=>("hidden"in A)&&A.hidden===!0,Vw8=(A)=>("default"in A),Uw8=(A)=>("default"in A)?A.default:void 0;function tq0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=Qw8(Q.effort);if(B!==void 0)Bw8(Q.mode,B);return B}function Kw8(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new F4(g7.unknownCommand(B),1,Z)}}async function QN0(A){return{...A,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new Dj(A.fileSystem),generateThreadTitle:BH4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>tQ(A.configService),pluginService:A.pluginService}}function DUA(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:bW,getEnvironmentData:(Q,B)=>oD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var eq0=J1.file(rI8.homedir()),_X1=process.env.XDG_CONFIG_HOME?J1.file(process.env.XDG_CONFIG_HOME):K1.joinPath(eq0,".config");function Ew8(A){return Sx4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(XK0())FK0();else if(process.platform==="darwin"&&Q==="idle"&&A.isTUIVoiceNotifEnabled())Tx4();else Vs(Q);let B=nP(),$=B00();if((!B||$||Mu())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(dG("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(dG("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(nP()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function A2(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;p84("0.0.1777879744-g2d678a");let Y=Jv({storage:A.settings,secretStorage:A.secrets,workspaceRoot:g0.of(J1.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:eq0,userConfigDir:_X1});rBA(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let d=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(d),j.info("API key lookup before login",{found:Boolean(d),ampURL:A.ampURL,deferAuth:$}),!d)if($)j.info("No API key found, continuing startup with deferred auth");else{N5.write(`No API key found. Starting login flow...
6236
6236
  `);let g=await Hw8(A),n=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:g,storedKeyPresent:Boolean(n),ampURL:A.ampURL}),!g)await eW(),process.exit(1);X=!0}}{let d=await Y.getLatest(),g=d.settings.url,n=d.secrets.isSet?.[g];j.info("Config secrets state after login",{configURL:g,apiKeySet:n?.apiKey??!1})}let F=y1(tQ(Y).pipe(L5(Zw8))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:bA(D),isError:vD(D),errorMessage:vD(D)?D.error.message:void 0});let G=F.then((d)=>Xw8(d));G.catch(()=>{return});let U=!A.executeMode&&!Q.takeMeBack&&bA(D)&&Mg(D.features,b2.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=bD0({configService:Y}),H=new Map,W=()=>H.clear(),z=new bm0(Y,A.settings.getWorkspaceRootPath()),q=qJ0({configService:Y,filesystem:e5}),N=_F4({configService:Y,trustStore:z,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(d,g,n)=>{let c=`${d}:${g}`,B0=H.get(c);if(B0)return j.debug("Reusing existing OAuth provider for server",{serverName:d,serverUrl:g}),B0;j.debug("Creating OAuth provider for server",{serverName:d,serverUrl:g});let O0=(async()=>{let l=new LO(A.secrets),Q0=await l.getClientInfo(d,g),U0=n?.scopes??Q0?.scopes,z0=$t4();j.info("OAuth headless mode check",{useHeadless:z0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:N5.isTTY});let A0;if(z0)A0=A.executeMode?Bt4():Qt4(d);let J0=new zb0({storage:l,serverName:d,serverUrl:g,clientId:n?.clientId??Q0?.clientId,clientSecret:n?.clientSecret??Q0?.clientSecret,authUrl:n?.authUrl??Q0?.authUrl,tokenUrl:n?.tokenUrl??Q0?.tokenUrl,scopes:U0,headlessAuthHandler:A0});return j.debug("OAuth provider created",{serverName:d,serverUrl:g,hasManualClientId:!!(n?.clientId??Q0?.clientId),willUseDCR:!(n?.clientId??Q0?.clientId),scopes:U0,headlessMode:z0,executeMode:A.executeMode}),J0})();return H.set(c,O0),O0}}),I=Qs({configService:Y,filesystem:e5,spawn:nf}),w;if(J)w=new Map;else if(A.executeMode){let d=await Bv4({toolService:K,providers:[N,I],initialTimeout:15000});w=d.registrations;for(let[g,n]of d.initErrors)j.warn(`${g} provider initialization slow or failed:`,n)}else w=Bs({toolService:K,providers:[N,I]});if(Q.jetbrains)HO("JetBrains");else if(Q.ide&&gt4())HO("VS Code");else if(Q.ide&&mt4())HO("Neovim");else if(Q.ide){let d=await eI8();if(d){let g=D70(d.ideName);if(g)HO(g)}}if(A.executeMode)d84(!0);let C,O=n8.status.pipe(O1((d)=>Boolean(d.connected&&d.authenticated&&d.ideName&&q34(d.ideName))),m4()).subscribe((d)=>{if(d){if(!C)C=K.registerTool(Qv4)}else C?.dispose(),C=void 0}),P;if(!A.executeMode){let d=await A.settings.get("fuzzy.alwaysIncludePaths")??[];P=new qu(process.cwd(),{alwaysIncludePaths:d},!0)}else P=new class extends qu{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let S=new ec0(jj(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let _=new I$1,f=Q.headless?E1A():void 0,h=f??new Su({configService:Y}),b=h instanceof Su?h:void 0;if(b)b.pluginExecutorKind="local";let y=mi({configService:Y,fileSystem:e5,platform:h,internalPlugins:Te,loadGlobalPlugins:Ee(Y),pluginFilter:U}),u=N$0({pluginService:y,toolService:K}),p={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:z,threadService:S,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:P,fileSystem:e5,terminal:_,pluginService:y,pluginPlatform:b,headlessPluginPlatform:f,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...p,async asyncDispose(){if(p.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await p.mcpService.waitForAuthentication();for(let d of w.values())d.dispose();await p.mcpService.dispose(),W(),await p.threadService.asyncDispose(),p.configService.unsubscribe(),E(),p.fuzzyServer.dispose(),p.settingsStorage[Symbol.dispose](),O.unsubscribe(),C?.dispose(),u.dispose(),await p.pluginService.dispose()}}}async function Hw8(A){if(!A.executeMode){if(!await tK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return N5.write(`Login cancelled. Run the command again to retry.
6237
6237
  `),!1}return await GUA(A)}async function GUA(A){let Q=XUA(32).toString("hex"),B=await Tu(A.ampURL,Q),$=new AbortController;try{await ID(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Tu(A.ampURL,Q,!1);N5.write(`If your browser does not open automatically, visit:
6238
6238
 
@@ -6240,7 +6240,7 @@ ${o0.blue.bold(J)}
6240
6240
 
6241
6241
  `);try{return await Q1A(A.ampURL,Q,A.secrets,$),N5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),GY.write(`
6242
6242
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
6243
- `),!1}}function Ww8(A){let Q=new Zw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)jP(),process.exit(0);let H=E.originalError??E;aa4(H)}),V4A(Q,{version:"0.0.1777875280-g2566d7",buildTimestamp:"2026-05-04T06:18:29.836Z",buildType:"'release'"}),Q.addHelpText("after",bt4()),Q.configureHelp({formatHelp:ut4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Ow8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Lw8(z,await qe(W,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);await ns4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await as4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await B0A({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("cplog <threadIDOrURL>",{hidden:!0}).summary("Copy a thread-scoped log file to the clipboard").description("Internal: snapshot <cwd>/.amp/in/<threadID>.log (written by the CLI for thread-scoped logs) to a timestamped JSONL file in the OS temp directory and copy that file to the clipboard for Slack paste.").action(async(E)=>{await ha4(E),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6243
+ `),!1}}function Ww8(A){let Q=new Zw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((E)=>{if(E.code==="commander.help"||E.code==="commander.version"||E.exitCode===0)jP(),process.exit(0);let H=E.originalError??E;aa4(H)}),V4A(Q,{version:"0.0.1777879744-g2d678a",buildTimestamp:"2026-05-04T07:32:44.192Z",buildType:"'release'"}),Q.addHelpText("after",bt4()),Q.configureHelp({formatHelp:ut4}),Q.command("logout").description("Log out by removing stored API key").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Ow8(z)}),Q.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await Lw8(z,await qe(W,z.settings))}),Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(E,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);await ns4(E??"get",q.ampURL,q.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await as4(z.ampURL,z.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(E)=>{await B0A({raw:E.raw===!0}),process.exit(process.exitCode??0)}),Q.command("cplog <threadIDOrURL>",{hidden:!0}).summary("Copy a thread-scoped log file to the clipboard").description("Internal: snapshot <cwd>/.amp/in/<threadID>.log (written by the CLI for thread-scoped logs) to a timestamped JSONL file in the OS temp directory and copy that file to the clipboard for Slack paste.").action(async(E)=>{await ha4(E),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
6244
6244
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(E,H,W)=>{if(E&&H.apply)throw new F4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let z=H.apply??E;if(!z||z.trim().length===0)N5.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
6245
6245
 
6246
6246
  `),W.outputHelp(),process.exit(0);let q=l8(z)??WB(z),N=W.optsWithGlobals(),I=await E8(N);J9(W,N);let w=await A2(I,N),C=!1;try{if(H.checkout&&H.skipCheckout)throw new F4("Choose either --checkout or --skip-checkout, not both.",1);if(vD(w.serverStatus))throw P40(w.serverStatus,I.ampURL);let O=bA(w.serverStatus)?w.serverStatus.features:void 0;if(!Mg(O,b2.V2))throw new F4("live-sync is not enabled for your user",1);await c0A({ampURL:I.ampURL,threadId:q,configService:w.configService,threadService:w.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:tK0}),C=!0}finally{if(await w.asyncDispose(),C)process.exit(0)}});let B=async(E,H,W)=>{Jv({storage:H.settings,secretStorage:H.secrets,workspaceRoot:g0.of(J1.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:eq0,userConfigDir:_X1});let z={...H,executeMode:!1};await AN0(z,{...E,openThreadSwitcher:!0},W,A)},$=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await ZUA(W,z,H)});$.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(E,H)=>{let W=H.optsWithGlobals(),z=await E8(W);await fw8(W,z,H)}),$.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(E,H,W)=>{let z=W.optsWithGlobals(),q=await E8(z);if(H.pick)GY.write(`${o0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -6273,8 +6273,8 @@ ${I}
6273
6273
  `))}),H.args.length>0)Kw8(z,H);await AN0(z,W,H,A)}),qe4(Q),Q}async function Lg(A,Q){await kZ((B)=>$E0(B,A,Q))}async function JUA(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([LA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.info(`[fetchAndStartThread] Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new F4(`Cannot resume thread created by another user.
6274
6274
 
6275
6275
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function VUA(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await MW0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await MW0()).trimEnd(),stdinInput:null}}function UUA(A,Q,B){if(A.streamJson&&!Q)throw new F4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new F4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new F4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new F4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new F4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new F4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new F4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new F4("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
6276
- Or pipe via stdin: echo "your message" | amp --execute`)}function zw8(A,Q){if(KQ4([O90.parse({tool:"*",action:"allow"})]),bBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:H$1})}async function AN0(A,Q,B,$){if(Q.headless)return qw8(A,Q,B);let J=await A2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=bA(Y)&&Mg(Y.features,b2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new F4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return zw8(Z,J.pluginService),Nw8(A,Q,B,J);else{if(Q.threadId&&W7(Q.threadId)){let D=await LA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new F4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Iw8(A,Q,B,$,{dependencies:J})}}async function qw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=fA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};J9(B,Q);let J=process.hrtime.bigint(),Y=await A2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(vD(Z))throw P40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await PX1(B,Q,Z);let D=e_(Z),G=D00(Q,D);if(G instanceof Error)c5(G.message);if(X&&!Bv(Q.mode,F))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new F4("Headless executor mode is only available for Amp employees",1);OU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new F4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new F4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await yw8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new F4("Failed to resolve headless thread ID",1);let W=await Xt4(H);if(W.status==="already-running")await Y.asyncDispose(),await eW(),process.exit(0);try{await ts4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await eW(),process.exit(0)}async function Nw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await VUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;UUA({...Q,streamJson:Z},A.executeMode,J),J9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?l8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(vD(D))throw P40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new F4("API key required. Please run `amp login` first.",1);let V=bA(D)&&ZQ(D.user.email);if(V)OU0();if(A.executeMode){f31($.mcpService,A.settings);try{let U=tq0(B,Q),K=await BC(),E=X?U:eK0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:AE0(await ku($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ws4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:H});if(await Lg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await eW(),process.exit(0)}else{let U=tq0(B,Q),K=jj($.configService,{usesThreadActors:!0}),E=new v_($.fuzzyServer),H=process.cwd();await E$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??dJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>hw({fileSystem:$.fileSystem,workspaceRoot:H},W),completionBuilder:E,workspaceRoot:H,listThreads:()=>K.listThreads(),getThreadFromServer:(W)=>K.getThread(W),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Iw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let J0=Number(process.hrtime.bigint()-A0)/1e6,a=fA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(J0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await VUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;UUA({...Q,streamJson:D},A.executeMode,X),J9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await A2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&vD(E))throw P40(E,A.ampURL);let H=bA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)OU0();if(!K)await PX1(B,Q,E);let q=e_(E),N=q?.features??[],I=q?.team??null,w=D00(Q,q);if(w instanceof Error)c5(w.message);if(H&&!Bv(Q.mode,W))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await QN0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Lg(z0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,J0=await jU0(A.settings,process.cwd(),e_(A0),w);if(J0 instanceof Error)c5(J0.message);return AZ1(O,{threadMeta:J0?xZ(J0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){JUA(z0,V.configService,V.viewerUserIDPromise).catch((J0)=>{if(J0 instanceof F4){if(A0.onOwnershipError){A0.onOwnershipError(J0,z0);return}Az(J0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await JUA(z0,V.configService,V.viewerUserIDPromise)}catch(J0){if(J0 instanceof F4)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Az},_=async()=>{try{return TFA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof F4)throw z0;throw await Az(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=Pc(z0),J0=await LA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new L$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(vD(z0))throw P40(z0,A.ampURL);await PX1(B,Q,z0);let A0=process.hrtime.bigint(),J0=await _();if(Z("runMainThread:createThreadPool",A0),b.attach(J0),X){let a=await y1(J0.threadHandles$);if(!a)throw new F4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await Az(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&Mg(H.features,b2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=bA(z0)&&Mg(z0.features,b2.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Ew8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(n4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,J0])=>({[A0.id]:J0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){f31(V.mcpService,A.settings);let z0=tq0(B,Q),A0=await BC(),J0=C?z0:eK0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:J0,labels:Q.label},r=await Ho4({threadPool:y,...a});if(await Lg(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await G70();let z0=await TD({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)n8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=Q31("0.0.1777875280-g2566d7",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new b31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await y1(y.threadHandles$);if(!z0)throw new F4("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let l=await BC();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",l);let Q0=tq0(B,Q),U0={...l,launchCount:l.launchCount+1,lastReasoningEffortByMode:Q0?{...l.lastReasoningEffortByMode,[Q.mode]:Q0}:l.lastReasoningEffortByMode};kZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await d$A({history:new Fe,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:LA,threadPool:y,createSystemPromptDeps:async()=>DUA(V),ideClient:n8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:O0,updateService:B0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:tI8,logFile:{path:$},sessionState:U0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-04T06:18:29.836Z"},(z0)=>new S$1({...z0,threadPool:z0.threadPool},(A0)=>new tY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)GY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6277
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await yF4({get:async(X)=>{if(X!==Ti)return;try{let F=await FUA(RX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Ti)return;await aI8(R40.dirname(RX1),{recursive:!0}),await oI8(RX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:oB0()});c84($);let J=await KK0({...A,workspaceTrust:{current:!0,changes:ix0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await V1A(A.mcpConfig);J=U1A(J,X)}let Y=R40.dirname(J.getSettingsFilePath());_x4(Iu,Y),J=O54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!BN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:BE0(await qe(A,J))}}function ww8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Cw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=R40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?sI8:rt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Mw8(){Oc4();let A=ww8(process.argv),Q=Cw8(process.argv,A),B=va4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(Aw8(j),j.info("Starting Amp CLI.",{version:"0.0.1777875280-g2566d7",buildTimestamp:"2026-05-04T06:18:29.836Z"}),process.platform==="win32"&&xP())Ye4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new F4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Ww8(B).parseAsync(process.argv)}Rx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Mw8().catch(Az)});async function Lw8(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),N5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6276
+ Or pipe via stdin: echo "your message" | amp --execute`)}function zw8(A,Q){if(KQ4([O90.parse({tool:"*",action:"allow"})]),bBA(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:H$1})}async function AN0(A,Q,B,$){if(Q.headless)return qw8(A,Q,B);let J=await A2(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=bA(Y)&&Mg(Y.features,b2.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showNeoWelcome&&!X)throw await J.asyncDispose(),new F4("--show-neo-welcome is only available with the Neo TUI feature flag",1);if(F)return zw8(Z,J.pluginService),Nw8(A,Q,B,J);else{if(Q.threadId&&W7(Q.threadId)){let D=await LA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new F4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return Iw8(A,Q,B,$,{dependencies:J})}}async function qw8(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=fA1();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};J9(B,Q);let J=process.hrtime.bigint(),Y=await A2(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(vD(Z))throw P40(Z,A.ampURL);let X=bA(Z)?Z:null,F=X?.user.email;await PX1(B,Q,Z);let D=e_(Z),G=D00(Q,D);if(G instanceof Error)c5(G.message);if(X&&!Bv(Q.mode,F))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!ZQ(F)))throw new F4("Headless executor mode is only available for Amp employees",1);OU0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new F4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!W7(K))throw new F4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await yw8({dependencies:Y,apiKey:U,visibility:G??void 0}),H=K??E?.threadId;if(!H)throw new F4("Failed to resolve headless thread ID",1);let W=await Xt4(H);if(W.status==="already-running")await Y.asyncDispose(),await eW(),process.exit(0);try{await ts4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:H,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await W.release(),await Y.asyncDispose()}await eW(),process.exit(0)}async function Nw8(A,Q,B,$){let{userInput:J,stdinInput:Y}=await VUA(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;UUA({...Q,streamJson:Z},A.executeMode,J),J9(B,Q);let X=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0,F=Q.observe?l8(Q.observe)??WB(Q.observe):void 0,D=await $.serverStatusPromise;if(vD(D))throw P40(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new F4("API key required. Please run `amp login` first.",1);let V=bA(D)&&ZQ(D.user.email);if(V)OU0();if(A.executeMode){f31($.mcpService,A.settings);try{let U=tq0(B,Q),K=await BC(),E=X?U:eK0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=X?void 0:AE0(await ku($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=await Ws4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:H});if(await Lg(W,"execute"),Q.archive)await $.threadService.archive(W,!0)}finally{await $.asyncDispose()}await eW(),process.exit(0)}else{let U=tq0(B,Q),K=jj($.configService,{usesThreadActors:!0}),E=new v_($.fuzzyServer),H=process.cwd();await E$1({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??dJ(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:W})=>hw({fileSystem:$.fileSystem,workspaceRoot:H},W),completionBuilder:E,workspaceRoot:H,listThreads:()=>K.listThreads(),getThreadFromServer:(W)=>K.getThread(W),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showNeoWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function Iw8(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(z0,A0)=>{let J0=Number(process.hrtime.bigint()-A0)/1e6,a=fA1();j.info("Startup phase",{phase:z0,phaseMs:Math.round(J0),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:X,stdinInput:F}=await VUA(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;UUA({...Q,streamJson:D},A.executeMode,X),J9(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await A2(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&vD(E))throw P40(E,A.ampURL);let H=bA(E)?E:null,W=H?.user.email,z=!!(W&&ZQ(W));if(z)OU0();if(!K)await PX1(B,Q,E);let q=e_(E),N=q?.features??[],I=q?.team??null,w=D00(Q,q);if(w instanceof Error)c5(w.message);if(H&&!Bv(Q.mode,W))throw new F4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&W7(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await QN0(V);Z("runMainThread:createWorkerDeps",G);let P=A.executeMode?void 0:async(z0)=>Lg(z0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(z0)=>{let A0=K?await V.serverStatusPromise:E,J0=await jU0(A.settings,process.cwd(),e_(A0),w);if(J0 instanceof Error)c5(J0.message);return AZ1(O,{threadMeta:J0?xZ(J0):void 0,agentMode:z0??Q.mode,onFirstAssistantMessage:P})},validateThreadOwnership:async(z0,A0)=>{if(A0?.nonBlockingOwnershipCheck){JUA(z0,V.configService,V.viewerUserIDPromise).catch((J0)=>{if(J0 instanceof F4){if(A0.onOwnershipError){A0.onOwnershipError(J0,z0);return}Az(J0,z0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})});return}try{await JUA(z0,V.configService,V.viewerUserIDPromise)}catch(J0){if(J0 instanceof F4)throw J0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:J0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:P,handleError:Az},_=async()=>{try{return TFA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(z0){if(z0 instanceof F4)throw z0;throw await Az(z0,Q.threadId),Error("handleError should have called process.exit()")}},f=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let z0=await V.configService.getLatest(),A0=Pc(z0),J0=await LA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(A0)});if(J0.ok)return j.info("User free tier status:",J0),J0.result;return}catch(z0){j.error("Failed to fetch free tier status:",z0);return}})(),b=!A.executeMode?new L$1:null,y,u=null;if(b)y=b,u=(async()=>{let z0=K?await V.serverStatusPromise:V.serverStatus;if(vD(z0))throw P40(z0,A.ampURL);await PX1(B,Q,z0);let A0=process.hrtime.bigint(),J0=await _();if(Z("runMainThread:createThreadPool",A0),b.attach(J0),X){let a=await y1(J0.threadHandles$);if(!a)throw new F4("No active thread is available yet.",1);await a.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(z0)=>{let A0=z0 instanceof Error?z0:Error(String(z0));b.setInitError(A0),await Az(z0,Q.threadId)});else G=process.hrtime.bigint(),y=await _(),Z("runMainThread:createThreadPool",G);let p=Q.notifications!==void 0?Q.notifications:!A.executeMode,d=H!==null&&Mg(H.features,b2.TUI_VOICE_NOTIF);if(K)V.serverStatusPromise.then((z0)=>{d=bA(z0)&&Mg(z0.features,b2.TUI_VOICE_NOTIF)}).catch((z0)=>{j.debug("Failed to resolve TUI voice notification feature flag",{error:z0})});G=process.hrtime.bigint();let g=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),Ew8({configService:V.configService,threadService:V.threadService,config:g,useNotificationsForService:p,isTUIVoiceNotifEnabled:()=>d,threadViewStates$:()=>y.threadHandles$.pipe(n4((z0)=>{if(!z0)return g0.of({});return u6(z0.thread$,z0.threadViewState$).pipe(O1(([A0,J0])=>({[A0.id]:J0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){f31(V.mcpService,A.settings);let z0=tq0(B,Q),A0=await BC(),J0=C?z0:eK0({agentMode:Q.mode,explicitEffort:z0,sessionState:A0}),a={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:J0,labels:Q.label},r=await Ho4({threadPool:y,...a});if(await Lg(r,"execute"),Q.archive)await V.threadService.archive(r,!0);await V.asyncDispose(),process.exit(0)}let n=!1,c=!1;if(Q.jetbrains||Q.ide){await G70();let z0=await TD({jetbrainsOnly:Q.jetbrains});if(z0.length===0){if(Q.jetbrains)n=!await V.configService.get("jetbrains.skipInstall")}else if(z0.length===1){let A0=z0[0];if(A0)n8.selectConfig(A0)}else c=!0}G=process.hrtime.bigint();let B0=Q31("0.0.1777879744-g2d678a",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let O0=new b31(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let z0=await y1(y.threadHandles$);if(!z0)throw new F4("No active thread is available yet.",1);await z0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let l=await BC();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",l);let Q0=tq0(B,Q),U0={...l,launchCount:l.launchCount+1,lastReasoningEffortByMode:Q0?{...l.lastReasoningEffortByMode,[Q.mode]:Q0}:l.lastReasoningEffortByMode};kZ((z0)=>({...z0,launchCount:z0.launchCount+1}));try{if(G=process.hrtime.bigint(),await d$A({history:new Fe,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:LA,threadPool:y,createSystemPromptDeps:async()=>DUA(V),ideClient:n8,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:O0,updateService:B0,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:n,showIdePickerHint:c,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:tI8,logFile:{path:$},sessionState:U0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-04T07:32:44.192Z"},(z0)=>new S$1({...z0,threadPool:z0.threadPool},(A0)=>new tY1({...A0,threadState:A0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await y.dispose().catch((z0)=>{j.error("Failed to dispose thread pool during shutdown",z0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function E8(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)GY.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
6277
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await yF4({get:async(X)=>{if(X!==Ti)return;try{let F=await FUA(RX1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==Ti)return;await aI8(R40.dirname(RX1),{recursive:!0}),await oI8(RX1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:oB0()});c84($);let J=await KK0({...A,workspaceTrust:{current:!0,changes:ix0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await V1A(A.mcpConfig);J=U1A(J,X)}let Y=R40.dirname(J.getSettingsFilePath());_x4(Iu,Y),J=O54(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=x9;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!BN(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:BE0(await qe(A,J))}}function ww8(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function Cw8(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=R40.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?sI8:rt));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function Mw8(){Oc4();let A=ww8(process.argv),Q=Cw8(process.argv,A),B=va4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(Aw8(j),j.info("Starting Amp CLI.",{version:"0.0.1777879744-g2d678a",buildTimestamp:"2026-05-04T07:32:44.192Z"}),process.platform==="win32"&&xP())Ye4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new F4(g7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Ww8(B).parseAsync(process.argv)}Rx4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await Mw8().catch(Az)});async function Lw8(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),N5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
6278
6278
  `);else if(!BN(A.ampURL))N5.write(`Logging in to ${new URL(A.ampURL).hostname}
6279
6279
  `);let $=process.env.AMP_API_KEY;if($)N5.write(`API key found in environment variable, storing...
6280
6280
  `),await Q.set("apiKey",$,A.ampURL),N5.write(`API key successfully stored.