@sourcegraph/amp 0.0.1778158028-g39bfa2 → 0.0.1778171486-g3e6a89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +15 -15
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4701,10 +4701,10 @@ ${Q.join(`
|
|
|
4701
4701
|
`)}function na(A){return A==="in-progress"||A==="queued"}function Ds0(A,Q){let B=[...A],$=new Set(B.map((J)=>`${J.kind}:${J.title}`));for(let J of Ny4(Q)){let Y=`${J.kind}:${J.title}`;if($.has(Y))continue;$.add(Y),B.push(J)}return B}function Ny4(A){return YV5(A).map((Q)=>({kind:"read",title:`Read ${s$(Q.uri)}`,...typeof Q.content==="string"?{detail:Q.content}:{},icon:"docs"}))}function YV5(A){if(A.status!=="done"||!dB(A.result))return[];let{discoveredGuidanceFiles:Q}=A.result;if(!Array.isArray(Q))return[];return Q.flatMap((B)=>{if(!dB(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 ZV5(A,Q,B){if(A==="oracle"){let $=typeof Q.task==="string"?Q.task.trim():void 0;return Qs0({label:{active:"Oracle exploring",complete:"Oracle has spoken"},detail:$,run:B})}if(A==="librarian"){let $=typeof Q.query==="string"?Q.query.trim():void 0;return Qs0({label:{active:"Librarian researching",complete:"Librarian researched"},detail:$,run:B})}if(A==="Task"){let $=typeof Q.description==="string"?Q.description.trim():void 0,J=typeof Q.prompt==="string"?Q.prompt.trim():void 0;return Qs0({label:{active:"Subagent working",complete:"Subagent finished"},detail:$??J,run:B})}if(A==="code_review"){let $=XV5(B,Q),J=Ds0($.actions,B),Y={label:{active:"Reviewing code",complete:"Reviewed code"},actions:J,summary:$.summary,hasInProgress:na(B.status),status:B.status},Z=typeof Q.diff_description==="string"?Q.diff_description.trim():void 0;if(Z!==void 0)Y.detail=Z;let F=Q8(B);if(F!==void 0)Y.error=F;return Y}return}function Qs0(A){let Q=Ds0([],A.run),B={label:A.label,actions:Q,summary:Js0(Q),hasInProgress:na(A.run.status),status:A.run.status};if(A.detail!==void 0)B.detail=A.detail;let $=Q8(A.run);if($!==void 0)B.error=$;return B}function FV5(A){let Q="result"in A&&dB(A.result)?A.result:void 0,B=Uy4("progress"in A?A.progress:void 0),$=dB(B)?B:void 0;return{main:(dB(Q?.main)?Q.main:void 0)??(dB($?.main)?$.main:void 0),checks:(dB(Q?.checks)?Q.checks:void 0)??(dB($?.checks)?$.checks:void 0)}}function XV5(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}=FV5(A);if(A.status==="queued")J({kind:"review",title:"Code review queued"});if(A.status==="error"){let G=Q8(A)??"Unknown error";J({kind:"review",title:`Code review failed: ${G}`})}let F=0,X=0;for(let[G,V]of Object.entries(Z??{})){if(!dB(V))continue;X+=1;let U=BV5(G,V);if(V.status==="done"){F+=1;let K=$V5(V);if(K===void 0)J({kind:"review",title:`Check ${U}: complete`});else if(K===0)J({kind:"review",title:`Check ${U}: ok`});else J({kind:"review",title:`Check ${U}: ${K} ${W4(K,"issue")} found`});continue}if(V.status==="error"){F+=1;let K=typeof V.error==="string"&&V.error.trim()?V.error.trim():"Unknown error";J({kind:"review",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:"review",title:`Check ${U}: ${K}`})}}if(Y?.status==="done"&&X>0&&F<X)J({kind:"review",title:"Main review complete, running checks..."});if(A.status==="done")J({kind:"review",title:"Code review complete"});if(B.length===0)J({kind:"review",title:A.status==="queued"?"Code review queued":"Reviewing code changes..."});let D=Q.thinking==="low"?"quick code review":"code review";return{actions:B,summary:X>0?`${F}/${X} checks · ${D}`:D}}function Js0(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,F,X]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"],["review","review","reviews"],["list","list",void 0]]){let D=Z==="guidance"?B:Z==="skill"?$:J.get(Z);if(!D)continue;Y.push(`${D} ${W4(D,F,X)}`)}if(Y.length>0)return Y.join(", ");return Q}function DV5(A){if(A.kind==="search"&&GV5(A.program)&&A.query){if(A.path)return`Grep ${A.path} "${A.query}"`;return`Grep "${A.query}"`}return yY0(A)}function GV5(A){if(!A)return!1;return new Set(["rg","ripgrep","grep","egrep","fgrep","ag","ack","pt","git grep"]).has(A)}function dB(A){return typeof A==="object"&&A!==null}HB();function Gs0(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")}t5();wk();s1();uS0();HB();var E3=u.string().min(1),lN=E3.brand(),Us0=u.string().regex(/^[0-9A-Za-z]{22}$/),VV5=u.templateLiteral([u.string().regex(/^[0-9a-f]{8}$/),"-",u.string().regex(/^[0-9a-f]{4}$/),"-",u.string().regex(/^[0-9a-f]{4}$/),"-",u.string().regex(/^[0-9a-f]{4}$/),"-",u.string().regex(/^[0-9a-f]{12}$/)]),aa=u.templateLiteral(["T-",VV5]),UV5=u.enum(["fork","handoff","mention"]),KV5=u.enum(["parent","child"]),Iy4=u.object({threadID:aa,type:UV5,role:KV5,messageIndex:u.number().int().nonnegative().optional(),blockIndex:u.number().int().nonnegative().optional(),createdAt:u.number().int().nonnegative(),comment:u.string().optional()}),u6=u.templateLiteral(["M-",Us0]);function IF0(){return`M-${Gs0(pT())}`}var l3=u.templateLiteral(["TU-",Us0]);var wy4=u.templateLiteral(["E-",Us0]);function Cy4(){return`E-${Gs0(pT())}`}var EV5=u.looseObject({type:u.literal("object"),properties:u.record(u.string(),u.unknown()),required:u.array(u.string()).optional(),additionalProperties:u.boolean().optional()}),WV5=u.union([u.literal("builtin"),u.object({toolbox:E3}).strict(),u.object({mcp:E3,target:u.enum(["global","workspace","flag","default"]).optional()}).strict(),u.object({plugin:E3}).strict(),u.object({remote:E3}).strict()]),zV5=u.object({serial:u.boolean().optional(),deferred:u.boolean().optional(),skillNames:u.array(E3).optional()}),My4=u.looseObject({name:E3,description:u.string(),inputSchema:EV5,source:WV5,meta:zV5.optional()}),KE8=u.object({id:E3,category:E3,title:E3,description:u.string().optional(),pluginName:E3}),Kx=u.enum(["none","minimal","low","medium","high","xhigh","max"]),wF0=u.object({"agent.skipTitleGenerationIfMessageContains":u.array(u.string()).optional(),"anthropic.thinking.enabled":u.boolean().optional(),"anthropic.interleavedThinking.enabled":u.boolean().optional(),"anthropic.temperature":u.number().optional(),"anthropic.provider":u.enum(["anthropic","vertex"]).optional(),"openai.speed":u.enum(["standard","fast"]).optional(),"painter.model":u.enum(["gemini-3-pro-image","gpt-image-2"]).optional(),"reasoning.effort":Kx.optional(),"internal.compactionThresholdPercent":u.number().min(0).max(100).optional(),"internal.model":u.union([u.string(),u.record(u.string(),u.string())]).optional(),"internal.oracleReasoningEffort":u.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":u.enum(["minimal","low","medium","high"]).optional(),"tools.disable":u.array(u.string()).optional(),"tools.enable":u.array(u.string()).optional()}),Ly4=u.object({workspaceId:u.string(),workingDirectory:u.string(),environment:u.object({os:u.enum(["darwin","linux","windows"]),hasDocker:u.boolean().optional(),hasBrowser:u.boolean().optional()}).strict(),tags:u.array(u.string())}).strict(),Oy4=u.enum(["sandbox","local-client"]),oa=u.any().and(u.object({status:u.string()})),jy4=u.discriminatedUnion("type",[u.object({type:u.literal("delta"),blocks:u.array(u.unknown()).optional(),state:u.enum(["start","generating","tool_use","complete","error","aborted"])}),u.object({type:u.literal("snapshot"),value:u.unknown()})]),NU=E3,Ry4=30000,Ex=sJ,HV5=u.enum(["file","directory"]),qV5=u.object({mtimeMs:u.number().nonnegative().optional()}),ra=u.tuple([u.string(),HV5,qV5.nullish()]),NV5=u.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),iN=u.object({code:NV5,message:u.string()}),IV5=u.object({ok:u.literal(!0),entries:u.array(ra)}),wV5=u.object({ok:u.literal(!1),error:iN}),EE8=u.discriminatedUnion("ok",[IV5,wV5]),CV5=u.object({ok:u.literal(!0),contentBase64:u.string()}),MV5=u.object({ok:u.literal(!1),error:iN}),WE8=u.discriminatedUnion("ok",[CV5,MV5]),LV5=E3,Ks0=u.object({key:E3,dataType:LV5,contentBase64:u.string()}),Es0=Ks0.extend({toolCallId:l3.optional(),updatedAt:u.string()}),Ws0=u.looseObject({uri:sJ,content:u.string().optional(),lineCount:u.int().optional(),hash:u.string().optional()}),OV5=u.enum(RJ4),Py4=u.object({path:sJ,error:u.string(),hint:u.string().optional()}),_y4=u.object({uri:sJ,hash:u.string(),lineCount:u.int().optional()}),Ty4=u.object({name:E3,description:u.string(),baseDir:sJ,frontmatter:u.object({name:E3,description:u.string()}).catchall(u.unknown()),files:u.array(u.string()).optional(),source:OV5.optional()}),zs0=u.object({type:u.literal("text"),text:u.string(),hidden:u.boolean().optional()}),Sy4=u.looseObject({type:u.literal("image"),source:u.discriminatedUnion("type",[u.object({type:u.literal("base64"),mediaType:u.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:u.string()}),u.object({type:u.literal("url"),url:u.string()})]),sourcePath:u.string()}),sa=u.array(u.discriminatedUnion("type",[zs0,Sy4])),Ux=u.record(u.string(),u.unknown()),ky4=u.object({type:u.literal("tool_use"),id:u.string().min(1),name:u.string().min(1),normalizedName:u.string().optional(),metadata:u.record(u.string(),u.unknown()).optional()}),jV5=ky4.extend({complete:u.literal(!0),input:Ux,normalizedInput:Ux.optional()}),RV5=ky4.extend({complete:u.literal(!1),input:Ux,inputIncomplete:Ux,inputPartialJSON:u.object({json:u.string()}),normalizedInput:Ux.optional()}),PV5=u.object({accepted:u.boolean(),askAnswers:u.record(u.string(),u.string()).optional(),denyFeedback:u.string().optional()}),_V5=u.object({type:u.literal("tool_result"),toolUseID:u.string().min(1),run:oa,userInput:PV5.optional()}),TV5=u.object({type:u.literal("thinking"),thinking:u.string(),signature:u.string()}),SV5=u.object({type:u.literal("redacted_thinking"),data:u.string()}),kV5=u.object({type:u.literal("server_tool_use"),id:u.string().min(1),name:u.string().min(1),input:Ux}),vV5=u.object({type:u.literal("manual_bash_invocation"),args:u.object({cmd:u.string(),args:u.array(u.string()).readonly().optional(),cwd:u.string().optional()}),toolRun:oa,hidden:u.boolean().optional()}),Hs0=u.object({sentAt:u.number().int().nonnegative().optional(),fromAggman:u.boolean().optional(),fromExecutorThreadID:aa.optional()}),yV5=u.union([zs0,Sy4,_V5]),xV5=u.union([zs0,TV5,SV5,jV5,RV5,kV5]),qs0=u.array(yV5),Ns0=u.array(xV5),fV5=u.array(vV5),Vs0=u.looseObject({line:u.number().int(),column:u.number().int()}),bV5=u.looseObject({start:Vs0,end:Vs0}),uV5=u.looseObject({name:u.string(),repositoryURL:u.string()}),hV5=u.looseObject({currentURL:u.string(),availableProjects:u.array(uV5).optional()}),Is0=u.looseObject({currentlyVisibleFiles:u.array(sJ),runningTerminalCommands:u.array(u.string()).optional(),activeEditor:u.any().optional(),cursorLocation:Vs0.optional(),cursorLocationLine:u.string().optional(),selectionRange:bV5.optional(),aggmanContext:hV5.optional()}),Xj=u.custom((A)=>typeof A==="string"&&b3(A)!==void 0),gV5=u.object({threadId:aa,role:u.literal("user"),content:qs0,agentMode:Xj.optional(),meta:Hs0.optional(),userState:Is0.optional(),readAt:u.string().nullable().optional(),messageId:u6,createdAt:u.string().optional()}),ws0=u.object({model:u.string().optional(),maxInputTokens:u.number(),inputTokens:u.number(),outputTokens:u.number(),cacheCreationInputTokens:u.number().nullable(),cacheReadInputTokens:u.number().nullable(),totalInputTokens:u.number(),thinkingBudget:u.number().optional(),timestamp:u.string().optional()}),mV5=u.union([u.object({type:u.literal("complete")}),u.object({type:u.literal("cancelled")})]),pV5=u.object({threadId:aa,role:u.literal("assistant"),content:Ns0,state:mV5.optional(),usage:ws0.optional(),readAt:u.string().nullable().optional(),messageId:u6,createdAt:u.string().optional()}),dV5=u.object({threadId:aa,role:u.literal("info"),content:fV5,messageId:u6,createdAt:u.string().optional()}),Cs0=u.discriminatedUnion("role",[gV5,pV5,dV5]),ta=u.object({workspaceRoot:sJ.optional(),workingDirectory:sJ.optional(),rootDirectoryListing:u.string().nullable().optional(),trees:u.array(u.any()).optional(),platform:u.any().optional(),tags:u.array(u.string()).optional(),git:u.object({branch:u.string().optional()}).optional(),updatedAt:u.string().optional()}),cV5=u.object({added:u.number().int().nonnegative(),deleted:u.number().int().nonnegative(),changed:u.number().int().nonnegative()}),lV5=u.object({path:u.string(),previousPath:u.string().optional(),changeType:u.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:u.boolean(),diff:u.string(),fullFileDiff:u.string().optional(),oldContent:u.string().optional(),newContent:u.string().optional(),diffStat:cV5}),iV5=u.object({hash:u.string(),shortHash:u.string(),subject:u.string()}),vy4=u.object({provider:u.literal("git"),capturedAt:u.number(),available:u.boolean(),repositoryRoot:u.string().nullable(),repositoryName:u.string().nullable(),branch:u.string().nullable(),head:u.string().nullable(),baseRef:u.string().nullable().optional(),baseRefHead:u.string().nullable().optional(),aheadCount:u.number().int().nonnegative().optional(),behindCount:u.number().int().nonnegative().optional(),aheadCommits:u.array(iV5).optional(),diffHash:u.string().optional(),files:u.array(lV5),unavailableReason:u.string().optional(),unchanged:u.boolean().optional()}),CF0=u.object({id:u.string(),toolCallId:l3,toolName:u.string(),args:u.record(u.string(),u.unknown()),reason:u.string().optional(),toAllow:u.array(u.string()).optional(),context:u.enum(["thread","subagent"]),subagentToolName:u.string().optional(),parentToolCallId:l3.optional(),timestamp:u.number(),matchedRule:u.object({tool:u.string(),action:u.string(),matches:u.record(u.string(),u.unknown()).optional()}).optional(),ruleSource:u.enum(["user","built-in"]).optional()}),nV5=u.object({type:u.literal("request"),id:E3,method:E3,params:u.unknown()}),aV5=u.object({type:u.literal("response"),id:E3,result:u.unknown().optional(),error:u.string().optional()}),oV5=u.object({type:u.literal("event"),event:E3,data:u.unknown(),span:u.string().optional()}),MF0=u.discriminatedUnion("type",[nV5,aV5,oV5]);var rV5=u.object({type:u.literal("executor_connect"),clientId:lN,capabilities:Ly4,executorType:Oy4.optional()}),sV5=u.object({type:u.literal("client_update_thread_settings"),settings:wF0}),tV5=u.object({type:u.literal("executor_tools_register"),tools:u.array(My4)}),eV5=u.object({type:u.literal("executor_tools_unregister"),toolNames:u.array(E3)}),AU5=u.object({type:u.literal("executor_tools_bootstrap_complete"),ok:u.boolean(),error:u.string().optional()}),QU5=u.object({type:u.literal("executor_tool_lease_ack"),toolCallId:l3}),Ms0=u.object({type:u.literal("tool_progress"),toolCallId:l3,progress:u.union([jy4,u.unknown()]).optional(),parentToolCallId:l3.optional()}),BU5=u.object({type:u.literal("executor_tool_result"),toolCallId:l3,run:oa}),$U5=u.object({type:u.literal("executor_guidance_snapshot"),snapshotId:E3,files:u.array(Ws0),isLast:u.boolean(),userConfigDir:u.any().optional()}),JU5=u.object({type:u.literal("executor_guidance_discovery"),toolCallId:l3,files:u.array(Ws0),isLast:u.boolean()}),YU5=u.object({type:u.literal("executor_skill_snapshot"),snapshotId:E3,skills:u.array(Ty4),isLast:u.boolean(),errors:u.array(Py4).optional()}),ZU5=u.object({type:u.literal("executor_environment_snapshot"),environment:ta}),FU5=u.object({type:u.literal("executor_environment_update"),environment:ta}),XU5=u.object({type:u.literal("executor_artifact_upsert"),artifact:Ks0,toolCallId:l3.optional()}),DU5=u.object({type:u.literal("executor_artifact_delete"),key:E3}),GU5=u.object({type:u.literal("executor_tool_approval_request"),approval:CF0}),VU5=u.object({type:u.literal("executor_plugin_message"),message:MF0}),UU5=u.object({type:u.literal("client_append_user_msg"),content:sa,userState:Is0.optional(),agentMode:Xj.optional(),reasoningEffort:Kx.optional(),messageId:u6,steer:u.boolean().optional()}),KU5=u.object({type:u.literal("client_remove_queued_msg"),queuedMessageId:u6}),EU5=u.object({type:u.literal("client_steer_queued_msg"),queuedMessageId:u6}),WU5=u.object({type:u.literal("client_edit_message"),messageId:u6,editId:wy4,content:sa,agentMode:Xj.optional(),reasoningEffort:Kx.optional()}),zU5=u.object({type:u.literal("client_mark_message_read"),messageId:u6}),HU5=u.object({type:u.literal("client_mark_message_unread"),messageId:u6}),qU5=u.object({type:u.literal("client_set_thread_title"),title:u.string().trim().min(1).max(256)}),NU5=u.object({auth:u.string().min(1),p256dh:u.string().min(1)}),IU5=u.object({endpoint:u.string().url(),keys:NU5}),wU5=u.object({type:u.literal("client_upsert_notification_subscription"),subscription:IU5,threadURL:u.string().min(1)}),CU5=u.object({type:u.literal("client_filesystem_read_directory"),requestId:NU,uri:Ex}),MU5=u.object({type:u.literal("client_filesystem_read_file"),requestId:NU,uri:Ex}),LU5=u.object({type:u.literal("executor_filesystem_read_directory_result"),requestId:NU,ok:u.boolean(),entries:u.array(ra).optional(),error:iN.optional()}).superRefine((A,Q)=>{if(A.ok){if(!A.entries)Q.addIssue({code:u.ZodIssueCode.custom,message:"entries is required when ok is true"});if(A.error)Q.addIssue({code:u.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:u.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.entries)Q.addIssue({code:u.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),OU5=u.object({type:u.literal("executor_filesystem_read_file_result"),requestId:NU,ok:u.boolean(),contentBase64:u.string().optional(),error:iN.optional()}).superRefine((A,Q)=>{if(A.ok){if(A.contentBase64===void 0)Q.addIssue({code:u.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(A.error)Q.addIssue({code:u.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!A.error)Q.addIssue({code:u.ZodIssueCode.custom,message:"error is required when ok is false"});if(A.contentBase64!==void 0)Q.addIssue({code:u.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),jU5=u.object({type:u.literal("client_resume"),version:u.number()}),RU5=u.object({type:u.literal("client_retry")}),PU5=u.object({type:u.literal("client_dismiss_active_error"),seq:u.number().optional()}),_U5=u.object({type:u.literal("client_cancel")}),TU5=u.object({type:u.literal("client_append_manual_bash_invocation"),args:u.object({cmd:u.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:u.array(u.string()).optional(),cwd:u.string().optional()}),run:oa,hidden:u.boolean().optional()}),SU5=u.object({type:u.literal("client_tool_approval_response"),toolCallId:l3,accepted:u.boolean(),input:u.object({askAnswers:u.record(u.string(),u.string()).optional(),denyFeedback:u.string().optional()}).optional()}),kU5=u.union([u.object({name:u.string(),type:u.literal("git").optional(),url:u.string()}),u.object({driveName:u.string().min(1).describe("Drive name. Must be a single path component."),name:u.string(),namespace:u.string(),type:u.literal("drive")})]),vU5=u.object({type:u.literal("client_spawn_executor"),requestId:u.string().optional(),repositoryURL:u.string().optional(),projectID:u.uuid().optional(),additionalRepositories:u.array(kU5).optional()}),yy4=u.discriminatedUnion("type",[rV5,sV5,tV5,eV5,AU5,QU5,Ms0,BU5,$U5,JU5,YU5,ZU5,FU5,XU5,DU5,GU5,VU5,UU5,KU5,EU5,WU5,zU5,HU5,qU5,wU5,CU5,MU5,LU5,OU5,jU5,RU5,PU5,_U5,TU5,SU5,vU5]);HB();var LF0=(A)=>u.codec(u.string(),A,{decode:(Q,B)=>{try{return JSON.parse(Q)}catch($){return B.issues.push({code:"invalid_format",format:"json",input:Q,message:$.message}),u.NEVER}},encode:(Q)=>JSON.stringify(Q)});HB();HB();var Ls0=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],CE8=new Set(Ls0);var yU5=["working","streaming","tool_use","running_tools"],xU5=new Set(yU5);function cB(A){if(typeof A!=="string")return!1;return xU5.has(A)}function ea(A){return typeof A==="object"&&A!==null}function fU5(A){return ea(A)&&A.type==="text"&&typeof A.text==="string"}function Os0(A){if(!A)return;let Q=A.filter(fU5).map((B)=>B.text).join("");return Q.length>0?Q:void 0}function js0(A){if(typeof A==="string")return A;if(Array.isArray(A))return Os0(A);if(!ea(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=js0(A[Q]);if(B!==void 0)return B}return}function xy4(A,Q){if(typeof A==="string")return A+Q;if(Array.isArray(A)){if(!A.every((B)=>ea(B)&&typeof B.type==="string"))return;return[...A,{type:"text",text:Q}]}if(!ea(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=xy4(A.value,Q);if(B!==void 0)return{...A,value:B}}return}function bU5(A){return ea(A)&&typeof A.status==="string"}function uU5(A,Q){return{type:"delta",...A?{blocks:[{type:"text",text:A}]}:{},state:Q}}function hU5(A){if(!A)return;if(A.type==="snapshot")return js0(A.value);return Os0(A.blocks)}function Wx(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 fy4(A,Q){if(Q.type!=="snapshot"||bU5(Q.value))return Q;let B=hU5(A),$=js0(Q.value);if(B===void 0||$===void 0)return Q;if(!$.startsWith(B))return Q;return uU5($.slice(B.length),"generating")}function OF0(A,Q){let B=A===void 0?void 0:Wx(A,"snapshot"),$=Wx(Q,"snapshot");if($.type==="snapshot")return $;if(!B)return $;let J=Os0($.blocks);if(J===void 0)return B;if(B.type==="snapshot"){let Z=xy4(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 gU5=u.enum(Ls0),mU5=u.enum(["start","generating","tool_use","complete","error","aborted"]),pU5=u.object({message:u.string(),code:u.string().optional(),stack:u.string().optional(),retryAt:u.number().optional(),attempt:u.number().optional()}),dU5=u.object({userId:u.string(),name:u.string(),avatarURL:u.string().optional()}),cU5=u.enum(["starting","running","failed"]),lU5=u.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),iU5=u.enum(["pending","ready","failed"]).nullable(),nU5=u.enum(["allocating_environment","configuring_workspace","starting_headless"]).nullable(),aU5=u.enum(["idle","creating","recovering"]),oU5=u.enum(["unknown","running","paused","missing"]),rU5=u.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"]),sU5=u.object({environmentId:u.string().nullable().optional(),stage:lU5.optional(),setupState:iU5.optional(),setupPhase:nU5.optional(),operation:aU5.optional(),providerState:oU5.optional(),restartAttempts:u.number().optional()}),tU5=u.object({reasonCode:rU5.optional(),executionEnvironment:sU5.optional()}),eU5=u.object({cutMessageId:u6,createdAt:u.string()}),by4=u.object({steer:u.boolean(),queuedMessage:u.object({role:u.literal("user"),messageId:u6,content:sa,userState:u.any().optional(),meta:Hs0.optional(),createdAt:u.string().optional()})}),AK5=u.object({type:u.literal("agent_state"),state:gU5,messageId:u6.optional(),agentMode:Xj.optional(),reasoningEffort:Kx.optional()}),QK5=u.object({type:u.literal("inference_tools"),messageId:u6,agentMode:Xj,tools:u.array(E3),parentToolCallId:l3.optional()}),BK5=u.object({type:u.literal("thread_settings"),settings:wF0}),$K5=u.object({type:u.literal("error"),message:u.string(),code:u.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()}),JK5=u.object({type:u.literal("error_set"),seq:u.number(),error:pU5}),YK5=u.object({type:u.literal("error_cleared"),seq:u.number()}),ZK5=u.object({type:u.literal("cancelled"),seq:u.number(),messageId:u6.optional()}),FK5=u.object({type:u.literal("retry_scheduled"),retryAt:u.number(),attempt:u.number(),maxAttempts:u.number(),reason:u.string()}),XK5=u.object({type:u.literal("retry_started")}),DK5=u.object({type:u.literal("retry_cancelled")}),GK5=u.object({type:u.literal("executor_connected"),executorId:lN,registeredToolCount:u.number(),guidanceInventory:u.array(_y4),resumeBootstrap:u.boolean().optional(),rejectedTools:u.array(u.object({name:u.string(),reason:u.string()})).optional()}),VK5=u.object({type:u.literal("tool_lease"),toolCallId:l3,toolName:u.string(),args:u.unknown(),messageId:u6,parentToolCallId:l3.optional()}),UK5=u.object({type:u.literal("executor_filesystem_read_directory"),requestId:NU,uri:Ex}),KK5=u.object({type:u.literal("executor_filesystem_read_file"),requestId:NU,uri:Ex}),EK5=u.object({type:u.literal("client_filesystem_read_directory_result"),requestId:NU,ok:u.boolean(),entries:u.array(ra).optional(),error:iN.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"})}),WK5=u.object({type:u.literal("client_filesystem_read_file_result"),requestId:NU,ok:u.boolean(),contentBase64:u.string().optional(),error:iN.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"})}),zK5=u.object({type:u.literal("tool_approval_queue"),approvals:u.array(CF0)}),HK5=u.object({type:u.literal("executor_tool_lease_revoked"),toolCallId:l3,reason:u.enum(["executor_disconnected","reassigned","user_canceled"])}),qK5=u.object({type:u.literal("executor_tool_result_ack"),toolCallId:l3}),NK5=u.object({type:u.literal("plugin_message"),message:MF0}),IK5=u.object({type:u.literal("executor_tool_approval_response"),toolCallId:l3,accepted:u.boolean(),input:u.object({askAnswers:u.record(u.string(),u.string()).optional(),denyFeedback:u.string().optional()}).optional()}),wK5=u.object({type:u.literal("executor_error"),message:u.string(),toolCallId:l3.optional(),code:u.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),CK5=u.object({type:u.literal("delta"),messageId:u6,role:u.literal("assistant"),blocks:Ns0.optional(),blockIndex:u.number().int().nonnegative().optional(),state:mU5,usage:ws0.optional(),parentToolCallId:l3.optional()}),MK5=u.object({type:u.literal("delta"),messageId:u6,role:u.literal("user"),blocks:qs0.optional(),state:u.literal("complete"),parentToolCallId:l3.optional()}),LK5=u.discriminatedUnion("role",[CK5,MK5]),OK5=u.object({type:u.literal("queued_messages"),messages:u.array(by4)}),jK5=u.object({type:u.literal("queued_message_added"),message:by4,seq:u.number()}),RK5=u.object({type:u.literal("queued_message_removed"),queuedMessageId:u6,seq:u.number()}),PK5=u.object({type:u.literal("queued_message_dequeued"),queuedMessageId:u6,seq:u.number()}),_K5=u.object({type:u.literal("message_added"),message:Cs0,seq:u.number(),parentToolUseId:l3.optional()}),TK5=u.object({type:u.literal("message_updated"),message:Cs0,seq:u.number()}),SK5=u.object({type:u.literal("edit_rejected"),editId:u.string(),message:u.string()}),kK5=u.object({type:u.literal("thread_truncated"),seq:u.number(),truncateFromMessage:u6}),vK5=u.object({type:u.literal("observers"),count:u.number(),observers:u.array(dU5),hasExecutor:u.boolean().optional()}),yK5=u.object({type:u.literal("executor_status"),spawnId:u.string().optional(),status:cU5,message:u.string().optional(),executorId:u.string().optional(),details:tU5.optional()}),xK5=u.object({type:u.literal("environment_update"),environment:ta}),fK5=u.object({type:u.literal("artifacts_snapshot"),artifacts:u.array(Es0)}),bK5=u.object({type:u.literal("artifact_upserted"),artifact:Es0}),uK5=u.object({type:u.literal("artifact_deleted"),key:E3}),hK5=u.object({type:u.literal("thread_title"),title:u.string().nullable()}),gK5=u.object({type:u.literal("thread_status"),status:u.union([u.literal("merging"),u.literal("merged"),u.null()])}),mK5=u.object({type:u.literal("thread_relationships"),seq:u.number(),relationships:u.array(Iy4)}),pK5=u.object({type:u.literal("compaction_started")}),dK5=u.object({type:u.literal("compaction_complete"),cutMessageId:u6}),cK5=u.object({type:u.literal("compaction_records"),records:u.array(eU5)}),jF0=u.discriminatedUnion("type",[AK5,QK5,BK5,$K5,JK5,YK5,ZK5,FK5,XK5,DK5,GK5,VK5,UK5,KK5,EK5,WK5,zK5,HK5,qK5,NK5,IK5,Ms0,wK5,LK5,kK5,OK5,jK5,RK5,PK5,_K5,TK5,SK5,vK5,yK5,xK5,fK5,bK5,uK5,hK5,gK5,mK5,pK5,dK5,cK5]);var uy4=LF0(yy4),lK5=u.union([jF0,u.array(jF0)]),vE8=LF0(jF0),hy4=LF0(lK5);s1();function gy4(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 F;try{F=u1(s0.parse(Z.uri))}catch{if($)return null;continue}let X={uri:F};if(typeof Z.content==="string")X.content=Z.content;if(typeof Z.lineCount==="number"&&Number.isFinite(Z.lineCount))X.lineCount=Z.lineCount;if(typeof Z.hash==="string")X.hash=Z.hash;J.push(X)}return J}function Rs0(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 dy4(A,Q,B){let $;switch(Q.type){case"message_added":$=iK5(A,Q);break;case"message_updated":$=nK5(A,Q);break;case"delta":$=aK5(A,Q,B);break;case"tool_progress":$=oK5(A,Q,B);break;case"thread_truncated":$=rK5(A,Q);break}return $}function iK5(A,Q){let B=Dj(Q.message,Q.parentToolUseId??Q.message.parentToolUseId),$=FE5(A,DE5(B)),J=Ao($,B.messageId),Y=$.slice();if(J>=0)return Y[J]=B,Y;return Y.push(B),Y}function nK5(A,Q){let B=Ao(A,Q.message.messageId),$=B>=0?A[B]:void 0,J=Dj(Q.message,$?.parentToolUseId),Y=A.slice();if(B>=0)return Y[B]=J,Y;return Y.push(J),Y}function Dj(A,Q){let B={...A};if(Q!==void 0)B.parentToolUseId=Q;return B}function aK5(A,Q,B){let $=Q.role==="assistant"&&Q.state==="aborted"?BE5(A,Q.messageId):A;if(!Q.blocks||Q.blocks.length===0){if(Q.role==="assistant"&&(Q.state==="complete"||Q.state==="tool_use"))return my4($,{...Q,blocks:[],blockIndex:Q.blockIndex??0},B);return $.slice()}if(Q.role==="assistant")return my4($,Q,B);return sK5($,{...Q,blocks:Q.blocks},B)}function oK5(A,Q,B){let $=ZE5(Q.progress);if($!==void 0&&$!=="in-progress")return A.slice();if(py4(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=py4(A,Q.toolCallId),Z=Y&&"progress"in Y.block.run?Y.block.run.progress:void 0,F=Q.progress===void 0?Z:OF0(Z,Q.progress),X=F===void 0?{status:"in-progress"}:{status:"in-progress",progress:F},D=Y?.block.userInput===void 0?{type:"tool_result",toolUseID:Q.toolCallId,run:X}:{type:"tool_result",toolUseID:Q.toolCallId,run:X,userInput:Y.block.userInput};if(Y)return $E5(A,Y,D);return[...A,Dj({threadId:B.threadId,messageId:cy4(Q.toolCallId),role:"user",content:[D]},Q.parentToolCallId)]}function rK5(A,Q){let B=Ao(A,Q.truncateFromMessage);return B>=0?A.slice(0,B):A.slice()}function my4(A,Q,B){let $=Ao(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="assistant"?J.content:[],Z=tK5(Y,Q.blocks,Q.blockIndex),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="assistant"?Dj({...J,content:Z},F):Dj({threadId:B.threadId,messageId:Q.messageId,role:"assistant",content:Z},F);if(Q.usage!==void 0)X.usage=Q.usage;if(Q.state==="aborted")X.state={type:"cancelled"},delete X.isStreaming;else if(Q.state==="complete"||Q.state==="tool_use")X.state={type:"complete"},delete X.isStreaming;else X.isStreaming=!0;return Ps0(A,$,X)}function sK5(A,Q,B){let $=Ao(A,Q.messageId),J=$>=0?A[$]:void 0,Y=J?.role==="user"?J.content:[],Z=QE5(Y,Q.blocks),F=Q.parentToolCallId??J?.parentToolUseId,X=J?.role==="user"?Dj({...J,content:Z},F):Dj({threadId:B.threadId,messageId:Q.messageId,role:"user",content:Z},F);return Ps0(A,$,X)}function tK5(A,Q,B){let $=[...A];for(let[J,Y]of Q.entries()){let Z=B+J;eK5($,Z);let F=$[Z];if(AE5(F))$[Z]=Y;else if(F?.type==="text"&&Y.type==="text")$[Z]={...F,text:F.text+Y.text};else if(F?.type==="thinking"&&Y.type==="thinking")$[Z]={...F,thinking:F.thinking+Y.thinking};else $[Z]=Y}return $}function eK5(A,Q){while(A.length<Q)A.push({type:"text",text:"",hidden:!0})}function AE5(A){return A?.type==="text"&&A.hidden===!0&&A.text===""}function QE5(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 Ps0(A,Q,B){let $=A.slice();if(Q>=0)return $[Q]=B,$;return $.push(B),$}function BE5(A,Q){return A.filter((B)=>B.messageId!==Q)}function Ao(A,Q){return A.findIndex((B)=>B.messageId===Q)}function py4(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 $E5(A,Q,B){let $=Q.message.content.slice();return $[Q.blockIndex]=B,Ps0(A,Q.messageIndex,{...Q.message,content:$})}var JE5=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function YE5(A){return typeof A==="string"&&JE5.includes(A)}function ZE5(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 YE5($)?$:void 0}function FE5(A,Q){if(Q.size===0)return A;return A.filter((B)=>!XE5(B,Q))}function XE5(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===cy4(B.toolUseID)}function DE5(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 cy4(A){return`M-${A.replace(/^TU-/,"")}`}class _s0{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.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=GE5(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=dy4(Q,A,{threadId:this.threadID}),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(UE5(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;let B={...Q,state:{type:"complete"}};return delete B.isStreaming,B})}}function GE5(A){if(A.type==="message_added"&&VE5(A)===void 0)return A.message.messageId;if(A.type==="delta"&&A.parentToolCallId===void 0)return A.messageId;return}function VE5(A){return A.parentToolUseId??A.message.parentToolUseId}function UE5(A){return`M-${A.replace(/^TU-/,"")}`}c4();function ly4(A,Q){let B=A.parentToolUseId;if(A.role==="assistant"){let J={role:"assistant",content:A.content,state:A.state?.type==="cancelled"?{type:"cancelled"}:A.isStreaming===!0?{type:"streaming"}:{type:"complete",stopReason:null},usage:A.usage,messageId:Q,protocolMessageID:A.messageId,readAt:A.readAt};if(B===void 0)return J;return{...J,parentToolUseId:B}}if(A.role==="info"){let J={role:"info",content:A.content,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return J;return{...J,parentToolUseId:B}}let $={role:"user",content:A.content,meta:j30(A.meta),userState:A.userState,readAt:A.readAt,messageId:Q,protocolMessageID:A.messageId};if(B===void 0)return $;return{...$,parentToolUseId:B}}class RF0{accumulator;currentVersion=0;constructor(A){this.accumulator=new _s0(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:EE5(Q,0),version:this.currentVersion}}apply(A){if(A.type==="message_added"&&WE5(A)===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:KE5(Q,$),version:this.currentVersion}}protocolMessages(){return this.accumulator.sortedMessages()}coreMessages(){return this.accumulator.sortedMessages().map((A,Q)=>ly4(A,Q))}buildTranscriptEntries(A={}){return Qy4(this.protocolMessages(),{threadID:this.accumulator.getThreadID(),...A})}}function KE5(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 EE5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}function WE5(A){return A.parentToolUseId??A.message.parentToolUseId}function PF0(A,Q={}){let B=!1,$=!1;return A.connectionChanges().subscribe({next:(J)=>{let Y=J.state==="connected"&&(Q.requireRole===void 0||J.role===Q.requireRole);if(Y&&!B){if($)try{A.resumeFromVersion(A.getResumeVersion())}catch(Z){Q.onError?.({threadID:A.getThreadId(),error:Z})}$=!0}B=Y}})}zl();L1();var Ts0=Number.MAX_SAFE_INTEGER;class Ss0{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_dequeued",queuedMessageId:Q,seq:Ts0});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.pending.size>0)return"queued_message_added";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:Ts0});return}this.emitQueuedMessages({type:"queued_message_added",message:{steer:!1,queuedMessage:{role:"user",messageId:Q.messageId,content:Q.content,userState:Q.userState}},seq:Ts0})}emitMessageAdded(A){this.callbacks.observerCallbacks((Q)=>{Q.onMessageAdded?.(A)})}emitQueuedMessages(A){this.callbacks.observerCallbacks((Q)=>{Q.onQueuedMessages?.(A)})}}class ks0{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(!HE5(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),zE5(this.retryTimer)}clearRetryTimer(){if(this.retryTimer===null)return;clearTimeout(this.retryTimer),this.retryTimer=null}}function zE5(A){if(typeof A!=="object"||A===null||!("unref"in A))return;let Q=A.unref;if(typeof Q==="function")Q.call(A)}function HE5(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 qE5(Q.messages,A.messageId);default:return!1}}function qE5(A,Q){return A.some((B)=>B.queuedMessage.messageId===Q)}c0();L1();var NE5=1000,IE5=30000,wE5=124,CE5=30000,ME5=15000,LE5=1000,OE5=200,jE5=30000,iy4=["online","focus","pageshow","keydown","pointerdown"],ny4=["visibilitychange"];function ys0(){return globalThis}function oy4(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 ay4(){return oy4(ys0().window)}function vs0(){let A=ys0().document;if(!oy4(A))return null;return A}function RE5(){let A=ys0().navigator;if(!A||typeof A!=="object")return null;return A}function PE5(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 xs0{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 Y4({state:"disconnected",role:null,clientId:null});lifecycleEventSubject=new Y4([]);config;threadIDSubject=new Y4(null);_currentThreadID=null;log=j;get currentThreadID(){return this._currentThreadID}set currentThreadID(A){if(A!==null&&A!==this._currentThreadID)this._currentThreadID=A,this.log=j.with({threadId:A}),this.threadIDSubject.next(A);else this._currentThreadID=A}constructor(A){this.config={threadId:A.threadId,webSocketProvider:A.webSocketProvider,reconnectDelayMs:A.reconnectDelayMs??NE5,maxReconnectDelayMs:A.maxReconnectDelayMs??IE5,maxReconnectAttempts:A.maxReconnectAttempts??wE5,pingIntervalMs:A.pingIntervalMs??CE5,connectTimeoutMs:A.connectTimeoutMs??ME5,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}:{}},$=OE5,J=this.lifecycleEvents.slice(-($-1));this.lifecycleEvents=[...J,B],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(A){if(this.disposed)throw new I8("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??LE5);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 I8("WebSocket is not connected");let Q=this.ws;if(!Q)throw new I8("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=(F)=>{if($)return;if($=!0,J)clearTimeout(J);A.removeEventListener("close",Z),B(F)},Z=(F)=>{let X=F;Y({status:X.code===1000?"server_acknowledged":"timeout",...typeof X.code==="number"?{closeCode:X.code}:{},...typeof X.reason==="string"?{closeReason:X.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=${PE5(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 I8(`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",F)},Y=()=>{J(),Q()},Z=(X)=>{J(),this.updateConnectionState("disconnected");let D="message"in X?X.message:("error"in X)&&X.error instanceof Error?X.error.message:X.type;B(new I8(`WebSocket connection failed: ${D}`))},F=(X)=>{J(),this.updateConnectionState("disconnected"),B(new I8(`WebSocket closed during connect: code=${X.code} reason=${X.reason||"none"}`))};if(A.addEventListener("open",Y),A.addEventListener("error",Z),A.addEventListener("close",F),A.readyState===WebSocket.OPEN)return Y();if(A.readyState===WebSocket.CLOSED||A.readyState===WebSocket.CLOSING)return F({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=ay4(),Q=vs0();if(!A&&!Q)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let A=RE5();if(typeof A?.onLine!=="boolean")return!1;return A.onLine===!1}isDocumentHidden(){let A=vs0();if(!A)return!1;return A.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let A=ay4(),Q=vs0();if(!A&&!Q)return;let B=()=>{this.handleReconnectActivity()};for(let $ of iy4)A?.addEventListener($,B);for(let $ of ny4)Q?.addEventListener($,B);this.reconnectActivityCleanup=()=>{for(let $ of iy4)A?.removeEventListener($,B);for(let $ of ny4)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},jE5)}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}}var _E5=3000,TE5=30000,SE5=5;function ry4(A){if(A instanceof r7)return A;if(A instanceof Error){let Q=A.message||"Unknown thread-client connection error";return new r7(Q,A)}if(typeof A==="string"&&A.length>0)return new r7(A,A);return new r7("Unknown thread-client connection error",A)}function kE5(A){let Q=atob(A),B=new Uint8Array(Q.length);for(let $=0;$<Q.length;$++)B[$]=Q.charCodeAt($);return B}function vE5(A){return{type:"error",message:`Failed to send user message: ${A}`,code:"MESSAGE_ERROR"}}class IU extends xs0{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=Rs0(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new Y4(null);threadIDSubscription;constructor(A){super(A.transport);if(this.threadHistoryLoader=A.threadHistoryLoader,this.outbox=new ks0({trySend:(Q)=>this.trySendOutboxMessage(Q)}),this.optimisticUserMessages=new Ss0({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 ry4(A)}}async reconnect(){await this.disconnectAndWait(),await this.connect()}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??_E5,B=A?.maxDelayMs??TE5,$=A?.maxAttempts??SE5;if(A?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let J=0;J<$;J++){try{await this.connect()}catch(X){let D=ry4(X);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 F=J+1<$?Math.min(Q*2**(J+1),B):null;A?.onAttemptTimeout?.({attempt:J+1,maxAttempts:$,nextDelayMs:F})}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)=>{let Z={type:"message_added",message:J,seq:$},F=l3.safeParse(J.parentToolUseId);if(F.success)Z.parentToolUseId=F.data;Y.onMessageAdded?.(Z)});return Q}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(A,Q,B){let $=B?.messageId??IF0(),J={type:"client_append_user_msg",content:e$(A),agentMode:Q,reasoningEffort:B?.reasoningEffort,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,$,J){this.outbox.send({type:"client_edit_message",messageId:A,editId:B,content:e$(Q),agentMode:$,reasoningEffort:J?.reasoningEffort}),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,this.retryConnectIfTerminallyDisconnected("agent loop cancel requested");return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(A){this.send({type:"client_append_manual_bash_invocation",args:e$(A.args),run:e$(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 I8("Transport is disposed");if(!this.hasOpenSocket()){if(this.getConnectionInfo().state==="connected")this.forceReconnect("executor handshake attempted without open socket");throw new I8("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,F)=>{let X=!1,D=null,G=null,V=()=>Math.round(performance.now()-$),U=(z,H,q)=>{let N=this.getConnectionInfo();this.log.error(z,{...Y,durationMs:V(),connectionState:N.state,role:N.role,reconnectCauseType:N.reconnectCause?.type,reconnectCode:N.reconnectCause?.code,reconnectReason:N.reconnectCause?.reason,error:H,...q})},K=(z)=>{this.log.info("[thread-client] Executor handshake completed",{...Y,durationMs:V(),executorId:z.executorId,registeredToolCount:z.registeredToolCount,resumeBootstrap:z.resumeBootstrap}),W(()=>Z(z))},E=(z)=>{let H=Error(z.message);U("[thread-client] Executor handshake rejected by server",H,{code:z.code}),W(()=>F(H))},W=(z)=>{if(X)return;if(X=!0,D)clearTimeout(D),D=null;this.executorConnectedListeners.delete(K),this.executorErrorListeners.delete(E),G?.unsubscribe(),z()};this.executorConnectedListeners.add(K),this.executorErrorListeners.add(E),G=this.connectionChanges().subscribe({next:(z)=>{if(z.state==="connected")return;let H=new I8(z.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");U("[thread-client] Executor handshake interrupted",H),W(()=>F(H))}}),this.send({type:"executor_connect",clientId:A,capabilities:Q,executorType:B?.executorType}),D=setTimeout(()=>{let z=Error("Executor connect timeout");U("[thread-client] Executor handshake timed out",z),W(()=>F(z))},J)})}ackToolLease(A){this.send({type:"executor_tool_lease_ack",toolCallId:A})}sendToolProgress(A,Q){let B=Wx(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=Rs0(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=hy4.safeDecode(A);if(!Q.success)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_dequeued":this.optimisticUserMessages.reconcileQueuedMessageRemoved(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?.(vE5(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 I8("WebSocket is not connected"));return new Promise(($,J)=>{let Y=setTimeout(()=>{A.delete(Q),J(new I8(`Filesystem request timed out: ${Q}`))},Ry4);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(kE5(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 I8(A)),this.pendingReadDirectoryRequests.delete(Q);for(let[Q,B]of this.pendingReadFileRequests)clearTimeout(B.timeoutID),B.reject(new I8(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(uy4.encode(A))}catch(Q){let B=Q instanceof Error?Q.message:String(Q);throw new I8(`Failed to encode thread-protocol message "${A.type}": ${B}`,Q)}}}L1();function fs0(A){return{...A,pendingRemoval:!0}}function sy4(A,Q){if(Q.find(($)=>$.queuedMessage.messageId===A.queuedMessage.messageId)?.pendingRemoval!==!0)return A;return fs0(A)}function ty4(A,Q,B){if(Q.type==="queued_messages")return Q.messages.map(($)=>sy4($,A));if(Q.type==="queued_message_added"){if(A.find((J)=>J.queuedMessage.messageId===Q.message.queuedMessage.messageId)&&B.dedupeAdded)return[...A];return[...A,sy4(Q.message,A)]}if(!A.some(($)=>$.queuedMessage.messageId===Q.queuedMessageId))return[...A];return A.filter(($)=>$.queuedMessage.messageId!==Q.queuedMessageId)}var ey4={state:"disconnected",role:null,clientId:null};function Ax4(A){return[...A].sort((Q,B)=>Q.key.localeCompare(B.key))}function yE5(A,Q){let B=A.findIndex((J)=>J.key===Q.key);if(B===-1)return Ax4([...A,Q]);let $=[...A];return $[B]=Q,$}class _F0{connectionInfo;agentLoopState;pendingSend=new Y4(!1);queuedMessages=new Y4([]);pendingApprovals=new Y4([]);lastError=new Y4(null);activeError=new Y4(null);cancelledMessageId=new Y4(null);retryState=new Y4(null);executorError=new Y4(null);observers=new Y4(null);executorStatus=new Y4(null);environment=new Y4(null);compactionState=new Y4("idle");compactionRecords=new Y4([]);artifacts=new Y4([]);threadSettings;threadTitle=new Y4(void 0);threadId=new Y4(null);messageAddedEvents=new h4;messageUpdatedEvents=new h4;deltaEvents=new h4;toolProgressEvents=new h4;truncateEvents=new h4;pluginMessages=new h4;now;dedupeQueuedMessageAdds;compactionRecordsState;constructor(A={}){this.connectionInfo=new Y4(A.initialConnectionInfo??ey4),this.agentLoopState=new Y4(A.initialAgentLoopState??"idle"),this.threadSettings=new Y4(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(cB(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(ty4(this.queuedMessages.getValue(),A,{dedupeAdded:this.dedupeQueuedMessageAdds}))}onUserActionMessageDeliveryStatusChanged(A,Q,B){if(Q!=="buffered")return;let $=this.queuedMessages.getValue(),J=$.findIndex((F)=>F.queuedMessage.messageId===A);if(J===-1)return;let Y=$[J];if(!Y)return;let Z=[...$];Z[J]=fs0(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.compactionState.next("idle");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(Ax4(A.artifacts));return;case"artifact_upserted":this.artifacts.next(yE5(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(ey4),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()&&!cB(this.agentLoopState.getValue()))this.pendingSend.next(!1)}}c0();function TF0(A){let{client:Q,observer:B,toolService:$,callbacks:J}=A,Y=new Set,Z=[],F=!1,X=!1,D=null,G=!1,V=[],U=setInterval(()=>{},1000),E=Gx(()=>{if(G)return;j.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{Q.cancelAgentLoop()}catch(z){j.warn("Failed to cancel remote agent loop on signal",{error:z})}J.onSignal()});return E.install(),V.push(B.activeError$.subscribe((z)=>{if(!z)return;J.onError(z.message)})),V.push(B.errorNotice$.subscribe((z)=>{J.onError(z)})),V.push($.pendingApprovals$.subscribe((z)=>{Z=z})),V.push(B.agentState$.subscribe((z)=>{D=z.state;let H=cB(z.state);if(H&&z.messageId)Y.add(z.messageId);if(H){F=!0,X=!0;return}if(X=!1,!F)return;J.onTransitionToIdle(Z)})),V.push(B.messageAdded$.subscribe((z)=>{J.onMessageAdded(z)})),{currentTurnAssistantIds:Y,pendingApprovals:()=>Z,agentStarted:()=>F,agentActive:()=>X,agentIdle:()=>D==="idle",dispose:()=>{if(G)return;G=!0,E.remove(),clearInterval(U);for(let z of V)z.unsubscribe()}}}c0();import xE5 from"node:process";var SF0=j.getChild("thread-actors-transport"),bs0=Number(xE5.env.SIMULATE_LATENCY??0),fE5=Number.isFinite(bs0)&&bs0>0?bs0:0;function zx(A,Q){let B=Q;return async()=>{let $=await A(B);return B=$.threadId,$}}function Hx(A){let Q=HU({endpoint:A.rivetEndpoint});return{...A.initialThreadID?{threadId:A.initialThreadID}:{},...A.maxReconnectAttempts!==void 0?{maxReconnectAttempts:A.maxReconnectAttempts}:{},pingIntervalMs:A.pingIntervalMs??5000,webSocketLatencyMs:()=>fE5,webSocketProvider:async()=>{SF0.debug("Fetching connection credentials");let B=await A.credentialsProvider({forceRefresh:!0});SF0.debug("Fetched connection credentials",{threadId:B.threadId,threadVersion:B.threadVersion});let $=Q.threadActor.getOrCreate([B.threadId],{params:{wsToken:B.wsToken},createWithInput:{threadId:B.threadId,threadVersion:B.threadVersion,ownerUserId:B.ownerUserId,...B.agentMode?{agentMode:B.agentMode}:{}}});SF0.debug("Opening Rivet actor WebSocket",{threadId:B.threadId});let J=await $.webSocket("/",void 0,{skipReadyWait:!0});return SF0.debug("Opened Rivet actor WebSocket",{threadId:B.threadId}),{webSocket:J,threadId:B.threadId}}}}c4();function kF0(A){let Q=A.agentMode||Gp(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)=>$x4(A,B)),agentMode:Q,needsImport:!uE5(A)}}function Bx4(A){let Q=A.agentMode||Gp(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)=>bE5(A,B)),agentMode:Q,...A.meta?{meta:A.meta}:{}}}function bE5(A,Q){let{threadId:B,parentToolUseId:$,...J}=$x4(A,Q);if(Q.parentToolUseId!==void 0)return{...J,parentToolUseId:Q.parentToolUseId};return J}function uE5(A){if(!A.meta||typeof A.meta!=="object")return!1;return A.meta.usesThreadActors===!0}function $x4(A,Q){let B=hE5(Q);switch(Q.role){case"user":return us0(Q,{threadId:A.id,role:"user",content:[...Q.content],meta:j30(Q.meta),userState:gE5(Q.userState),readAt:Q.readAt,messageId:B});case"assistant":return us0(Q,{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 us0(Q,{threadId:A.id,role:"info",content:Q.content.filter(mE5),messageId:B})}}function us0(A,Q){if(A.parentToolUseId!==void 0)Q.parentToolUseId=A.parentToolUseId;return Q}function hE5(A){let Q=Qx4(A.protocolMessageID);if(Q)return Q;let B=A.messageId;if(typeof B==="string"){let $=Qx4(B);if($)return $}return IF0()}function Qx4(A){if(!A)return null;let Q=u6.safeParse(A);return Q.success?Q.data:null}function gE5(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 mE5(A){return A.type==="manual_bash_invocation"}MQ();s1();import Qo from"node:path";class Gj extends Error{code;constructor(A,Q){super(Q);this.code=A;this.name="ExecutorFileSystemPathError"}}function Yx4(A,Q){let B=s0.parse(A);if(B.scheme!=="file")throw new Gj("INVALID_URI","Only file:// URIs are supported");if(!B.path.startsWith("/"))throw new Gj("INVALID_URI","File URI path must be absolute");if(B.path.split("/").some((X)=>X===".."))throw new Gj("ACCESS_DENIED","File URI resolves outside workspace root");let J=Qo.posix.normalize(B.path).replace(/^\/+/u,"");if(J===".."||J.startsWith("../"))throw new Gj("ACCESS_DENIED","File URI resolves outside workspace root");let Y=Qo.resolve(Q),Z=J.length>0?Qo.resolve(Y,J):Y,F=Qo.relative(Y,Z);if(F.startsWith("..")||Qo.isAbsolute(F))throw new Gj("ACCESS_DENIED","File URI resolves outside workspace root");return Z}async function qx(A,Q){try{let B=Yx4(Q,A.workspaceRoot),$=await A.fileSystem.readdir(s0.file(B));return{ok:!0,entries:await Promise.all($.map(async(Y)=>{let Z=Y.isDirectory?"directory":"file",F=Z==="file"?await pE5(A.fileSystem,Y.uri):void 0;return[X1.basename(Y.uri),Z,F]}))}}catch(B){return{ok:!1,error:Fx4(B,"read_directory")}}}async function pE5(A,Q){try{let B=await A.getMtime(Q);if(!Number.isFinite(B)||B<0)return;return{mtimeMs:B}}catch{return}}async function Zx4(A,Q){try{let B=Yx4(Q,A.workspaceRoot),$=await A.fileSystem.readBinaryFile(s0.file(B));return{ok:!0,contentBase64:Buffer.from($).toString("base64")}}catch(B){return{ok:!1,error:Fx4(B,"read_file")}}}function Fx4(A,Q){if(A instanceof Gj)return{code:A.code,message:A.message};if(v8(A))return{code:"NOT_FOUND",message:"File or directory not found"};if(vF0(A,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(vF0(A,"ENOTDIR"))return{code:Q==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Q==="read_directory"?"Expected a directory":Jx4(A)};if(vF0(A,"EACCES")||vF0(A,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:Jx4(A)}}function vF0(A,Q){if(!(A instanceof Error))return!1;return"code"in A&&A.code===Q}function Jx4(A){if(A instanceof Error)return A.message;return String(A)}c0();_5();zl();c4();s1();L1();c0();function yF0(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}),dE5(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(Xx4(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(Xx4(B.id,void 0,J instanceof Error?J.message:String(J)))})}}function Xx4(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 dE5(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 cE5}from"node:child_process";import{promisify as lE5}from"node:util";MV();c4();s1();var iE5=lE5(cE5);async function Dx4(A){let Q=await EW(),B=HQ(A)?A:p2(),$=await tX({filesystem:O3},Q,B),J=await nE5($.workingDirectory??$.workspaceRoot);return{...Q,...$,...J?{git:{branch:J}}:{},updatedAt:new Date().toISOString()}}async function nE5(A){if(!A)return;let Q;try{Q=s0.parse(A).fsPath}catch{return}try{let{stdout:B}=await iE5("git symbolic-ref --quiet --short HEAD",{cwd:Q});return B.trim()||void 0}catch{return}}function aE5(A){return new TextEncoder().encode(JSON.stringify(A)).length}function Nx(A,Q,B){if(A.length===0)return[];let $=[],J=[];for(let Y of A){let Z=[...J,Y],F=aE5(B(Z));if(J.length>0&&F>Q){$.push(J),J=[Y];continue}J=Z}if(J.length>0)$.push(J);return $}var Vx4=1048576;function Gx4(A){let Q=new Map;for(let B of A)Q.set(B.name,{schema:B,serializedSchema:JSON.stringify(B)});return Q}function oE5(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 rE5(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:oE5(A)}}function hs0(A){return A.map((Q)=>rE5(Q.spec))}function Ux4(A,Q){let B=Gx4(A),$=Gx4(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 Kx4(A,Q=Vx4){return Nx(A,Q,(B)=>({type:"executor_tools_register",tools:B}))}function Ex4(A,Q=Vx4){return Nx(A,Q,(B)=>({type:"executor_tools_unregister",toolNames:B}))}import{execFile as QW5}from"node:child_process";import{createHash as BW5}from"node:crypto";import{readFile as $W5,stat as JW5}from"node:fs/promises";import{basename as YW5,join as ZW5}from"node:path";import Cx4 from"node:process";import{promisify as FW5}from"node:util";async function Wx4(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 zx4=2097152,nN="(Content omitted — git status artifact exceeds size limit)";function sE5(A){return(A.fullFileDiff?.length??0)+(A.oldContent?.length??0)+(A.newContent?.length??0)}function tE5(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!==nN)A.oldContent=nN,Q=!0;if(A.newContent!==void 0&&A.newContent!==nN)A.newContent=nN,Q=!0;return Q}function eE5(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 AW5(A){let Q=!1;if(A.diff!==nN)A.diff=nN,Q=!0;if(A.fullFileDiff!==void 0&&A.fullFileDiff!==nN)A.fullFileDiff=nN,Q=!0;return Q}function Ix(A){let Q=Buffer.from(JSON.stringify(A),"utf8").toString("base64"),B=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:pk,dataType:"application/json",contentBase64:Q}})).length;return{contentBase64:Q,messageSizeBytes:B}}function Hx4(A,Q){let B={...A,aheadCommits:[...A.aheadCommits],files:A.files.map((Z)=>({...Z}))},$=Ix(B);if($.messageSizeBytes<=Q)return $.contentBase64;let J=B.files.map((Z,F)=>({index:F,weight:sE5(Z)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of J){let F=B.files[Z];if(!F||!tE5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}for(let{index:Z}of J){let F=B.files[Z];if(!F||!eE5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}let Y=B.files.map((Z,F)=>({index:F,weight:Z.diff.length+(Z.fullFileDiff?.length??0)})).filter((Z)=>Z.weight>0).sort((Z,F)=>F.weight-Z.weight);for(let{index:Z}of Y){let F=B.files[Z];if(!F||!AW5(F))continue;if($=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}if(B.aheadCommits.length>0){if(B.aheadCommits=[],$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64}while(B.files.length>0)if(B.files.pop(),$=Ix(B),$.messageSizeBytes<=Q)return $.contentBase64;return $.contentBase64}var XW5=FW5(QW5),Cx=20971520,DW5=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],xF0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],GW5=999999,qx4="refs/remotes/origin/",VW5=20,UW5=10;function fF0(A){return A.replace(/\n+$/,"")}var gs0=Cx4.platform==="win32"?"NUL":"/dev/null";function KW5(A=Cx4.env,Q={}){let{isolateGitConfig:B=!0}=Q,$={...A};if(B){for(let J of Object.keys($))if(DW5.includes(J)||J.startsWith("GIT_CONFIG_KEY_")||J.startsWith("GIT_CONFIG_VALUE_"))delete $[J];$.GIT_CONFIG_NOSYSTEM="1",$.GIT_CONFIG_SYSTEM=gs0,$.GIT_CONFIG_GLOBAL=gs0}return $}function Nx4(A,Q){return{provider:"git",capturedAt:A,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Q}}function EW5(A){return A instanceof Error}async function wx(A,Q,B={}){try{let{stdout:$}=await XW5("git",Q,{cwd:A,env:KW5(),maxBuffer:B.maxBufferBytes??Cx});return $}catch($){if(B?.allowExitCodeOne&&EW5($)&&($.code===1||$.code==="1")&&typeof $.stdout==="string")return $.stdout;throw $}}async function CW(A,Q){try{return await wx(A,Q)}catch{return null}}function WW5(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 ms0(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 F=WW5(Y);if(F==="renamed"||F==="copied"){let X=B[$+1];if(X){Q.push({path:Z,previousPath:X,changeType:F}),$+=1;continue}}Q.push({path:Z,changeType:F})}return Q.sort(($,J)=>$.path.localeCompare(J.path))}function zW5(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 F of A.split(`
|
|
4702
4702
|
`)){if(F.startsWith("+")&&!F.startsWith("+++")){Q+=1,J+=1;continue}if(F.startsWith("-")&&!F.startsWith("---")){B+=1,Y+=1;continue}Z()}return Z(),{added:Q,deleted:B,changed:$}}function HW5(A){let Q=BW5("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 Ix4(A,Q,B,$,J=Cx){let Y=$!==void 0?[`--unified=${$}`]:[];if(B)return wx(A,[...xF0,...Y,"HEAD","--",Q],{maxBufferBytes:J});let[Z,F]=await Promise.all([wx(A,[...xF0,...Y,"--cached","--",Q],{maxBufferBytes:J}).catch(()=>""),wx(A,[...xF0,...Y,"--",Q],{maxBufferBytes:J}).catch(()=>"")]);return[fF0(Z),fF0(F)].filter(Boolean).join(`
|
|
4703
4703
|
`)}async function qW5(A,Q,B=Cx){return wx(A,[...xF0,"--no-index","--",gs0,Q],{allowExitCodeOne:!0,maxBufferBytes:B})}async function NW5(A,Q,B,$=Cx){let J=B??"HEAD";try{return await wx(A,["show",`${J}:${Q}`],{maxBufferBytes:$})}catch{return}}async function IW5(A,Q,B=Cx){try{let $=ZW5(A,Q);if((await JW5($)).size>B)return;return await $W5($,"utf-8")}catch{return}}function wx4(A){let Q=Number.parseInt(A.trim(),10);if(!Number.isFinite(Q))return null;return Q}async function wW5(A){let Q=(await CW(A,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Q?.startsWith(qx4))return null;let B=Q.slice(qx4.length);if(!B)return null;let $=`origin/${B}`,Y=(await CW(A,["rev-parse","--verify","--quiet",`${$}^{commit}`]))?.trim();if(!Y)return null;return{baseRef:B,comparisonRef:$,baseRefHead:Y}}function CW5(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 MW5(A,Q){let B=await CW(A,["log","-z",`--max-count=${VW5}`,"--format=%H%x00%s",`${Q}..HEAD`]);if(!B)return[];return CW5(B)}async function LW5(A,Q){if(!Q)return null;let B=await wW5(A);if(!B)return null;let $=await CW(A,["rev-list","--count",`${B.comparisonRef}..HEAD`]);if(!$)return null;let J=await CW(A,["rev-list","--count",`HEAD..${B.comparisonRef}`]);if(!J)return null;let Y=wx4($);if(Y===null)return null;let Z=wx4(J);if(Z===null)return null;return{baseRef:B.baseRef,comparisonRef:B.comparisonRef,baseRefHead:B.baseRefHead,aheadCount:Y,behindCount:Z}}async function bF0(A,Q={}){let{maxDiffBufferBytes:B=Cx}=Q,$=Date.now(),J=await CW(A,["rev-parse","--show-toplevel"]);if(!J)return Nx4($,"not a git repository");let Y=J.trim(),Z=YW5(Y),[F,X,D]=await Promise.all([CW(Y,["rev-parse","--verify","HEAD"]),CW(Y,["symbolic-ref","--short","HEAD"]),CW(Y,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(D===null)return Nx4($,"failed to read git status");let G=F?.trim()||null,V=X?.trim()||null,U=ms0(D),K=await LW5(Y,G),E=K?.aheadCount&&K.aheadCount>0?await MW5(Y,K.comparisonRef):[],W=await Wx4(U,UW5,async(z)=>{let H=fF0(z.changeType==="untracked"?await qW5(Y,z.path,B).catch(()=>""):await Ix4(Y,z.path,G,void 0,B).catch(()=>"")),q=fF0(z.changeType==="modified"?await Ix4(Y,z.path,G,GW5,B).catch(()=>""):H),N=z.changeType!=="added"&&z.changeType!=="untracked"?await NW5(Y,z.previousPath??z.path,G,B):void 0,I=z.changeType!=="deleted"?await IW5(Y,z.path,B):void 0;return{path:z.path,previousPath:z.previousPath,changeType:z.changeType,created:z.changeType==="added"||z.changeType==="untracked",diff:H,fullFileDiff:q,oldContent:N,newContent:I,diffStat:zW5(H)}});return{provider:"git",capturedAt:$,available:!0,repositoryRoot:Y,repositoryName:Z,branch:V,head:G,diffHash:HW5(W),baseRef:K?.baseRef??null,baseRefHead:K?.baseRefHead??null,aheadCount:K?.aheadCount??0,behindCount:K?.behindCount,aheadCommits:E,files:W}}function OW5(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 ps0(A){let Q=Hx4(OW5(A),zx4);return{key:pk,dataType:"application/json",contentBase64:Q}}import{createHash as jW5}from"node:crypto";function ds0(A){return jW5("sha256").update(A).digest("hex")}class Bo{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(Bo.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(Bo.key(A,Q))}isInitialized(){return this.initialized}}function cs0(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 Mx4=1048576;function Lx4(A,Q,B,$=Mx4){return Nx(A,$,(J)=>({type:"executor_guidance_snapshot",snapshotId:Q,files:J,isLast:!1,userConfigDir:B}))}function Ox4(A,Q,B=Mx4){return Nx(A,B,($)=>({type:"executor_guidance_discovery",toolCallId:Q,files:$,isLast:!1}))}var Mx={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function uF0(A,Q){if(A>=Q.maxAttempts)return null;let B=Math.max(1,A);return Math.min(Q.baseDelayMs*2**(B-1),Q.maxDelayMs)}var lB=j.getChild("executor");function RW5(A){return typeof A==="object"&&A!==null&&"output"in A&&A.output===""}function PW5(){let A=()=>{return},Q=()=>{return};return{promise:new Promise(($,J)=>{A=$,Q=J}),resolve:A,reject:Q}}function _W5(A){if(A==="darwin")return"darwin";if(A==="win32")return"windows";return"linux"}function jx4(A){let Q=A.previouslyAdvertisedTools??[],{toolsToRegister:B,toolNamesToUnregister:$}=Ux4(Q,A.nextTools),J=A.forceRegisterAll?[...A.nextTools]:B;for(let Y of Kx4(J))A.logMessage?.("SEND",{type:"executor_tools_register",tools:Y.map((Z)=>Z.name)}),A.transport.registerTools(Y);for(let Y of Ex4($))A.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:Y}),A.transport.unregisterTools(Y);return[...A.nextTools]}async function TW5(A){let{transport:Q,threadId:B,configService:$,skillService:J,logMessage:Y}=A,Z=A.fileSystem??O3,F=performance.now(),X={clientID:A.executorClientID,threadID:B,executorType:A.executorType,allowResumeBootstrap:A.allowResumeBootstrap===!0},D={},G="executorHandshake",V=!1,U=performance.now(),K=(z)=>{D[`${z}Ms`]=Math.round(performance.now()-U)};lB.info("Starting executor bootstrap",X);let E={workspaceId:A.workspaceRoot,workingDirectory:A.workspaceRoot,environment:{os:_W5(process.platform)},tags:[]};Y?.("SEND",{type:"executor_connect",clientId:A.executorClientID,capabilities:E,executorType:A.executorType}),G="executorHandshake",U=performance.now();let W=await Q.executorHandshake(A.executorClientID,E,{executorType:A.executorType});K(G),Y?.("RECV",W),A.guidanceContentCache?.replace(W.guidanceInventory),V=A.allowResumeBootstrap===!0&&W.resumeBootstrap===!0;try{if(!V){A.onBootstrapProgress?.("environment"),G="buildEnvironmentSnapshot",U=performance.now();let N=await Dx4(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 SW5(Q,Z,$,w,Y,A.guidanceContentCache),K(G),A.onBootstrapProgress?.("skills"),G="sendSkillSnapshot",U=performance.now(),await kW5(Q,J,Y),K(G),A.sendGitSnapshot!==!1){A.onBootstrapProgress?.("git");try{G="sendGitSnapshot",U=performance.now();let C=await bF0(A.workspaceRoot);Y?.("SEND",{type:"executor_artifact_upsert",available:C.available,fileCount:C.files.length,branch:C.branch,head:C.head}),Q.sendExecutorArtifactUpsert(ps0(C)),K(G)}catch{}}}A.onBootstrapProgress?.("tools"),G="initialToolDiscovery",U=performance.now(),await A.initialToolDiscovery,K(G),G="loadToolStatuses",U=performance.now();let z=await y1(A.toolService.tools);K(G);let H=hs0(z);G="syncExecutorToolRegistrations",U=performance.now();let q=jx4({transport:Q,nextTools:H,previouslyAdvertisedTools:A.previouslyAdvertisedTools,forceRegisterAll:!V,logMessage:Y});return K(G),Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Q.sendExecutorToolsBootstrapComplete(!0),lB.info("Executor bootstrap completed",{...X,resumeBootstrap:V,toolCount:H.length,advertisedToolCount:q.length,totalMs:Math.round(performance.now()-F),...D}),{advertisedTools:q}}catch(z){let H=z instanceof Error?z.message:String(z);throw Y?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:H}),Q.sendExecutorToolsBootstrapComplete(!1,H),lB.error("Executor bootstrap failed",{...X,currentPhase:G,resumeBootstrap:V,totalMs:Math.round(performance.now()-F),...D,error:z}),z}}async function SW5(A,Q,B,$,J,Y){let F=(await Cq({filesystem:Q,configService:B,threadService:{observe:()=>m0.of({id:p2(),created:Date.now(),v:0,messages:[],env:{initial:$}})}},{messages:[],env:{initial:$}})).map((U)=>({uri:U.uri,content:U.content,lineCount:U.content.split(`
|
|
4704
|
-
`).length,hash:ds0(U.content)})),X=Y?cs0(F,Y):F,D=crypto.randomUUID(),G=B.userConfigDir?u1(B.userConfigDir):void 0;if(X.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=Lx4(X,D,G);for(let U=0;U<V.length;U++){let K=V[U];if(!K)continue;let E=U===V.length-1,W=K.filter((H)=>H.content!==void 0).map((H)=>H.uri),z=K.filter((H)=>H.content===void 0).map((H)=>H.uri);J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:K.length,withContent:W,contentOmitted:z,isLast:E}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:K,isLast:E,userConfigDir:G})}}async function kW5(A,Q,B){let[$,J]=await Promise.all([Q.getSkills(),Q.getSkillErrors()]),Y=crypto.randomUUID(),Z=20,F=$.map((D)=>({name:D.name,description:D.description,baseDir:D.baseDir,frontmatter:D.frontmatter,files:D.files,source:D.source})),X=J.map((D)=>({path:D.path,error:D.error,...D.hint?{hint:D.hint}:{}}));if(F.length===0){B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:0,errorCount:X.length,isLast:!0}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:[],isLast:!0,errors:X});return}for(let D=0;D<F.length;D+=20){let G=F.slice(D,D+20),V=D+20>=F.length;B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:G.length,...V?{errorCount:X.length}:{},isLast:V}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:G,isLast:V,...V?{errors:X}:{}})}}class Rx4{options;inFlight=null;readyWaiter=null;retryTimer=null;readyTimer=null;readyTimeoutConfig=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(A){this.options=A;this.baseDelayMs=A.baseDelayMs??Mx.baseDelayMs,this.maxDelayMs=A.maxDelayMs??Mx.maxDelayMs,this.maxAttempts=A.maxAttempts??Mx.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=PW5();if(A?.timeoutMs)this.readyTimeoutConfig={timeoutMs:A.timeoutMs,timeoutMessage:A.timeoutMessage??`Timed out waiting for handshake after ${A.timeoutMs}ms`},this.armReadyTimeout();return this.tryHandshake("connect"),this.readyWaiter.promise}handleConnectionChange(A){let Q=this.lastInfo;this.lastInfo=A;let B=A.state!=="connected"?"reset_disconnected":A.role==="executor"?"mark_ready":"ensure_handshake";if(lB.info("Handshake manager handling connection change",{action:B,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}if(!Q||Q.state!=="connected")this.armReadyTimeout();this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.clearReadyTimer(),this.readyTimeoutConfig=null,this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){this.clearReadyTimer(),this.readyTimeoutConfig=null;let A=this.readyWaiter;if(!A)return;this.readyWaiter=null,A.resolve()}rejectReadyWaiter(A){this.clearReadyTimer(),this.readyTimeoutConfig=null;let Q=this.readyWaiter;if(!Q)return;this.readyWaiter=null,Q.reject(A)}reset(A){this.generation++,this.attempt=0,this.clearRetryTimer(),this.clearReadyTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}armReadyTimeout(){if(!this.readyTimeoutConfig||!this.readyWaiter)return;this.clearReadyTimer();let{timeoutMs:A,timeoutMessage:Q}=this.readyTimeoutConfig;this.readyTimer=setTimeout(()=>{this.readyTimer=null,this.rejectReadyWaiter(Error(Q))},A)}clearReadyTimer(){if(!this.readyTimer)return;clearTimeout(this.readyTimer),this.readyTimer=null}tryHandshake(A){if(this.disposed)return lB.info("Handshake manager ignored trigger while disposed",{trigger:A}),this.inFlight;if(this.inFlight)return lB.info("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;lB.info("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;lB.info("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=uF0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),$=B===null;if($)lB.error("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(),lB.info("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 Px4{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 F=()=>{this.activeTools.delete(Q)};try{let X=A;if(this.options.requestPluginToolCall&&this.options.threadID){let V=await this.requestPluginToolCall(A);if(Y.signal.aborted){F();return}if("shortCircuitRun"in V){this.prepareAndSendToolResult(A,V.shortCircuitRun,Z);return}X=V.lease}let D=await this.options.invokeTool(X);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?e$(U):void 0;if(K!==void 0&&!RW5(K)){let E=Wx(K,"snapshot"),W=OF0(Z.progress,E),z=Z.needsProgressSnapshot&&W.type==="snapshot"?W:fy4(Z.sentProgress,W);if(Z.progress=W,this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Q,progress:z}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Q,z),{toolCallId:Q}))Z.sentProgress=W,Z.needsProgressSnapshot=!1;else Z.needsProgressSnapshot=!0}if(V3(V.status))G.unsubscribe(),this.prepareAndSendToolResult(X,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){F();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(X,U,Z)}});Z.subscription=G}catch(X){this.options.log.error(`${this.clientID} tool execution setup failed: ${B}`,X);let D={status:"error",error:{message:X instanceof Error?X.message:String(X)}};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(),$=e$(Q),{run:J,files:Y}=this.extractGuidanceFromRun($),Z=this.prepareGuidanceDiscoveryBatches(A,Y),F={run:J,guidanceBatches:Z};this.pendingTerminalResults.set(A,F),this.sendPendingTerminalResult(A,F,"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:ds0(Y.content)}}),$=this.options.guidanceContentCache,J=$?cs0(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((F)=>F.content!==void 0).map((F)=>F.uri),Z=$.filter((F)=>F.content===void 0).map((F)=>F.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(ps0(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=gy4(Q.discoveredGuidanceFiles),{discoveredGuidanceFiles:$,...J}=Q;return{run:{...A,result:J},files:B}}sendTransportMessage(A,Q,B){try{return Q(),!0}catch($){if($ instanceof I8)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 Vj{options;toolRunner;sentApprovalRequests;handshakeManager;runtimeLog;guidanceContentCache=new Bo;toolSyncSubscription;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(A){this.options=A;this.runtimeLog=this.options.log??{info:(Q,B)=>lB.info(Q,{...B,threadID:this.options.threadID}),error:(Q,B)=>lB.error(Q,{error:B,threadID:this.options.threadID}),wsMessage:(Q,B,$)=>{lB.info("websocket message",{direction:Q,clientID:B,threadID:this.options.threadID,...typeof $==="object"&&$!==null?$:{message:$}})}},this.toolSyncSubscription=this.options.toolService.tools.subscribe({next:(Q)=>{this.syncExecutorToolRegistrations(hs0(Q))}}),this.handshakeManager=new Rx4({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 Px4({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)}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=yF0({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.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=void 0,this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}syncExecutorToolRegistrations(A){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=jx4({transport:this.options.transport,nextTools:A,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:(B,$)=>{this.runtimeLog.wsMessage(B,this.options.clientID,$)}})}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)lB.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:Y}=await TW5({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 lB.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.")}}G9();async function hY(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 I2("/api/thread-actors",_x4({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 _x4(A,Q){if(!Q)return A;return{...A,headers:{...A?.headers,Authorization:`Bearer ${Q}`}}}async function Tx4(A,Q,B,$={}){let J={};if($.executorType)J.executorType=$.executorType;let Y=await I2(`/api/thread-actors/${A}`,_x4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),...$.signal?{signal:$.signal}:{}},B),Q);if(!Y.ok)throw Error(`Failed to mark thread ${A} as imported: ${Y.status} ${await Y.text()}`)}c0();c4();L1();function Sx4(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=Rv4(Q,B,null,{includeThinking:$});for(let F of Q.content)if(F.type==="tool_use")Y.add(F.id);return Z}function kx4(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 Pv4(Q,B,null)}function vx4(A){return A.inputDone&&A.assistantDone&&A.idleSinceLastSend&&A.agentIdle}var yx4=1048576;async function xx4(A){let{client:Q,observer:B,dependencies:$,threadID:J,userInput:Y,stdinInput:Z,agentMode:F,reasoningEffort:X,streamJsonThinking:D,streamJsonInput:G,stdin:V}=A;if(Z&&Z.length>yx4)throw Error(`Stdin input too large: ${Z.length} bytes (max ${yx4})`);let U=J,K=Date.now(),E=F??"smart",W=xW5($),z=null,H=()=>{return z??=yW5($,E),z},q=!1,N=!1,I=0,w="",C=!1,O=!0,R=new Set;return new Promise((S,T)=>{let f=[],h="pending",x=null,k=null,b=EF0(async(F0)=>{try{await F0()}catch(_0){j.error("stream-json-actors emit failed",{error:_0})}}),c=async(F0)=>{if(h==="emitted")return;let _0=await W;await fW5({sessionId:U,tools:F0,mcpServers:_0,agentMode:E,reasoningEffort:X}),h="emitted";let B0=f.splice(0);for(let K0 of B0)await xF(K0)},l=(F0)=>{if(h!=="pending")return;h="queued",x=F0,b(async()=>{await c(F0)})},g=(F0)=>{if(h!=="emitted"){f.push(F0);return}b(async()=>{await xF(F0)})},i=async()=>{if(h==="emitted")return;await c(x??await H())},d=vW5({onSuccess:async()=>{await b(async()=>{await i(),await bW5({sessionId:U,startTime:K,numTurns:I,result:w})}),S({threadID:J,outcome:"success"})},onError:async(F0)=>{await b(async()=>{await i(),await uW5({sessionId:U,startTime:K,numTurns:I,error:F0})}),S({threadID:J,outcome:"error"})},onFatal:(F0)=>T(F0),cleanup:()=>{if(N)return;N=!0,k?.unsubscribe(),Q0.dispose()},isComplete:()=>N}),Q0=TF0({client:Q,observer:B,toolService:$.toolService,callbacks:{onError:(F0)=>{d.error(F0)},onTransitionToIdle:(F0)=>{if(F0.length>0){hW5({client:Q,approvals:F0,complete:d});return}if(Q0.agentIdle())O=!0;H0()},onMessageAdded:(F0)=>{if(F0.parentToolUseId)return;let _0=F0.message;if(_0.role==="assistant"){let B0=Sx4({message:_0,sessionId:U,streamJsonThinking:D,currentTurnAssistantIds:Q0.currentTurnAssistantIds,currentTurnToolUseIds:R});if(!B0)return;if(g(B0),I++,B0.message.stop_reason==="end_turn")w=U8(_0.content),C=!0,H0()}else if(_0.role==="user"){let B0=kx4({message:_0,sessionId:U,currentTurnToolUseIds:R});if(!B0)return;g(B0)}},onSignal:()=>{d.error("User cancelled (SIGINT/SIGTERM)")}}});k=B.inferenceTools$.subscribe((F0)=>{if(F0.parentToolCallId)return;l(F0.tools)});let H0=()=>{if(N)return;if(vx4({inputDone:q,assistantDone:C,idleSinceLastSend:O,agentIdle:Q0.agentIdle()}))d.success()},a=(F0,_0)=>{O=!1,Q.sendUserMessage(F0,E,_0)};if(G){(async()=>{try{for await(let F0 of WF0(V)){if(N)break;a(F0.contentBlocks,gW5(F0))}q=!0,H0()}catch(F0){d.error(qU(F0))}})();return}let I0=[{type:"text",text:Y}];if(Z)I0.unshift({type:"text",text:`Input received on stdin:
|
|
4704
|
+
`).length,hash:ds0(U.content)})),X=Y?cs0(F,Y):F,D=crypto.randomUUID(),G=B.userConfigDir?u1(B.userConfigDir):void 0;if(X.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=Lx4(X,D,G);for(let U=0;U<V.length;U++){let K=V[U];if(!K)continue;let E=U===V.length-1,W=K.filter((H)=>H.content!==void 0).map((H)=>H.uri),z=K.filter((H)=>H.content===void 0).map((H)=>H.uri);J?.("SEND",{type:"executor_guidance_snapshot",snapshotId:D,fileCount:K.length,withContent:W,contentOmitted:z,isLast:E}),A.sendExecutorGuidanceSnapshot({snapshotId:D,files:K,isLast:E,userConfigDir:G})}}async function kW5(A,Q,B){let[$,J]=await Promise.all([Q.getSkills(),Q.getSkillErrors()]),Y=crypto.randomUUID(),Z=20,F=$.map((D)=>({name:D.name,description:D.description,baseDir:D.baseDir,frontmatter:D.frontmatter,files:D.files,source:D.source})),X=J.map((D)=>({path:D.path,error:D.error,...D.hint?{hint:D.hint}:{}}));if(F.length===0){B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:0,errorCount:X.length,isLast:!0}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:[],isLast:!0,errors:X});return}for(let D=0;D<F.length;D+=20){let G=F.slice(D,D+20),V=D+20>=F.length;B?.("SEND",{type:"executor_skill_snapshot",snapshotId:Y,skillCount:G.length,...V?{errorCount:X.length}:{},isLast:V}),A.sendExecutorSkillSnapshot({snapshotId:Y,skills:G,isLast:V,...V?{errors:X}:{}})}}class Rx4{options;inFlight=null;readyWaiter=null;retryTimer=null;readyTimer=null;readyTimeoutConfig=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(A){this.options=A;this.baseDelayMs=A.baseDelayMs??Mx.baseDelayMs,this.maxDelayMs=A.maxDelayMs??Mx.maxDelayMs,this.maxAttempts=A.maxAttempts??Mx.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=PW5();if(A?.timeoutMs)this.readyTimeoutConfig={timeoutMs:A.timeoutMs,timeoutMessage:A.timeoutMessage??`Timed out waiting for handshake after ${A.timeoutMs}ms`},this.armReadyTimeout();return this.tryHandshake("connect"),this.readyWaiter.promise}handleConnectionChange(A){let Q=this.lastInfo;this.lastInfo=A;let B=A.state!=="connected"?"reset_disconnected":A.role==="executor"?"mark_ready":"ensure_handshake";if(lB.info("Handshake manager handling connection change",{action:B,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}if(!Q||Q.state!=="connected")this.armReadyTimeout();this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.clearReadyTimer(),this.readyTimeoutConfig=null,this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){this.clearReadyTimer(),this.readyTimeoutConfig=null;let A=this.readyWaiter;if(!A)return;this.readyWaiter=null,A.resolve()}rejectReadyWaiter(A){this.clearReadyTimer(),this.readyTimeoutConfig=null;let Q=this.readyWaiter;if(!Q)return;this.readyWaiter=null,Q.reject(A)}reset(A){this.generation++,this.attempt=0,this.clearRetryTimer(),this.clearReadyTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}armReadyTimeout(){if(!this.readyTimeoutConfig||!this.readyWaiter)return;this.clearReadyTimer();let{timeoutMs:A,timeoutMessage:Q}=this.readyTimeoutConfig;this.readyTimer=setTimeout(()=>{this.readyTimer=null,this.rejectReadyWaiter(Error(Q))},A)}clearReadyTimer(){if(!this.readyTimer)return;clearTimeout(this.readyTimer),this.readyTimer=null}tryHandshake(A){if(this.disposed)return lB.info("Handshake manager ignored trigger while disposed",{trigger:A}),this.inFlight;if(this.inFlight)return lB.info("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;lB.info("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;lB.info("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=uF0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),$=B===null;if($)lB.error("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(),lB.info("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 Px4{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 F=()=>{this.activeTools.delete(Q)};try{let X=A;if(this.options.requestPluginToolCall&&this.options.threadId){let V=await this.requestPluginToolCall(A);if(Y.signal.aborted){F();return}if("shortCircuitRun"in V){this.prepareAndSendToolResult(A,V.shortCircuitRun,Z);return}X=V.lease}let D=await this.options.invokeTool(X);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?e$(U):void 0;if(K!==void 0&&!RW5(K)){let E=Wx(K,"snapshot"),W=OF0(Z.progress,E),z=Z.needsProgressSnapshot&&W.type==="snapshot"?W:fy4(Z.sentProgress,W);if(Z.progress=W,this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Q,progress:z}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Q,z),{toolCallId:Q}))Z.sentProgress=W,Z.needsProgressSnapshot=!1;else Z.needsProgressSnapshot=!0}if(V3(V.status))G.unsubscribe(),this.prepareAndSendToolResult(X,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){F();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(X,U,Z)}});Z.subscription=G}catch(X){this.options.log.error(`${this.clientID} tool execution setup failed: ${B}`,X);let D={status:"error",error:{message:X instanceof Error?X.message:String(X)}};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(),$=e$(Q),{run:J,files:Y}=this.extractGuidanceFromRun($),Z=this.prepareGuidanceDiscoveryBatches(A,Y),F={run:J,guidanceBatches:Z};this.pendingTerminalResults.set(A,F),this.sendPendingTerminalResult(A,F,"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:ds0(Y.content)}}),$=this.options.guidanceContentCache,J=$?cs0(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((F)=>F.content!==void 0).map((F)=>F.uri),Z=$.filter((F)=>F.content===void 0).map((F)=>F.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(ps0(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=gy4(Q.discoveredGuidanceFiles),{discoveredGuidanceFiles:$,...J}=Q;return{run:{...A,result:J},files:B}}sendTransportMessage(A,Q,B){try{return Q(),!0}catch($){if($ instanceof I8)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 Vj{options;toolRunner;sentApprovalRequests;handshakeManager;runtimeLog;guidanceContentCache=new Bo;toolSyncSubscription;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(A){this.options=A;this.runtimeLog=this.options.log??{info:(Q,B)=>lB.info(Q,{...B,threadId:this.options.threadId}),error:(Q,B)=>lB.error(Q,{error:B,threadId:this.options.threadId}),wsMessage:(Q,B,$)=>{lB.info("websocket message",{direction:Q,clientID:B,threadId:this.options.threadId,...typeof $==="object"&&$!==null?$:{message:$}})}},this.toolSyncSubscription=this.options.toolService.tools.subscribe({next:(Q)=>{this.syncExecutorToolRegistrations(hs0(Q))}}),this.handshakeManager=new Rx4({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 Px4({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)}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=yF0({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.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=void 0,this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}syncExecutorToolRegistrations(A){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=jx4({transport:this.options.transport,nextTools:A,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:(B,$)=>{this.runtimeLog.wsMessage(B,this.options.clientID,$)}})}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)lB.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:Y}=await TW5({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 lB.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.")}}G9();async function hY(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 I2("/api/thread-actors",_x4({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 _x4(A,Q){if(!Q)return A;return{...A,headers:{...A?.headers,Authorization:`Bearer ${Q}`}}}async function Tx4(A,Q,B,$={}){let J={};if($.executorType)J.executorType=$.executorType;let Y=await I2(`/api/thread-actors/${A}`,_x4({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),...$.signal?{signal:$.signal}:{}},B),Q);if(!Y.ok)throw Error(`Failed to mark thread ${A} as imported: ${Y.status} ${await Y.text()}`)}c0();c4();L1();function Sx4(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=Rv4(Q,B,null,{includeThinking:$});for(let F of Q.content)if(F.type==="tool_use")Y.add(F.id);return Z}function kx4(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 Pv4(Q,B,null)}function vx4(A){return A.inputDone&&A.assistantDone&&A.idleSinceLastSend&&A.agentIdle}var yx4=1048576;async function xx4(A){let{client:Q,observer:B,dependencies:$,threadID:J,userInput:Y,stdinInput:Z,agentMode:F,reasoningEffort:X,streamJsonThinking:D,streamJsonInput:G,stdin:V}=A;if(Z&&Z.length>yx4)throw Error(`Stdin input too large: ${Z.length} bytes (max ${yx4})`);let U=J,K=Date.now(),E=F??"smart",W=xW5($),z=null,H=()=>{return z??=yW5($,E),z},q=!1,N=!1,I=0,w="",C=!1,O=!0,R=new Set;return new Promise((S,T)=>{let f=[],h="pending",x=null,k=null,b=EF0(async(F0)=>{try{await F0()}catch(_0){j.error("stream-json-actors emit failed",{error:_0})}}),c=async(F0)=>{if(h==="emitted")return;let _0=await W;await fW5({sessionId:U,tools:F0,mcpServers:_0,agentMode:E,reasoningEffort:X}),h="emitted";let B0=f.splice(0);for(let K0 of B0)await xF(K0)},l=(F0)=>{if(h!=="pending")return;h="queued",x=F0,b(async()=>{await c(F0)})},g=(F0)=>{if(h!=="emitted"){f.push(F0);return}b(async()=>{await xF(F0)})},i=async()=>{if(h==="emitted")return;await c(x??await H())},d=vW5({onSuccess:async()=>{await b(async()=>{await i(),await bW5({sessionId:U,startTime:K,numTurns:I,result:w})}),S({threadID:J,outcome:"success"})},onError:async(F0)=>{await b(async()=>{await i(),await uW5({sessionId:U,startTime:K,numTurns:I,error:F0})}),S({threadID:J,outcome:"error"})},onFatal:(F0)=>T(F0),cleanup:()=>{if(N)return;N=!0,k?.unsubscribe(),Q0.dispose()},isComplete:()=>N}),Q0=TF0({client:Q,observer:B,toolService:$.toolService,callbacks:{onError:(F0)=>{d.error(F0)},onTransitionToIdle:(F0)=>{if(F0.length>0){hW5({client:Q,approvals:F0,complete:d});return}if(Q0.agentIdle())O=!0;H0()},onMessageAdded:(F0)=>{if(F0.parentToolUseId)return;let _0=F0.message;if(_0.role==="assistant"){let B0=Sx4({message:_0,sessionId:U,streamJsonThinking:D,currentTurnAssistantIds:Q0.currentTurnAssistantIds,currentTurnToolUseIds:R});if(!B0)return;if(g(B0),I++,B0.message.stop_reason==="end_turn")w=U8(_0.content),C=!0,H0()}else if(_0.role==="user"){let B0=kx4({message:_0,sessionId:U,currentTurnToolUseIds:R});if(!B0)return;g(B0)}},onSignal:()=>{d.error("User cancelled (SIGINT/SIGTERM)")}}});k=B.inferenceTools$.subscribe((F0)=>{if(F0.parentToolCallId)return;l(F0.tools)});let H0=()=>{if(N)return;if(vx4({inputDone:q,assistantDone:C,idleSinceLastSend:O,agentIdle:Q0.agentIdle()}))d.success()},a=(F0,_0)=>{O=!1,Q.sendUserMessage(F0,E,_0)};if(G){(async()=>{try{for await(let F0 of WF0(V)){if(N)break;a(F0.contentBlocks,gW5(F0))}q=!0,H0()}catch(F0){d.error(qU(F0))}})();return}let I0=[{type:"text",text:Y}];if(Z)I0.unshift({type:"text",text:`Input received on stdin:
|
|
4705
4705
|
\`\`\`
|
|
4706
4706
|
${Z}
|
|
4707
|
-
\`\`\``});try{a(I0),q=!0}catch(F0){d.error(qU(F0))}})}function vW5(A){let{onSuccess:Q,onError:B,onFatal:$,cleanup:J,isComplete:Y}=A;return{success:async()=>{if(Y())return;J();try{await Q()}catch(Z){$(Z)}},error:async(Z)=>{if(Y())return;J();try{await B(Z)}catch(F){$(F)}}}}async function yW5(A,Q){try{return(await y1(A.toolService.getTools(Q).pipe(p9(1),qB(5000)))).map(($)=>$.spec.name)}catch(B){return j.warn("Unable to obtain fallback tool list for system init message",{err:B}),[]}}async function xW5(A){try{return(await y1(A.mcpService.servers.pipe(p9(1),qB(5000)))).map((B)=>({name:B.name,status:B.status.type}))}catch(Q){return j.warn("Unable to obtain MCP server list for system init message",{err:Q}),[]}}async function fW5(A){let Q={type:"system",subtype:"init",cwd:process.cwd(),session_id:A.sessionId,tools:A.tools,mcp_servers:A.mcpServers,agent_mode:A.agentMode};if(A.reasoningEffort!==void 0)Q.reasoning_effort=A.reasoningEffort;await xF(Q)}async function bW5(A){let Q={type:"result",subtype:"success",duration_ms:Date.now()-A.startTime,is_error:!1,num_turns:A.numTurns,result:A.result,session_id:A.sessionId};await xF(Q)}async function uW5(A){let Q={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-A.startTime,is_error:!0,num_turns:A.numTurns,error:A.error,session_id:A.sessionId};await xF(Q)}function hW5(A){let{client:Q,approvals:B,complete:$}=A;for(let Z of B)try{Q.resolveToolApproval(Z.toolUseId,!1,{denyFeedback:"stream-json execute-mode rejected blocked approval"})}catch(F){j.warn("Failed to resolve blocked approval",{error:F})}let J=[...new Set(B.map((Z)=>Z.toolName))],Y=J.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";$.error(Y)}function gW5(A){return A.steer!==void 0?{steer:A.steer}:void 0}aX();LY0();Cc();Rn0();MV();c4();s1();L1();async function aN(A){let{toolName:Q,dtwArtifactSyncService:B,configService:$,toolService:J,mcpService:Y,skillService:Z,fsTracker:F,toolUseID:X,discoveredGuidanceFileURIs:D,
|
|
4707
|
+
\`\`\``});try{a(I0),q=!0}catch(F0){d.error(qU(F0))}})}function vW5(A){let{onSuccess:Q,onError:B,onFatal:$,cleanup:J,isComplete:Y}=A;return{success:async()=>{if(Y())return;J();try{await Q()}catch(Z){$(Z)}},error:async(Z)=>{if(Y())return;J();try{await B(Z)}catch(F){$(F)}}}}async function yW5(A,Q){try{return(await y1(A.toolService.getTools(Q).pipe(p9(1),qB(5000)))).map(($)=>$.spec.name)}catch(B){return j.warn("Unable to obtain fallback tool list for system init message",{err:B}),[]}}async function xW5(A){try{return(await y1(A.mcpService.servers.pipe(p9(1),qB(5000)))).map((B)=>({name:B.name,status:B.status.type}))}catch(Q){return j.warn("Unable to obtain MCP server list for system init message",{err:Q}),[]}}async function fW5(A){let Q={type:"system",subtype:"init",cwd:process.cwd(),session_id:A.sessionId,tools:A.tools,mcp_servers:A.mcpServers,agent_mode:A.agentMode};if(A.reasoningEffort!==void 0)Q.reasoning_effort=A.reasoningEffort;await xF(Q)}async function bW5(A){let Q={type:"result",subtype:"success",duration_ms:Date.now()-A.startTime,is_error:!1,num_turns:A.numTurns,result:A.result,session_id:A.sessionId};await xF(Q)}async function uW5(A){let Q={type:"result",subtype:"error_during_execution",duration_ms:Date.now()-A.startTime,is_error:!0,num_turns:A.numTurns,error:A.error,session_id:A.sessionId};await xF(Q)}function hW5(A){let{client:Q,approvals:B,complete:$}=A;for(let Z of B)try{Q.resolveToolApproval(Z.toolUseId,!1,{denyFeedback:"stream-json execute-mode rejected blocked approval"})}catch(F){j.warn("Failed to resolve blocked approval",{error:F})}let J=[...new Set(B.map((Z)=>Z.toolName))],Y=J.length>0?`The following tools require user approval, which is not supported in stream JSON mode: ${J.join(", ")}`:"A tool requires user approval, which is not supported in stream JSON mode";$.error(Y)}function gW5(A){return A.steer!==void 0?{steer:A.steer}:void 0}aX();LY0();Cc();Rn0();MV();c4();s1();L1();async function aN(A){let{toolName:Q,dtwArtifactSyncService:B,configService:$,toolService:J,mcpService:Y,skillService:Z,fsTracker:F,toolUseID:X,discoveredGuidanceFileURIs:D,threadId:G}=A,V={id:G??p2(),created:Date.now(),v:0,messages:[]},U=s0.file(process.cwd()),K=X??gZ(),E=await $.getLatest(),W,z;if(F)W=F.trackedFileSystem(K),z=F.tracker;else z=CY0(Tu0,V.id,async()=>{}),W=Pn0(O3,z,K);let H=(q,N)=>tX({filesystem:W},q,N);return{dir:U,tool:Q,thread:V,dtwArtifactSyncService:B,trackedFiles:new RQ,toolUseID:K,todos:void 0,configService:$,toolService:J,mcpService:Y,config:E,filesystem:W,fileChangeTracker:z,getAllTrackedChanges:async()=>z.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>m0.of(V),get:()=>Promise.resolve(V),getPrimitiveProperty:(q,N)=>Promise.resolve(V[N]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),getEnvironmentData:H,threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:O3,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:Tu0,discoveredGuidanceFileURIs:D??new Set,skillService:Z??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}var fx4=45000;async function bx4(A){let{apiKey:Q,ampURL:B,workspaceRoot:$,dependencies:J,userInput:Y,stdinInput:Z,stats:F,streamJson:X,streamJsonThinking:D,streamJsonInput:G,stdin:V,agentMode:U,reasoningEffort:K,labels:E,initialThreadID:W,initialSettings:z}=A,H=process.env.RIVET_PUBLIC_ENDPOINT??yF(B),q=Ll(J.configService),N=async(S)=>{let T=await q.getThread(S);return T?kF0(T):null},I=new ux4,w=zx((S)=>hY(S,J.configService,Q,{...U?{agentMode:U}:{},executorType:"local-client"}),W),C=new IU({transport:Hx({rivetEndpoint:H,credentialsProvider:w,initialThreadID:W,pingIntervalMs:5000}),threadHistoryLoader:N,observerCallbacks:I}),O=lN.parse(`amp-x-${mW5()}`),R=null;try{let S=W?(await C.loadThreadHistory(W))?.version??0:0;await C.connect();let T=C.getThreadId();if(!T)throw new r7("Thread client connected without a thread ID");if(!W&&z)C.sendClientUpdateThreadSettings(z);if(R=new Vj({transport:C,toolService:J.toolService,configService:J.configService,clientID:O,threadId:T,pluginService:J.pluginService,requestPluginToolCall:(h)=>J.pluginService.event.toolCall(h),requestPluginToolResult:(h)=>J.pluginService.event.toolResult(h),invokeTool:async(h)=>{let x=typeof h.args==="object"&&h.args!==null?h.args:{},k=await aN({toolName:h.toolName,configService:J.configService,toolService:J.toolService,mcpService:J.mcpService,skillService:J.skillService,toolUseID:h.toolCallId,threadId:T});return J.toolService.invokeTool(h.toolName,{args:x},k)},readFileSystemDirectory:({uri:h})=>qx({fileSystem:J.fileSystem,workspaceRoot:$},h),skillService:J.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:$}),R.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),R.handleConnectionChange(C.getConnectionInfo()),await R.ensureReady({timeoutMs:fx4,timeoutMessage:`Timed out waiting for executor handshake after ${fx4}ms`}),C.resumeFromVersion(S),X){let h=await xx4({client:C,observer:I,dependencies:J,threadID:T,userInput:Y,stdinInput:Z,agentMode:U,reasoningEffort:K,streamJsonThinking:!!D,streamJsonInput:!!G,stdin:V??process.stdin});if(h.outcome==="success"&&E&&E.length>0)await Fj(h.threadID,E,J.configService);return h.threadID}let f=await pW5(C,I,J,Y,Z,U,F,T);if(E&&E.length>0)await Fj(f,E,J.configService);return f}finally{if(R)R.dispose();C.dispose()}}function pW5(A,Q,B,$,J,Y,Z,F){return new Promise((X,D)=>{let G=!1,V=()=>{if(G)return;G=!0,K.dispose(),X(F)},U=(W)=>{j.error("error",{error:W}),process.stderr.write(`Error: ${W}
|
|
4708
4708
|
`),V()},K=TF0({client:A,observer:Q,toolService:B.toolService,callbacks:{onError:U,onTransitionToIdle:(W)=>{if(W.length===0)return;dW5(A,W[0]),V()},onMessageAdded:(W)=>{if(W.parentToolUseId)return;let z=W.message;if(!K.agentStarted())return;if(z.role!=="assistant")return;if(!K.currentTurnAssistantIds.has(z.messageId))return;if(!z.state)return;if(z.content.some((q)=>q.type==="tool_use"))return;let H=z.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim();if(Z){let q=z.usage,N={result:H,usage:{input_tokens:q?.inputTokens||0,output_tokens:q?.outputTokens||0,cache_creation_input_tokens:q?.cacheCreationInputTokens||0,cache_read_input_tokens:q?.cacheReadInputTokens||0}};process.stdout.write(`${JSON.stringify(N)}
|
|
4709
4709
|
`)}else if(H)process.stdout.write(`${H}
|
|
4710
4710
|
`);V()},onSignal:V}}),E=[{type:"text",text:$}];if(J)E.unshift({type:"text",text:`Input received on stdin:
|
|
@@ -5157,7 +5157,7 @@ password=${Y}
|
|
|
5157
5157
|
... (truncated ${Q.length-iF0} chars)`);return Q}function Qt0(A){if(typeof A!=="object"||A===null)return A;if(Array.isArray(A))return A.map(Qt0);let Q={};for(let[B,$]of Object.entries(A))if(typeof $==="string"&&$.length>iF0)Q[B]=`<${$.length} chars>`;else if(typeof $==="object"&&$!==null)Q[B]=Qt0($);else Q[B]=$;return Q}function Kj(A,Q,B){let $=Qt0(B);if(Do.info("websocket message",{direction:A,clientId:Q,...typeof $==="object"&&$!==null?$:{message:$}}),!$t0)return;let J=o0.dim(`[${Bt0()}]`),Y=o0.magenta(`[${Q}]`),Z=A==="SEND"?o0.green(">>>"):o0.yellow("<<<"),F=Jt0($);process.stderr.write(`${J} ${Y} ${Z} ${F}
|
|
5158
5158
|
`)}function B9(A,Q){if(Q)Do.info(A,Q);else Do.info(A);if(!$t0)return;let B=o0.dim(`[${Bt0()}]`),$=o0.cyan("[INFO]"),J=Q?` ${Jt0(Q)}`:"";process.stderr.write(`${B} ${$} ${A}${J}
|
|
5159
5159
|
`)}function MW(A,Q){if(Q!==void 0)Do.error(A,{error:Q});else Do.error(A);if(!$t0)return;let B=o0.dim(`[${Bt0()}]`),$=o0.red("[ERROR]"),J=Jt0(Q);process.stderr.write(`${B} ${$} ${A} ${J}
|
|
5160
|
-
`)}function dz5(A,Q){let B=new URL(A);if(!B.pathname.endsWith("/"))B.pathname+="/";return new URL(`threads/${Q}`,B).toString()}class Df4{options;client=null;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(A){this.options=A}bindClientThread(A,Q){let B=A.threadId!==Q;if(A.threadId=Q,A.fsTracker&&!B)return;let $=this.options.fileSystem??O3,J=new EL($);A.fsTracker=MY0({fileChangeTrackerStorage:J},$,Q)}async connectTransport(A,Q,B){let $=await A.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:Xf4});if(!$){let J=A.getConnectionInfo();B9(`${Q} waiting for reconnect during ${B}`,{connectionState:J.state,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,waitedMs:Xf4})}return $}async recoverTransport(A,Q,B,$){let J=this.client;if(!J||J.recoveringTransport||this.disposed)return;J.recoveringTransport=!0,B9(`${A} recovering transport after send failure`,{messageType:Q,error:B.message,...$});try{let Y=J.transport.getConnectionInfo();if(Y.state==="connecting"||Y.state==="authenticating"||Y.state==="reconnecting"){B9(`${A} recovery waiting for in-flight connection`,{connectionState:Y.state,reconnectCauseType:Y.reconnectCause?.type,reconnectCauseCode:Y.reconnectCause?.code,reconnectCauseReason:Y.reconnectCause?.reason});return}if(Y.state==="connected")J.transport.disconnect();let Z=await this.connectTransport(J.transport,A,"recovery"),F=J.transport.getThreadId();if(F)this.bindClientThread(J,F);if(!Z)return;let X=J.transport.getConnectionInfo();B9(`${A} requesting executor handshake after transport recovery`,{trigger:"retry",connectionState:X.state,role:X.role,transportClientId:X.clientId}),J.executorRuntime.ensureHandshake("retry")}catch(Y){MW(`${A} transport recovery failed`,Y)}finally{J.recoveringTransport=!1}}async start(){B9("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let A=await this.createClient(this.options.threadId);B9("Initial client created",{clientId:A.id,threadId:A.threadId}),this.logThreadURL(A.threadId);let Q=await this.runLoop();if(Q!==0)throw Error(`Headless DTW harness exited with code ${Q}`)}catch(A){throw MW("Failed to start harness",A),A}}logThreadURL(A){if(!A)return;let Q=dz5(this.options.ampURL,A);B9(`Thread URL: ${o0.blue.underline(Q)}`)}async shutdown(A,Q){if(this.pendingExitCode===null||A>this.pendingExitCode)this.pendingExitCode=A;let B=this.resolveRunLoop;if(B)this.resolveRunLoop=null;if(!this.disposed){if(A===0)B9(Q);else MW(Q);await this.dispose()}if(B){let $=this.pendingExitCode??A;this.pendingExitCode=null,B($)}}async invokeToolForClient(A,Q){let{toolService:B,configService:$,mcpService:J,skillService:Y}=this.options;if(!B||!$||!J)throw Error("Tool service not available");let{toolName:Z,toolCallId:F,args:X}=Q,D=typeof X==="object"&&X!==null?X:{},V=await aN({toolName:Z,dtwArtifactSyncService:{upsertArtifact:(U,K)=>{let E=l3.safeParse(K);A.transport.sendExecutorArtifactUpsert(U,E.success?E.data:void 0)},deleteArtifact:(U)=>{A.transport.sendExecutorArtifactDelete(U)}},configService:$,toolService:B,mcpService:J,skillService:Y,fsTracker:A.fsTracker??void 0,toolUseID:F,discoveredGuidanceFileURIs:A.toolRunner.discoveredGuidanceFileURIs,threadID:A.threadId});return B.invokeTool(Z,{args:D},V)}async createClient(A){let Q=`cli-headless-${crypto.randomUUID()}`,B={current:null},$=()=>{let N=B.current;if(!N)throw Error("Headless client callbacks invoked before initialization");return N},J=process.env.RIVET_PUBLIC_ENDPOINT??yF(this.options.ampURL);B9(`Creating client ${Q}`,{threadId:A,rivetPublicEndpoint:J,options:this.options});let Y=HU({endpoint:J}),Z={threadId:A,webSocketProvider:async()=>{return{webSocket:await Y.threadActor.getOrCreate([A],{params:{apiKey:this.options.apiKey,threadId:A,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:A,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/",void 0,{skipReadyWait:!0}),threadId:A}},maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000},F=null,{toolService:X}=this.options,D=new At0({clientID:Q,logWsMessage:Kj,logInfo:B9,logError:MW,overrides:{onConnectionChanged:(N)=>{let I=$();B9(`${Q} forwarding connection change to executor runtime`,{...N});let w=U.getThreadId();if(N.state==="connected"&&w)this.bindClientThread(I,w);I.executorRuntime.handleConnectionChange(N)},onExecutorToolApprovalResponse:(N)=>{if(!X){MW(`${Q} received approval response without tool service`);return}B9(`${Q} approval resolved`,{toolCallId:N.toolCallId,accepted:N.accepted}),X.resolveApproval(N.toolCallId,N.accepted,N.input?.denyFeedback)}}}),G=null,V=this.options.pluginService?yF0({pluginService:this.options.pluginService,sendPluginMessage:(N)=>G?.(N)}):void 0,U=new IU({transport:Z,threadHistoryLoader:async()=>null,observerCallbacks:D,executorCallbacks:{onToolLease:(N)=>{F?.onToolLeaseMessage(N)},onToolLeaseRevoked:(N)=>{F?.onToolLeaseRevokedMessage(N)},onFileSystemReadDirectoryRequest:(N)=>{F?.onExecutorFileSystemReadDirectoryRequestMessage(N)},onFileSystemReadFileRequest:(N)=>{F?.onExecutorFileSystemReadFileRequestMessage(N)},...V?{onPluginMessage:V}:{}}});G=(N)=>U.sendPluginMessage(N);let K=(N)=>({...N??{},threadId:A}),E={info:(N,I)=>{B9(N,K(I))},error:(N,I)=>{MW(N,I)},wsMessage:(N,I,w)=>{Kj(N,I,K(typeof w==="object"&&w!==null?w:{message:w}))}};F=new Vj({transport:U,toolService:this.options.toolService,configService:this.options.configService,clientID:Q,threadID:A,invokeTool:(N)=>this.invokeToolForClient($(),N),skillService:this.options.skillService,fileSystem:this.options.fileSystem,bootstrapLogMessage:(N,I)=>{Kj(N,Q,I)},initialToolDiscovery:this.options.initialToolDiscovery,onBootstrapSuccess:async()=>{let N=$();if(!N.hasLoggedPostBootstrapThreadURL&&N.threadId)this.logThreadURL(N.threadId),N.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(N),this.bootstrapPluginsAfterExecutorConnect(N)},sendGitSnapshot:!0,executorType:"sandbox",workspaceRoot:this.options.workspaceRoot,handshakeManagerOptions:{onError:({error:N,attempt:I,delayMs:w})=>{MW(`${Q} executor handshake failed`,{error:N,attempt:I,delayMs:w})},onExhausted:({error:N,maxAttempts:I})=>{this.shutdown(1,`${Q} executor handshake failed after ${I} attempts: ${N instanceof Error?N.message:String(N)}`)}},captureGitStatus:()=>bF0(this.options.workspaceRoot),batchGuidanceFiles:Ox4,renderToolRunError:ih0,onTransportSendFailure:(N,I,w,C)=>{this.recoverTransport(N,I,w,C)},log:E,autoResolvePendingApprovals:!1,handleExecutorFileSystemReadDirectoryRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadDirectoryRequest(I,N)},handleExecutorFileSystemReadFileRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadFileRequest(I,N)},logInboundExecutorMessages:!0});let W={id:Q,transport:U,threadId:A,hasLoggedPostBootstrapThreadURL:!1,executorRuntime:F,toolRunner:F.toolRunner,fsTracker:null,recoveringTransport:!1};B.current=W,this.client=W;let z=U.getConnectionInfo();B9(`${Q} seeding executor runtime with initial connection info`,{connectionState:z.state,role:z.role,transportClientId:z.clientId,reconnectCauseType:z.reconnectCause?.type,reconnectCauseCode:z.reconnectCause?.code,reconnectCauseReason:z.reconnectCause?.reason}),F.handleConnectionChange(z),this.subscribeToApprovalRequests(W),B9(`Connecting ${Q}...`);let H=await this.connectTransport(U,Q,"startup"),q=U.getThreadId();if(q)this.bindClientThread(W,q);if(H)B9(`Connected ${Q}`,{threadId:q});if(H)W.executorRuntime.ensureHandshake("connect");return W}setNotifyForwarder(A){let Q=this.options.pluginPlatform;if(!Q)return;Q.setNotifyForwarder(async(B)=>{let $={type:"event",event:"ui.notify",data:{message:B}};try{Kj("SEND",A.id,{type:"executor_plugin_message",message:$}),A.transport.sendPluginMessage($)}catch(J){MW(`${A.id} failed to forward plugin notification`,J)}})}bootstrapPluginsAfterExecutorConnect(A){let Q=this.options.pluginService;if(!Q)return;if(!this.pluginsBootstrapped)this.pluginsBootstrapped=!0,B9(`${A.id} reloading plugins after executor bootstrap`),Q.reload();try{A.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(B){MW(`${A.id} failed to advertise plugin readiness`,B)}}syncApprovalRequests(A,Q){if(!A.threadId)return;let B=Q.filter((J)=>J.threadId===A.threadId||J.mainThreadId===A.threadId),$=new Set(B.map(lF0));for(let J of[...A.toolRunner.sentApprovalRequests])if(!$.has(J))A.toolRunner.sentApprovalRequests.delete(J);for(let J of B){let Y=lF0(J);if(A.toolRunner.sentApprovalRequests.has(Y))continue;let Z=Ff4(J);Kj("SEND",A.id,{type:"executor_tool_approval_request",toolCallId:Z.toolCallId,toolName:Z.toolName}),A.transport.sendExecutorToolApprovalRequest(Z),A.toolRunner.sentApprovalRequests.add(Y)}}subscribeToApprovalRequests(A){let{toolService:Q}=this.options;if(Q)Q.pendingApprovals$.subscribe((B)=>{this.syncApprovalRequests(A,B)})}async handleExecutorFileSystemReadDirectoryRequest(A,Q){let B=await qx({fileSystem:this.options.fileSystem??O3,workspaceRoot:this.options.workspaceRoot},Q.uri);Kj("SEND",A.id,{type:"executor_filesystem_read_directory_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadDirectoryResult(Q.requestId,B)}async handleExecutorFileSystemReadFileRequest(A,Q){let B=await Zx4({fileSystem:this.options.fileSystem??O3,workspaceRoot:this.options.workspaceRoot},Q.uri);Kj("SEND",A.id,{type:"executor_filesystem_read_file_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadFileResult(Q.requestId,B)}async runLoop(){if(B9("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((A)=>{let Q=!1,B=(Y)=>{if(Q){B9(`Received ${Y} while shutdown is already in progress`);return}Q=!0,this.shutdown(0,`Received ${Y}, shutting down harness...`)},$=()=>B("SIGINT"),J=()=>B("SIGTERM");this.resolveRunLoop=(Y)=>{process.off("SIGINT",$),process.off("SIGTERM",J),A(Y)},process.on("SIGINT",$),process.on("SIGTERM",J)})}async dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);let A=this.client;if(A){if((await A.transport.disconnectAndWait()).status==="timeout")B9(`${A.id} timed out waiting for close acknowledgement before dispose`);A.transport.dispose(),A.executorRuntime.dispose()}this.client=null}}async function Gf4(A){let Q=await hY(A.threadId,A.configService,A.apiKey);await new Df4({...A,threadId:Q.threadId,ownerUserId:Q.ownerUserId,threadVersion:Q.threadVersion,agentMode:Q.agentMode}).start()}import{stderr as RD,stdin as cz5}from"node:process";import{createInterface as lz5}from"node:readline";import{stdout as Yt0}from"node:process";function Vf4(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function nF0(){return Yt0.isTTY&&Vf4()}function aF0(A=Yt0){A.write("\x07")}function Uf4(){if(!Yt0.isTTY)return!0;if(Vf4())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var oF0=[],Zt0=null;function Ft0(A){if(Zt0=A,A&&oF0.length>0){for(let Q of oF0)A(Q);oF0=[]}}function Kf4(A){return async(Q,B)=>{return new Promise(($,J)=>{let Y={serverName:A,authorizationUrl:Q,redirectUrl:B,resolve:$,reject:J};if(Zt0)Zt0(Y);else oF0.push(Y)})}}function Ef4(){return async(A,Q)=>{return RD.write(`
|
|
5160
|
+
`)}function dz5(A,Q){let B=new URL(A);if(!B.pathname.endsWith("/"))B.pathname+="/";return new URL(`threads/${Q}`,B).toString()}class Df4{options;client=null;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;resolveRunLoop=null;constructor(A){this.options=A}bindClientThread(A,Q){let B=A.threadId!==Q;if(A.threadId=Q,A.fsTracker&&!B)return;let $=this.options.fileSystem??O3,J=new EL($);A.fsTracker=MY0({fileChangeTrackerStorage:J},$,Q)}async connectTransport(A,Q,B){let $=await A.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:Xf4});if(!$){let J=A.getConnectionInfo();B9(`${Q} waiting for reconnect during ${B}`,{connectionState:J.state,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,waitedMs:Xf4})}return $}async recoverTransport(A,Q,B,$){let J=this.client;if(!J||J.recoveringTransport||this.disposed)return;J.recoveringTransport=!0,B9(`${A} recovering transport after send failure`,{messageType:Q,error:B.message,...$});try{let Y=J.transport.getConnectionInfo();if(Y.state==="connecting"||Y.state==="authenticating"||Y.state==="reconnecting"){B9(`${A} recovery waiting for in-flight connection`,{connectionState:Y.state,reconnectCauseType:Y.reconnectCause?.type,reconnectCauseCode:Y.reconnectCause?.code,reconnectCauseReason:Y.reconnectCause?.reason});return}if(Y.state==="connected")J.transport.disconnect();let Z=await this.connectTransport(J.transport,A,"recovery"),F=J.transport.getThreadId();if(F)this.bindClientThread(J,F);if(!Z)return;let X=J.transport.getConnectionInfo();B9(`${A} requesting executor handshake after transport recovery`,{trigger:"retry",connectionState:X.state,role:X.role,transportClientId:X.clientId}),J.executorRuntime.ensureHandshake("retry")}catch(Y){MW(`${A} transport recovery failed`,Y)}finally{J.recoveringTransport=!1}}async start(){B9("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null});try{let A=await this.createClient(this.options.threadId);B9("Initial client created",{clientId:A.id,threadId:A.threadId}),this.logThreadURL(A.threadId);let Q=await this.runLoop();if(Q!==0)throw Error(`Headless DTW harness exited with code ${Q}`)}catch(A){throw MW("Failed to start harness",A),A}}logThreadURL(A){if(!A)return;let Q=dz5(this.options.ampURL,A);B9(`Thread URL: ${o0.blue.underline(Q)}`)}async shutdown(A,Q){if(this.pendingExitCode===null||A>this.pendingExitCode)this.pendingExitCode=A;let B=this.resolveRunLoop;if(B)this.resolveRunLoop=null;if(!this.disposed){if(A===0)B9(Q);else MW(Q);await this.dispose()}if(B){let $=this.pendingExitCode??A;this.pendingExitCode=null,B($)}}async invokeToolForClient(A,Q){let{toolService:B,configService:$,mcpService:J,skillService:Y}=this.options;if(!B||!$||!J)throw Error("Tool service not available");let{toolName:Z,toolCallId:F,args:X}=Q,D=typeof X==="object"&&X!==null?X:{},V=await aN({toolName:Z,dtwArtifactSyncService:{upsertArtifact:(U,K)=>{let E=l3.safeParse(K);A.transport.sendExecutorArtifactUpsert(U,E.success?E.data:void 0)},deleteArtifact:(U)=>{A.transport.sendExecutorArtifactDelete(U)}},configService:$,toolService:B,mcpService:J,skillService:Y,fsTracker:A.fsTracker??void 0,toolUseID:F,discoveredGuidanceFileURIs:A.toolRunner.discoveredGuidanceFileURIs,threadId:A.threadId});return B.invokeTool(Z,{args:D},V)}async createClient(A){let Q=`cli-headless-${crypto.randomUUID()}`,B={current:null},$=()=>{let N=B.current;if(!N)throw Error("Headless client callbacks invoked before initialization");return N},J=process.env.RIVET_PUBLIC_ENDPOINT??yF(this.options.ampURL);B9(`Creating client ${Q}`,{threadId:A,rivetPublicEndpoint:J,options:this.options});let Y=HU({endpoint:J}),Z={threadId:A,webSocketProvider:async()=>{return{webSocket:await Y.threadActor.getOrCreate([A],{params:{apiKey:this.options.apiKey,threadId:A,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:A,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/",void 0,{skipReadyWait:!0}),threadId:A}},maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000},F=null,{toolService:X}=this.options,D=new At0({clientID:Q,logWsMessage:Kj,logInfo:B9,logError:MW,overrides:{onConnectionChanged:(N)=>{let I=$();B9(`${Q} forwarding connection change to executor runtime`,{...N});let w=U.getThreadId();if(N.state==="connected"&&w)this.bindClientThread(I,w);I.executorRuntime.handleConnectionChange(N)},onExecutorToolApprovalResponse:(N)=>{if(!X){MW(`${Q} received approval response without tool service`);return}B9(`${Q} approval resolved`,{toolCallId:N.toolCallId,accepted:N.accepted}),X.resolveApproval(N.toolCallId,N.accepted,N.input?.denyFeedback)}}}),G=null,V=this.options.pluginService?yF0({pluginService:this.options.pluginService,sendPluginMessage:(N)=>G?.(N)}):void 0,U=new IU({transport:Z,threadHistoryLoader:async()=>null,observerCallbacks:D,executorCallbacks:{onToolLease:(N)=>{F?.onToolLeaseMessage(N)},onToolLeaseRevoked:(N)=>{F?.onToolLeaseRevokedMessage(N)},onFileSystemReadDirectoryRequest:(N)=>{F?.onExecutorFileSystemReadDirectoryRequestMessage(N)},onFileSystemReadFileRequest:(N)=>{F?.onExecutorFileSystemReadFileRequestMessage(N)},...V?{onPluginMessage:V}:{}}});G=(N)=>U.sendPluginMessage(N);let K=(N)=>({...N??{},threadId:A}),E={info:(N,I)=>{B9(N,K(I))},error:(N,I)=>{MW(N,I)},wsMessage:(N,I,w)=>{Kj(N,I,K(typeof w==="object"&&w!==null?w:{message:w}))}};F=new Vj({transport:U,toolService:this.options.toolService,configService:this.options.configService,clientID:Q,threadId:A,invokeTool:(N)=>this.invokeToolForClient($(),N),skillService:this.options.skillService,fileSystem:this.options.fileSystem,bootstrapLogMessage:(N,I)=>{Kj(N,Q,I)},initialToolDiscovery:this.options.initialToolDiscovery,onBootstrapSuccess:async()=>{let N=$();if(!N.hasLoggedPostBootstrapThreadURL&&N.threadId)this.logThreadURL(N.threadId),N.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(N),this.bootstrapPluginsAfterExecutorConnect(N)},sendGitSnapshot:!0,executorType:"sandbox",workspaceRoot:this.options.workspaceRoot,handshakeManagerOptions:{onError:({error:N,attempt:I,delayMs:w})=>{MW(`${Q} executor handshake failed`,{error:N,attempt:I,delayMs:w})},onExhausted:({error:N,maxAttempts:I})=>{this.shutdown(1,`${Q} executor handshake failed after ${I} attempts: ${N instanceof Error?N.message:String(N)}`)}},captureGitStatus:()=>bF0(this.options.workspaceRoot),batchGuidanceFiles:Ox4,renderToolRunError:ih0,onTransportSendFailure:(N,I,w,C)=>{this.recoverTransport(N,I,w,C)},log:E,autoResolvePendingApprovals:!1,handleExecutorFileSystemReadDirectoryRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadDirectoryRequest(I,N)},handleExecutorFileSystemReadFileRequest:async(N)=>{let I=$();await this.handleExecutorFileSystemReadFileRequest(I,N)},logInboundExecutorMessages:!0});let W={id:Q,transport:U,threadId:A,hasLoggedPostBootstrapThreadURL:!1,executorRuntime:F,toolRunner:F.toolRunner,fsTracker:null,recoveringTransport:!1};B.current=W,this.client=W;let z=U.getConnectionInfo();B9(`${Q} seeding executor runtime with initial connection info`,{connectionState:z.state,role:z.role,transportClientId:z.clientId,reconnectCauseType:z.reconnectCause?.type,reconnectCauseCode:z.reconnectCause?.code,reconnectCauseReason:z.reconnectCause?.reason}),F.handleConnectionChange(z),this.subscribeToApprovalRequests(W),B9(`Connecting ${Q}...`);let H=await this.connectTransport(U,Q,"startup"),q=U.getThreadId();if(q)this.bindClientThread(W,q);if(H)B9(`Connected ${Q}`,{threadId:q});if(H)W.executorRuntime.ensureHandshake("connect");return W}setNotifyForwarder(A){let Q=this.options.pluginPlatform;if(!Q)return;Q.setNotifyForwarder(async(B)=>{let $={type:"event",event:"ui.notify",data:{message:B}};try{Kj("SEND",A.id,{type:"executor_plugin_message",message:$}),A.transport.sendPluginMessage($)}catch(J){MW(`${A.id} failed to forward plugin notification`,J)}})}bootstrapPluginsAfterExecutorConnect(A){let Q=this.options.pluginService;if(!Q)return;if(!this.pluginsBootstrapped)this.pluginsBootstrapped=!0,B9(`${A.id} reloading plugins after executor bootstrap`),Q.reload();try{A.transport.sendPluginMessage({type:"event",event:"plugins.ready",data:{}})}catch(B){MW(`${A.id} failed to advertise plugin readiness`,B)}}syncApprovalRequests(A,Q){if(!A.threadId)return;let B=Q.filter((J)=>J.threadId===A.threadId||J.mainThreadId===A.threadId),$=new Set(B.map(lF0));for(let J of[...A.toolRunner.sentApprovalRequests])if(!$.has(J))A.toolRunner.sentApprovalRequests.delete(J);for(let J of B){let Y=lF0(J);if(A.toolRunner.sentApprovalRequests.has(Y))continue;let Z=Ff4(J);Kj("SEND",A.id,{type:"executor_tool_approval_request",toolCallId:Z.toolCallId,toolName:Z.toolName}),A.transport.sendExecutorToolApprovalRequest(Z),A.toolRunner.sentApprovalRequests.add(Y)}}subscribeToApprovalRequests(A){let{toolService:Q}=this.options;if(Q)Q.pendingApprovals$.subscribe((B)=>{this.syncApprovalRequests(A,B)})}async handleExecutorFileSystemReadDirectoryRequest(A,Q){let B=await qx({fileSystem:this.options.fileSystem??O3,workspaceRoot:this.options.workspaceRoot},Q.uri);Kj("SEND",A.id,{type:"executor_filesystem_read_directory_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadDirectoryResult(Q.requestId,B)}async handleExecutorFileSystemReadFileRequest(A,Q){let B=await Zx4({fileSystem:this.options.fileSystem??O3,workspaceRoot:this.options.workspaceRoot},Q.uri);Kj("SEND",A.id,{type:"executor_filesystem_read_file_result",requestId:Q.requestId,...B}),A.transport.sendExecutorFileSystemReadFileResult(Q.requestId,B)}async runLoop(){if(B9("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((A)=>{let Q=!1,B=(Y)=>{if(Q){B9(`Received ${Y} while shutdown is already in progress`);return}Q=!0,this.shutdown(0,`Received ${Y}, shutting down harness...`)},$=()=>B("SIGINT"),J=()=>B("SIGTERM");this.resolveRunLoop=(Y)=>{process.off("SIGINT",$),process.off("SIGTERM",J),A(Y)},process.on("SIGINT",$),process.on("SIGTERM",J)})}async dispose(){this.disposed=!0,this.options.pluginPlatform?.setNotifyForwarder(null);let A=this.client;if(A){if((await A.transport.disconnectAndWait()).status==="timeout")B9(`${A.id} timed out waiting for close acknowledgement before dispose`);A.transport.dispose(),A.executorRuntime.dispose()}this.client=null}}async function Gf4(A){let Q=await hY(A.threadId,A.configService,A.apiKey);await new Df4({...A,threadId:Q.threadId,ownerUserId:Q.ownerUserId,threadVersion:Q.threadVersion,agentMode:Q.agentMode}).start()}import{stderr as RD,stdin as cz5}from"node:process";import{createInterface as lz5}from"node:readline";import{stdout as Yt0}from"node:process";function Vf4(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function nF0(){return Yt0.isTTY&&Vf4()}function aF0(A=Yt0){A.write("\x07")}function Uf4(){if(!Yt0.isTTY)return!0;if(Vf4())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var oF0=[],Zt0=null;function Ft0(A){if(Zt0=A,A&&oF0.length>0){for(let Q of oF0)A(Q);oF0=[]}}function Kf4(A){return async(Q,B)=>{return new Promise(($,J)=>{let Y={serverName:A,authorizationUrl:Q,redirectUrl:B,resolve:$,reject:J};if(Zt0)Zt0(Y);else oF0.push(Y)})}}function Ef4(){return async(A,Q)=>{return RD.write(`
|
|
5161
5161
|
`),RD.write(o0.yellow.bold(`OAuth Authorization Required
|
|
5162
5162
|
`)),RD.write(o0.dim("─".repeat(60)+`
|
|
5163
5163
|
`)),RD.write(`
|
|
@@ -5288,12 +5288,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,X(Error(`Failed to spawn brew: ${K.message}`))}
|
|
|
5288
5288
|
${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
|
|
5289
5289
|
|
|
5290
5290
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
5291
|
-
npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}c0();c0();FN();async function $X0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Mo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],z=Date.now();if(E)U=Math.floor((z-new Date(E).getTime())/3600000);if(W)K=Math.floor((z-new Date(W).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(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Mq5="https://static.ampcode.com/cli/cli-version.txt";async function JX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Mq5}?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=Mo(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 Lq5=604800000;function Pb4(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>Lq5)return{ageMs:B};return null}function Mo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)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 St0(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?mV(B):void 0;return{sha:$,age:J}}catch{return null}}L1();c0();import{readFile as Oq5,realpath as jq5}from"node:fs/promises";import{homedir as Rq5}from"node:os";import{dirname as _b4,join as kt0}from"node:path";async function Tb4(A){switch(A){case"binary":case"brew":return Pq5(No());case"npm":case"pnpm":case"yarn":case"bun":return _q5();case"bootstrap":return Tq5()}}async function Pq5(A){let Q=await PD(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 _q5(){try{let A=process.argv[1];if(!A)return null;let Q=await jq5(A),B=_b4(_b4(Q));return await Sb4(kt0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Tq5(){try{let A=process.env.AMP_HOME??kt0(Rq5(),".amp");return await Sb4(kt0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Sb4(A){let Q=await Oq5(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 Sq5=3600000,kq5=5000;function vt0(A,Q,B={}){let $=new h4,J=$.pipe(nA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Sq5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await lV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await vq5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await lV(kq5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await lV(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function vq5(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 tN(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await JX0(A);else{let V=await Hj();X=await $X0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Tb4(Z);if(V&&Mo(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Mo(A,V)<0){let U=await LW(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(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.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!==No()){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 Co(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await LW(X.latestVersion),U={from:X.currentVersion,to:X.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}}FN();import{stderr as _D}from"node:process";function kb4(A){let Q=new yN().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 Nt0($.force||!1,$.verbose||!1,"0.0.
|
|
5291
|
+
npm install -g @sourcegraph/amp`;X(Error(W))}},error:(K)=>{if(!V)V=!0,X(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,F()}})})}c0();c0();FN();async function $X0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let F=await fetch(J,{signal:Y.signal});if(!F.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let X=await F.json(),D=X.version??X["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=Mo(A,D),V=G<0,U,K;if(X.time){let E=X.time[A],W=X.time[D],z=Date.now();if(E)U=Math.floor((z-new Date(E).getTime())/3600000);if(W)K=Math.floor((z-new Date(W).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(F){return j.debug("Error checking npm version",{error:F}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var Mq5="https://static.ampcode.com/cli/cli-version.txt";async function JX0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${Mq5}?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=Mo(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 Lq5=604800000;function Pb4(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>Lq5)return{ageMs:B};return null}function Mo(A,Q){let B=(Z)=>{let[F,X]=Z.split("-");return{parts:F?.split(".").map(Number)||[],label:X}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let F=$.parts[Z]||0,X=J.parts[Z]||0;if(F<X)return-1;if(F>X)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 St0(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?mV(B):void 0;return{sha:$,age:J}}catch{return null}}L1();c0();import{readFile as Oq5,realpath as jq5}from"node:fs/promises";import{homedir as Rq5}from"node:os";import{dirname as _b4,join as kt0}from"node:path";async function Tb4(A){switch(A){case"binary":case"brew":return Pq5(No());case"npm":case"pnpm":case"yarn":case"bun":return _q5();case"bootstrap":return Tq5()}}async function Pq5(A){let Q=await PD(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 _q5(){try{let A=process.argv[1];if(!A)return null;let Q=await jq5(A),B=_b4(_b4(Q));return await Sb4(kt0(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function Tq5(){try{let A=process.env.AMP_HOME??kt0(Rq5(),".amp");return await Sb4(kt0(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Sb4(A){let Q=await Oq5(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 Sq5=3600000,kq5=5000;function vt0(A,Q,B={}){let $=new h4,J=$.pipe(nA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??Sq5,F=!1,X=()=>{F=!0};return setImmediate(async()=>{let D=j.getChild("update");if(Y>0){if(await lV(Y),F)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!F){let U=await vq5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await lV(kq5),F)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!F){let W=Math.min(K,E);await lV(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:X}}async function vq5(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 tN(),F=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:F});let X;if(F)X=await JX0(A);else{let V=await Hj();X=await $X0(A,V)}if(!(X.latestVersion&&X.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Tb4(Z);if(V&&Mo(V,X.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:X.latestVersion}),J.updatedTo=V,Mo(A,V)<0){let U=await LW(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(X.currentVersionAge!==void 0&&X.latestVersionAge!==void 0){let V=X.currentVersionAge-X.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:X.currentVersionAge,latestVersionAge:X.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!==No()){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 Co(X.latestVersion,Z),J.updatedTo=X.latestVersion;let V=await LW(X.latestVersion),U={from:X.currentVersion,to:X.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}}FN();import{stderr as _D}from"node:process";function kb4(A){let Q=new yN().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 Nt0($.force||!1,$.verbose||!1,"0.0.1778171486-g3e6a89"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new yN("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 xq5($.targetVersion)});A.addCommand(B)}function yq5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
|
|
5292
5292
|
`),$=!1,B=0}function Y(Z){if(!Q)return;let F=Z.padEnd(B," ");A.write(`\r${F}`),$=!0,B=F.length}return{flushProgressLine:J,renderProgress:Y}}async function xq5(A){let B=process.platform==="win32"&&zj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=yq5(_D);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_D.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
5293
5293
|
|
|
5294
5294
|
`));try{if(!A){_D.write(o0.blue(`Checking for updates...
|
|
5295
|
-
`));let F=!1,X;if(zj()){let D=await JX0("0.0.
|
|
5296
|
-
`));let V=await LW("0.0.
|
|
5295
|
+
`));let F=!1,X;if(zj()){let D=await JX0("0.0.1778171486-g3e6a89");F=D.hasUpdate,X=D.latestVersion}else{let D=await Hj(),G=await $X0("0.0.1778171486-g3e6a89",D);F=G.hasUpdate,X=G.latestVersion}if(!F){let D=St0("0.0.1778171486-g3e6a89"),G=D?.age?`released ${D.age} ago`:`built ${mV(new Date("2026-05-07T16:34:46.143Z"))} ago`;_D.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1778171486-g3e6a89"} (${G})
|
|
5296
|
+
`));let V=await LW("0.0.1778171486-g3e6a89",B);if(V.warning)_D.write(`
|
|
5297
5297
|
`+o0.yellow(V.warning)+`
|
|
5298
5298
|
`);process.exit(0)}if(!X)_D.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);A=X}_D.write(o0.blue(`Updating to version ${A}...
|
|
5299
5299
|
`)),await Co(A,void 0,(F)=>{$(),_D.write(o0.dim(`Running: ${F}
|
|
@@ -5572,7 +5572,7 @@ Examples:
|
|
|
5572
5572
|
`),process.exit(0)}finally{await F.asyncDispose()}}catch(Z){process.stderr.write((Z instanceof Error?Z.message:String(Z))+`
|
|
5573
5573
|
`),process.exit(1)}})}function xC5(A,Q){if(Q.header&&Q.header.length>0)throw Error("HTTP headers cannot be used with command-based MCP servers. Use --env instead");let B,$,J=A.indexOf("--");if(J!==-1){let F=A.slice(J+1);if(F.length===0)throw Error("No command provided after -- separator");B=F[0],$=F.length>1?F.slice(1):void 0}else{if(Q.env&&Q.env.length>0&&A.length===0)throw Error("Environment variables provided but no command specified. Use: amp mcp add <name> --env KEY=VAL -- <command>");B=A[0],$=A.length>1?A.slice(1):void 0}let Z=fC5(Q.env||[]);return{command:B,args:$,env:Object.keys(Z).length>0?Z:void 0}}function Lh4(A,Q){return Q.concat(A)}function fC5(A){let Q={};for(let B of A){let $=B.indexOf("=");if($<=0)throw Error(`Invalid --env format: ${B}. Expected KEY=VALUE`);let J=B.slice(0,$),Y=B.slice($+1);if(J.trim()==="")throw Error(`Invalid --env format: ${B}. Expected KEY=VALUE`);if(Y==="")throw Error(`Invalid --env format: ${B}. Expected KEY=VALUE`);Q[J]=Y}return Q}function bC5(A){let Q={};for(let B of A){let $=B.indexOf("=");if($<=0)throw Error(`Invalid --header format: ${B}. Expected KEY=VALUE`);let J=B.slice(0,$),Y=B.slice($+1);if(Y==="")throw Error(`Invalid --header format: ${B}. Expected KEY=VALUE`);Q[J]=Y}return Q}function uC5(A){return"url"in A}function hC5(A){let Q=A.clientId??A.client_id,B=A.authUrl??A.authorizationUrl??A.auth_url??A.authorization_url,$=A.tokenUrl??A.token_url;if(!Q||!B||!$)return;return{clientId:Q,clientSecret:A.clientSecret??A.client_secret,authUrl:B,tokenUrl:$,scopes:A.scopes,redirectUrl:A.redirectUrl??A.redirect_url}}function gC5(A){if(!uC5(A))return A;let Q={url:A.url};if(A.headers)Q.headers=A.headers;if(A.transport)Q.transport=A.transport;if(A.oauth){let B=hC5(A.oauth);if(B)Q.oauth=B}return Q}function jh4(A){return Object.fromEntries(Object.entries(A).map(([Q,B])=>[Q,gC5(B)]))}wQ();var mC5=u.object({clientId:u.string().optional(),clientSecret:u.string().optional(),authUrl:u.string().optional(),authorizationUrl:u.string().optional(),tokenUrl:u.string().optional(),scopes:u.array(u.string()).optional(),redirectUrl:u.string().optional(),client_id:u.string().optional(),client_secret:u.string().optional(),auth_url:u.string().optional(),authorization_url:u.string().optional(),token_url:u.string().optional(),redirect_url:u.string().optional()}).refine((A)=>{let Q=A.clientId||A.client_id,B=A.authUrl||A.authorizationUrl||A.auth_url||A.authorization_url,$=A.tokenUrl||A.token_url;return Q&&B&&$},{message:"OAuth config requires clientId (or client_id), authUrl/authorizationUrl (or auth_url/authorization_url), and tokenUrl (or token_url)"}),pC5=u.object({command:u.string(),args:u.array(u.string()).optional(),env:u.record(u.string(),u.string()).optional()}).strict(),dC5=u.looseObject({url:u.string(),headers:u.record(u.string(),u.string()).optional(),transport:u.string().optional(),oauth:mC5.optional()}),cC5=u.union([pC5,dC5]),lC5=u.record(u.string(),cC5);async function Rh4(A){let Q;if(A.trim().startsWith("{"))Q=A;else{let{readFile:Y}=await import("node:fs/promises");try{Q=await Y(A,"utf-8")}catch(Z){throw new J4(`Failed to read --mcp-config file: ${Z instanceof Error?Z.message:String(Z)}`)}}let $;try{$=JSON.parse(Q)}catch(Y){throw new J4(`Failed to parse --mcp-config as JSON: ${Y instanceof Error?Y.message:String(Y)}`)}let J;try{J=lC5.parse($)}catch(Y){if(Y instanceof u.ZodError){let Z=Y.issues.map((F)=>`${F.path.join(".")}: ${F.message}`).join(", ");throw new J4(`Invalid MCP server configuration: ${Z}`)}throw new J4(`Failed to validate MCP server configuration: ${String(Y)}`)}return jh4(J)}function Ph4(A,Q){return{...A,async get(B,$){if(B!=="mcpServers")return A.get(B);let J=Object.fromEntries(Object.entries(Q).map(([F,X])=>[F,{...X,_target:"flag"}])),Y=await A.get(B,"global"),Z=await A.get(B,"workspace");if($==="global")return rF0({global:Y,override:J});else if($==="workspace")return Z;return rF0({global:Y,workspace:Z,override:J})},async keys(){let B=await A.keys();if(!B.includes("mcpServers"))B.push("mcpServers");return B}}}c0();L1();import{stderr as iC5}from"node:process";function Ke0(A,Q){A.onUntrustedWorkspaceServer=(B)=>{let $=Q.getSettingsFilePath();iC5.write(o0.yellow(`Warning: Untrusted MCP server '${B}' found in workspace settings.
|
|
5574
5574
|
To fix: Add "amp.mcpTrustedWorkspaces": ["${Q.getWorkspaceRootPath()}"] to ${$}
|
|
5575
|
-
`))}}class Ee0{mcpService;workspaceFolder;pendingServers=new Set;notificationTimeout;_pendingServersSubject=new Y4([]);serversSubscription;pendingServers$=this._pendingServersSubject;constructor(A,Q){this.mcpService=A;this.workspaceFolder=Q;this.setupListener()}setupListener(){this.mcpService.onUntrustedWorkspaceServer=(Q,B)=>{if(this.pendingServers.add(Q),this.notificationTimeout)clearTimeout(this.notificationTimeout);this.notificationTimeout=setTimeout(()=>{this._pendingServersSubject.next(Array.from(this.pendingServers)),this.notificationTimeout=void 0},700)};let A=this.mcpService.trustStore.changes?this.mcpService.trustStore.changes.pipe(K6(void 0)):m0.of(void 0);this.serversSubscription=P6(this.mcpService.servers,A).pipe(u4(([Q,B])=>IA(async()=>{let $=new Set;for(let J of Q)if(J.requiresApproval&&J.specHash){if(!await this.mcpService.trustStore.hasEntry?.({serverName:J.name,specHash:J.specHash}))$.add(J.name)}return $}))).subscribe((Q)=>{if(this.pendingServers.size===0)return;let B=!1,$=Array.from(this.pendingServers);for(let J of $)if(!Q.has(J))this.pendingServers.delete(J),B=!0;if(B)this._pendingServersSubject.next(Array.from(this.pendingServers))})}async trustAlways(){try{await this.mcpService.allowWorkspace(this.workspaceFolder);let A=Array.from(this.pendingServers);for(let Q of A)try{await this.mcpService.approveWorkspaceServer(Q)}catch(B){j.error("Failed to approve MCP server",{serverName:Q,error:B})}}catch(A){j.error("Failed to allow workspace",{error:A})}this.clear()}async trustOnce(A){try{await this.mcpService.approveWorkspaceServer(A),this.pendingServers.delete(A),this._pendingServersSubject.next(Array.from(this.pendingServers))}catch(Q){j.error("Failed to approve MCP server",{serverName:A,error:Q})}}async deny(){let A=Array.from(this.pendingServers);for(let Q of A)try{await this.mcpService.denyWorkspaceServer(Q)}catch(B){j.error("Failed to deny MCP server",{serverName:Q,error:B})}this.clear()}clear(){this.pendingServers.clear(),this._pendingServersSubject.next([])}dispose(){if(this.notificationTimeout)clearTimeout(this.notificationTimeout);if(this.serversSubscription)this.serversSubscription.unsubscribe()}}c0();dk();c0();L1();AE();K8();y7();async function hx(A){let Q=await A.getLatest();return v30(Q.settings)}function nC5(A){let Q=b3(A)?.reasoningEffort;return Q&&kX(A,Q)?Q:void 0}function We0(A,Q){let B=A.lastReasoningEffortByMode?.[Q];return B&&kX(Q,B)?B:void 0}function yX0(A){return A.explicitEffort??We0(A.sessionState,A.agentMode)??nC5(A.agentMode)}function xX0(A,Q){let B=yX0(Q);if(B===void 0)return A;return{...A,"reasoning.effort":B}}function aB(A){let Q=b3(A)?.primaryModel;if(!Q)return;let{provider:B,model:$}=x$(Q);if(B===a4.OPENAI&&$.startsWith("gpt-"))return"openai.speed";return}function fX0(A,Q){let B=A.lastSpeedByMode?.[Q];return B==="fast"||B==="standard"?B:void 0}function ze0(A,Q,B={}){let $={},J=Q["internal.model"]??B["internal.model"];if(J!==void 0)$["internal.model"]=J;if(Q["reasoning.effort"]!==void 0)$["reasoning.effort"]=Q["reasoning.effort"];return hH(A,$)}c0();K8();L1();var aC5="T-00000000-0000-0000-0000-000000000000";class bX0{projection=new RF0(aC5);transcriptEntries=[];transcriptListeners=new Set;transcriptReader={read:()=>this.transcriptEntries,subscribe:(A)=>{return this.transcriptListeners.add(A),()=>this.transcriptListeners.delete(A)}};_agentMode;_reasoningEffort=void 0;observerState;activeErrorPayload=null;activeErrorSeq=null;connectionErrorSubject=new Y4(null);activeErrorSubject=new Y4(null);agentMessageIdSubject=new Y4(null);cancelledSubject=new h4;queuedMessageRemovalSubject=new h4;transcriptRebuildBatchDepth=0;pendingTranscriptRebuildPreviousLength=null;log=j;constructor(A,Q=null){this._agentMode=A,this._reasoningEffort=hH(A,Q??{}),this.observerState=new _F0({initialAgentLoopState:"idle",initialThreadSettings:Q,dedupeQueuedMessageAdds:!1,compactionRecordsState:"idle"})}get agentMode(){return this._agentMode}set agentMode(A){if(this._agentMode===A)return;if(this._agentMode=A,this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}get reasoningEffort(){return this._reasoningEffort}reader(){return this.transcriptReader}protocolMessages(){return this.projection.protocolMessages()}agentState(){return this.observerState.agentLoopState}agentMessageId(){return this.agentMessageIdSubject}connectionInfo(){return this.observerState.connectionInfo}connectionError(){return this.connectionErrorSubject}setConnectionError(A){if(this.connectionErrorSubject.getValue()===A)return;this.connectionErrorSubject.next(A)}pendingSend(){return this.observerState.pendingSend}activeError(){return this.activeErrorSubject}cancelled(){return this.cancelledSubject}getActiveErrorSeq(){return this.activeErrorSeq}title(){return this.observerState.threadTitle}queuedMessages(){return this.observerState.queuedMessages}queuedMessageRemovalEvents(){return this.queuedMessageRemovalSubject}threadSettings(){return this.observerState.threadSettings}compactionState(){return this.observerState.compactionState}beginTranscriptRebuildBatch(){this.transcriptRebuildBatchDepth+=1}endTranscriptRebuildBatch(){if(this.transcriptRebuildBatchDepth===0)return;if(this.transcriptRebuildBatchDepth-=1,this.transcriptRebuildBatchDepth>0)return;let A=this.pendingTranscriptRebuildPreviousLength;if(this.pendingTranscriptRebuildPreviousLength=null,A!==null)this.rebuildTranscriptEntries(A)}dismissActiveError(){if(this.activeErrorPayload===null)return;this.activeErrorPayload=null,this.activeErrorSeq=null,this.activeErrorSubject.next(null)}onMessageAdded(A){this.log.info("[observer] onMessageAdded",{data:A}),this.applyThreadMessageEvent(A)}onMessageUpdated(A){this.log.info("[observer] onMessageUpdated",{data:A}),this.applyThreadMessageEvent(A)}onDelta(A){this.applyThreadMessageEvent(A)}onTruncate(A){this.log.info("[observer] onTruncate",{data:A}),this.applyThreadMessageEvent(A)}onAgentState(A){this.log.info("[observer] onAgentState",{data:A});let Q=cB(this.observerState.agentLoopState.getValue()),B=this._agentMode;if(A.agentMode!==void 0)this._agentMode=A.agentMode;this._reasoningEffort=A.reasoningEffort,this.agentMessageIdSubject.next(A.messageId??null),this.observerState.onAgentState(A);let $=cB(this.observerState.agentLoopState.getValue());if((B!==this._agentMode||Q!==$)&&this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}onThreadSettings(A){this.log.info("[observer] onThreadSettings",{data:A}),this.observerState.onThreadSettings(A)}onThreadId(A){this.log.info("[observer] onThreadId",{data:{threadId:A}}),this.log=j.with({threadId:A}),this.projection.setThreadID(A),this.observerState.onThreadId(A),this.observerState.threadId.complete()}onConnectionChanged(A){if(this.log.info("[observer] onConnectionChanged",{data:A}),this.observerState.onConnectionChanged(A),A.state==="connected")this.setConnectionError(null)}onQueuedMessages(A){this.log.info("[observer] onQueuedMessages",{data:A});let Q=A.type==="queued_message_removed"?this.observerState.queuedMessages.getValue().find((B)=>B.queuedMessage.messageId===A.queuedMessageId):void 0;if(this.observerState.onQueuedMessages(A),A.type==="queued_message_removed"&&Q!==void 0)this.queuedMessageRemovalSubject.next({message:Q,serverMessage:A})}onUserActionMessageDeliveryStatusChanged(A,Q,B){this.log.info("[observer] onUserActionMessageDeliveryStatusChanged",{data:{messageId:A,status:Q,sentAt:B}}),this.observerState.onUserActionMessageDeliveryStatusChanged(A,Q,B)}onUserMessageSendPending(A,Q){this.log.info("[observer] onUserMessageSendPending",{data:{messageId:A,sentAt:Q}}),this.observerState.onUserMessageSendPending(A,Q)}onErrorNotice(A){if(this.log.info("[observer] onErrorNotice",{data:A}),this.activeErrorPayload!==null)return;this.observerState.onErrorNotice(A)}onActiveError(A){if(this.log.info("[observer] onActiveError",{data:A}),this.observerState.onActiveError(A),A.type==="error_set")this.activeErrorPayload=A.error,this.activeErrorSeq=A.seq;else this.activeErrorPayload=null,this.activeErrorSeq=null;this.activeErrorSubject.next(this.activeErrorPayload)}onCancelled(A){this.log.info("[observer] onCancelled",{data:A}),this.observerState.onCancelled(A),this.cancelledSubject.next(A)}onToolProgress(A){this.log.info("[observer] onToolProgress",{data:A}),this.applyThreadMessageEvent(A)}onThreadTitle(A){this.log.info("[observer] onThreadTitle",{data:A}),this.observerState.onThreadTitle(A)}onCompactionEvent(A){this.log.info("[observer] onCompactionEvent",{data:A});let Q=A.type==="compaction_started"?"compacting":"idle";if(A.type==="compaction_started"&&this.observerState.compactionState.getValue()===Q)return;let B=this.transcriptEntries.length;if(this.observerState.onCompactionEvent(A),A.type==="compaction_complete"||A.type==="compaction_records")this.requestTranscriptRebuild(B)}applyThreadMessageEvent(A){let Q=this.transcriptEntries.length;if(!this.projection.apply(A).changed)return;this.requestTranscriptRebuild(Q)}requestTranscriptRebuild(A){if(this.transcriptRebuildBatchDepth===0){this.rebuildTranscriptEntries(A);return}this.pendingTranscriptRebuildPreviousLength=Math.min(this.pendingTranscriptRebuildPreviousLength??A,A)}rebuildTranscriptEntries(A){let Q=this.projection.buildTranscriptEntries({...Ay4(this._agentMode),isWorking:cB(this.observerState.agentLoopState.getValue()),compactionCutMessageIDs:this.observerState.compactionRecords.getValue().map((B)=>B.cutMessageId)});this.transcriptEntries.length=0,this.transcriptEntries.push(...Q),this.notifyTranscriptReaders(oC5(A,Q.length))}notifyTranscriptReaders(A){for(let Q of this.transcriptListeners)Q(A)}}function oC5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}var rC5=45000;class He0{rivetEndpoint;apiKey;configService;runtimeDependencies;loadThreadHistory;importThreadIntoActor;observingClients=[];_lastActiveObservingClient=null;connectionErrorSubject=new h4;constructor(A,Q,B,$,J,Y){this.rivetEndpoint=A;this.apiKey=Q;this.configService=B;this.runtimeDependencies=$;this.loadThreadHistory=J;this.importThreadIntoActor=Y}get lastActiveObservingClient(){return this._lastActiveObservingClient}get connectionErrors$(){return this.connectionErrorSubject}async connectToThread(A,Q={}){let B=Q.observerOnly??!1,$=this.observingClients.find((X)=>X.observerOnly===B&&(X.threadID===A||X.client.getThreadId()===A));if($)return this._lastActiveObservingClient=$,this.persistLastThreadID(A),$;let J=this.createClient({threadID:A}),Y=await J.loadThreadHistory(A);if(!Y)throw J.dispose(),new r7("Thread not found");if(Y.needsImport){if(!this.importThreadIntoActor)throw J.dispose(),new r7("Thread requires import before connecting");try{await this.importThreadIntoActor(A)}catch(X){throw J.dispose(),uX0(X)}}let Z=new bX0(Y.agentMode);Z.beginTranscriptRebuildBatch();try{J.setObserverCallbacks(Z)}finally{Z.endTranscriptRebuildBatch()}let F={client:J,observer:Z,threadID:A,logger:j.with({threadId:A}),observerOnly:B,connectionSubscription:PF0(J,{requireRole:B?void 0:"executor",onError:({threadID:X,error:D})=>this.emitConnectionError(Z,D,X)})};return this.connectAndResume(J,Y.version,{observerOnly:B}).catch((X)=>{this.emitConnectionError(Z,X,A),this.removeObservingClient(F)}),this.persistLastThreadID(A),this.observingClients.push(F),this._lastActiveObservingClient=F,F}createNewThread(A,Q,B){let $=this.createClient({agentMode:A,initialThreadMeta:B}),J=new bX0(A,Q??null);$.setObserverCallbacks(J);let Y={client:$,observer:J,threadID:null,logger:j,observerOnly:!1,connectionSubscription:PF0($,{requireRole:"executor",onError:({threadID:Z,error:F})=>this.emitConnectionError(J,F,Z)})};if(Q)$.sendClientUpdateThreadSettings(Q);else hx(this.configService).then((Z)=>{$.sendClientUpdateThreadSettings(Z)}).catch((Z)=>{j.warn("Failed to seed thread settings",{threadID:$.getThreadId(),error:Z instanceof Error?Z.message:String(Z)})});return this.observingClients.push(Y),this.connectAndResume($,0).then(({client:Z})=>{let F=Z.getThreadId();if(Y.threadID=F,F)Y.logger=j.with({threadId:F}),this.persistLastThreadID(F)}).catch((Z)=>{this.emitConnectionError(J,Z),this.removeObservingClient(Y)}),this._lastActiveObservingClient=Y,Y}dispose(){for(let{client:A,connectionSubscription:Q}of this.observingClients.values())Q.unsubscribe(),A.dispose();this.observingClients.length=0,this._lastActiveObservingClient=null,this.connectionErrorSubject.complete()}createClient(A={}){let{threadID:Q,agentMode:B,initialThreadMeta:$}=A,J=zx(async(Y)=>{try{let Z={agentMode:B,executorType:"local-client"};if(!Y&&$)Z.threadMeta=$;return await hY(Y,this.configService,this.apiKey,Z)}catch(Z){throw uX0(Z)}},Q);return new IU({transport:Hx({rivetEndpoint:this.rivetEndpoint,credentialsProvider:J,initialThreadID:Q,pingIntervalMs:5000}),threadHistoryLoader:this.loadThreadHistory})}async connectAndResume(A,Q,B={}){let $=B.observerOnly??!1,J=null;try{await A.connect();let Y=A.getThreadId();if(!Y)throw A.disconnect(),new r7("Thread client connected without a thread ID");if($)return A.resumeFromVersion(Q),{client:A,executor:null};return J=this.createExecutor(A,Y),await sC5(J,A),A.resumeFromVersion(Q),{client:A,executor:J}}catch(Y){if(A.disconnect(),J)J.dispose();throw uX0(Y)}}createExecutor(A,Q){return new Vj({transport:A,toolService:this.runtimeDependencies.toolService,configService:this.configService,clientID:this.runtimeDependencies.clientID,threadID:Q,invokeTool:(B)=>this.runtimeDependencies.invokeTool(Q,B),requestPluginToolCall:this.runtimeDependencies.requestPluginToolCall,requestPluginToolResult:this.runtimeDependencies.requestPluginToolResult,pluginService:this.runtimeDependencies.pluginService,readFileSystemDirectory:this.runtimeDependencies.readFileSystemDirectory,skillService:this.runtimeDependencies.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:process.cwd()})}emitConnectionError(A,Q,B){let $=uX0(Q);A.setConnectionError($.message),this.connectionErrorSubject.next({threadID:B??void 0,error:$})}removeObservingClient(A){A.connectionSubscription.unsubscribe();let Q=this.observingClients.indexOf(A);if(Q!==-1)this.observingClients.splice(Q,1);if(this._lastActiveObservingClient?.client===A.client)this._lastActiveObservingClient=null}persistLastThreadID(A){this.runtimeDependencies.persistLastThreadID(A).catch((Q)=>{j.warn("Failed to persist last active thread ID",{threadID:A,error:Q instanceof Error?Q.message:String(Q)})})}}async function sC5(A,Q){A.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),A.handleConnectionChange(Q.getConnectionInfo()),await A.ensureReady({timeoutMs:rC5,timeoutMessage:"Couldn’t connect to Amp servers — run amp: reconnect to retry"})}function uX0(A){if(A instanceof r7)return A;if(A instanceof Error){let Q=A.message||"Unknown connection error";return new r7(Q,A)}if(typeof A==="string"&&A.length>0)return new r7(A,A);return new r7("Unknown connection error",A)}async function _h4(A){let Q=yF(A.ampURL),B=HU({endpoint:Q}),$=await A.configService.getLatest(A.signal),J=await $.secrets.getToken("apiKey",$.settings.url);if(!J)throw Error("API key required. Please run `amp login` first.");let Y=await B.threadActor.get([A.threadID]).fetch("/skills",{method:"GET",headers:{Authorization:`Bearer ${J}`},signal:A.signal,skipReadyWait:!0});if(!Y.ok){let F=await Y.text();throw Error(`Skills request failed (${Y.status}): ${F}`)}let Z=await Y.json();if(!Z.ok)throw Error(Z.error);return{skills:Z.skills,errors:Z.errors}}fZ();c0();s1();L1();c0();MQ();function Th4(A,Q,B){let $=new h4,Y=(()=>{let K=new Map;return(E,W)=>{let H=(K.get(E)?.catch(()=>{})||Promise.resolve()).then(()=>W()).finally(()=>{if(K.get(E)===H)K.delete(E)});return K.set(E,H),H}})(),Z=B?X1.joinPath(Q,B):Q;function F(K){return X1.joinPath(Z,`${K.toString()}.json`)}async function X(K){let E=F(K);try{let W=await A.readBinaryFile(E),z=52428800;if(W.length>52428800){let H=Math.round(W.length/1048576);j.warn(`File too large to load safely: ${String(K)} (${H}MB)`,{key:String(K),size:W.length,maxSize:52428800});return}try{let H=W instanceof Uint8Array?W:new Uint8Array(W);return JSON.parse(new TextDecoder().decode(H))}catch(H){let q=H,{contentLength:N,contentPreview:I}=tC5(W);j.warn("Corrupted JSON detected.",{key:String(K),storageUri:Z.toString(),error:q.message,contentLength:N,contentPreview:I});return}}catch(W){if(v8(W))return;throw W}}async function D(K,E){let W=F(K),z=W.with({path:W.path+".amptmp"}),H=JSON.stringify(E,null,2);await A.mkdirp(X1.joinPath(W,"..")),await Y(K,async()=>{await A.writeFile(z,H),await A.rename(z,W)}),$.next(K)}async function G(K){let E=F(K);await Y(K,async()=>{await A.delete(E)}),$.next(K)}async function V(){let K;try{K=await A.readdir(Z)}catch(z){if(v8(z))return[];throw z}let E=K.filter((z)=>{let H=z.uri.path.split("/").pop()||"";return!z.isDirectory&&H.endsWith(".json")});return(await Promise.all(E.map(async(z)=>{let q=(z.uri.path.split("/").pop()||"").slice(0,-5);try{let N=await A.getMtime(z.uri);return{key:q,mtime:N}}catch(N){if(!v8(N))throw N;return null}}))).filter((z)=>z!==null).toSorted((z,H)=>H.mtime-z.mtime).map((z)=>z.key)}async function U(K){return F(K).fsPath}return{get:X,set:D,delete:G,keys:V,path:U,changes:$}}function tC5(A){try{let Q=A instanceof Uint8Array?A:new Uint8Array(A),B=new TextDecoder().decode(Q);return{contentLength:A.length,contentPreview:B.slice(0,128)}}catch{let Q=A instanceof Uint8Array?A:new Uint8Array(A),$=Array.from(Q.slice(0,64)).map((J)=>{if(J>=32&&J<=126)return String.fromCharCode(J);return`\\x${J.toString(16).padStart(2,"0")}`}).join("");return{contentLength:A.length,contentPreview:`${$}${A.length>64?"...":""}`}}}s1();var xD={agentMode:"smart",launchCount:0,shortcutsHintUsed:!1,neoWelcomeDismissed:!1};function kh4(A,Q){if(Q==="execute")return A.lastExecuteThreadId??A.lastThreadId;return A.lastThreadId}function hX0(A,Q,B){if(B==="execute")return{...A,lastExecuteThreadId:Q};return{...A,lastThreadId:Q}}function vh4(A){return{...A,neoWelcomeDismissed:!0}}function qe0(A={}){let Q=A.fs??O3,B=A.dataDir??CT;return Th4(Q,s0.file(B))}var yh4=qe0(),Sh4=Promise.resolve();async function DI(A={}){let Q=A.dataDir||A.fs?qe0(A):yh4;try{let B=await Q.get("session"),$={...xD,agentMode:B?.agentMode??xD.agentMode,launchCount:B?.launchCount??xD.launchCount,neoWelcomeDismissed:B?.neoWelcomeDismissed??xD.neoWelcomeDismissed,shortcutsHintUsed:B?.shortcutsHintUsed??xD.shortcutsHintUsed,lastThreadId:B?.lastThreadId,lastExecuteThreadId:B?.lastExecuteThreadId},J={...B?.lastReasoningEffortByMode};if(Object.keys(J).length>0)$.lastReasoningEffortByMode=J;let Y={...B?.lastSpeedByMode};if(Object.keys(Y).length>0)$.lastSpeedByMode=Y;return $}catch{return{...xD}}}async function eC5(A,Q){try{await Q.set("session",A)}catch(B){j.warn("Failed to save session state.",{error:B instanceof Error?B.message:String(B)})}}function AM5(A={}){return A.dataDir||A.fs?qe0(A):yh4}async function EJ(A,Q={}){let B=AM5(Q),$={...xD},J=Sh4.catch(()=>{return}).then(async()=>{let Y=await DI(Q);$={...xD,...A(Y)},await eC5($,B)});return Sh4=J.then(()=>{return},()=>{return}),await J,$}class Ne0{constructor(){}isEnabled(A){return!0}consumesKey(A){return!0}toString(){return`${this.constructor.name}()`}}class D4 extends Ne0{onInvoke;constructor(A){super();this.onInvoke=A}invoke(A){return this.onInvoke(A)}}function QM5(A){return"state"in A}function xh4(A,Q){let B=A.element.parent;while(B){if(QM5(B)&&B.state instanceof gX0){if(Q(B.state))return}B=B.parent}}class mX0{invokeAction(A,Q){let B=this.findAction(A,Q);if(B&&B.enabled)return B.action.invoke(A);return null}findAction(A,Q){let B=null;return xh4(Q,($)=>{let J=$.getActionForIntent(A);if(!J)return!1;return B={action:J,enabled:J.isEnabled(A)},!0}),B}}class t4 extends v0{actions;child;dispatcher;constructor({actions:A,child:Q,dispatcher:B,key:$}){super({key:$});this.actions=A,this.child=Q,this.dispatcher=B}createState(){return new gX0}static invoke(A,Q){return t4.of(A).invokeAction(Q,A)}static maybeInvoke(A,Q){try{return t4.invoke(A,Q)}catch{return null}}static find(A,Q){let B=t4.maybeFind(A,Q);if(!B){let $=Q?.constructor.name||"unknown";throw Error(`No action found for intent type: ${$}`)}return B}static maybeFind(A,Q){if(!Q)return null;let B=null;return xh4(A,($)=>{let J=$.getActionForIntent(Q);if(!J)return!1;return B=J,!0}),B}static of(A){let Q=A.findAncestorStateOfType(gX0);if(!Q)throw Error("No Actions widget found in context");return Q.dispatcher}static handler(A,Q){let B=t4.of(A).findAction(Q,A);if(B&&B.enabled)return()=>B.action.invoke(Q);return null}}class gX0 extends S0{dispatcher=new mX0;getActionForIntent(A){let Q=A.constructor;return this.widget.actions.get(Q)}build(A){return this.widget.child}}class l4{constructor(){}toString(){return`${this.constructor.name}()`}}class GI extends l4{constructor(){super()}}class ho extends l4{constructor(){super()}}class go extends l4{constructor(){super()}}class mo extends l4{constructor(){super()}}class po extends l4{constructor(){super()}}class VI extends l4{constructor(){super()}}class pX0 extends l4{constructor(){super()}}class co extends l4{constructor(){super()}}class gx extends l4{constructor(){super()}}class lo extends l4{constructor(){super()}}class mx extends l4{constructor(){super()}}class px extends l4{direction;constructor(A){super();this.direction=A}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class jj extends l4{constructor(){super()}}class TW extends l4{constructor(){super()}}function BM5(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let B=A.key.toLowerCase();if(["control","meta","alt","shift"].includes(B))return"";if(B===" ")B="space";return Q.push(B),Q.join("+")}function fh4(A){let Q=A.toLowerCase().split("+"),B=Q.pop()||"";return{modifiers:new Set(Q),key:B}}function bh4(A,Q){let B=fh4(A),$=fh4(Q);if(B.key!==$.key)return!1;for(let J of $.modifiers)if(!B.modifiers.has(J))return!1;if($.modifiers.size===0&&B.modifiers.size>0)return!1;return!0}class dx{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(A,Q={}){this.sequence=A,this.timeout=Q.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(A){let Q=BM5(A);if(!Q)return"none";let B=this.matchedKeys.length,$=this.sequence[B];if($&&bh4(Q,$)){if(this.matchedKeys.push($),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let J=this.sequence[0];if(J&&bh4(Q,J))return this.matchedKeys.push(J),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((A)=>{return A.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class cx{sequences;activeSequence=null;constructor(A=new Map){this.sequences=A}handleKeyEvent(A){if(this.activeSequence){let Q=this.activeSequence.handleKeyEvent(A);if(Q==="matched"){let B=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:B,consumed:!0,progress:null}}else if(Q==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Q,B]of this.sequences){let $=Q.handleKeyEvent(A);if($==="matched")return{intent:B,consumed:!0,progress:null};else if($==="progress")return this.activeSequence=Q,{intent:null,consumed:!0,progress:Q.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let A of this.sequences.keys())A.reset()}dispose(){for(let A of this.sequences.keys())A.dispose()}}class X6{static _nextDebugId=0;_debugId;_parent=null;_children=[];_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;_manager=null;constructor(A={}){if(this._debugId=`focus-${X6._nextDebugId++}`,this._debugLabel=A.debugLabel??null,this._canRequestFocus=A.canRequestFocus??!0,this._skipTraversal=A.skipTraversal??!1,A.onKey)this._keyHandlers.push(A.onKey);this._onPasteCallback=A.onPaste??null}get debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let A=this._manager?.primaryFocus;return this._hasPrimaryFocus||(A?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(A){if(this._canRequestFocus!==A){if(this._canRequestFocus=A,!A&&this._hasPrimaryFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(A){this._skipTraversal=A}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(A){this._onPasteCallback=A}get enclosingScope(){let A=this._parent;while(A!==null){if(Ie0(A))return A;A=A._parent}return null}get ancestors(){let A=[],Q=this._parent;while(Q!==null)A.push(Q),Q=Q._parent;return A}requestFocus(){if(!this._canRequestFocus)return!1;return this._doRequestFocus({findFirstFocus:!0}),this._manager!==null}unfocus(A="scope"){if(!this.hasFocus&&this._manager?._markedForFocus!==this)return;let Q=this.enclosingScope;if(Q===null)return;switch(A){case"scope":{let B=Q;B._clearFocusedChildren();let $=B.enclosingScope;while(!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,B._clearFocusedChildren(),$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!1});break}case"previouslyFocusedChild":{let B=Q;B._removeFromHistory(this);let $=B.enclosingScope;while(B.focusedChild===null&&!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!0});break}}}_doRequestFocus({findFirstFocus:A}){if(!this._canRequestFocus)return;if(this._hasPrimaryFocus&&this._manager?._markedForFocus===null)return;this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this)}_setAsFocusedChildForScope(){let A=this;for(let Q of this.ancestors)if(Ie0(Q))Q._pushFocusedChild(A),A=Q}_isDecendantOf(A){if(A===null)return!1;if(this._parent===A)return!0;return this._parent?._isDecendantOf(A)??!1}_isAncestorTo(A){return A?._isDecendantOf(this)??!1}_reparent(A){if(A._parent===this)return;let Q=A.enclosingScope,B=Q!==null&&Q===this.enclosingScope;if(A._parent?._removeChild(A,!B),this._children.push(A),A._parent=this,A._updateManager(this._manager),A._requestFocusWhenReparented)A._doRequestFocus({findFirstFocus:!0}),A._requestFocusWhenReparented=!1}_removeChild(A,Q=!0){let B=this._children.indexOf(A);if(B!==-1)this._children.splice(B,1);if(Q){let $=A.enclosingScope;if($!==null)$._removeFromHistory(A),A._collectDescendants().forEach((J)=>$._removeFromHistory(J))}A._parent=null}_collectDescendants(){let A=[],Q=[...this._children];while(Q.length>0){let B=Q.pop();A.push(B);for(let $ of B._children)Q.push($)}return A}_updateManager(A){this._manager=A;for(let Q of this._children)Q._updateManager(A)}_requestFocusWhenReparented=!1;_setFocus(A){if(this._hasPrimaryFocus===A)return;let Q=this.hasFocus;this._hasPrimaryFocus=A;let B=this.hasFocus;if(this._notifyListeners(),Q!==B)this._notifyAncestorListeners()}addListener(A){this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A(this)}_notifyAncestorListeners(){let A=this._parent;while(A)A._notifyListeners(),A=A._parent}_handleKeyEvent(A){return this.handleKeyEvent(A)}_handlePasteEvent(A){if(this._onPasteCallback)return this._onPasteCallback(A);return"ignored"}toStringShort(){let A=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasPrimaryFocus?" FOCUSED":"",B=this._canRequestFocus?"":" (can't focus)";return`Focus${Ie0(this)?"Scope":""}Node${A}${Q}${B}`}toStringDeep(A="",Q=!0){let B=A+this.toStringShort();if(Q&&this._children.length>0){let $=A+" ";for(let J of this._children)B+=`
|
|
5575
|
+
`))}}class Ee0{mcpService;workspaceFolder;pendingServers=new Set;notificationTimeout;_pendingServersSubject=new Y4([]);serversSubscription;pendingServers$=this._pendingServersSubject;constructor(A,Q){this.mcpService=A;this.workspaceFolder=Q;this.setupListener()}setupListener(){this.mcpService.onUntrustedWorkspaceServer=(Q,B)=>{if(this.pendingServers.add(Q),this.notificationTimeout)clearTimeout(this.notificationTimeout);this.notificationTimeout=setTimeout(()=>{this._pendingServersSubject.next(Array.from(this.pendingServers)),this.notificationTimeout=void 0},700)};let A=this.mcpService.trustStore.changes?this.mcpService.trustStore.changes.pipe(K6(void 0)):m0.of(void 0);this.serversSubscription=P6(this.mcpService.servers,A).pipe(u4(([Q,B])=>IA(async()=>{let $=new Set;for(let J of Q)if(J.requiresApproval&&J.specHash){if(!await this.mcpService.trustStore.hasEntry?.({serverName:J.name,specHash:J.specHash}))$.add(J.name)}return $}))).subscribe((Q)=>{if(this.pendingServers.size===0)return;let B=!1,$=Array.from(this.pendingServers);for(let J of $)if(!Q.has(J))this.pendingServers.delete(J),B=!0;if(B)this._pendingServersSubject.next(Array.from(this.pendingServers))})}async trustAlways(){try{await this.mcpService.allowWorkspace(this.workspaceFolder);let A=Array.from(this.pendingServers);for(let Q of A)try{await this.mcpService.approveWorkspaceServer(Q)}catch(B){j.error("Failed to approve MCP server",{serverName:Q,error:B})}}catch(A){j.error("Failed to allow workspace",{error:A})}this.clear()}async trustOnce(A){try{await this.mcpService.approveWorkspaceServer(A),this.pendingServers.delete(A),this._pendingServersSubject.next(Array.from(this.pendingServers))}catch(Q){j.error("Failed to approve MCP server",{serverName:A,error:Q})}}async deny(){let A=Array.from(this.pendingServers);for(let Q of A)try{await this.mcpService.denyWorkspaceServer(Q)}catch(B){j.error("Failed to deny MCP server",{serverName:Q,error:B})}this.clear()}clear(){this.pendingServers.clear(),this._pendingServersSubject.next([])}dispose(){if(this.notificationTimeout)clearTimeout(this.notificationTimeout);if(this.serversSubscription)this.serversSubscription.unsubscribe()}}c0();dk();c0();L1();AE();K8();y7();async function hx(A){let Q=await A.getLatest();return v30(Q.settings)}function nC5(A){let Q=b3(A)?.reasoningEffort;return Q&&kX(A,Q)?Q:void 0}function We0(A,Q){let B=A.lastReasoningEffortByMode?.[Q];return B&&kX(Q,B)?B:void 0}function yX0(A){return A.explicitEffort??We0(A.sessionState,A.agentMode)??nC5(A.agentMode)}function xX0(A,Q){let B=yX0(Q);if(B===void 0)return A;return{...A,"reasoning.effort":B}}function aB(A){let Q=b3(A)?.primaryModel;if(!Q)return;let{provider:B,model:$}=x$(Q);if(B===a4.OPENAI&&$.startsWith("gpt-"))return"openai.speed";return}function fX0(A,Q){let B=A.lastSpeedByMode?.[Q];return B==="fast"||B==="standard"?B:void 0}function ze0(A,Q,B={}){let $={},J=Q["internal.model"]??B["internal.model"];if(J!==void 0)$["internal.model"]=J;if(Q["reasoning.effort"]!==void 0)$["reasoning.effort"]=Q["reasoning.effort"];return hH(A,$)}c0();K8();L1();var aC5="T-00000000-0000-0000-0000-000000000000";class bX0{projection=new RF0(aC5);transcriptEntries=[];transcriptListeners=new Set;transcriptReader={read:()=>this.transcriptEntries,subscribe:(A)=>{return this.transcriptListeners.add(A),()=>this.transcriptListeners.delete(A)}};_agentMode;_reasoningEffort=void 0;observerState;activeErrorPayload=null;activeErrorSeq=null;connectionErrorSubject=new Y4(null);activeErrorSubject=new Y4(null);agentMessageIdSubject=new Y4(null);cancelledSubject=new h4;queuedMessageRemovalSubject=new h4;transcriptRebuildBatchDepth=0;pendingTranscriptRebuildPreviousLength=null;log=j;constructor(A,Q=null){this._agentMode=A,this._reasoningEffort=hH(A,Q??{}),this.observerState=new _F0({initialAgentLoopState:"idle",initialThreadSettings:Q,dedupeQueuedMessageAdds:!1,compactionRecordsState:"idle"})}get agentMode(){return this._agentMode}set agentMode(A){if(this._agentMode===A)return;if(this._agentMode=A,this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}get reasoningEffort(){return this._reasoningEffort}reader(){return this.transcriptReader}protocolMessages(){return this.projection.protocolMessages()}agentState(){return this.observerState.agentLoopState}agentMessageId(){return this.agentMessageIdSubject}connectionInfo(){return this.observerState.connectionInfo}connectionError(){return this.connectionErrorSubject}setConnectionError(A){if(this.connectionErrorSubject.getValue()===A)return;this.connectionErrorSubject.next(A)}pendingSend(){return this.observerState.pendingSend}activeError(){return this.activeErrorSubject}cancelled(){return this.cancelledSubject}getActiveErrorSeq(){return this.activeErrorSeq}title(){return this.observerState.threadTitle}queuedMessages(){return this.observerState.queuedMessages}queuedMessageRemovalEvents(){return this.queuedMessageRemovalSubject}threadSettings(){return this.observerState.threadSettings}compactionState(){return this.observerState.compactionState}beginTranscriptRebuildBatch(){this.transcriptRebuildBatchDepth+=1}endTranscriptRebuildBatch(){if(this.transcriptRebuildBatchDepth===0)return;if(this.transcriptRebuildBatchDepth-=1,this.transcriptRebuildBatchDepth>0)return;let A=this.pendingTranscriptRebuildPreviousLength;if(this.pendingTranscriptRebuildPreviousLength=null,A!==null)this.rebuildTranscriptEntries(A)}dismissActiveError(){if(this.activeErrorPayload===null)return;this.activeErrorPayload=null,this.activeErrorSeq=null,this.activeErrorSubject.next(null)}onMessageAdded(A){this.log.info("[observer] onMessageAdded",{data:A}),this.applyThreadMessageEvent(A)}onMessageUpdated(A){this.log.info("[observer] onMessageUpdated",{data:A}),this.applyThreadMessageEvent(A)}onDelta(A){this.applyThreadMessageEvent(A)}onTruncate(A){this.log.info("[observer] onTruncate",{data:A}),this.applyThreadMessageEvent(A)}onAgentState(A){this.log.info("[observer] onAgentState",{data:A});let Q=cB(this.observerState.agentLoopState.getValue()),B=this._agentMode;if(A.agentMode!==void 0)this._agentMode=A.agentMode;this._reasoningEffort=A.reasoningEffort,this.agentMessageIdSubject.next(A.messageId??null),this.observerState.onAgentState(A);let $=cB(this.observerState.agentLoopState.getValue());if((B!==this._agentMode||Q!==$)&&this.transcriptEntries.length>0)this.requestTranscriptRebuild(this.transcriptEntries.length)}onThreadSettings(A){this.log.info("[observer] onThreadSettings",{data:A}),this.observerState.onThreadSettings(A)}onThreadId(A){this.log.info("[observer] onThreadId",{data:{threadId:A}}),this.log=j.with({threadId:A}),this.projection.setThreadID(A),this.observerState.onThreadId(A),this.observerState.threadId.complete()}onConnectionChanged(A){if(this.log.info("[observer] onConnectionChanged",{data:A}),this.observerState.onConnectionChanged(A),A.state==="connected")this.setConnectionError(null)}onQueuedMessages(A){this.log.info("[observer] onQueuedMessages",{data:A});let Q=A.type==="queued_message_removed"?this.observerState.queuedMessages.getValue().find((B)=>B.queuedMessage.messageId===A.queuedMessageId):void 0;if(this.observerState.onQueuedMessages(A),A.type==="queued_message_removed"&&Q!==void 0)this.queuedMessageRemovalSubject.next({message:Q,serverMessage:A})}onUserActionMessageDeliveryStatusChanged(A,Q,B){this.log.info("[observer] onUserActionMessageDeliveryStatusChanged",{data:{messageId:A,status:Q,sentAt:B}}),this.observerState.onUserActionMessageDeliveryStatusChanged(A,Q,B)}onUserMessageSendPending(A,Q){this.log.info("[observer] onUserMessageSendPending",{data:{messageId:A,sentAt:Q}}),this.observerState.onUserMessageSendPending(A,Q)}onErrorNotice(A){if(this.log.info("[observer] onErrorNotice",{data:A}),this.activeErrorPayload!==null)return;this.observerState.onErrorNotice(A)}onActiveError(A){if(this.log.info("[observer] onActiveError",{data:A}),this.observerState.onActiveError(A),A.type==="error_set")this.activeErrorPayload=A.error,this.activeErrorSeq=A.seq;else this.activeErrorPayload=null,this.activeErrorSeq=null;this.activeErrorSubject.next(this.activeErrorPayload)}onCancelled(A){this.log.info("[observer] onCancelled",{data:A}),this.observerState.onCancelled(A),this.cancelledSubject.next(A)}onToolProgress(A){this.log.info("[observer] onToolProgress",{data:A}),this.applyThreadMessageEvent(A)}onThreadTitle(A){this.log.info("[observer] onThreadTitle",{data:A}),this.observerState.onThreadTitle(A)}onCompactionEvent(A){this.log.info("[observer] onCompactionEvent",{data:A});let Q=A.type==="compaction_started"?"compacting":"idle";if(A.type==="compaction_started"&&this.observerState.compactionState.getValue()===Q)return;let B=this.transcriptEntries.length;if(this.observerState.onCompactionEvent(A),A.type==="compaction_complete"||A.type==="compaction_records")this.requestTranscriptRebuild(B)}applyThreadMessageEvent(A){let Q=this.transcriptEntries.length;if(!this.projection.apply(A).changed)return;this.requestTranscriptRebuild(Q)}requestTranscriptRebuild(A){if(this.transcriptRebuildBatchDepth===0){this.rebuildTranscriptEntries(A);return}this.pendingTranscriptRebuildPreviousLength=Math.min(this.pendingTranscriptRebuildPreviousLength??A,A)}rebuildTranscriptEntries(A){let Q=this.projection.buildTranscriptEntries({...Ay4(this._agentMode),isWorking:cB(this.observerState.agentLoopState.getValue()),compactionCutMessageIDs:this.observerState.compactionRecords.getValue().map((B)=>B.cutMessageId)});this.transcriptEntries.length=0,this.transcriptEntries.push(...Q),this.notifyTranscriptReaders(oC5(A,Q.length))}notifyTranscriptReaders(A){for(let Q of this.transcriptListeners)Q(A)}}function oC5(A,Q){return Array.from({length:Math.max(A,Q)},(B,$)=>$)}var rC5=45000;class He0{rivetEndpoint;apiKey;configService;runtimeDependencies;loadThreadHistory;importThreadIntoActor;observingClients=[];_lastActiveObservingClient=null;connectionErrorSubject=new h4;constructor(A,Q,B,$,J,Y){this.rivetEndpoint=A;this.apiKey=Q;this.configService=B;this.runtimeDependencies=$;this.loadThreadHistory=J;this.importThreadIntoActor=Y}get lastActiveObservingClient(){return this._lastActiveObservingClient}get connectionErrors$(){return this.connectionErrorSubject}async connectToThread(A,Q={}){let B=Q.observerOnly??!1,$=this.observingClients.find((X)=>X.observerOnly===B&&(X.threadID===A||X.client.getThreadId()===A));if($)return this._lastActiveObservingClient=$,this.persistLastThreadID(A),$;let J=this.createClient({threadID:A}),Y=await J.loadThreadHistory(A);if(!Y)throw J.dispose(),new r7("Thread not found");if(Y.needsImport){if(!this.importThreadIntoActor)throw J.dispose(),new r7("Thread requires import before connecting");try{await this.importThreadIntoActor(A)}catch(X){throw J.dispose(),uX0(X)}}let Z=new bX0(Y.agentMode);Z.beginTranscriptRebuildBatch();try{J.setObserverCallbacks(Z)}finally{Z.endTranscriptRebuildBatch()}let F={client:J,observer:Z,threadID:A,logger:j.with({threadId:A}),observerOnly:B,connectionSubscription:PF0(J,{requireRole:B?void 0:"executor",onError:({threadID:X,error:D})=>this.emitConnectionError(Z,D,X)})};return this.connectAndResume(J,Y.version,{observerOnly:B}).catch((X)=>{this.emitConnectionError(Z,X,A),this.removeObservingClient(F)}),this.persistLastThreadID(A),this.observingClients.push(F),this._lastActiveObservingClient=F,F}createNewThread(A,Q,B){let $=this.createClient({agentMode:A,initialThreadMeta:B}),J=new bX0(A,Q??null);$.setObserverCallbacks(J);let Y={client:$,observer:J,threadID:null,logger:j,observerOnly:!1,connectionSubscription:PF0($,{requireRole:"executor",onError:({threadID:Z,error:F})=>this.emitConnectionError(J,F,Z)})};if(Q)$.sendClientUpdateThreadSettings(Q);else hx(this.configService).then((Z)=>{$.sendClientUpdateThreadSettings(Z)}).catch((Z)=>{j.warn("Failed to seed thread settings",{threadID:$.getThreadId(),error:Z instanceof Error?Z.message:String(Z)})});return this.observingClients.push(Y),this.connectAndResume($,0).then(({client:Z})=>{let F=Z.getThreadId();if(Y.threadID=F,F)Y.logger=j.with({threadId:F}),this.persistLastThreadID(F)}).catch((Z)=>{this.emitConnectionError(J,Z),this.removeObservingClient(Y)}),this._lastActiveObservingClient=Y,Y}dispose(){for(let{client:A,connectionSubscription:Q}of this.observingClients.values())Q.unsubscribe(),A.dispose();this.observingClients.length=0,this._lastActiveObservingClient=null,this.connectionErrorSubject.complete()}createClient(A={}){let{threadID:Q,agentMode:B,initialThreadMeta:$}=A,J=zx(async(Y)=>{try{let Z={agentMode:B,executorType:"local-client"};if(!Y&&$)Z.threadMeta=$;return await hY(Y,this.configService,this.apiKey,Z)}catch(Z){throw uX0(Z)}},Q);return new IU({transport:Hx({rivetEndpoint:this.rivetEndpoint,credentialsProvider:J,initialThreadID:Q,pingIntervalMs:5000}),threadHistoryLoader:this.loadThreadHistory})}async connectAndResume(A,Q,B={}){let $=B.observerOnly??!1,J=null;try{await A.connect();let Y=A.getThreadId();if(!Y)throw A.disconnect(),new r7("Thread client connected without a thread ID");if($)return A.resumeFromVersion(Q),{client:A,executor:null};return J=this.createExecutor(A,Y),await sC5(J,A),A.resumeFromVersion(Q),{client:A,executor:J}}catch(Y){if(A.disconnect(),J)J.dispose();throw uX0(Y)}}createExecutor(A,Q){return new Vj({transport:A,toolService:this.runtimeDependencies.toolService,configService:this.configService,clientID:this.runtimeDependencies.clientID,threadId:Q,invokeTool:(B)=>this.runtimeDependencies.invokeTool(Q,B),requestPluginToolCall:this.runtimeDependencies.requestPluginToolCall,requestPluginToolResult:this.runtimeDependencies.requestPluginToolResult,pluginService:this.runtimeDependencies.pluginService,readFileSystemDirectory:this.runtimeDependencies.readFileSystemDirectory,skillService:this.runtimeDependencies.skillService,sendGitSnapshot:!1,executorType:"local-client",workspaceRoot:process.cwd()})}emitConnectionError(A,Q,B){let $=uX0(Q);A.setConnectionError($.message),this.connectionErrorSubject.next({threadID:B??void 0,error:$})}removeObservingClient(A){A.connectionSubscription.unsubscribe();let Q=this.observingClients.indexOf(A);if(Q!==-1)this.observingClients.splice(Q,1);if(this._lastActiveObservingClient?.client===A.client)this._lastActiveObservingClient=null}persistLastThreadID(A){this.runtimeDependencies.persistLastThreadID(A).catch((Q)=>{j.warn("Failed to persist last active thread ID",{threadID:A,error:Q instanceof Error?Q.message:String(Q)})})}}async function sC5(A,Q){A.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),A.handleConnectionChange(Q.getConnectionInfo()),await A.ensureReady({timeoutMs:rC5,timeoutMessage:"Couldn’t connect to Amp servers — run amp: reconnect to retry"})}function uX0(A){if(A instanceof r7)return A;if(A instanceof Error){let Q=A.message||"Unknown connection error";return new r7(Q,A)}if(typeof A==="string"&&A.length>0)return new r7(A,A);return new r7("Unknown connection error",A)}async function _h4(A){let Q=yF(A.ampURL),B=HU({endpoint:Q}),$=await A.configService.getLatest(A.signal),J=await $.secrets.getToken("apiKey",$.settings.url);if(!J)throw Error("API key required. Please run `amp login` first.");let Y=await B.threadActor.get([A.threadID]).fetch("/skills",{method:"GET",headers:{Authorization:`Bearer ${J}`},signal:A.signal,skipReadyWait:!0});if(!Y.ok){let F=await Y.text();throw Error(`Skills request failed (${Y.status}): ${F}`)}let Z=await Y.json();if(!Z.ok)throw Error(Z.error);return{skills:Z.skills,errors:Z.errors}}fZ();c0();s1();L1();c0();MQ();function Th4(A,Q,B){let $=new h4,Y=(()=>{let K=new Map;return(E,W)=>{let H=(K.get(E)?.catch(()=>{})||Promise.resolve()).then(()=>W()).finally(()=>{if(K.get(E)===H)K.delete(E)});return K.set(E,H),H}})(),Z=B?X1.joinPath(Q,B):Q;function F(K){return X1.joinPath(Z,`${K.toString()}.json`)}async function X(K){let E=F(K);try{let W=await A.readBinaryFile(E),z=52428800;if(W.length>52428800){let H=Math.round(W.length/1048576);j.warn(`File too large to load safely: ${String(K)} (${H}MB)`,{key:String(K),size:W.length,maxSize:52428800});return}try{let H=W instanceof Uint8Array?W:new Uint8Array(W);return JSON.parse(new TextDecoder().decode(H))}catch(H){let q=H,{contentLength:N,contentPreview:I}=tC5(W);j.warn("Corrupted JSON detected.",{key:String(K),storageUri:Z.toString(),error:q.message,contentLength:N,contentPreview:I});return}}catch(W){if(v8(W))return;throw W}}async function D(K,E){let W=F(K),z=W.with({path:W.path+".amptmp"}),H=JSON.stringify(E,null,2);await A.mkdirp(X1.joinPath(W,"..")),await Y(K,async()=>{await A.writeFile(z,H),await A.rename(z,W)}),$.next(K)}async function G(K){let E=F(K);await Y(K,async()=>{await A.delete(E)}),$.next(K)}async function V(){let K;try{K=await A.readdir(Z)}catch(z){if(v8(z))return[];throw z}let E=K.filter((z)=>{let H=z.uri.path.split("/").pop()||"";return!z.isDirectory&&H.endsWith(".json")});return(await Promise.all(E.map(async(z)=>{let q=(z.uri.path.split("/").pop()||"").slice(0,-5);try{let N=await A.getMtime(z.uri);return{key:q,mtime:N}}catch(N){if(!v8(N))throw N;return null}}))).filter((z)=>z!==null).toSorted((z,H)=>H.mtime-z.mtime).map((z)=>z.key)}async function U(K){return F(K).fsPath}return{get:X,set:D,delete:G,keys:V,path:U,changes:$}}function tC5(A){try{let Q=A instanceof Uint8Array?A:new Uint8Array(A),B=new TextDecoder().decode(Q);return{contentLength:A.length,contentPreview:B.slice(0,128)}}catch{let Q=A instanceof Uint8Array?A:new Uint8Array(A),$=Array.from(Q.slice(0,64)).map((J)=>{if(J>=32&&J<=126)return String.fromCharCode(J);return`\\x${J.toString(16).padStart(2,"0")}`}).join("");return{contentLength:A.length,contentPreview:`${$}${A.length>64?"...":""}`}}}s1();var xD={agentMode:"smart",launchCount:0,shortcutsHintUsed:!1,neoWelcomeDismissed:!1};function kh4(A,Q){if(Q==="execute")return A.lastExecuteThreadId??A.lastThreadId;return A.lastThreadId}function hX0(A,Q,B){if(B==="execute")return{...A,lastExecuteThreadId:Q};return{...A,lastThreadId:Q}}function vh4(A){return{...A,neoWelcomeDismissed:!0}}function qe0(A={}){let Q=A.fs??O3,B=A.dataDir??CT;return Th4(Q,s0.file(B))}var yh4=qe0(),Sh4=Promise.resolve();async function DI(A={}){let Q=A.dataDir||A.fs?qe0(A):yh4;try{let B=await Q.get("session"),$={...xD,agentMode:B?.agentMode??xD.agentMode,launchCount:B?.launchCount??xD.launchCount,neoWelcomeDismissed:B?.neoWelcomeDismissed??xD.neoWelcomeDismissed,shortcutsHintUsed:B?.shortcutsHintUsed??xD.shortcutsHintUsed,lastThreadId:B?.lastThreadId,lastExecuteThreadId:B?.lastExecuteThreadId},J={...B?.lastReasoningEffortByMode};if(Object.keys(J).length>0)$.lastReasoningEffortByMode=J;let Y={...B?.lastSpeedByMode};if(Object.keys(Y).length>0)$.lastSpeedByMode=Y;return $}catch{return{...xD}}}async function eC5(A,Q){try{await Q.set("session",A)}catch(B){j.warn("Failed to save session state.",{error:B instanceof Error?B.message:String(B)})}}function AM5(A={}){return A.dataDir||A.fs?qe0(A):yh4}async function EJ(A,Q={}){let B=AM5(Q),$={...xD},J=Sh4.catch(()=>{return}).then(async()=>{let Y=await DI(Q);$={...xD,...A(Y)},await eC5($,B)});return Sh4=J.then(()=>{return},()=>{return}),await J,$}class Ne0{constructor(){}isEnabled(A){return!0}consumesKey(A){return!0}toString(){return`${this.constructor.name}()`}}class D4 extends Ne0{onInvoke;constructor(A){super();this.onInvoke=A}invoke(A){return this.onInvoke(A)}}function QM5(A){return"state"in A}function xh4(A,Q){let B=A.element.parent;while(B){if(QM5(B)&&B.state instanceof gX0){if(Q(B.state))return}B=B.parent}}class mX0{invokeAction(A,Q){let B=this.findAction(A,Q);if(B&&B.enabled)return B.action.invoke(A);return null}findAction(A,Q){let B=null;return xh4(Q,($)=>{let J=$.getActionForIntent(A);if(!J)return!1;return B={action:J,enabled:J.isEnabled(A)},!0}),B}}class t4 extends v0{actions;child;dispatcher;constructor({actions:A,child:Q,dispatcher:B,key:$}){super({key:$});this.actions=A,this.child=Q,this.dispatcher=B}createState(){return new gX0}static invoke(A,Q){return t4.of(A).invokeAction(Q,A)}static maybeInvoke(A,Q){try{return t4.invoke(A,Q)}catch{return null}}static find(A,Q){let B=t4.maybeFind(A,Q);if(!B){let $=Q?.constructor.name||"unknown";throw Error(`No action found for intent type: ${$}`)}return B}static maybeFind(A,Q){if(!Q)return null;let B=null;return xh4(A,($)=>{let J=$.getActionForIntent(Q);if(!J)return!1;return B=J,!0}),B}static of(A){let Q=A.findAncestorStateOfType(gX0);if(!Q)throw Error("No Actions widget found in context");return Q.dispatcher}static handler(A,Q){let B=t4.of(A).findAction(Q,A);if(B&&B.enabled)return()=>B.action.invoke(Q);return null}}class gX0 extends S0{dispatcher=new mX0;getActionForIntent(A){let Q=A.constructor;return this.widget.actions.get(Q)}build(A){return this.widget.child}}class l4{constructor(){}toString(){return`${this.constructor.name}()`}}class GI extends l4{constructor(){super()}}class ho extends l4{constructor(){super()}}class go extends l4{constructor(){super()}}class mo extends l4{constructor(){super()}}class po extends l4{constructor(){super()}}class VI extends l4{constructor(){super()}}class pX0 extends l4{constructor(){super()}}class co extends l4{constructor(){super()}}class gx extends l4{constructor(){super()}}class lo extends l4{constructor(){super()}}class mx extends l4{constructor(){super()}}class px extends l4{direction;constructor(A){super();this.direction=A}toString(){return`NavigateToPromptHistoryIntent(direction: ${this.direction})`}}class jj extends l4{constructor(){super()}}class TW extends l4{constructor(){super()}}function BM5(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let B=A.key.toLowerCase();if(["control","meta","alt","shift"].includes(B))return"";if(B===" ")B="space";return Q.push(B),Q.join("+")}function fh4(A){let Q=A.toLowerCase().split("+"),B=Q.pop()||"";return{modifiers:new Set(Q),key:B}}function bh4(A,Q){let B=fh4(A),$=fh4(Q);if(B.key!==$.key)return!1;for(let J of $.modifiers)if(!B.modifiers.has(J))return!1;if($.modifiers.size===0&&B.modifiers.size>0)return!1;return!0}class dx{sequence;timeout;matchedKeys=[];timeoutId=null;constructor(A,Q={}){this.sequence=A,this.timeout=Q.timeout??2000}getProgress(){return{matched:[...this.matchedKeys],remaining:this.sequence.slice(this.matchedKeys.length)}}isInProgress(){return this.matchedKeys.length>0}reset(){if(this.matchedKeys=[],this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null}handleKeyEvent(A){let Q=BM5(A);if(!Q)return"none";let B=this.matchedKeys.length,$=this.sequence[B];if($&&bh4(Q,$)){if(this.matchedKeys.push($),this.timeoutId)clearTimeout(this.timeoutId),this.timeoutId=null;if(this.matchedKeys.length===this.sequence.length)return this.reset(),"matched";return this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}else if(this.matchedKeys.length>0){this.reset();let J=this.sequence[0];if(J&&bh4(Q,J))return this.matchedKeys.push(J),this.timeoutId=setTimeout(()=>this.reset(),this.timeout),"progress"}return"none"}dispose(){this.reset()}toString(){return this.sequence.map((A)=>{return A.replace("ctrl+","C-").replace("meta+","M-").replace("alt+","A-")}).join(" ")}}class cx{sequences;activeSequence=null;constructor(A=new Map){this.sequences=A}handleKeyEvent(A){if(this.activeSequence){let Q=this.activeSequence.handleKeyEvent(A);if(Q==="matched"){let B=this.sequences.get(this.activeSequence);return this.activeSequence=null,{intent:B,consumed:!0,progress:null}}else if(Q==="progress")return{intent:null,consumed:!0,progress:this.activeSequence.getProgress()};else this.activeSequence=null}for(let[Q,B]of this.sequences){let $=Q.handleKeyEvent(A);if($==="matched")return{intent:B,consumed:!0,progress:null};else if($==="progress")return this.activeSequence=Q,{intent:null,consumed:!0,progress:Q.getProgress()}}return{intent:null,consumed:!1,progress:null}}isInProgress(){return this.activeSequence!==null}getProgress(){return this.activeSequence?.getProgress()??null}reset(){this.activeSequence=null;for(let A of this.sequences.keys())A.reset()}dispose(){for(let A of this.sequences.keys())A.dispose()}}class X6{static _nextDebugId=0;_debugId;_parent=null;_children=[];_hasPrimaryFocus=!1;_canRequestFocus=!0;_skipTraversal=!1;_keyHandlers=[];_onPasteCallback=null;_listeners=new Set;_debugLabel=null;_manager=null;constructor(A={}){if(this._debugId=`focus-${X6._nextDebugId++}`,this._debugLabel=A.debugLabel??null,this._canRequestFocus=A.canRequestFocus??!0,this._skipTraversal=A.skipTraversal??!1,A.onKey)this._keyHandlers.push(A.onKey);this._onPasteCallback=A.onPaste??null}get debugId(){return this._debugId}get hasPrimaryFocus(){return this._hasPrimaryFocus}get hasFocus(){let A=this._manager?.primaryFocus;return this._hasPrimaryFocus||(A?._isDecendantOf(this)??!1)}get canRequestFocus(){return this._canRequestFocus}set canRequestFocus(A){if(this._canRequestFocus!==A){if(this._canRequestFocus=A,!A&&this._hasPrimaryFocus)this.unfocus()}}get skipTraversal(){return this._skipTraversal}set skipTraversal(A){this._skipTraversal=A}get parent(){return this._parent}get children(){return this._children}get debugLabel(){return this._debugLabel}get onPaste(){return this._onPasteCallback}set onPaste(A){this._onPasteCallback=A}get enclosingScope(){let A=this._parent;while(A!==null){if(Ie0(A))return A;A=A._parent}return null}get ancestors(){let A=[],Q=this._parent;while(Q!==null)A.push(Q),Q=Q._parent;return A}requestFocus(){if(!this._canRequestFocus)return!1;return this._doRequestFocus({findFirstFocus:!0}),this._manager!==null}unfocus(A="scope"){if(!this.hasFocus&&this._manager?._markedForFocus!==this)return;let Q=this.enclosingScope;if(Q===null)return;switch(A){case"scope":{let B=Q;B._clearFocusedChildren();let $=B.enclosingScope;while(!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,B._clearFocusedChildren(),$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!1});break}case"previouslyFocusedChild":{let B=Q;B._removeFromHistory(this);let $=B.enclosingScope;while(B.focusedChild===null&&!B.canRequestFocus&&$!==null)$._removeFromHistory(B),B=$,$=B.enclosingScope;B._doRequestFocus({findFirstFocus:!0});break}}}_doRequestFocus({findFirstFocus:A}){if(!this._canRequestFocus)return;if(this._hasPrimaryFocus&&this._manager?._markedForFocus===null)return;this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this)}_setAsFocusedChildForScope(){let A=this;for(let Q of this.ancestors)if(Ie0(Q))Q._pushFocusedChild(A),A=Q}_isDecendantOf(A){if(A===null)return!1;if(this._parent===A)return!0;return this._parent?._isDecendantOf(A)??!1}_isAncestorTo(A){return A?._isDecendantOf(this)??!1}_reparent(A){if(A._parent===this)return;let Q=A.enclosingScope,B=Q!==null&&Q===this.enclosingScope;if(A._parent?._removeChild(A,!B),this._children.push(A),A._parent=this,A._updateManager(this._manager),A._requestFocusWhenReparented)A._doRequestFocus({findFirstFocus:!0}),A._requestFocusWhenReparented=!1}_removeChild(A,Q=!0){let B=this._children.indexOf(A);if(B!==-1)this._children.splice(B,1);if(Q){let $=A.enclosingScope;if($!==null)$._removeFromHistory(A),A._collectDescendants().forEach((J)=>$._removeFromHistory(J))}A._parent=null}_collectDescendants(){let A=[],Q=[...this._children];while(Q.length>0){let B=Q.pop();A.push(B);for(let $ of B._children)Q.push($)}return A}_updateManager(A){this._manager=A;for(let Q of this._children)Q._updateManager(A)}_requestFocusWhenReparented=!1;_setFocus(A){if(this._hasPrimaryFocus===A)return;let Q=this.hasFocus;this._hasPrimaryFocus=A;let B=this.hasFocus;if(this._notifyListeners(),Q!==B)this._notifyAncestorListeners()}addListener(A){this._listeners.add(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A(this)}_notifyAncestorListeners(){let A=this._parent;while(A)A._notifyListeners(),A=A._parent}_handleKeyEvent(A){return this.handleKeyEvent(A)}_handlePasteEvent(A){if(this._onPasteCallback)return this._onPasteCallback(A);return"ignored"}toStringShort(){let A=this._debugLabel?`"${this._debugLabel}"`:"",Q=this._hasPrimaryFocus?" FOCUSED":"",B=this._canRequestFocus?"":" (can't focus)";return`Focus${Ie0(this)?"Scope":""}Node${A}${Q}${B}`}toStringDeep(A="",Q=!0){let B=A+this.toStringShort();if(Q&&this._children.length>0){let $=A+" ";for(let J of this._children)B+=`
|
|
5576
5576
|
`+J.toStringDeep($,!0)}return B}addKeyHandler(A){this._keyHandlers.push(A)}removeKeyHandler(A){let Q=this._keyHandlers.indexOf(A);if(Q!==-1)this._keyHandlers.splice(Q,1)}handleKeyEvent(A){for(let Q of this._keyHandlers)if(Q(A)==="handled")return"handled";return"ignored"}dispose(){this._parent?._removeChild(this,!0),this._children.length=0,this._keyHandlers=[]}}function Ie0(A){return A._isFocusScopeNode===!0}class lx extends X6{_isFocusScopeNode=!0;_focusedChildren=[];constructor(A={}){super({canRequestFocus:A.canRequestFocus??!0,skipTraversal:A.skipTraversal??!0,...A})}get focusedChild(){return this._focusedChildren.length===0?null:this._focusedChildren[this._focusedChildren.length-1]}autofocus(A){if(A.parent===null)this._reparent(A);let Q=this._manager;if(Q===null){A._requestFocusWhenReparented=!0;return}Q._enqueueAutofocus(this,A)}_doRequestFocus({findFirstFocus:A}){while(this._focusedChildren.length>0&&(!this._focusedChildren[this._focusedChildren.length-1].canRequestFocus||this._focusedChildren[this._focusedChildren.length-1].enclosingScope===null))this._focusedChildren.pop();let Q=this.focusedChild;if(!A||Q===null){if(this.canRequestFocus)this._setAsFocusedChildForScope(),this._manager?._markNextFocus(this);return}Q._doRequestFocus({findFirstFocus:!0})}_pushFocusedChild(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1);this._focusedChildren.push(A)}_removeFromHistory(A){let Q=this._focusedChildren.indexOf(A);if(Q!==-1)this._focusedChildren.splice(Q,1)}_clearFocusedChildren(){this._focusedChildren.length=0}get focusedChildren(){return this._focusedChildren}}class b8{static _instance=null;static _keystrokes=[];static _MAX_KEYSTROKES=100;_rootScope;_primaryFocus=null;_markedForFocus=null;_pendingAutofocuses=[];_haveScheduledUpdate=!1;constructor(){this._rootScope=new lx({debugLabel:"Root Focus Scope",canRequestFocus:!1}),this._rootScope._updateManager(this)}static getRecentKeystrokes(){return[...b8._keystrokes]}static _recordKeystroke(A,Q,B){if(b8._keystrokes.push({timestamp:Date.now(),key:A,focusPath:Q,handled:B}),b8._keystrokes.length>b8._MAX_KEYSTROKES)b8._keystrokes.shift()}static get instance(){if(!b8._instance)b8._instance=new b8;return b8._instance}get primaryFocus(){return this._primaryFocus}get rootScope(){return this._rootScope}requestFocus(A){if(!A.canRequestFocus)return!1;return A._doRequestFocus({findFirstFocus:!0}),!0}_markNextFocus(A){if(this._primaryFocus===A){this._markedForFocus=null;return}this._commitFocus(A)}_commitFocus(A){if(this._primaryFocus===A)return;let Q=this._primaryFocus;this._primaryFocus=A,Q?._setFocus(!1),A?._setFocus(!0)}_enqueueAutofocus(A,Q){this._pendingAutofocuses.push({scope:A,node:Q}),this._scheduleUpdate()}_scheduleUpdate(){if(this._haveScheduledUpdate)return;this._haveScheduledUpdate=!0,queueMicrotask(()=>{this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()})}_applyFocusChangesIfNeeded(){let A=this._pendingAutofocuses;this._pendingAutofocuses=[];for(let Q of A)this._applyAutofocusIfValid(Q)}_applyAutofocusIfValid(A){let{scope:Q,node:B}=A;if((Q.parent!==null||Q===this._rootScope)&&Q._manager===this&&Q.focusedChild===null&&B.ancestors.includes(Q))B._doRequestFocus({findFirstFocus:!0})}flushAutofocus(){this._haveScheduledUpdate=!1,this._applyFocusChangesIfNeeded()}handleKeyEvent(A){if(!this._primaryFocus)return!1;let Q=void 0,B=this._primaryFocus;while(B){let J=B._handleKeyEvent(A)==="handled";if(Q)Q.push({id:B.debugId,debugLabel:B.debugLabel,handled:J});if(J){if(Q)b8._recordKeystroke(this.formatKeyEvent(A),Q,!0);return!0}B=B.parent}if(Q)b8._recordKeystroke(this.formatKeyEvent(A),Q,!1);return!1}formatKeyEvent(A){let Q=[];if(A.ctrlKey)Q.push("Ctrl");if(A.altKey)Q.push("Alt");if(A.shiftKey)Q.push("Shift");if(A.metaKey)Q.push("Meta");if(A.key)Q.push(A.key);return Q.join("+")}handlePasteEvent(A){if(!this._primaryFocus)return!1;let Q=this._primaryFocus;while(Q){if(Q._handlePasteEvent(A)==="handled")return!0;Q=Q.parent}return!1}registerNode(A,Q=null){N4(A!==Q,"Focus node cannot be its own parent"),(Q??this._rootScope)._reparent(A)}unregisterNode(A){if(A.hasPrimaryFocus||this._markedForFocus===A)A.unfocus("previouslyFocusedChild");if(this._pendingAutofocuses=this._pendingAutofocuses.filter((B)=>B.node!==A&&B.scope!==A),A.parent?._removeChild(A,!0),this._primaryFocus===A)this._commitFocus(null);A._updateManager(null)}_focusNodeToDebugInfo(A){let Q=A instanceof lx,B=Q?A:null;return{id:A.debugId,debugLabel:A.debugLabel,hasPrimaryFocus:A.hasPrimaryFocus,hasFocus:A.hasFocus,canRequestFocus:A.canRequestFocus,skipTraversal:A.skipTraversal,isPrimaryFocus:this._primaryFocus===A,isScope:Q,focusedChildIds:B?B.focusedChildren.map(($)=>$.debugId):[],children:A.children.map(($)=>this._focusNodeToDebugInfo($))}}debugDumpFocusTree(){return{timestamp:Date.now(),rootScope:this._focusNodeToDebugInfo(this._rootScope),primaryFocusId:this._primaryFocus?.debugId??null,focusStack:this._rootScope.focusedChildren.map((A)=>({id:A.debugId,debugLabel:A.debugLabel}))}}dispose(){this._primaryFocus=null,this._markedForFocus=null,this._pendingAutofocuses=[],this._haveScheduledUpdate=!1,this._rootScope.dispose(),b8._instance=null}}class m4 extends v0{focusNode;child;autofocus;canRequestFocus;skipTraversal;onKey;onPaste;onFocusChange;debugLabel;constructor({key:A,focusNode:Q,child:B,autofocus:$=!1,canRequestFocus:J=!0,skipTraversal:Y=!1,onKey:Z,onPaste:F,onFocusChange:X,debugLabel:D}){super({key:A});this.focusNode=Q,this.child=B,this.autofocus=$,this.canRequestFocus=J,this.skipTraversal=Y,this.onKey=Z||null,this.onPaste=F||null,this.onFocusChange=X||null,this.debugLabel=D||null}createState(){return new ix}}class ix extends S0{_internalFocusNode=null;_isDisposed=!1;_focusChangeHandler=null;_didAutofocus=!1;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}createFocusNode(A){return new X6(A)}initState(){if(super.initState(),!this.widget.focusNode){let B={canRequestFocus:this.widget.canRequestFocus,skipTraversal:this.widget.skipTraversal};if(this.widget.onKey)B.onKey=this.widget.onKey;if(this.widget.onPaste)B.onPaste=this.widget.onPaste;if(this.widget.debugLabel)B.debugLabel=this.widget.debugLabel;this._internalFocusNode=this.createFocusNode(B)}if(this.widget.onKey&&this.widget.focusNode)this.effectiveFocusNode.addKeyHandler(this.widget.onKey);if(this.widget.onPaste)this.effectiveFocusNode.onPaste=this.widget.onPaste;if(this.widget.onFocusChange)this._focusChangeHandler=(B)=>{if(!this._isDisposed&&this.widget.onFocusChange)this.widget.onFocusChange(B.hasFocus)},this.effectiveFocusNode.addListener(this._focusChangeHandler);let Q=this.context.findAncestorStateOfType(ix)?.effectiveFocusNode||null;if(b8.instance.registerNode(this.effectiveFocusNode,Q),this.widget.autofocus&&!this._didAutofocus)this._didAutofocus=!0,this.findEnclosingScope().autofocus(this.effectiveFocusNode)}findEnclosingScope(){return this.effectiveFocusNode.enclosingScope??b8.instance.rootScope}dispose(){if(this._didAutofocus=!1,this.widget.onKey)this.effectiveFocusNode.removeKeyHandler(this.widget.onKey);if(b8.instance.unregisterNode(this.effectiveFocusNode),this._isDisposed=!0,this._focusChangeHandler)this.effectiveFocusNode.removeListener(this._focusChangeHandler),this._focusChangeHandler=null;if(this._internalFocusNode)this._internalFocusNode.dispose(),this._internalFocusNode=null;super.dispose()}build(A){return this.widget.child}}function uh4(A){let Q=A.key;if(Q.length===1&&Q>="a"&&Q<="z")return Q;if(A.code!==void 0)return A.code;return Q}class T1{key;shift;ctrl;alt;meta;constructor(A,Q={}){this.key=A;this.shift=Q.shift??!1,this.ctrl=Q.ctrl??!1,this.alt=Q.alt??!1,this.meta=Q.meta??!1}accepts(A){return uh4(A)===this.key&&A.shiftKey===this.shift&&A.ctrlKey===this.ctrl&&A.altKey===this.alt&&A.metaKey===this.meta}static key(A){return new T1(A)}static ctrl(A){return new T1(A,{ctrl:!0})}static shift(A){return new T1(A,{shift:!0})}static alt(A){return new T1(A,{alt:!0})}static meta(A){return new T1(A,{meta:!0})}modifiers(){let A=[];if(this.meta)A.push("Meta");if(this.ctrl)A.push("Ctrl");if(this.alt)A.push("Alt");if(this.shift)A.push("Shift");return A}toString(){let A=this.modifiers();return A.length>0?`${A.join("+")}+${this.key}`:this.key}}class we0{shortcuts=new Map;constructor(A=new Map){this.shortcuts=new Map(A)}handleKeyEvent(A){for(let[Q,B]of this.shortcuts)if(Q.accepts(A))return B;return null}addShortcut(A,Q){this.shortcuts.set(A,Q)}removeShortcut(A){return this.shortcuts.delete(A)}getAllShortcuts(){return new Map(this.shortcuts)}copyWith(A){let Q=new Map([...this.shortcuts,...A]);return new we0(Q)}}class m5 extends v0{shortcuts;child;manager;debugLabel;focusNode;constructor({shortcuts:A,child:Q,manager:B,debugLabel:$,focusNode:J,key:Y}){super({key:Y});this.shortcuts=A,this.child=Q,this.manager=B,this.debugLabel=$,this.focusNode=J}createState(){return new hh4}}class hh4 extends S0{manager=null;initState(){if(super.initState(),this.createManager(),this.widget.focusNode)this.widget.focusNode.addKeyHandler(this.handleKeyEvent)}didUpdateWidget(A){if(super.didUpdateWidget(A),A.shortcuts!==this.widget.shortcuts||A.manager!==this.widget.manager)this.createManager()}createManager(){if(this.widget.manager)this.manager=this.widget.manager;else this.manager=new we0(this.widget.shortcuts)}dispose(){if(this.widget.focusNode)this.widget.focusNode.removeKeyHandler(this.handleKeyEvent);super.dispose()}handleKeyEvent=(A)=>{if(!this.manager)return"ignored";let Q=this.manager.handleKeyEvent(A);if(Q){if(this.invokeIntent(Q)==="handled")return"handled"}return"ignored"};invokeIntent(A){let B=new mX0().findAction(A,this.context);if(B&&B.enabled){if(B.action.invoke(A)==="ignored")return null;return"handled"}return null}build(A){if(this.widget.focusNode)return this.widget.child;else return new m4({onKey:this.handleKeyEvent,autofocus:!1,canRequestFocus:!0,skipTraversal:!1,debugLabel:this.widget.debugLabel,child:this.widget.child})}}c0();c0();import{execSync as gh4}from"node:child_process";function Ce0(){let A=$M5();if(A)return A;let Q=JM5();if(Q)return{...Q,pixelWidth:0,pixelHeight:0};return null}function $M5(){try{let A=(()=>{throw new Error("Cannot require module "+"ffi-napi");})(),Q=(()=>{throw new Error("Cannot require module "+"ref-napi");})(),$=(()=>{throw new Error("Cannot require module "+"ref-struct-di");})()(Q)({ws_row:Q.types.ushort,ws_col:Q.types.ushort,ws_xpixel:Q.types.ushort,ws_ypixel:Q.types.ushort}),J=A.Library("libc",{ioctl:["int",["int","ulong","pointer"]]}),Y=process.platform==="darwin"?1074295912:21523,Z=new $;if(J.ioctl(process.stdout.fd,Y,Z.ref())===0)return{rows:Z.ws_row,columns:Z.ws_col,pixelWidth:Z.ws_xpixel,pixelHeight:Z.ws_ypixel};return null}catch(A){return null}}function JM5(){try{if(process.stdout.isTTY&&process.stdout.columns&&process.stdout.rows)return{columns:process.stdout.columns,rows:process.stdout.rows};let A=process.stdin;if(process.stdin.isTTY&&A.columns&&A.rows)return{columns:A.columns,rows:A.rows};let Q=process.stdout;if(typeof Q.getWindowSize==="function"){let B=Q.getWindowSize();if(B[0]>0&&B[1]>0)return{columns:B[0],rows:B[1]}}return null}catch(A){return null}}function io(A){return{syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:!0,supportsCursorShape:!0,animationSupport:"fast",kittyKeyboard:!1,osc52:!1,kittyGraphics:!1,background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:$9()?"none":"standard",scrollStep:()=>3,...A}}var mh4=[{sequence:"\x1B[?1049h\x1B[H\x1B]66;w=1; \x1B\\\x1B[6n\x1B[?1049l",description:"Query Kitty explicit width support"},{sequence:"\x1B]10;?\x07",description:"Query terminal foreground color (OSC 10)"},{sequence:"\x1B]11;?\x07",description:"Query terminal background color (OSC 11)"},{sequence:"\x1B]12;?\x07",description:"Query terminal cursor color (OSC 12)"},{sequence:"\x1B]4;0;?\x07",description:"Query terminal color 0 (OSC 4)"},{sequence:"\x1B]4;1;?\x07",description:"Query terminal color 1 (OSC 4)"},{sequence:"\x1B]4;2;?\x07",description:"Query terminal color 2 (OSC 4)"},{sequence:"\x1B]4;3;?\x07",description:"Query terminal color 3 (OSC 4)"},{sequence:"\x1B]4;4;?\x07",description:"Query terminal color 4 (OSC 4)"},{sequence:"\x1B]4;5;?\x07",description:"Query terminal color 5 (OSC 4)"},{sequence:"\x1B]4;6;?\x07",description:"Query terminal color 6 (OSC 4)"},{sequence:"\x1B]4;7;?\x07",description:"Query terminal color 7 (OSC 4)"},{sequence:"\x1B[?2026$p",description:"Query synchronized output support"},{sequence:"\x1B[?2027$p",description:"Query emoji width mode support"},{sequence:"\x1B[?1016$p",description:"Query pixel mouse mode support"},{sequence:"\x1B[?2031$p",description:"Query color palette change notifications support (mode 2031)"},{sequence:"\x1B[?u",description:"Query Kitty keyboard protocol support"},{sequence:"\x1B[>0q",description:"Query terminal version (XTVERSION)"},{sequence:"\x1BP+q4d73\x1B\\",description:"Query OSC 52 clipboard support (XTGETTCAP Ms)"},{sequence:SD("\x1B_Gi=1,a=q\x1B\\"),description:"Query Kitty graphics protocol support",shouldSend:()=>{return!$9()&&process.env.TERM_PROGRAM!=="Apple_Terminal"&&!_x()}},{sequence:"\x1B[c",description:"Device Attributes (DA1)",isFinal:!0}];class dX0{options;capabilities;constructor(A={}){this.options=A;this.capabilities={syncOutput:!1,emojiWidth:!1,pixelMouse:!1,pixelDimensions:!1,xtversion:null,canRgb:this.detectRgbSupport(),supportsCursorShape:this.detectCursorShapeSupport(),animationSupport:this.detectAnimationSupport(),kittyKeyboard:!1,osc52:!1,kittyGraphics:this.detectKittyGraphicsFromEnv(),background:"unknown",colorPaletteNotifications:!1,kittyExplicitWidth:!1,underlineSupport:$9()?"none":"standard",scrollStep:()=>this.getScrollStep()}}complete=!1;colorUpdateTimer=null;onColorPaletteChange;inbandPixelData=null;kittyWidthQuerySent=!1;rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]};processDecrqss(A,Q){if(A==="?2026")this.capabilities.syncOutput=Q==="1"||Q==="2";if(A==="?2027")this.capabilities.emojiWidth=Q==="1"||Q==="2";if(A==="?1016")this.capabilities.pixelMouse=Q==="1"||Q==="2";if(A==="?2031")this.capabilities.colorPaletteNotifications=Q==="1"||Q==="2";if(A==="u")this.capabilities.kittyKeyboard=!0;return!1}processDeviceAttributes(A,Q){if(this.checkPixelDimensions(),this.detectJetBrains()||this.detectTmux())this.capabilities.emojiWidth=!0;return this.complete=!0,!0}processXtversion(A){this.capabilities.xtversion=A;let Q=["ghostty","kitty","wezterm","foot","alacritty","iterm2","tmux"],B=A.toLowerCase();if(Q.some(($)=>B.includes($)))this.capabilities.osc52=!0;return!1}processXtgettcap(A,Q){if(A.toLowerCase()==="4d73")this.capabilities.osc52=Q.length>0;return!1}processKittyGraphics(){if(this.isITerm2())return this.capabilities.kittyGraphics=!1,!1;return this.capabilities.kittyGraphics=!0,!1}processCursorPositionReport(A,Q){if(this.kittyWidthQuerySent){if(A===1&&Q===2)this.capabilities.kittyExplicitWidth=!0,j.info("Kitty explicit width support detected");this.kittyWidthQuerySent=!1}return!1}markKittyWidthQuerySent(){this.kittyWidthQuerySent=!0}processOsc10(A){let Q=A.match(/^10;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),F=Math.round(Y($)),X=Math.round(Y(J));return this.rgbColors.foreground={r:Z,g:F,b:X},!1}processOsc11(A){let Q=A.match(/^11;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},Z=Math.round(Y(B)),F=Math.round(Y($)),X=Math.round(Y(J));this.rgbColors.background={r:Z,g:F,b:X};let D=0.299*Z+0.587*F+0.114*X;return this.capabilities.background=D<128?"dark":"light",!1}processOsc12(A){let Q=A.match(/^12;rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3])return!1;let B=Q[1],$=Q[2],J=Q[3],Y=(D)=>{let G=Number.parseInt(D,16),V=D.length*4;return G/(2**V-1)*255},Z=Math.round(Y(B)),F=Math.round(Y($)),X=Math.round(Y(J));return this.rgbColors.cursor={r:Z,g:F,b:X},!1}processOsc4(A){let Q=A.match(/^4;(\d+);rgba?:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!Q||!Q[1]||!Q[2]||!Q[3]||!Q[4])return!1;let B=Number.parseInt(Q[1],10),$=Q[2],J=Q[3],Y=Q[4],Z=(G)=>{let V=Number.parseInt(G,16),U=G.length*4;return V/(2**U-1)*255},F=Math.round(Z($)),X=Math.round(Z(J)),D=Math.round(Z(Y));if(B>=0&&B<=7)this.rgbColors.indices[B]={r:F,g:X,b:D};return!1}setColorPaletteChangeCallback(A){this.onColorPaletteChange=A}handleColorPaletteChangeNotification(){if(j.info("Color palette changed, re-querying colors..."),this.rgbColors={foreground:null,background:null,cursor:null,indices:[null,null,null,null,null,null,null,null]},this.colorUpdateTimer)clearTimeout(this.colorUpdateTimer);this.colorUpdateTimer=setTimeout(()=>{let A=this.getRgbColors();if(this.onColorPaletteChange&&A)j.info("Color re-query complete, notifying callback"),this.onColorPaletteChange();this.colorUpdateTimer=null},200)}getColorQuerySequences(){return["\x1B]10;?\x07","\x1B]11;?\x07","\x1B]12;?\x07","\x1B]4;0;?\x07","\x1B]4;1;?\x07","\x1B]4;2;?\x07","\x1B]4;3;?\x07","\x1B]4;4;?\x07","\x1B]4;5;?\x07","\x1B]4;6;?\x07","\x1B]4;7;?\x07"]}updateInbandPixelData(A,Q,B,$){if(B&&$&&B>0&&$>0)this.inbandPixelData={pixelWidth:B,pixelHeight:$,columns:A,rows:Q},this.capabilities.pixelDimensions=!0}checkPixelDimensions(){if(this.inbandPixelData){this.capabilities.pixelDimensions=!0;return}let A=Ce0();this.capabilities.pixelDimensions=!!(A&&A.pixelWidth>0&&A.pixelHeight>0)}isComplete(){return this.complete}getCapabilities(){return{...this.capabilities}}getRgbColors(){if(!this.rgbColors.foreground||!this.rgbColors.background||!this.rgbColors.cursor)return j.info("Missing fg, bg, or cursor color",{fg:!!this.rgbColors.foreground,bg:!!this.rgbColors.background,cursor:!!this.rgbColors.cursor}),null;for(let A=0;A<8;A++)if(!this.rgbColors.indices[A])return j.info(`Missing palette color ${A}`),null;return j.info("All RGB colors available",{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indicesCount:this.rgbColors.indices.filter((A)=>A!==null).length}),{fg:this.rgbColors.foreground,bg:this.rgbColors.background,cursor:this.rgbColors.cursor,indices:this.rgbColors.indices}}shouldUsePixelMouse(){return this.capabilities.pixelMouse&&this.capabilities.pixelDimensions}getPixelDimensions(){if(this.inbandPixelData)return this.inbandPixelData;let A=Ce0();if(A&&A.pixelWidth>0&&A.pixelHeight>0)return{pixelWidth:A.pixelWidth,pixelHeight:A.pixelHeight,columns:A.columns,rows:A.rows};return null}getPendingQueries(){return this.complete?[]:["\x1B[c"]}detectKittyGraphicsFromEnv(){let A=["kitty","ghostty","wezterm"];if(TD())try{let Q="",B="";try{Q=gh4("tmux show-environment -g TERM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM=/,"").toLowerCase()}catch{}try{B=gh4("tmux show-environment -g TERM_PROGRAM 2>/dev/null",{encoding:"utf8",timeout:1000}).trim().replace(/^TERM_PROGRAM=/,"").toLowerCase()}catch{}for(let $ of A)if(Q.includes($)||B.includes($))return j.debug("Detected Kitty graphics support from tmux environment",{term:Q,termProgram:B}),!0}catch{}return!1}detectRgbSupport(){if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;return!0}detectCursorShapeSupport(){return!this.detectEmacs()&&!this.detectJetBrains()}detectAnimationSupport(){if(this.options.animationDisabled)return"disabled";if(process.env.NO_ANIMATION==="1"||process.env.NO_ANIMATIONS==="1")return"disabled";if(this.detectEmacs()||this.detectSSH())return"disabled";if(this.detectAppleTerminalUnderTmux())return"disabled";if(this.detectJetBrains())return"slow";return"fast"}detectEmacs(){return!!process.env.INSIDE_EMACS}detectJetBrains(){return process.env.TERMINAL_EMULATOR?.includes("JetBrains")??!1}detectSSH(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}detectTmux(){return!!process.env.TMUX}detectAppleTerminalUnderTmux(){return!!process.env.TMUX&&process.env.__CFBundleIdentifier==="com.apple.Terminal"}isITerm2(){if(this.capabilities.xtversion?.toLowerCase().includes("iterm2"))return!0;return process.env.TERM_PROGRAM==="iTerm.app"}getScrollStep(){if(this.capabilities.xtversion?.startsWith("ghostty"))return 1;if($9())return 1;return 3}}c0();import{execFile as Rj}from"node:child_process";import{existsSync as YM5}from"node:fs";import{platform as cX0}from"node:os";import{promisify as ZM5}from"node:util";var no=ZM5(Rj);function ph4(){if(cX0()!=="linux")return!1;return Boolean(process.env.WSL_DISTRO_NAME)||YM5("/proc/sys/fs/binfmt_misc/WSLInterop")}var FM5=(A)=>`\x1B]52;c;${A}\x1B\\`,XM5="\x1B]52;c;?\x1B\\",DM5="\x1B]52;p;?\x1B\\";class dh4{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;tmuxSetClipboard="unknown";setCapabilities(A){if(this.capabilities=A,TD())this.detectTmuxSetClipboard()}detectTmuxSetClipboard(){Rj("tmux",["show-options","-s","-v","set-clipboard"],{timeout:1000},(A,Q)=>{if(!A){let B=Q.trim();if(B==="on"||B==="external"||B==="off")this.tmuxSetClipboard=B}})}isTmuxOsc52Allowed(){return this.tmuxSetClipboard==="on"||this.tmuxSetClipboard==="unknown"}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(A){try{return await no("which",[A]),!0}catch{return!1}}async writeToPbcopy(A){try{let Q=Rj("pbcopy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`pbcopy exited with code ${J}`))})}),!0}catch{return!1}}async writeToWlCopy(A){try{let Q=Rj("wl-copy");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`wl-copy exited with code ${J}`))})}),!0}catch{return!1}}async writeToXclip(A){try{let Q=Rj("xclip",["-selection","clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`xclip exited with code ${J}`))})}),!0}catch{return!1}}async writeToClipExe(A){try{let Q=Rj("clip.exe");return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`clip.exe exited with code ${J}`))})}),!0}catch{return!1}}async writeToPowerShell(A){try{let Q=Rj("powershell.exe",["-NoProfile","-Command","$Input | Set-Clipboard"]);return Q.stdin?.write(A),Q.stdin?.end(),await new Promise((B,$)=>{Q.on("close",(J)=>{if(J===0)B();else $(Error(`powershell.exe exited with code ${J}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(A){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise!==void 0)return this.pendingReadPromise;this.pendingReadPromise=new Promise((B)=>{this.readResolve=B,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,B(null)},2000),process.stdout.write(A)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(XM5)}handleOSC52Response(A){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(A,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:A}=await no("pbpaste");return A}catch{return null}}async readFromWlPaste(A){try{let Q=["--no-newline"];if(A==="primary")Q.push("--primary");let{stdout:B}=await no("wl-paste",Q);return B}catch{return null}}async readFromXclip(A){try{let{stdout:Q}=await no("xclip",["-selection",A,"-o"]);return Q}catch{return null}}async readFromPowerShell(){try{let{stdout:A}=await no("powershell.exe",["-NoProfile","-Command","Get-Clipboard"]);return A}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(DM5)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}let A=cX0();if(A==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else if(A==="win32"){let Q=await this.readFromPowerShell();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}if(ph4()){let Q=await this.readFromPowerShell();if(Q!==null)return Q}}return null}async readPrimarySelection(){let A=cX0();if(A==="darwin"||A==="win32")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(A){let Q=TD(),B=!1;if(this.isOsc52Supported()&&(!Q||this.isTmuxOsc52Allowed())){let J=Buffer.from(A).toString("base64"),Y=FM5(J);if(process.stdout.write(Y),B=!0,!Q)return!0}let $=cX0();if($==="darwin"){if(await this.writeToPbcopy(A))return!0}else if($==="win32"){if(await this.writeToPowerShell(A))return!0;if(await this.writeToClipExe(A))return!0}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(A))return!0;if(await this.commandExists("xclip")&&await this.writeToXclip(A))return!0;if(ph4()){if(await this.writeToPowerShell(A))return!0}}if(B)return!0;return!1}}var gF=new dh4;function GM5(A){return A.replace(/\r\n|\r/g,`
|
|
5577
5577
|
`)}function VM5(A){return A.replace(/[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F]/g,"")}function ch4(A){let Q=A;return Q=GM5(Q),Q=VM5(Q),Q}var UM5=50,KM5=200,EM5=200,WM5=50;class ih4{eventBuffer=[];bufferTimer=null;filterDirection=null;lastEventTime=0;onEmitEvent=()=>{};constructor(A){this.onEmitEvent=A}handleWheelEvent(A){if(A.button!=="wheel_up"&&A.button!=="wheel_down")return!0;let Q=Date.now();if(this.filterDirection!==null)if(Q-this.lastEventTime>KM5)this.filterDirection=null;else return this.lastEventTime=Q,A.button===this.filterDirection;if(this.lastEventTime=Q,this.eventBuffer.push(A),!this.bufferTimer)this.bufferTimer=setTimeout(()=>{this.processBuffer()},UM5);return!1}processBuffer(){if(this.bufferTimer=null,this.eventBuffer.length===0)return;if(this.eventBuffer.some((Q)=>Q.button==="wheel_down")){this.filterDirection="wheel_down";for(let Q of this.eventBuffer)if(Q.button==="wheel_down")this.onEmitEvent(Q)}else{this.filterDirection="wheel_up";for(let Q of this.eventBuffer)this.onEmitEvent(Q)}this.eventBuffer=[]}}class Me0{parser=null;initialized=!1;inAltScreen=!1;suspended=!1;tty;screen;renderer;queryParser=null;capabilities=null;capabilityPromise=null;capabilityResolve=null;capabilityTimeout=null;windowsKittyProbeTimeout=null;windowsKittyProbePending=!1;terminalSize={width:80,height:24};jetBrainsWheelFilter;keyHandlers=[];mouseHandlers=[];resizeHandlers=[];focusHandlers=[];pasteHandlers=[];capabilityHandlers=[];boundHandleResize=this.handleResize.bind(this);boundCleanup=this.cleanup.bind(this);boundExitCleanup=this.exitCleanup.bind(this);boundHandleResume=this.handleResume.bind(this);resizeDebounceTimer=null;pendingResize=!1;lastRenderDiffStats={repaintedCellCount:0,totalCellCount:1920,repaintedPercent:0,bytesWritten:0};options={};constructor(){this.screen=new pY(80,24),this.renderer=new ko,this.tty=EX0(),this.jetBrainsWheelFilter=new ih4((A)=>{for(let Q of this.mouseHandlers)Q(A)})}setOptions(A){this.options={...this.options,...A}}init(){if(this.initialized)throw Error("TUI is already initialized");try{if(this.parser=new Ij,this.parser.onKey(this.handleKeyEvent.bind(this)),this.parser.onPaste(this.handlePasteEvent.bind(this)),this.parser.onOsc(this.handleOscEvent.bind(this)),this.queryParser=new dX0(this.options.queryOptions),this.parser.onDeviceAttributes((A)=>{if(this.queryParser&&this.initialized){if(this.queryParser.processDeviceAttributes(A.primary,A.secondary))this.finishInitialization()}}),this.parser.onDecrqss((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processDecrqss(A.request,A.response),this.handleWindowsKittyProbeResponse(A.request,A.response)}),this.parser.onDcs((A)=>{if(this.queryParser&&this.initialized){if(A.final==="|"&&A.private===">")this.queryParser.processXtversion(A.data);if(A.final==="r"&&A.intermediates==="+"&&A.params.length>0&&A.params[0]?.value===1)this.parseXtgettcapResponse(A.data)}}),this.parser.onApc((A)=>{if(this.queryParser&&this.initialized){if(A.data.startsWith("G"))this.queryParser.processKittyGraphics()}}),this.parser.onCursorPositionReport((A)=>{if(this.queryParser&&this.initialized)this.queryParser.processCursorPositionReport(A.row,A.col)}),this.parser.onColorPaletteChange((A)=>{if(this.queryParser&&this.initialized){j.info("Color palette change detected, re-querying colors");let Q=this.queryParser.getColorQuerySequences();for(let B of Q)process.stdout.write(B);this.queryParser.handleColorPaletteChangeNotification()}}),this.parser.onMouse((A)=>{if($9()&&!this.jetBrainsWheelFilter.handleWheelEvent(A))return;for(let Q of this.mouseHandlers)Q(A)}),this.parser.onFocus((A)=>{for(let Q of this.focusHandlers)Q(A)}),this.parser.onResize((A)=>{this.handleInbandResize(A)}),this.tty.on("data",(A)=>{this.parser?.parse(A)}),this.tty.resume(),process.on("SIGWINCH",this.boundHandleResize),process.stdout.isTTY)process.stdout.on("resize",this.boundHandleResize);this.updateTerminalSize(),this.screen.resize(this.terminalSize.width,this.terminalSize.height),this.setupCleanupHandlers(),this.initialized=!0,this.enableMouse(),this.enableBracketedPaste(),this.createCapabilityPromise(),this.startCapabilityDetection()}catch(A){throw this.deinit().catch(()=>{}),A}}async deinit(){if(this.initialized){let A="",Q="",B=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys(),$=async(J)=>{if(!J)return;await new Promise((Y)=>{process.stdout.write(J,()=>{Y()})})};if(A+=this.renderer.endSync(),this.inAltScreen)A+=this.renderer.clearScreen()+B+this.renderer.exitAltScreen(),B="",this.inAltScreen=!1;if(Q+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+B+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)Q+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))Q+=this.renderer.setProgressBarOff();if(await $(A),process.platform==="win32"&&A)await new Promise((J)=>{setTimeout(J,WM5)});await $(Q)}if(this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer),this.resizeDebounceTimer=null;if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;if(this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;this.windowsKittyProbePending=!1,this.keyHandlers.length=0,this.mouseHandlers.length=0,this.resizeHandlers.length=0,this.focusHandlers.length=0,this.pasteHandlers.length=0,this.capabilityHandlers.length=0,process.removeListener("SIGWINCH",this.boundHandleResize),process.stdout.removeListener("resize",this.boundHandleResize),process.removeListener("SIGINT",this.boundCleanup),process.removeListener("SIGTERM",this.boundCleanup),process.removeListener("exit",this.boundExitCleanup),process.removeListener("SIGCONT",this.boundHandleResume),this.tty.dispose(),this.parser=null,this.queryParser=null,this.capabilities=null,this.capabilityPromise=null,this.capabilityResolve=null,this.initialized=!1}getEarlyInputText(){return this.tty.getEarlyInputText()}onKey(A){this.keyHandlers.push(A)}offKey(A){let Q=this.keyHandlers.indexOf(A);if(Q!==-1)this.keyHandlers.splice(Q,1)}onMouse(A){this.mouseHandlers.push(A)}offMouse(A){let Q=this.mouseHandlers.indexOf(A);if(Q!==-1)this.mouseHandlers.splice(Q,1)}onResize(A){this.resizeHandlers.push(A)}offResize(A){let Q=this.resizeHandlers.indexOf(A);if(Q!==-1)this.resizeHandlers.splice(Q,1)}onFocus(A){this.focusHandlers.push(A)}offFocus(A){let Q=this.focusHandlers.indexOf(A);if(Q!==-1)this.focusHandlers.splice(Q,1)}onPaste(A){this.pasteHandlers.push(A)}offPaste(A){let Q=this.pasteHandlers.indexOf(A);if(Q!==-1)this.pasteHandlers.splice(Q,1)}onCapabilities(A){this.capabilityHandlers.push(A)}offCapabilities(A){let Q=this.capabilityHandlers.indexOf(A);if(Q!==-1)this.capabilityHandlers.splice(Q,1)}isInitialized(){return this.initialized}getCapabilities(){return this.capabilities}getQueryParser(){return this.queryParser}async waitForCapabilities(A=1000){if(!this.initialized)throw Error("TUI is not initialized");if(this.capabilities)return this.capabilities;if(!this.capabilityPromise)throw Error("Capability detection not started");return this.capabilityPromise}getSize(){return{...this.terminalSize}}getScreen(){return this.screen}getLastRenderDiffStats(){return this.lastRenderDiffStats}render(){if(!this.initialized)throw Error("TUI not initialized");if(this.suspended)return;let A=this.screen.getDiff(),Q=this.screen.getSize(),B=Q.width*Q.height,$=A.length,J=B>0?$/B*100:0;this.lastRenderDiffStats={repaintedCellCount:$,totalCellCount:B,repaintedPercent:J,bytesWritten:0};let Y=this.screen.getCursor();if(A.length>0||Y!==null){let F=new So;F.append(this.renderer.startSync()),F.append(this.renderer.hideCursor()),F.append(this.renderer.reset()),F.append(this.renderer.moveTo(0,0));let X=this.renderer.render(A);if(F.append(X),Y)if(F.append(this.renderer.moveTo(Y.x,Y.y)),this.screen.isCursorVisible())F.append(this.renderer.setCursorShape(this.screen.getCursorShape())),F.append(this.renderer.showCursor());else F.append(this.renderer.hideCursor());else F.append(this.renderer.hideCursor());F.append(this.renderer.endSync());let D=F.toString();this.lastRenderDiffStats={...this.lastRenderDiffStats,bytesWritten:Buffer.byteLength(D,"utf8")},process.stdout.write(D),this.screen.present()}}clearScreen(){let A=this.renderer.clearScreen()+this.renderer.hideCursor();process.stdout.write(A),this.renderer.resetState()}showCursor(){process.stdout.write(this.renderer.showCursor())}hideCursor(){process.stdout.write(this.renderer.hideCursor())}setCursor(A,Q){this.screen.setCursor(A,Q)}clearCursor(){this.screen.clearCursor()}setCursorShape(A){this.screen.setCursorShape(A)}setMouseCursor(A){let Q=`\x1B]22;${A}\x07`;process.stdout.write(Q)}resetMouseCursor(){this.setMouseCursor(a6.DEFAULT)}enableBracketedPaste(){process.stdout.write(this.renderer.enableBracketedPaste())}disableBracketedPaste(){process.stdout.write(this.renderer.disableBracketedPaste())}enableKittyKeyboard(){process.stdout.write(this.renderer.enableKittyKeyboard())}disableKittyKeyboard(){process.stdout.write(this.renderer.disableKittyKeyboard())}enableModifyOtherKeys(){process.stdout.write(this.renderer.enableModifyOtherKeys())}disableModifyOtherKeys(){process.stdout.write(this.renderer.disableModifyOtherKeys())}async writeClipboard(A){return gF.writeText(A)}get clipboard(){return gF}enterAltScreen(){if(!this.initialized)throw Error("TUI not initialized");if(!this.inAltScreen)process.stdout.write(this.renderer.enterAltScreen()),this.inAltScreen=!0}exitAltScreen(){if(this.inAltScreen)process.stdout.write(this.renderer.exitAltScreen()),this.inAltScreen=!1}isInAltScreen(){return this.inAltScreen}enableMouse(){if(this.initialized){let A=process.platform!=="win32"&&(this.queryParser?.shouldUsePixelMouse()??!1),Q=this.renderer.enableMouse(A);process.stdout.write(Q)}}disableMouse(){if(this.initialized)process.stdout.write(this.renderer.disableMouse())}enableEmojiWidth(){if(this.initialized){let A=this.renderer.enableEmojiWidth();process.stdout.write(A)}}disableEmojiWidth(){if(this.initialized)process.stdout.write(this.renderer.disableEmojiWidth())}enableInBandResize(){if(this.initialized){let A=this.renderer.enableInBandResize();process.stdout.write(A)}}disableInBandResize(){if(this.initialized)process.stdout.write(this.renderer.disableInBandResize())}enableColorPaletteNotifications(){if(this.initialized)j.info("Enabling mode 2031 (color palette change notifications)"),process.stdout.write("\x1B[?2031h")}disableColorPaletteNotifications(){if(this.initialized)process.stdout.write("\x1B[?2031l")}setMouseShape(A){if(this.initialized)process.stdout.write(this.renderer.setMouseShape(A))}suspend(){if(!this.initialized||this.suspended)return;let A="";if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys()+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();if(this.inAltScreen)A+=this.renderer.exitAltScreen(),this.inAltScreen=!1;if(process.stdout.write(A),this.tty.pause(),this.suspended=!0,process.stdout.isTTY)process.stdout.uncork()}resume(){if(!this.initialized||!this.suspended)return;if(this.tty.resume(),this.parser)this.parser.reset();if(this.enterAltScreen(),this.hideCursor(),this.enableMouse(),this.enableBracketedPaste(),this.capabilities?.emojiWidth)this.enableEmojiWidth();if(this.capabilities?.kittyKeyboard)this.enableKittyKeyboard();this.enableModifyOtherKeys(),this.enableInBandResize(),this.screen.markForRefresh(),this.suspended=!1}isSuspended(){return this.suspended}handleSuspend(){if(!this.initialized||this.suspended)return;if(process.platform==="win32")return;this.suspend();try{process.kill(0,"SIGTSTP"),j.debug(`Successfully suspended process ${process.pid}`)}catch(A){j.debug(`Failed to suspend process ${process.pid}: ${A}`)}}handleResume(){if(!this.initialized||!this.suspended)return;this.resume(),setImmediate(()=>{if(this.initialized&&!this.suspended)this.render()})}updateTerminalSize(){if(!this.tty.stdin||!lh4(this.tty.stdin)){this.terminalSize={width:80,height:24};return}let A=zM5(process.stdout);if(A)this.terminalSize=A}handleKeyEvent(A){for(let Q of this.keyHandlers)Q(A)}handlePasteEvent(A){this.dispatchSyntheticPaste(A.text)}dispatchSyntheticPaste(A){let Q={type:"paste",text:ch4(A)};for(let B of this.pasteHandlers)B(Q)}handleOscEvent(A){if(A.data.startsWith("10;")&&this.queryParser){this.queryParser.processOsc10(A.data);return}if(A.data.startsWith("11;")&&this.queryParser){this.queryParser.processOsc11(A.data);return}if(A.data.startsWith("12;")&&this.queryParser){this.queryParser.processOsc12(A.data);return}if(A.data.startsWith("4;")&&this.queryParser){this.queryParser.processOsc4(A.data);return}if(A.data.startsWith("52;c;")){let Q=A.data.slice(5);if(Q&&Q!=="?")gF.handleOSC52Response(Q)}}createCapabilityPromise(){this.capabilityPromise=new Promise((A)=>{this.capabilityResolve=A})}startCapabilityDetection(){if(!this.tty.stdin||!lh4(this.tty.stdin)){if(this.capabilityResolve)this.capabilityResolve(null);return}if(this.queryParser=new dX0(this.options.queryOptions),process.env.TERM_PROGRAM==="Apple_Terminal"){let A=io({canRgb:!1});this.capabilities=A;let Q={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities);for(let B of this.capabilityHandlers)B(Q);if(this.capabilityResolve)this.capabilityResolve(A),this.capabilityResolve=null;return}if(process.platform==="win32"){this.startWindowsKittyProbe();return}this.sendCapabilityQueries(),this.startCapabilityTimeout()}finishInitialization(){if(!this.initialized||!this.queryParser||this.capabilities)return;if(this.capabilities=this.queryParser.getCapabilities(),this.capabilityTimeout)clearTimeout(this.capabilityTimeout),this.capabilityTimeout=null;let A={type:"capability",capabilities:this.capabilities};this.renderer.updateCapabilities(this.capabilities),XX0(this.capabilities.background);for(let Q of this.capabilityHandlers)Q(A);if(this.capabilityResolve)j.info("Terminal capabilities detected:",this.capabilities),this.capabilityResolve(this.capabilities),this.capabilityResolve=null;if(this.queryParser.shouldUsePixelMouse()){let Q=this.queryParser.getPixelDimensions();if(Q){let B=Q.pixelWidth/Q.columns,$=Q.pixelHeight/Q.rows;this.parser?.setSgrToMouseConverter((J)=>Lo(J,!0,B,$))}}if(this.capabilities.emojiWidth)this.enableEmojiWidth();if(this.capabilities.kittyKeyboard)this.enableKittyKeyboard();if(this.enableModifyOtherKeys(),this.enableInBandResize(),this.capabilities.colorPaletteNotifications)this.enableColorPaletteNotifications();gF.setCapabilities(this.capabilities)}sendCapabilityQueries(){if(!this.queryParser)return;for(let A of mh4){if(A.shouldSend&&!A.shouldSend())continue;if(process.stdout.write(A.sequence),A.description==="Query Kitty explicit width support")this.queryParser.markKittyWidthQuerySent()}}startCapabilityTimeout(){if(this.capabilityTimeout)clearTimeout(this.capabilityTimeout);this.capabilityTimeout=setTimeout(()=>{if(!this.capabilities&&this.capabilityResolve&&this.queryParser)this.finishInitialization()},2000)}startWindowsKittyProbe(){this.windowsKittyProbePending=!0,process.stdout.write(this.renderer.queryKittyKeyboard()),this.windowsKittyProbeTimeout=setTimeout(()=>{this.finishWindowsKittyProbe(!1)},EM5)}handleWindowsKittyProbeResponse(A,Q){if(process.platform!=="win32"||!this.windowsKittyProbePending||A!=="u")return;this.finishWindowsKittyProbe(!0)}finishWindowsKittyProbe(A){if(!this.windowsKittyProbePending)return;if(this.windowsKittyProbePending=!1,this.windowsKittyProbeTimeout)clearTimeout(this.windowsKittyProbeTimeout),this.windowsKittyProbeTimeout=null;if(!A)this.tty.enableWindowsVirtualTerminalInput();this.sendCapabilityQueries(),this.startCapabilityTimeout()}parseXtgettcapResponse(A){if(!this.queryParser)return;let Q=A.indexOf("=");if(Q!==-1){let B=A.slice(0,Q),$=A.slice(Q+1);if(this.queryParser.processXtgettcap(B,$))this.finishInitialization()}}handleResize(){if(this.pendingResize=!0,this.resizeDebounceTimer)clearTimeout(this.resizeDebounceTimer);this.resizeDebounceTimer=setTimeout(()=>{this.processResize()},10)}handleInbandResize(A){if(this.terminalSize={width:A.width,height:A.height},this.queryParser&&A.pixelWidth&&A.pixelHeight){let Q=this.queryParser.shouldUsePixelMouse();this.queryParser.updateInbandPixelData(A.width,A.height,A.pixelWidth,A.pixelHeight);let B=this.queryParser.shouldUsePixelMouse();if(process.platform!=="win32"&&!Q&&B)this.disableMouse(),this.enableMouse();if(B){let $=A.pixelWidth/A.width,J=A.pixelHeight/A.height;this.parser?.setSgrToMouseConverter((Y)=>Lo(Y,!0,$,J))}}this.screen.resize(A.width,A.height),setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch(B){j.error("Error in resize handler:",B)}})}processResize(){if(!this.pendingResize||!this.initialized)return;let A={...this.terminalSize};if(this.updateTerminalSize(),A.width===this.terminalSize.width&&A.height===this.terminalSize.height){this.pendingResize=!1;return}this.finishResize(),this.pendingResize=!1}finishResize(){this.screen.resize(this.terminalSize.width,this.terminalSize.height);let A={type:"resize",width:this.terminalSize.width,height:this.terminalSize.height};setImmediate(()=>{for(let Q of this.resizeHandlers)try{Q(A)}catch(B){j.error("Error in resize handler:",B)}})}setupCleanupHandlers(){process.setMaxListeners(0),process.on("SIGINT",this.boundCleanup),process.on("SIGTERM",this.boundCleanup),process.on("exit",this.boundExitCleanup),process.on("SIGCONT",this.boundHandleResume)}exitCleanup(){if(!this.initialized)return;let A=this.renderer.endSync(),Q=(this.capabilities?.kittyKeyboard?this.renderer.disableKittyKeyboard():"")+this.renderer.disableModifyOtherKeys();if(this.inAltScreen)A+=this.renderer.clearScreen()+Q+this.renderer.exitAltScreen(),Q="",this.inAltScreen=!1;if(A+=this.renderer.reset()+this.renderer.disableMouse()+this.renderer.disableEmojiWidth()+this.renderer.disableInBandResize()+this.renderer.disableBracketedPaste()+Q+this.renderer.setCursorShape(0)+this.renderer.showCursor(),this.capabilities?.colorPaletteNotifications)A+="\x1B[?2031l";if(this.capabilities?.xtversion?.startsWith("ghostty"))A+=this.renderer.setProgressBarOff();try{process.stdout.write(A)}catch{}this.tty.dispose(),this.initialized=!1}cleanup(){this.deinit().catch(()=>{})}}function lh4(A){return"isTTY"in A&&A.isTTY===!0&&typeof A.setRawMode==="function"}function zM5(A){try{if(A._refreshSize?.(),A.isTTY&&A.columns&&A.rows)return{width:A.columns,height:A.rows};let Q=A.getWindowSize?.();if(Q&&Q[0]>0&&Q[1]>0)return{width:Q[0],height:Q[1]}}catch{}return null}c0();c0();var ao;((J)=>{J.BUILD="build";J.LAYOUT="layout";J.PAINT="paint";J.RENDER="render"})(ao||={});var HM5=60,RU=1000/HM5;function qM5(){if(typeof process>"u")return!1;return process.env.BUN_TEST==="1"||process.env.VITEST==="true"||process.env.NODE_TEST_CONTEXT==="1"}class D6{static _instance;_frameCallbacks=new Map;_postFrameCallbacks=[];_frameScheduled=!1;_frameInProgress=!1;_executingPostFrameCallbacks=!1;_pendingFrameImmediate=null;_pendingFrameTimer=null;_lastFrameTimestamp=0;_useFramePacing=!qM5();_stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}};_lastCompletedStats=this.deepCopyStats(this._stats);static get instance(){return D6._instance??=new D6}requestFrame(){if(this._frameScheduled)return;if(this._frameInProgress){this._frameScheduled=!0;return}if(!this._useFramePacing){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let A=performance.now(),Q=this._lastFrameTimestamp,B=A-Q;if(Q===0||B>=RU){this._frameScheduled=!0,this.scheduleFrameExecution(0);return}let $=Math.max(0,RU-B);this._frameScheduled=!0,this.scheduleFrameExecution($)}scheduleFrameExecution(A){if(A<=0){this._pendingFrameImmediate=setImmediate(()=>this.runScheduledFrame());return}this._pendingFrameTimer=setTimeout(()=>this.runScheduledFrame(),A)}runScheduledFrame(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;if(this._frameInProgress)return;this.executeFrame()}addFrameCallback(A,Q,B,$=0,J){this._frameCallbacks.set(A,{callback:Q,phase:B,priority:$,name:J||A})}removeFrameCallback(A){this._frameCallbacks.delete(A)}addPostFrameCallback(A,Q){if(this._postFrameCallbacks.push({callback:A,name:Q}),!this._frameScheduled&&(!this._frameInProgress||this._executingPostFrameCallbacks))this.requestFrame()}executeFrame(){if(this._frameInProgress)return;let A=performance.now();this._frameScheduled=!1,this._frameInProgress=!0;try{for(let Q of["build","layout","paint","render"])this.executePhase(Q);this.executePostFrameCallbacks()}catch(Q){j.error("Frame execution error:",Q instanceof Error?Q.message:String(Q))}finally{if(this.recordFrameStats(performance.now()-A),this._lastFrameTimestamp=A,this._lastCompletedStats=this.deepCopyStats(this._stats),this._frameInProgress=!1,this._frameScheduled){let B=performance.now()-this._lastFrameTimestamp,$=B>=RU?0:Math.max(0,RU-B);this.scheduleFrameExecution($)}}}executePhase(A){let Q=performance.now();try{let B=Array.from(this._frameCallbacks.values()).filter(($)=>$.phase===A).sort(($,J)=>$.priority-J.priority);for(let $ of B)try{$.callback()}catch(J){j.error(`Frame callback error in ${A} phase (${$.name})`,{errorMessage:J instanceof Error?J.message:String(J),errorType:J?.constructor?.name,stackTrace:J instanceof Error?J.stack:void 0}),N4(!1,`FATAL: ${A} error in ${$.name}: ${J}`)}}finally{let B=performance.now()-Q;this.recordPhaseStats(A,B)}}executePostFrameCallbacks(){if(this._postFrameCallbacks.length===0)return;let A=this._postFrameCallbacks.splice(0);this._executingPostFrameCallbacks=!0;try{for(let{callback:Q,name:B}of A)try{Q()}catch($){j.error(`Post-frame callback error (${B||"anonymous"}):`,$ instanceof Error?$.message:String($))}}finally{this._executingPostFrameCallbacks=!1}}recordFrameStats(A){this._stats.lastFrameTime=A}recordPhaseStats(A,Q){this._stats.phaseStats[A].lastTime=Q}get isFrameScheduled(){return this._frameScheduled||this._frameInProgress}get isFrameInProgress(){return this._frameInProgress}get frameStats(){return this.deepCopyStats(this._lastCompletedStats)}deepCopyStats(A){return{...A,phaseStats:{["build"]:{...A.phaseStats.build},["layout"]:{...A.phaseStats.layout},["paint"]:{...A.phaseStats.paint},["render"]:{...A.phaseStats.render}}}}resetStats(){this._stats={lastFrameTime:0,phaseStats:{["build"]:{lastTime:0},["layout"]:{lastTime:0},["paint"]:{lastTime:0},["render"]:{lastTime:0}}}}get pendingPostFrameCallbacks(){return this._postFrameCallbacks.length}cancelPendingWork(){let A=this._pendingFrameImmediate!==null;if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;let Q=this._pendingFrameTimer!==null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;let B=this._postFrameCallbacks.length;this._postFrameCallbacks.length=0;let $=this._frameScheduled,J=this._frameInProgress;return this._frameScheduled=!1,{hadPendingImmediate:A,hadPendingTimer:Q,clearedPostFrameCallbacks:B,frameWasScheduled:$,frameInProgress:J}}dispose(){if(this._pendingFrameImmediate)clearImmediate(this._pendingFrameImmediate),this._pendingFrameImmediate=null;if(this._pendingFrameTimer)clearTimeout(this._pendingFrameTimer),this._pendingFrameTimer=null;this._frameCallbacks.clear(),this._postFrameCallbacks.length=0,this._frameScheduled=!1,this._frameInProgress=!1,this._lastFrameTimestamp=0,this.resetStats()}}class Le0{_dirtyElements=new Set;_stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0};_buildTimes=[];_elementsPerFrame=[];constructor(){}scheduleBuildFor(A){if(this._dirtyElements.has(A))return;this._dirtyElements.add(A),D6.instance.requestFrame()}buildScopes(){if(this._dirtyElements.size===0)return;let A=performance.now(),Q=0;try{while(this._dirtyElements.size>0){let B=Array.from(this._dirtyElements);this._dirtyElements.clear(),B.sort(($,J)=>$.depth-J.depth);for(let $ of B)if($.dirty)try{$.performRebuild(),$._dirty=!1,Q++}catch(J){j.error("Element rebuild error:",{error:J instanceof Error?J.message:String(J),stack:J instanceof Error?J.stack:void 0,elementType:$.widget.constructor.name,elementDebugLabel:$.widget.debugLabel}),$._dirty=!1}}}finally{this.recordBuildStats(performance.now()-A,Q)}}recordBuildStats(A,Q){if(this._stats.totalRebuilds+=Q,this._stats.elementsRebuiltThisFrame=Q,this._stats.lastBuildTime=A,this._stats.maxElementsPerFrame=Math.max(this._stats.maxElementsPerFrame,Q),this._stats.maxBuildTime=Math.max(this._stats.maxBuildTime,A),this._buildTimes.push(A),this._elementsPerFrame.push(Q),this._buildTimes.length>60)this._buildTimes.shift(),this._elementsPerFrame.shift();this._stats.averageBuildTime=this._buildTimes.reduce((B,$)=>B+$,0)/this._buildTimes.length,this._stats.averageElementsPerFrame=this._elementsPerFrame.reduce((B,$)=>B+$,0)/this._elementsPerFrame.length}get dirtyElements(){return Array.from(this._dirtyElements)}get hasDirtyElements(){return this._dirtyElements.size>0}get buildStats(){return{...this._stats}}resetBuildStats(){this._stats={totalRebuilds:0,elementsRebuiltThisFrame:0,maxElementsPerFrame:0,averageElementsPerFrame:0,lastBuildTime:0,averageBuildTime:0,maxBuildTime:0},this._buildTimes.length=0,this._elementsPerFrame.length=0}dispose(){this._dirtyElements.clear()}}function mF(A,Q){if(A.length===0)return 0;let B=[...A].sort((Y,Z)=>Y-Z),$=Math.max(0,Math.min(Q,1)),J=Math.ceil(B.length*$)-1;return B[Math.max(0,J)]||0}class nh4{frameTimes=[];phaseTimes={build:[],layout:[],paint:[],render:[]};keyEventTimes=[];mouseEventTimes=[];repaintPercents=[];bytesWritten=[];lastKeyEventTime=0;lastMouseEventTime=0;lastRepaintPercent=0;lastBytesWritten=0;MAX_SAMPLES=1024;recordFrame(A){if(this.frameTimes.push(A),this.frameTimes.length>this.MAX_SAMPLES)this.frameTimes.shift()}recordPhase(A,Q){let B=this.phaseTimes[A];if(B.push(Q),B.length>this.MAX_SAMPLES)B.shift()}recordKeyEvent(A){if(this.lastKeyEventTime=A,this.keyEventTimes.push(A),this.keyEventTimes.length>this.MAX_SAMPLES)this.keyEventTimes.shift()}recordMouseEvent(A){if(this.lastMouseEventTime=A,this.mouseEventTimes.push(A),this.mouseEventTimes.length>this.MAX_SAMPLES)this.mouseEventTimes.shift()}recordRepaintPercent(A){if(this.lastRepaintPercent=A,this.repaintPercents.push(A),this.repaintPercents.length>this.MAX_SAMPLES)this.repaintPercents.shift()}recordBytesWritten(A){if(this.lastBytesWritten=A,this.bytesWritten.push(A),this.bytesWritten.length>this.MAX_SAMPLES)this.bytesWritten.shift()}getFrameP99(){return mF(this.frameTimes,0.99)}getFrameP95(){return mF(this.frameTimes,0.95)}getPhaseP99(A){return mF(this.phaseTimes[A],0.99)}getPhaseP95(A){return mF(this.phaseTimes[A],0.95)}getLastKeyEventTime(){return this.lastKeyEventTime}getKeyEventP99(){return mF(this.keyEventTimes,0.99)}getKeyEventP95(){return mF(this.keyEventTimes,0.95)}getLastMouseEventTime(){return this.lastMouseEventTime}getMouseEventP99(){return mF(this.mouseEventTimes,0.99)}getMouseEventP95(){return mF(this.mouseEventTimes,0.95)}getLastRepaintPercent(){return this.lastRepaintPercent}getRepaintPercentP99(){return mF(this.repaintPercents,0.99)}getRepaintPercentP95(){return mF(this.repaintPercents,0.95)}getLastBytesWritten(){return this.lastBytesWritten}getBytesWrittenP99(){return mF(this.bytesWritten,0.99)}getBytesWrittenP95(){return mF(this.bytesWritten,0.95)}reset(){this.frameTimes=[];for(let A of Object.values(ao))this.phaseTimes[A]=[];this.keyEventTimes=[],this.mouseEventTimes=[],this.repaintPercents=[],this.bytesWritten=[],this.lastKeyEventTime=0,this.lastMouseEventTime=0,this.lastRepaintPercent=0,this.lastBytesWritten=0}}class Oe0{enabled=!1;tracker=new nh4;setEnabled(A){this.enabled=A}isEnabled(){return this.enabled}recordKeyEvent(A){this.tracker.recordKeyEvent(A)}recordMouseEvent(A){this.tracker.recordMouseEvent(A)}recordStats(A,Q){this.tracker.recordFrame(A.lastFrameTime);for(let B of Object.values(ao))this.tracker.recordPhase(B,A.phaseStats[B].lastTime);if(Q)this.tracker.recordRepaintPercent(Q.repaintedPercent),this.tracker.recordBytesWritten(Q.bytesWritten)}draw(A,Q){if(!this.enabled)return;let{width:B,height:$}=A.getSize(),J=34,Y=14,Z=B-J-2,F=1;if(Z<0||F+Y>=$)return;let X=Y2.default().colorScheme,D=X.border,G=X.foreground,V=X.warning,U=" Gotta Go Fast ",K=Math.floor((J-U.length)/2);A.setCell(Z,F,FA("╭",{fg:G}));for(let j0=1;j0<J-1;j0++)if(j0>=K&&j0<K+U.length)A.setCell(Z+j0,F,FA(U[j0-K]||"─",{fg:V}));else A.setCell(Z+j0,F,FA("─",{fg:G}));A.setCell(Z+J-1,F,FA("╮",{fg:G}));for(let j0=1;j0<Y-1;j0++){A.setCell(Z,F+j0,FA("│",{fg:G})),A.setCell(Z+J-1,F+j0,FA("│",{fg:G}));for(let b0=1;b0<J-1;b0++)A.setCell(Z+b0,F+j0,FA(" ",{fg:G}))}A.setCell(Z,F+Y-1,FA("╰",{fg:G}));for(let j0=1;j0<J-1;j0++)A.setCell(Z+j0,F+Y-1,FA("─",{fg:G}));A.setCell(Z+J-1,F+Y-1,FA("╯",{fg:G}));let E=Z+1,W=F+1;this.drawText(A,E,W++," Last P95 P99",D);let z=this.tracker.getLastKeyEventTime(),H=this.tracker.getKeyEventP95(),q=this.tracker.getKeyEventP99(),N=z.toFixed(2).padStart(5," "),I=H.toFixed(2).padStart(5," "),w=q.toFixed(2).padStart(5," "),C=this.getTimingColor(z),O=this.getTimingColor(H),R=this.getTimingColor(q);this.drawLastP95P99Row(A,E,W++,{label:"Key",labelColor:D,last:{text:N,color:C},p95:{text:I,color:O},p99:{text:w,color:R}});let S=this.tracker.getLastMouseEventTime(),T=this.tracker.getMouseEventP95(),f=this.tracker.getMouseEventP99(),h=S.toFixed(2).padStart(5," "),x=T.toFixed(2).padStart(5," "),k=f.toFixed(2).padStart(5," "),b=this.getTimingColor(S),c=this.getTimingColor(T),l=this.getTimingColor(f);this.drawLastP95P99Row(A,E,W++,{label:"Mouse",labelColor:D,last:{text:h,color:b},p95:{text:x,color:c},p99:{text:k,color:l}}),W++;for(let j0 of["build","layout","paint","render"]){let b0=Q.phaseStats[j0].lastTime,h0=this.tracker.getPhaseP95(j0),Z1=this.tracker.getPhaseP99(j0),x1=b0.toFixed(2).padStart(5," "),K4=h0.toFixed(2).padStart(5," "),i1=Z1.toFixed(2).padStart(5," "),a0=this.getTimingColor(b0),C0=this.getTimingColor(h0),R0=this.getTimingColor(Z1),d0=j0.charAt(0).toUpperCase()+j0.slice(1);this.drawLastP95P99Row(A,E,W++,{label:d0,labelColor:D,last:{text:x1,color:a0},p95:{text:K4,color:C0},p99:{text:i1,color:R0}})}W++;let g=Q.lastFrameTime,i=this.tracker.getFrameP95(),d=this.tracker.getFrameP99(),Q0=g.toFixed(2).padStart(5," "),H0=i.toFixed(2).padStart(5," "),a=d.toFixed(2).padStart(5," "),I0=this.getTimingColor(g),F0=this.getTimingColor(i),_0=this.getTimingColor(d);this.drawLastP95P99Row(A,E,W++,{label:"Frame",labelColor:G,last:{text:Q0,color:I0},p95:{text:H0,color:F0},p99:{text:a,color:_0}});let B0=this.tracker.getLastRepaintPercent(),K0=this.tracker.getRepaintPercentP95(),o=this.tracker.getRepaintPercentP99(),r=`${B0.toFixed(1)}%`.padStart(5," "),t=`${K0.toFixed(1)}%`.padStart(5," "),e=`${o.toFixed(1)}%`.padStart(5," "),D0=this.getPercentColor(B0),Z0=this.getPercentColor(K0),M0=this.getPercentColor(o);this.drawLastP95P99Row(A,E,W++,{label:"Repaint",labelColor:G,last:{text:r,color:D0},p95:{text:t,color:Z0},p99:{text:e,color:M0}});let L0=this.formatBytes(this.tracker.getLastBytesWritten()).padStart(5," "),O0=this.formatBytes(this.tracker.getBytesWrittenP95()).padStart(5," "),Y0=this.formatBytes(this.tracker.getBytesWrittenP99()).padStart(5," ");this.drawLastP95P99Row(A,E,W,{label:"Bytes",labelColor:G,last:{text:L0,color:G},p95:{text:O0,color:G},p99:{text:Y0,color:G}})}drawLastP95P99Row(A,Q,B,$){let J=` ${$.label.padStart(7," ")} `,Y=Q;this.drawText(A,Y,B,J,$.labelColor),Y+=J.length,this.drawText(A,Y,B,$.last.text,$.last.color),Y+=$.last.text.length,this.drawText(A,Y,B," ",$.labelColor),Y+=3,this.drawText(A,Y,B,$.p95.text,$.p95.color),Y+=$.p95.text.length,this.drawText(A,Y,B," ",$.labelColor),Y+=3,this.drawText(A,Y,B,$.p99.text,$.p99.color)}getTimingColor(A){let Q=Y2.default().colorScheme,B=RU,$=RU*0.7;if(A>=B)return Q.destructive;if(A>=$)return Q.warning;return Q.foreground}getPercentColor(A){let Q=Y2.default().colorScheme;if(A>=50)return Q.destructive;if(A>=20)return Q.warning;return Q.foreground}drawText(A,Q,B,$,J){for(let Y=0;Y<$.length;Y++)A.setCell(Q+Y,B,FA($[Y]||" ",{fg:J}))}formatBytes(A){if(A>=1e4)return`${Math.round(A/1000)}k`;if(A>=1000)return`${(A/1000).toFixed(1)}k`;return`${Math.round(A)}`}}class nx{size;capabilities;constructor(A,Q){this.size=A;this.capabilities=Q}get supportsEmojiWidth(){return this.capabilities.emojiWidth}get supportsSyncOutput(){return this.capabilities.syncOutput}}class t1 extends q6{data;constructor({key:A,data:Q,child:B}){super(A!==void 0?{key:A,child:B}:{child:B});this.data=Q}updateShouldNotify(A){return this.data!==A.data||this.data.size.width!==A.data.size.width||this.data.size.height!==A.data.size.height||this.data.capabilities!==A.data.capabilities}static of(A){let Q=A.dependOnInheritedWidgetOfExactType(t1);if(!Q)throw Error("MediaQuery not found in context. Wrap your app with MediaQuery widget.");return Q.data}static sizeOf(A){return t1.of(A).size}static capabilitiesOf(A){return t1.of(A).capabilities}}class je0{_nodesNeedingPaint=new Set;_rootRenderObject=null;_rootConstraints=null;constructor(){}requestLayout(A){if(!D6.instance.isFrameInProgress)D6.instance.requestFrame()}requestPaint(A){if(this._nodesNeedingPaint.has(A))return;if(this._nodesNeedingPaint.add(A),!D6.instance.isFrameInProgress)D6.instance.requestFrame()}setRootRenderObject(A){this._rootRenderObject=A}updateRootConstraints(A){let Q=new M1(0,A.width,0,A.height),B=!this._rootConstraints||this._rootConstraints.maxWidth!==Q.maxWidth||this._rootConstraints.maxHeight!==Q.maxHeight;if(this._rootConstraints=Q,B&&this._rootRenderObject&&"markNeedsLayout"in this._rootRenderObject)this._rootRenderObject.markNeedsLayout()}flushLayout(){let A=!1;if(this._rootRenderObject&&this._rootConstraints&&"needsLayout"in this._rootRenderObject&&this._rootRenderObject.needsLayout){if("layout"in this._rootRenderObject&&typeof this._rootRenderObject.layout==="function")this._rootRenderObject.layout(this._rootConstraints),A=!0}return A}flushPaint(){if(this._nodesNeedingPaint.size===0)return;try{for(let A of this._nodesNeedingPaint)if(A.needsPaint)A._needsPaint=!1}finally{this._nodesNeedingPaint.clear()}}get nodesNeedingLayout(){return[]}get nodesNeedingPaint(){return Array.from(this._nodesNeedingPaint)}get hasNodesNeedingLayout(){return Boolean(this._rootRenderObject&&this._rootRenderObject.needsLayout)}get hasNodesNeedingPaint(){return this._nodesNeedingPaint.size>0}dispose(){this._nodesNeedingPaint.clear()}removeFromQueues(A){this._nodesNeedingPaint.delete(A)}}class C4{static _instance;frameScheduler=D6.instance;buildOwner;pipelineOwner;focusManager=b8.instance;mouseManager=P3.instance;frameStatsOverlay=new Oe0;tui=new Me0;rootElement;isRunning=!1;rootElementMountedCallback;forcePaintOnNextFrame=!1;shouldPaintCurrentFrame=!1;didPaintCurrentFrame=!1;eventCallbacks={key:[],mouse:[],paste:[]};keyInterceptors=[];rgbColorChangeCallbacks=[];cachedRgbColors=null;static get instance(){return C4._instance??=new C4}pendingResizeEvent=null;constructor(){this.buildOwner=new Le0,this.pipelineOwner=new je0,this.frameScheduler.addFrameCallback("frame-start",()=>this.beginFrame(),"build",-2000,"WidgetsBinding.beginFrame"),this.frameScheduler.addFrameCallback("resize",()=>this.processResizeIfPending(),"build",-1000,"WidgetsBinding.processResizeIfPending"),this.frameScheduler.addFrameCallback("build",()=>{this.buildOwner.buildScopes(),this.updateRootRenderObject()},"build",0,"BuildOwner.buildScopes"),this.frameScheduler.addFrameCallback("layout",()=>{if(this.updateRootConstraints(),this.pipelineOwner.flushLayout())this.shouldPaintCurrentFrame=!0},"layout",0,"PipelineOwner.flushLayout"),this.frameScheduler.addFrameCallback("paint",()=>this.paint(),"paint",0,"WidgetsBinding.paint"),this.frameScheduler.addFrameCallback("render",()=>this.render(),"render",0,"WidgetsBinding.render"),Cu4({scheduleBuildFor:(A)=>this.buildOwner.scheduleBuildFor(A)},{requestLayout:(A)=>this.pipelineOwner.requestLayout(A),requestPaint:(A)=>this.pipelineOwner.requestPaint(A),removeFromQueues:(A)=>this.pipelineOwner.removeFromQueues(A)}),this.setupErrorHandler()}setupErrorHandler(){process.on("uncaughtException",(A)=>{j.error("Framework uncaught exception",A)})}getRgbColors(){return this.cachedRgbColors}onRgbColorsChanged(A){return this.rgbColorChangeCallbacks.push(A),()=>{let Q=this.rgbColorChangeCallbacks.indexOf(A);if(Q!==-1)this.rgbColorChangeCallbacks.splice(Q,1)}}notifyRgbColorsChanged(){for(let A of this.rgbColorChangeCallbacks)A()}updateRgbColors(A){this.cachedRgbColors=A;let Q=this.tui.getScreen();Q.setDefaultColors({type:"rgb",value:A.bg},{type:"rgb",value:A.fg}),Q.setIndexRgbMapping(A.indices),XX0(AI(),A.bg),this.notifyRgbColorsChanged(),this.requestForcedPaintFrame()}async runApp(A){if(this.isRunning)throw Error("App is already running");try{this.isRunning=!0,this.tui.init(),this.tui.enterAltScreen();let{initFocusTracking:Q}=await Promise.resolve().then(() => oh4);Q(this.tui);let{initIdleTracking:B}=await Promise.resolve().then(() => (iX0(),sh4));B(this.tui),await this.tui.waitForCapabilities(1000);let $=this.tui.getQueryParser(),J=$?.getRgbColors();if(j.info("Initial RGB colors from terminal",{available:!!J}),J)this.updateRgbColors(J);if($)$.setColorPaletteChangeCallback(()=>{let F=$.getRgbColors();if(F)this.updateRgbColors(F)});let Y=this.createMediaQueryWrapper(A);if(this.rootElement=Y.createElement(),this.rootElement.mount(),this.rootElementMountedCallback)this.rootElementMountedCallback(this.rootElement);let Z=this.rootElement.renderObject;if(!Z&&this.rootElement.children.length>0)Z=this.rootElement.children[0]?.renderObject;if(Z)this.pipelineOwner.setRootRenderObject(Z),this.updateRootConstraints();if(this.rootElement.renderObject)this.mouseManager.setRootRenderObject(this.rootElement.renderObject);this.mouseManager.setTui(this.tui),j.debug("Setting up event handlers..."),this.setupEventHandlers(),j.debug("Requesting initial frame..."),this.frameScheduler.requestFrame(),j.debug("Waiting for exit...",{isRunning:this.isRunning}),await this.waitForExit(),j.debug("waitForExit completed")}finally{j.debug("Cleaning up..."),await this.cleanup()}}stop(){if(this.isRunning=!1,this.exitResolve)this.exitResolve(),this.exitResolve=null}updateRootConstraints(){let A=this.tui.getSize();this.pipelineOwner.updateRootConstraints(A)}updateRootRenderObject(){if(!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(A)this.pipelineOwner.setRootRenderObject(A),this.mouseManager.setRootRenderObject(A)}processResizeIfPending(){if(!this.pendingResizeEvent)return;let A=this.pendingResizeEvent;if(this.pendingResizeEvent=null,this.rootElement){let Q={width:A.width,height:A.height},B=this.tui.getCapabilities()||io(),$=new nx(Q,B),J=this.rootElement;if(J.widget instanceof t1){let Z=new t1({data:$,child:J.widget.child});J.update(Z)}this.tui.getScreen().markForRefresh(),this.pipelineOwner.updateRootConstraints(Q),this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame(),this.frameScheduler.addPostFrameCallback(()=>{this.mouseManager.reestablishHoverState()},"MouseManager.reestablishHoverState")}}beginFrame(){this.didPaintCurrentFrame=!1,this.shouldPaintCurrentFrame=this.forcePaintOnNextFrame||this.buildOwner.hasDirtyElements||this.pipelineOwner.hasNodesNeedingLayout||this.pipelineOwner.hasNodesNeedingPaint||this.tui.getScreen().requiresFullRefresh,this.forcePaintOnNextFrame=!1}requestForcedPaintFrame(){this.forcePaintOnNextFrame=!0,this.frameScheduler.requestFrame()}paint(){if(!this.shouldPaintCurrentFrame)return;if(this.pipelineOwner.flushPaint(),!this.rootElement)return;let A=this.rootElement.renderObject;if(!A&&this.rootElement.children.length>0)A=this.rootElement.children[0]?.renderObject;if(!A)return;try{let Q=this.tui.getScreen();Q.clear(),Q.clearCursor(),this.renderRenderObject(A,Q,0,0);let B=this.frameScheduler.frameStats;this.frameStatsOverlay.recordStats(B,this.tui.getLastRenderDiffStats()),this.frameStatsOverlay.draw(Q,B),this.didPaintCurrentFrame=!0}catch(Q){j.error("Paint error:",Q)}}render(){if(!this.didPaintCurrentFrame)return;try{this.tui.render()}catch(A){j.error("Render error:",A)}}renderRenderObject(A,Q,B,$){if("paint"in A&&typeof A.paint==="function")A.paint(Q,B,$)}createMediaQueryWrapper(A){let Q=this.tui.getCapabilities()||io(),B=this.tui.getSize(),$=new nx(B,Q);return new t1({data:$,child:A})}setupEventHandlers(){this.tui.onResize((A)=>{this.mouseManager.clearHoverState(),this.pendingResizeEvent=A,this.frameScheduler.requestFrame()}),this.tui.onKey((A)=>{let Q=performance.now();for(let J of this.eventCallbacks.key)J(A);for(let J of this.keyInterceptors)if(J(A)){let Y=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(Y);return}if(this.focusManager.handleKeyEvent(A)){let J=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent(J);return}this.handleGlobalKeyEvent(A);let $=performance.now()-Q;this.frameStatsOverlay.recordKeyEvent($)}),this.tui.onMouse((A)=>{let Q=performance.now();for(let $ of this.eventCallbacks.mouse)$(A);this.mouseManager.handleMouseEvent(A);let B=performance.now()-Q;this.frameStatsOverlay.recordMouseEvent(B)}),this.tui.onPaste((A)=>{for(let Q of this.eventCallbacks.paste)Q(A);this.focusManager.handlePasteEvent(A)}),this.tui.onCapabilities((A)=>{if(this.rootElement){let Q=this.tui.getSize(),B=new nx(Q,A.capabilities),$=this.rootElement;if($.widget instanceof t1){let J=new t1({data:B,child:$.widget.child});$.update(J)}this.rootElement.markNeedsRebuild(),this.frameScheduler.requestFrame()}})}handleGlobalKeyEvent(A){if(A.ctrlKey&&A.key==="z"&&!A.shiftKey&&!A.altKey&&!A.metaKey){this.tui.handleSuspend();return}}toggleFrameStatsOverlay(){let A=!this.frameStatsOverlay.isEnabled();this.frameStatsOverlay.setEnabled(A),this.requestForcedPaintFrame()}exitPromise=null;exitResolve=null;async waitForExit(){if(this.exitPromise!==null)return this.exitPromise;return this.exitPromise=new Promise((A)=>{if(this.exitResolve=A,!this.isRunning)A()}),this.exitPromise}async cleanup(){if(this.isRunning=!1,this.rootElement)this.rootElement.unmount(),this.rootElement=void 0;this.buildOwner.dispose(),this.pipelineOwner.dispose(),this.focusManager.dispose(),this.mouseManager.dispose(),this.frameScheduler.cancelPendingWork(),this.frameScheduler.removeFrameCallback("frame-start"),this.frameScheduler.removeFrameCallback("resize"),this.frameScheduler.removeFrameCallback("build"),this.frameScheduler.removeFrameCallback("layout"),this.frameScheduler.removeFrameCallback("paint"),this.frameScheduler.removeFrameCallback("render"),await this.tui.deinit()}get tuiInstance(){return this.tui}get rootElementInstance(){return this.rootElement}setRootElementMountedCallback(A){this.rootElementMountedCallback=A}on(A,Q){let B=this.eventCallbacks[A];return B.push(Q),()=>{let $=B.indexOf(Q);if($!==-1)B.splice($,1)}}dispatchSyntheticPaste(A){this.tui.dispatchSyntheticPaste(A)}addKeyInterceptor(A){return this.keyInterceptors.push(A),()=>{let Q=this.keyInterceptors.indexOf(A);if(Q!==-1)this.keyInterceptors.splice(Q,1)}}}async function ro(A,Q){let B=C4.instance;if(Q?.onRootElementMounted)B.setRootElementMountedCallback(Q.onRootElementMounted);await B.runApp(A)}class N1 extends lQ{createElement(){return new Re0(this)}}class Re0 extends dY{_child;_context;constructor(A){super(A)}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._context=new kD(this,this.widget),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._context=void 0,super.unmount()}update(A){if(this.widget===A)return;if(super.update(A),this._context)this._context.widget=A;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context)throw Error("Cannot rebuild unmounted element");let A=this.widget.build(this._context);if(this._child){if(this._child.widget===A)return;if(this._child.widget.canUpdate(A))this._child.update(A);else{let Q=this._child,B=this.findNearestRenderObjectAncestor();if(B&&Q.renderObject)B.dropChild(Q.renderObject);else if(!B&&Q.renderObject)Q.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=A.createElement(),this.addChild(this._child),this._child.mount(),B&&this._child.renderObject)B.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!B&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}}else this._child=A.createElement(),this.addChild(this._child),this._child.mount()}findNearestRenderObjectAncestor(){let A=this.parent;while(A){if(A.renderObject){if(this._child?.renderObject&&A.renderObject===this._child.renderObject){A=A.parent;continue}return A.renderObject}A=A.parent}return}}class lY extends q6{forceDim;constructor({key:A,forceDim:Q,child:B}){super({key:A,child:B});this.forceDim=Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(lY)}static shouldForceDim(A){return lY.maybeOf(A)?.forceDim??!1}updateShouldNotify(A){return this.forceDim!==A.forceDim}}class PU extends q6{controller;constructor({key:A,controller:Q,child:B}){super({key:A,child:B});this.controller=Q}static of(A){return A.dependOnInheritedWidgetOfExactType(PU)?.controller??null}static require(A){let Q=PU.of(A);if(!Q)throw Error(`InheritedSelectionArea.require() called with a context that does not contain an InheritedSelectionArea.
|
|
5578
5578
|
No InheritedSelectionArea ancestor could be found starting from the given context. This can happen if the context comes from a widget above the SelectionArea.
|
|
@@ -5730,7 +5730,7 @@ ${$}`).join(`
|
|
|
5730
5730
|
`)}function iv5(A){return A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function i41(A){return A.replace(/\[(image(?:\s+\d+)?)\]/gi,"").trim()}function nv5(A){let Q=PI.extname(A.sourcePath).toLowerCase();if(Q.length>0)return Q;if(A.source.type==="base64")switch(A.source.mediaType){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}return".png"}async function av5(A,Q){let B=[];for(let[$,J]of Q.entries()){if(J.source.type!=="base64"){j.warn("Skipping non-base64 debug package issue image",{index:$,sourceType:J.source.type});continue}let Y=`issue-image-${$+1}${nv5(J)}`,Z=PI.join(A,Y);try{await Nf(Z,Buffer.from(J.source.data,"base64")),B.push(Y)}catch(F){j.warn("Failed to write debug package issue image",{index:$,fileName:Y,error:F})}}return B}function ov5(A,Q,B=[]){let $=["# Bug Report","","## Issue Description","",A,""];if(B.length>0){for(let[J,Y]of B.entries())$.push(``);$.push("")}if($.push("## Included Files","","- `cli-logs.json` — CLI logs filtered for this session PID","- `thread.yaml` — Full thread data (messages, metadata, agent mode, etc.)"),B.length>0)$.push("- `issue-image-*.*` — Images attached to the issue description");if(If(Q.thread))$.push("- `thread.sqlite` — DTW Durable Object SQLite dump","- `cloudflare-logs.json` — Worker logs from Cloudflare (if CLOUDFLARE_API_TOKEN was set)");if($.push("","## Debug Instructions","","To investigate, start with the issue description above, then:","","1. Review `cli-logs.json` for errors, warnings, and the sequence of events"),If(Q.thread))$.push("2. Open `thread.sqlite` and inspect the `messages` and `thread_events` tables:"," ```sh"," sqlite3 -json thread.sqlite 'SELECT * FROM messages ORDER BY created_at, rowid'"," sqlite3 -json thread.sqlite 'SELECT * FROM thread_events ORDER BY seq'"," ```","3. Review `cloudflare-logs.json` (if present) for server-side worker errors","4. Check Cloudflare dashboards for more detail:",` - Logs: <${c41(Q.thread.id)}>`,` - Data Studio: <${d41(Q.thread.id)}>`);return $.push("",IG0(Q)),$.join(`
|
|
5731
5731
|
`)}function n41(A){let Q=A.activeThreadHandle.getInitialTreeURI();return{thread:A.thread,ampURL:A.ampURL,effectiveAgentMode:A.getEffectiveAgentMode(),isProcessing:A.isProcessing,threadPoolIsDTW:A.threadPool.isDTWMode?.()===!0,transportState:A.threadPool.getTransportConnectionState?.(),transportRole:A.threadPool.getTransportConnectionRole?.(),threadViewState:A.threadViewStates[A.thread.id],initialTreePath:Q?K5(F8(Q)):void 0,currentWorkspacePath:K5(F8(A.currentWorkspace)),clientId:A.clientId,logFile:A.logFile,pid:process.pid}}async function ki4(A){try{let Q=PI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.json`),B=JSON.stringify(A.thread,null,2);await Nf(Q,B,"utf-8"),await zJ(Q),j.info("Thread JSON written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread JSON or open editor",Q),Error("Failed to write thread JSON or open editor",{cause:Q})}}async function vi4(A){try{let Q=PI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.yaml`),B=p41.default.stringify(A.thread);await Nf(Q,B,"utf-8"),await zJ(Q),j.info("Thread YAML written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread YAML or open editor",Q),Error("Failed to write thread YAML or open editor",{cause:Q})}}async function yi4(A,Q){if(typeof Q!=="string")return Error("Select a log option from the picker");switch(Q){case"cli-open":{let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $="less -R +G",J=NG0(process.pid,B,$);try{try{C4.instance.tuiInstance.suspend(),nr(J,{stdio:"inherit"})}finally{process.stdout.write("\x1B[?25l"),C4.instance.tuiInstance.resume()}j.info("Opened filtered CLI logs",{command:J,pid:process.pid,logFile:ar(B),outputCommand:$??null});return}catch(Y){return j.error("Failed to open filtered CLI logs",{error:Y,command:J}),Error("Failed to open filtered CLI logs",{cause:Y})}}case"cloudflare-logs":{await dA(A.context??A.contextFallback,c41(A.thread.id));return}case"cloudflare-data-studio":{await dA(A.context??A.contextFallback,d41(A.thread.id));return}default:return Error(`Unknown log option: ${Q}`)}}async function xi4(A){let Q=n41(A),B=Si4(Q),$=!1;try{await C4.instance.tuiInstance.clipboard.writeText(B),$=!0}catch(J){j.error("Failed to copy debug prompt",{error:J})}return new S2(new TA({child:new T6({markdown:[$?"**Copied Markdown debug prompt to clipboard.**":"**Clipboard copy failed. Select and copy manually.**","",B].join(`
|
|
5732
5732
|
`)})}),"Debug Prompt","info","help",{width:100,height:28})}function rv5(A){return typeof A==="object"&&A!==null&&"label"in A&&typeof A.label==="string"&&"command"in A&&typeof A.command==="string"}async function fi4(A,Q){if(!rv5(Q))return Error("Select a command from the picker");try{await C4.instance.tuiInstance.clipboard.writeText(Q.command),A.showToast(`Copied: ${Q.label}`,"success")}catch(B){j.error("Failed to copy DTW debug command",{error:B})}}async function bi4(A){return new S2(new TA({child:new T6({markdown:IG0(n41(A))})}),"Thread Diagnostics","info","help",{width:100,height:26})}async function ui4(A,Q){let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $=i41(Q.description);if($.trim().length===0)return Error("Description is required");let J=Q.images,Y=ar(B),Z=process.pid,F=iv5($)||"debug-package",X=mv5.tmpdir(),D=PI.join(X,`amp-${F}`),G=`${D}.zip`;A.showStatusMessage("Building debug package...");try{nr(`mkdir -p ${D}`);let V=`select(.pid == ${Z})`,U=nr(`cat ${Y} | jq -c '${V}'`,{encoding:"utf-8",maxBuffer:52428800});await Nf(PI.join(D,"cli-logs.json"),U,"utf-8"),await Nf(PI.join(D,"thread.yaml"),p41.default.stringify(A.thread),"utf-8");let K=await av5(D,J),E=ov5($,n41(A),K);await Nf(PI.join(D,"agent-read-this.md"),E,"utf-8"),nr(`zip -j ${G} ${D}/*`),nr(`osascript -e 'set the clipboard to POSIX file "${G}"'`),A.showToast("Debug package copied to clipboard — paste into Slack","success"),j.info("Packaged debug bundle to clipboard",{zipPath:G,packageDir:D,pid:Z,threadId:A.thread.id});return}catch(V){return j.error("Failed to package debug bundle",{error:V}),Error("Failed to package debug bundle",{cause:V})}}K8();var sv5=80,tv5=20,hi4=4,ev5=42,ci4=420,li4=640,Ay5=Math.max(32,RU),gi4="░▒▓█▁▂▃▄▅▆▇∿∾∽≋≈∼",wG0=["▁","▂","▃","▄","▅","▆","▇","█"],Qy5=["▏","▎","▍","▌","▋","▊","▉","█"],By5=["▕","▐","▉","▊","▋","▌","▍","▎"],$y5=W0.symmetric(1,0),Jy5=W0.all(1),Yy5=W0.all(1),Zy5={primary:{r:102,g:102,b:102},secondary:{r:255,g:255,b:255}},Fy5={primary:{r:77,g:0,b:10},secondary:{r:255,g:77,b:95}};function Xy5(A){return{borderShape:A?.borderShape??"notched",borderAnimation:A?.borderAnimation??"subtle",titleAnimation:A?.titleAnimation??"none",timeMs:A?.timeMs,animate:A?.animate,seed:A?.seed??ev5}}function ii4(A){switch(A){case"notched":return Jy5;case"classic":return $y5}}class SA extends N1{props;constructor(A){super();this.props=A}build(A){let Q=T0.of(A),B=t1.of(A),$=this.props.tone??"default",J=Xy5(this.props.visualStyle),Y=this.props.bodyFit??{kind:"shrink"},Z=zy5(this.props,Y,B,J.borderShape),F=Iy5($,Q),X=c1.all(new l1(F.border,1,"rounded")),D=o41(this.props.header,J.borderShape),G=r41(this.props.footer,J.borderShape),V=wy5(D===void 0?this.props.header:void 0,F.header,J),U=Oy5(this.props.child,Y),K=G===void 0?jy5(this.props.footer,Q):new U0({height:0}),E=Y.kind==="fill"?"max":"min",W=typeof this.props.header==="string"?`NeoModal:${this.props.header}`:"NeoModal",z=this.props.autofocus??!0,H=this.props.chromePadding??ii4(J.borderShape),q=D===void 0&&typeof this.props.header==="string"?1:0,N=G===void 0?Dn4(this.props.footer):0,I=new i4({autofocus:z,canRequestFocus:!0,debugLabel:W,onKey:(R)=>{if(R.key==="Escape")return this.props.onDismiss(),"handled";return"ignored"},child:new x0({mainAxisSize:E,crossAxisAlignment:"stretch",children:[V,new U0({height:q}),U,new U0({height:N}),K]})}),C=!(J.borderShape==="notched"||J.borderAnimation!=="none")?new g0({constraints:Z,decoration:new f4(Q.colors.background,X),padding:H,child:I}):Vy5({borderShape:J.borderShape,borderAnimation:J.borderAnimation,child:I,constraints:Z,background:Q.colors.background,borderColor:F.border,tone:$,headerColor:F.header,footerKeyColor:Q.app.keybind,footerHintColor:Q.colors.foreground,padding:H,title:D,footer:G,titleAnimation:J.titleAnimation,seed:J.seed,timeMs:J.timeMs,animate:J.animate}),O=new g0({decoration:new f4(Q.colors.background),padding:Yy5,child:C});return new e4({fit:"expand",children:[new ni4,new v1({onClick:()=>{},opaque:this.props.barrierOpaque??!0,child:U0.expand()}),new r1({child:O})]})}}class ni4 extends $8{createRenderObject(){return new ai4}}class ai4 extends $4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Number.isFinite(A.maxWidth)?A.maxWidth:A.minWidth,B=Number.isFinite(A.maxHeight)?A.maxHeight:A.minHeight;this.setSize(Q,B)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=A.getSize(),Z=Math.max(0,$),F=Math.max(0,J),X=Math.min(Y.width,$+this.size.width),D=Math.min(Y.height,J+this.size.height);for(let G=F;G<D;G++)for(let V=Z;V<X;V++){let U=A.getCell(V,G);if(!U||Dy5(U))continue;let K={char:U.char,style:{...U.style,dim:!0},width:U.width};if(U.hyperlink!==void 0)K.hyperlink=U.hyperlink;A.setCell(V,G,K)}}}function Dy5(A){return A.char===" "&&A.width===1&&A.hyperlink===void 0&&Gy5(A.style)}function Gy5(A){return A.fg===void 0&&A.bg===void 0&&A.bold===void 0&&A.italic===void 0&&A.underline===void 0&&A.strikethrough===void 0&&A.reverse===void 0&&A.dim===void 0}function o41(A,Q){return Q==="notched"&&typeof A==="string"?A:void 0}function r41(A,Q){if(Q!=="notched")return;if(A===void 0)return[{keys:["Esc"],label:"close"}];if(!CG0(A)||A.length===0)return;return A}function Vy5(A){if(A.timeMs!==void 0)return mi4(A,A.timeMs);if(!(A.animate??Uy5(A)))return mi4(A,0);return new oi4({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,initialTimeMs:0})}function mi4(A,Q){return new s41({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,timeMs:Q})}function Uy5(A){return A.titleAnimation!=="none"||A.borderAnimation!=="none"}class oi4 extends v0{props;constructor(A){super();this.props=A}createState(){return new ri4}}class ri4 extends S0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.borderShape!==this.widget.props.borderShape||A.props.borderAnimation!==this.widget.props.borderAnimation||A.props.seed!==this.widget.props.seed||A.props.title!==this.widget.props.title||A.props.titleAnimation!==this.widget.props.titleAnimation)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},RU),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){if(this.widget.props.borderAnimation!=="none")return!1;if(this.widget.props.titleAnimation!=="none")return Date.now()-this.startedAt>=Yn4(this.widget.props.titleAnimation);return!0}build(A){return new s41({borderShape:this.widget.props.borderShape,borderAnimation:this.widget.props.borderAnimation,child:this.widget.props.child,constraints:this.widget.props.constraints,background:this.widget.props.background,borderColor:this.widget.props.borderColor,tone:this.widget.props.tone,headerColor:this.widget.props.headerColor,footerKeyColor:this.widget.props.footerKeyColor,footerHintColor:this.widget.props.footerHintColor,padding:this.widget.props.padding,title:this.widget.props.title,footer:this.widget.props.footer,titleAnimation:this.widget.props.titleAnimation,seed:this.widget.props.seed,timeMs:Date.now()-this.startedAt+this.widget.props.initialTimeMs})}}class s41 extends z5{props;constructor(A){super({child:A.child});this.props=A}createRenderObject(){return new a41(this.props)}updateRenderObject(A){N4(A instanceof a41,"unexpected modal surface"),A.update(this.props)}}class a41 extends $4{props;glow;constructor(A){super();this.props=A;this.glow=new j9(A.seed)}update(A){let Q=!this.props.constraints.equals(A.constraints)||this.props.padding!==A.padding;if(A.seed!==this.props.seed)this.glow=new j9(A.seed);if(this.props=A,Q)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.enforce(this.props.constraints),B=2+this.props.padding.horizontal,$=2+this.props.padding.vertical,J=new M1(Math.max(0,Q.minWidth-B),Math.max(0,Q.maxWidth-B),Math.max(0,Q.minHeight-$),Math.max(0,Q.maxHeight-$)),Y=this.children[0];if(Y)Y.layout(J),Y.setOffset(1+this.props.padding.left,1+this.props.padding.top);let Z=(Y?.size.width??0)+B,F=(Y?.size.height??0)+$,X=Q.constrain(Z,F);this.setSize(X.width,X.height)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height);if(Y<=0||Z<=0)return;A.fill($,J,Y,Z," ",{bg:this.props.background}),this.paintBorder(A,$,J,Y,Z),super.paint(A,Q,B)}paintBorder(A,Q,B,$,J){if($<2||J<2)return;for(let Y=1;Y<$-1;Y++)this.paintBorderCell(A,Q+Y,B,Y,0,$,J,"top"),this.paintBorderCell(A,Q+Y,B+J-1,Y,J-1,$,J,"bottom");for(let Y=1;Y<J-1;Y++)this.paintBorderCell(A,Q,B+Y,0,Y,$,J,"left"),this.paintBorderCell(A,Q+$-1,B+Y,$-1,Y,$,J,"right");if(this.paintCorner(A,Q,B,0,0,$,J,"top-left"),this.paintCorner(A,Q+$-1,B,$-1,0,$,J,"top-right"),this.paintCorner(A,Q,B+J-1,0,J-1,$,J,"bottom-left"),this.paintCorner(A,Q+$-1,B+J-1,$-1,J-1,$,J,"bottom-right"),this.props.borderShape==="notched")this.paintNotchedLabels(A,Q,B,$,J)}paintBorderCell(A,Q,B,$,J,Y,Z,F){let X=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.borderGlyph(F,X),this.borderStyle(X),1)}paintCorner(A,Q,B,$,J,Y,Z,F){let X=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.cornerGlyph(F,X),this.borderStyle(X),1)}paintNotchedLabels(A,Q,B,$,J){let Y=this.props.title;if(Y){let G=My5(Y,this.props.titleAnimation,this.props.timeMs);this.paintBorderText(A,Q+2,B,` ${G} `,$-4,{fg:this.props.headerColor,bg:this.props.background,bold:!0})}let Z=this.props.footer;if(!Z||J<2)return;let F=si4(Z,{fg:this.props.footerKeyColor,bg:this.props.background},{fg:this.props.footerHintColor,bg:this.props.background,dim:!0}),X=ti4(F),D=Math.max(2,$-X-2);this.paintStyledBorderText(A,Q+D,B+J-1,F,Math.max(0,$-D-2))}paintBorderText(A,Q,B,$,J,Y){this.paintStyledBorderText(A,Q,B,[{text:$,style:Y}],J)}paintStyledBorderText(A,Q,B,$,J){let Y=Q,Z=Ey5($,J);for(let F of Z)A.setChar(Y,B,F.grapheme,F.style,F.width),Y+=F.width}borderGlyph(A,Q){switch(this.props.borderAnimation){case"mysterious-message":return this.mysteriousMessageBorderGlyph(A,Q);case"none":case"subtle":return A==="left"||A==="right"?"│":"─"}}mysteriousMessageBorderGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="left")return Qy5[B]??"▏";if(A==="right")return By5[B]??"▕";return wG0[B]??"▁"}mysteriousMessageBorderIndex(A){return Math.max(0,Math.min(wG0.length-1,Math.floor(A*wG0.length)))}mysteriousMessageCornerGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="top-left"||A==="top-right")return wG0[B]??"▁";return"█"}cornerGlyph(A,Q){if(this.props.borderAnimation==="mysterious-message")return this.mysteriousMessageCornerGlyph(A,Q);switch(A){case"top-left":return"╭";case"top-right":return"╮";case"bottom-left":return"╰";case"bottom-right":return"╯"}}borderStyle(A){let Q={fg:this.borderColor(A),bg:this.props.background};if(this.props.borderAnimation==="mysterious-message"&&A>0.72)Q.bold=!0;return Q}borderColor(A){switch(this.props.borderAnimation){case"none":return this.props.borderColor;case"subtle":case"mysterious-message":return this.animatedBorderColor(A)}}animatedBorderColor(A){let Q=0.18+or(A)*0.82;switch(this.props.tone){case"default":return nQ(Q,void 0,Zy5);case"warning":return nQ(Q,_M);case"success":return nQ(Q,void 0);case"error":return nQ(Q,void 0,Fy5)}}sampleBorderIntensity(A,Q,B,$){let J=Math.max(1,B*2+$*2-4),Y=Ky5(A,Q,B,$),Z=Y/J,F=this.props.timeMs/1000,X=this.glow.sample(A*1.3+Y*0.07,Q*1.1-F*5,F,1.2),D=(Z-F*0.18%1+1)%1,G=Math.min(D,1-D),V=Math.max(0,1-G/0.085)**2;return or(X*0.58+V*0.54)}}function Ky5(A,Q,B,$){if(Q<=0)return Math.max(0,A);if(A>=B-1)return B-1+Math.max(0,Q);if(Q>=$-1)return B+$-2+Math.max(0,B-1-A);return B*2+$-3+Math.max(0,$-1-Q)}function si4(A,Q,B){let $=[{text:" ",style:B}];return A.forEach((J,Y)=>{if(Y>0)$.push({text:" · ",style:B});J.keys.forEach((Z,F)=>{if(F>0)$.push({text:"/",style:B});$.push({text:Z,style:Q})}),$.push({text:` ${J.label}`,style:B})}),$.push({text:" ",style:B}),$}function ti4(A){return ei4(A).reduce((Q,B)=>Q+B.width,0)}function Ey5(A,Q){if(Q<=0)return[];let B=[],$=0;for(let J of ei4(A)){if($+J.width>Q)return Wy5(B,$,Q,J.style);B.push(J),$+=J.width}return B}function ei4(A){let Q=[];for(let B of A)for(let $ of L4(B.text))Q.push({grapheme:$,style:B.style,width:h6($)});return Q}function Wy5(A,Q,B,$){let Y=h6("…");if(Y>B)return A;let Z=Q;while(A.length>0&&Z+Y>B){let F=A.pop();if(F)Z-=F.width}if(Z+Y<=B)A.push({grapheme:"…",style:$,width:Y});return A}function or(A){return Math.max(0,Math.min(1,A))}function zy5(A,Q,B,$){let J=Math.max(0,B.size.width-hi4),Y=Math.max(0,B.size.height-hi4),Z=Math.max(A.minWidth??0,Hy5(A,$)),F=Math.max(0,Math.min(A.maxWidth??sv5,J));if(Q.kind==="fill"){let G=qy5(A,$),V=Math.max(Q.modalRows,G),U=Math.max(0,Math.min(V,Y));return new M1(Math.min(Z,F),F,U,U)}let X=Math.max(0,Math.min(A.maxHeight??tv5,Y)),D=Math.min(A.minHeight??0,X);return new M1(Math.min(Z,F),F,D,X)}function Hy5(A,Q){if(Q!=="notched")return 0;let B=0,$=o41(A.header,Q);if($)B=Math.max(B,4+d4(` ${$} `));let J=r41(A.footer,Q);if(J)B=Math.max(B,4+ti4(si4(J,{},{})));return B}function qy5(A,Q){let B=A.chromePadding??ii4(Q),$=o41(A.header,Q),J=r41(A.footer,Q),Y=2,Z=A.header===void 0||$!==void 0?0:1,F=$===void 0&&typeof A.header==="string"?1:0,X=J===void 0?Ny5(A.footer):0,D=J===void 0?Dn4(A.footer):0,G=1;return 2+B.top+B.bottom+Z+F+1+D+X}function Ny5(A){if(A===void 0)return 1;if(A==="none")return 0;if(CG0(A))return A.length===0?0:1;return 1}function Iy5(A,Q){switch(A){case"default":return{border:Q.colors.border,header:Q.app.command};case"warning":return{border:Q.colors.warning,header:Q.colors.warning};case"success":return{border:Q.app.toolSuccess,header:Q.app.toolSuccess};case"error":return{border:Q.app.toolError,header:Q.app.toolError}}}function wy5(A,Q,B){if(A===void 0)return new U0({height:0});if(typeof A==="string")return new g0({padding:W0.symmetric(1,0),child:new r1({child:Cy5(A,Q,B)})});return A}function Cy5(A,Q,B){if(B.titleAnimation==="none")return new p({text:new M(A,new v({color:Q,bold:!0}))});let $=B.timeMs??(B.animate===!1?0:void 0);if($!==void 0)return new p({text:Bn4(A,Q,B.titleAnimation,$)});return new An4({title:A,color:Q,animation:B.titleAnimation})}class An4 extends v0{props;constructor(A){super();this.props=A}createState(){return new Qn4}}class Qn4 extends S0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.title!==this.widget.props.title||A.props.animation!==this.widget.props.animation||A.props.color!==this.widget.props.color)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.widget.props.animation==="none"||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},Ay5),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){return Date.now()-this.startedAt>=Yn4(this.widget.props.animation)}build(A){return new p({text:Bn4(this.widget.props.title,this.widget.props.color,this.widget.props.animation,Date.now()-this.startedAt)})}}function Bn4(A,Q,B,$){let J=L4(A),Y=new v({color:Q,bold:!0}),Z=new v({color:Q,bold:!0,dim:!0});switch(B){case"none":return new M(A,Y);case"wipe":return new M("",void 0,pi4(J,$n4(J,$),Y,Z));case"scramble":return new M("",void 0,pi4(J,Jn4(J,$),Y,Z))}}function My5(A,Q,B){let $=L4(A);switch(Q){case"none":return A;case"wipe":return $n4($,B).join("");case"scramble":return Jn4($,B).join("")}}function pi4(A,Q,B,$){return Q.map((J,Y)=>{let Z=J===A[Y]?B:$;return new M(J,Z)})}function $n4(A,Q){let B=Zn4(or(Q/ci4)),$=Math.floor(B*(A.length+1));return A.map((J,Y)=>{if(Y<$)return J;if(Y===$)return"▒";return" "})}function Jn4(A,Q){let $=Zn4(or(Q/li4))*(A.length+5),J=Math.floor(Q/45);return A.map((Y,Z)=>{if(or(($-Z)/5)>=1)return Y;return Ly5(Z,J)})}function Ly5(A,Q){return gi4[(A*7+Q*11)%gi4.length]??"░"}function Yn4(A){if(A==="scramble")return li4;return ci4}function Zn4(A){return 1-(1-A)**3}function Oy5(A,Q){let B=Q.kind==="fill"?"tight":"loose";return new W3({fit:B,child:new Fn4({child:A})})}class Fn4 extends z5{constructor({child:A}){super({child:A})}createRenderObject(){return new Xn4}}class Xn4 extends $4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(Q)Q.layout(A.loosen()),Q.setOffset(0,0);let B=Q?.size.width??0,$=Q?.size.height??0,J=A.constrain(A.hasTightWidth?A.maxWidth:B,A.hasTightHeight?A.maxHeight:$);this.setSize(J.width,J.height)}}function jy5(A,Q){if(A===void 0)return di4([{keys:["Esc"],label:"close"}],Q);if(CG0(A))return A.length===0?new U0({height:0}):di4(A,Q);if(A==="none")return new U0({height:0});return A}function CG0(A){return Array.isArray(A)}function Dn4(A){return A===void 0||CG0(A)&&A.length>0?1:0}function di4(A,Q){let B=new v({color:Q.app.keybind}),$=new v({color:Q.colors.foreground,dim:!0}),J=[];return A.forEach((Y,Z)=>{if(Z>0)J.push(new M(" · ",$));Y.keys.forEach((F,X)=>{if(X>0)J.push(new M("/",$));J.push(new M(F,B))}),J.push(new M(` ${Y.label}`,$))}),new r1({child:p.spans(J)})}function Py5(A){return[{label:"cli: copy tail logs",command:_I("tail",process.pid,{path:A})},{label:"cli: copy logs snapshot",command:_I("snapshot",process.pid,{path:A})},{label:"cli: htop",command:`htop -p ${process.pid}`}]}async function _y5(A,Q){try{await C4.instance.tuiInstance.clipboard.writeText(A.command)}catch(B){j.error("Failed to copy debug command from Neo command palette",{error:B})}finally{Q()}}function Ty5(A,Q){let B=NG0(process.pid,{path:A},"less -R +G");Q();try{C4.instance.tuiInstance.suspend(),Ry5(B,{stdio:"inherit"})}catch($){j.error("Failed to open filtered CLI logs in pager",{error:$,command:B})}finally{process.stdout.write("\x1B[?25l"),C4.instance.tuiInstance.resume()}}function Gn4(A){return[{noun:"debug",verb:"page logs",description:"View CLI logs in pager",status:{type:"enabled"},run:(Q,B,$)=>{Ty5(A,$)}},{noun:"debug",verb:"copy command",description:"Copy debug command to clipboard",status:{type:"enabled"},run:(Q,B,$)=>{Q.pushWithDismiss((J)=>new SA({header:"Debug: Copy Command",minWidth:80,maxWidth:80,autofocus:!1,footer:"none",onDismiss:J,child:new g6({items:Py5(A),getLabel:(Y)=>Y.label,showBorder:!1,onAccept:(Y)=>{_y5(Y,$)},onDismiss:J})}))}}]}var wf="exit-app-key-pressed",Cf="cancel-key-pressed",TI="loading-thread",Mf="previous-thread-reference",Lf="double-enter-steer";class sr extends l4{}class MG0 extends l4{}class LG0 extends l4{}class tr extends l4{visualIndex;constructor(A){super();this.visualIndex=A}}class er extends l4{}class OG0 extends l4{}class As extends l4{}class Of extends l4{}class jf extends l4{}class Qs extends l4{}class Bs extends l4{}class $s extends l4{}class Rf extends l4{}class AQ extends l4{text;successMessage;failureMessage;constructor(A="",Q="Selection copied to clipboard",B="Failed to copy selection"){super();this.text=A;this.successMessage=Q;this.failureMessage=B}}class jG0 extends l4{}class Js extends l4{}class RG0 extends l4{}class PG0 extends l4{}class Ys extends l4{}class Zs extends l4{}class Fs extends l4{}class _G0 extends l4{}class TG0 extends l4{}class SG0 extends l4{}class YR extends l4{}class Xs extends l4{}class t41 extends l4{mode;constructor(A){super();this.mode=A}}C3();s1();var Vn4=process.platform==="win32"?" ":"█",Un4=process.platform==="win32"?"░":"█";class X2 extends v0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Vn4,thumbChar:Y=Un4,showTrack:Z=!0,thumbColor:F,trackColor:X}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=F,this.trackColor=X}createState(){return new Kn4}}class Kn4 extends S0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(A){let{totalContentHeight:Q,viewportHeight:B}=this.widget.getScrollInfo(),J=this.context.findRenderObject()?.size.height??0;if(J===0||Q<=B)return!1;let Y=this.widget.getScrollInfo(),Z=Math.min(1,B/Q),F=Math.max(1,J*Z),X=Math.max(0,Math.min(1,Y.scrollOffset/(Q-B))),D=J-F,G=Math.max(0,D*X),V=G+F;return A>=G&&A<=V}_handleHover=(A)=>{let Q=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(A.localPosition.y),Q!==this._isOverThumb)this.setState()};_handleDrag=(A)=>{let{totalContentHeight:Q,viewportHeight:B,scrollOffset:$}=this.widget.getScrollInfo(),Y=this.context.findRenderObject()?.size.height??0;if(Y===0||Q<=B)return;if(this._dragStartY===null)this._dragStartY=A.localPosition.y,this._dragStartOffset=$;let Z=A.localPosition.y-this._dragStartY,F=Math.min(1,B/Q),X=Math.max(1,Y*F),D=Y-X;if(D<=0)return;let G=Q-B,V=D/G,U=Z/V,K=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(K)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(A)=>{if(A.button!=="left")return;let Q=A.localPosition.y,{totalContentHeight:B,viewportHeight:$,scrollOffset:J}=this.widget.getScrollInfo(),Z=this.context.findRenderObject()?.size.height??0;if(Z===0||B<=$)return;let F=Math.min(1,$/B),X=Math.max(1,Z*F),D=B-$,G=Z-X,V=Math.max(0,Math.min(1,J/(B-$))),U=Math.max(0,G*V),K=U+X;if(Q>=U&&Q<=K)return;if(Q<U)this.widget.controller.animateTo(Math.max(0,J-$));else this.widget.controller.animateTo(Math.min(D,J+$))};build(A){return new v1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?a6.POINTER:a6.DEFAULT,child:new En4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class En4 extends $I{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=Vn4,thumbChar:Y=Un4,showTrack:Z=!0,thumbColor:F,trackColor:X}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=F,this.trackColor=X}createRenderObject(){return new Wn4(this)}updateRenderObject(A){A.updateWidget(this)}}class Wn4 extends $4{_widget;constructor(A){super();this._widget=A}updateWidget(A){this._widget=A,this.markNeedsLayout()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Math.min(A.maxWidth,this._widget.thickness),B=A.maxHeight;this.setSize(Q,B),super.performLayout()}getMinIntrinsicWidth(A){return this._widget.thickness}getMaxIntrinsicWidth(A){return this._widget.thickness}getMinIntrinsicHeight(A){return 0}getMaxIntrinsicHeight(A){return 0}paint(A,Q,B){let{thumbStartFloat:$,thumbSizeFloat:J,showScrollbar:Y}=this._calculateScrollbarMetrics();if(!Y)return;let Z=this._widget.trackColor,F=this._widget.thumbColor,X=process.platform==="win32",D=$,G=$+J;if(!X){let V=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let K="█",E=!0;if(U===Math.floor(D)){let W=1-(D-U),z=Math.floor(W*8);K=V[z]||"█",E=!1}else if(U===Math.floor(G)){let W=1-(G-U),z=Math.floor(W*8);K=V[z]||"█"}else if(U>D&&U<G)E=!1;A.setChar(Q,B+U,K,{fg:F,bg:Z,reverse:E},1)}return}for(let V=0;V<this.size.height;V++){let U=V+0.5,K=U>=D&&U<G,E=K?this._widget.thumbChar:this._widget.trackChar;A.setChar(Q,B+V,E,{fg:K?F:Z,bg:Z,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:A,viewportHeight:Q,scrollOffset:B}=this._widget.getScrollInfo(),$=this.size.height;if(A<=Q||$<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let J=Math.max(0,Math.min(1,B/(A-Q))),Y=Math.min(1,Q/A),Z=Math.max(1,$*Y),F=$-Z;return{thumbStartFloat:Math.max(0,F*J),thumbSizeFloat:Z,showScrollbar:!0}}}var zn4=1;class rY extends v0{props;constructor(A){super();this.props=A}createState(){return new Hn4}}class Hn4 extends S0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new rA;Q.followMode=!1,Q.jumpTo(0),this.ownership={controller:Q,owned:!0}}}didUpdateWidget(A){N4(A.props.controller===this.widget.props.controller,"NeoModalScrollArea.controller identity must be stable across rebuilds")}dispose(){if(this.ownership.owned)this.ownership.controller.dispose()}getScrollInfo=()=>{let{controller:A}=this.ownership,Q=this.viewportHeight;return{totalContentHeight:Math.max(A.maxScrollExtent+Q,0),viewportHeight:Q,scrollOffset:Math.max(A.offset,0)}};setMeasuredHeight=(A)=>{this.viewportHeight=A};build(A){let Q=T0.of(A),{controller:B}=this.ownership;return new qn4({thickness:zn4,onMeasured:this.setMeasuredHeight,scrollable:new TA({controller:B,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:!0,child:this.widget.props.child}),scrollbar:new X2({controller:B,thickness:zn4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class qn4 extends O9{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:B,onMeasured:$}){super({children:[A,Q]});this.thickness=B,this.onMeasured=$}createRenderObject(){return new Nn4(this.thickness,this.onMeasured)}}class Nn4 extends $4{thickness;onMeasured;constructor(A,Q){super();this.thickness=A;this.onMeasured=Q}performLayout(){let A=this._lastConstraints;N4(!!A,"ScrollAreaLayoutRenderObject.performLayout called without constraints");let Q=A.maxWidth,B=Math.max(0,Math.min(this.thickness,Q)),$=Q-B,[J,Y]=this.children;N4(J!==void 0&&Y!==void 0,"ScrollAreaLayout requires scrollable and scrollbar children"),J.layout(new M1($,$,0,A.maxHeight)),J.setOffset(0,0);let Z=J.size.height;this.onMeasured(Z),Y.layout(new M1(B,B,Z,Z)),Y.setOffset($,0),this.setSize(Q,Z)}}var In4=10;class e41 extends v0{pluginService;workspaceRoot;logFilePath;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.workspaceRoot=A.workspaceRoot,this.logFilePath=A.logFilePath,this.onDismiss=A.onDismiss}createState(){return new wn4}}class wn4 extends S0{plugins=[];subscription=null;initState(){this.subscription=this.widget.pluginService.plugins.subscribe((A)=>{this.setState(()=>{this.plugins=A})})}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscription=this.widget.pluginService.plugins.subscribe((Q)=>{this.setState(()=>{this.plugins=Q})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}relativePath(A){let Q=s0.file(this.widget.workspaceRoot),B=X1.relativePath(Q,OA(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return R5(A)}detailPrefix(A){if(A.length===0)return` ${" ".repeat(In4)}`;return` ${`${A}:`.padEnd(In4," ")}`}bunNotFoundExplanation(A,Q){let B=T0.of(A),{app:$,colors:J}=B,Y=new v({color:J.foreground}),Z=new v({color:$.toolError}),F=new v({color:$.link,underline:!0}),X=`${Q} ${W4(Q,"plugin")} could not start because Bun is not installed.`,D="https://ampcode.com/install",G="https://bun.sh",V=(U,K)=>new M(K,F,void 0,OW(U),()=>{dA(A,U)});return new f0({padding:W0.only({left:1,right:1,bottom:1}),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new p({text:new M(X,Z),maxLines:2,overflow:"ellipsis"}),new p({text:new M(" ",Y)}),new p({text:new M("To run plugins, either ",Y,[V("https://ampcode.com/install","install the Amp binary"),new M(" or ",Y),V("https://bun.sh","install bun"),new M(".",Y)])})]})})}pluginRows(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=new v({color:$.foreground,dim:!0}),Y=new v({color:B.link}),Z=new v({color:B.link,underline:!0});if(this.plugins.length===0)return[new f0({padding:W0.symmetric(1,1),child:new p({text:new M("No plugins found.",J)})})];let F=this.plugins.filter((V)=>V.errorMessage!==null),X=F.length>0&&F.every((V)=>id(V.errorMessage)),G=(X?this.plugins.filter((V)=>!id(V.errorMessage)):this.plugins).map((V)=>{let U=V.uri.toString(),K=U.startsWith("file://"),E=()=>{dA(A,U)},W=V.status==="active"?new v({color:B.toolSuccess}):V.status==="error"?new v({color:B.toolError}):new v({color:$.warning}),z=new p({text:new M(this.relativePath(V.uri),K?Z:new v({color:B.command}),void 0,K?OW(U):void 0,K?E:void 0),maxLines:1,overflow:"ellipsis"}),H=K?new v1({cursor:"pointer",onClick:E,child:z}):z,q=[new t0({children:[new p({text:new M(V.status,W,[new M(" ",J)]),maxLines:1,overflow:"clip"}),new W3({fit:"loose",child:H})]})];if(V.errorMessage)q.push(new p({text:new M(this.detailPrefix("Error"),J,[new M(V.errorMessage,new v({color:B.toolError}))]),maxLines:1,overflow:"ellipsis"}),new p({text:new M(this.detailPrefix(""),J,[new M(`see logs: ${this.widget.logFilePath}`,J)]),maxLines:1,overflow:"ellipsis"}));if(V.registeredEvents.length>0)q.push(new p({text:new M(this.detailPrefix("Events"),J,[new M(V.registeredEvents.join(", "),Y)]),maxLines:1,overflow:"ellipsis"}));for(let[N,I]of V.registeredCommands.entries())q.push(new p({text:new M(N===0?this.detailPrefix("Commands"):this.detailPrefix(""),J,[new M(`${I.category}: ${I.title}`,Y)]),maxLines:1,overflow:"ellipsis"}));for(let[N,I]of V.registeredTools.entries())q.push(new p({text:new M(N===0?this.detailPrefix("Tools"):this.detailPrefix(""),J,[new M(I.name,Y)]),maxLines:1,overflow:"ellipsis"}));return new f0({padding:W0.only({left:1,right:1,bottom:1}),child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})})});if(X)G.push(this.bunNotFoundExplanation(A,F.length));return G}build(A){let Q=this.plugins.filter((Y)=>Y.status==="active").length,B=this.plugins.reduce((Y,Z)=>Y+Z.registeredCommands.length,0),$=this.plugins.reduce((Y,Z)=>Y+Z.registeredTools.length,0),J=`${Q}/${this.plugins.length} ${W4(this.plugins.length,"plugin")} active (${B} ${W4(B,"command")}, ${$} ${W4($,"tool")})`;return new SA({header:"Plugins",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new f0({padding:W0.only({left:1,right:1,bottom:1}),child:new p({text:new M(J,new v({bold:!0}))})}),new W3({fit:"loose",child:new rY({child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}function Cn4(A){return[{noun:"plugins",verb:"list",description:"List all loaded plugins",keywords:["extensions","tools","commands"],status:{type:"enabled"},run:(Q,B,$)=>{Q.push(new e41({pluginService:A.pluginService,workspaceRoot:A.workspaceRoot,logFilePath:A.logFilePath,onDismiss:$}))}},{noun:"plugins",verb:"reload",description:"Reload all plugins",keywords:["refresh","restart","extensions"],status:{type:"enabled"},run:(Q,B,$)=>{A.pluginService.reload(),A.toastController.show("Reloading plugins..."),$()}}]}c0();class Ds extends l4{}class Pf extends l4{}class AA1 extends v0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Mn4}}class Mn4 extends S0{build(A){let{options:Q,onConfirm:B,onCancel:$}=this.widget.props,{colors:J}=T0.of(A),Y=Q.message?new p({text:new M(Q.message,new v({color:J.foreground}))}):new U0({height:1});return new SA({header:Q.title,minWidth:64,maxWidth:80,footer:[{keys:["Y"],label:Q.confirmButtonText??"yes"},{keys:["N","Esc"],label:"cancel"},{keys:["↑↓","j/k"],label:"scroll"}],autofocus:!1,onDismiss:$,child:new t4({actions:new Map([[Ds,new D4(()=>B())],[Pf,new D4(()=>$())]]),child:new m5({debugLabel:"NeoConfirmDialogShortcuts",shortcuts:Sy5(),child:new rY({child:Y})})})})}}function Sy5(){return new Map([[T1.key("y"),new Ds],[T1.shift("Y"),new Ds],[T1.shift("y"),new Ds],[T1.key("n"),new Pf],[T1.shift("N"),new Pf],[T1.shift("n"),new Pf],[T1.key("Escape"),new Pf]])}class Gs extends v0{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}createState(){return new Ln4}}class Ln4 extends S0{controller=new M8;onTextChanged=()=>{this.setState()};initState(){this.controller.text=this.widget.props.initialValue??"",this.controller.addListener(this.onTextChanged)}dispose(){this.controller.removeListener(this.onTextChanged),this.controller.dispose(),super.dispose()}handleSubmit(){let A=this.controller.text.trim();if((this.widget.props.isRequired??!0)&&A.length===0)return;this.widget.props.onSubmit(A)}build(A){let{colors:Q,app:B}=T0.of(A),Y=!(this.widget.props.isRequired??!0)||this.controller.text.trim().length>0?[{keys:["Enter"],label:"submit"},{keys:["Esc"],label:"cancel"}]:[{keys:["Esc"],label:"cancel"}],Z=[];if(this.widget.props.helpText)Z.push(new p({text:new M(this.widget.props.helpText,new v({color:Q.foreground}))})),Z.push(new U0({height:1}));return Z.push(new t0({children:[new p({text:new M("> ",new v({color:B.command}))}),new _1({child:new oB({controller:this.controller,placeholder:this.widget.props.placeholder??"",autofocus:!0,maxLines:1,style:{textColor:Q.foreground,border:null},onSubmitted:()=>this.handleSubmit()})})]})),new SA({header:this.widget.props.header,minWidth:80,maxWidth:80,footer:Y,autofocus:!1,bodyFit:this.widget.props.bodyFit,onDismiss:this.widget.props.onDismiss,child:new x0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:Z})})}}class QA1 extends N1{props;constructor(A){super(A.key===void 0?{}:{key:A.key});this.props=A}build(A){return new SA({header:this.props.options.title,minWidth:64,maxWidth:80,footer:[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"},{keys:["Esc"],label:"cancel"}],autofocus:!1,onDismiss:this.props.onCancel,child:ky5(this.props)})}}function ky5(A){let Q=A.options.options.map((B)=>({value:B,label:B}));return new J9({options:Q,body:A.options.message,onSelect:(B)=>{if(B===null){A.onCancel();return}A.onSelect(B)},padding:W0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}class BA1{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;activeDialog=null;queuedDialogs=[];disposed=!1;constructor(A){this.options=A}init(){this.disposed=!1,this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.disposed=!0,this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[],this.cancelPendingDialogs()}hasBlockingDialog(){return this.activeDialog!==null}buildDialogLayers(){let A=this.activeDialog;if(!A)return[];switch(A.kind){case"input":return[new Gs({key:new RW(A),header:A.options.title??"Input",helpText:A.options.helpText,initialValue:A.options.initialValue,isRequired:!1,onSubmit:(Q)=>this.resolveInputDialog(A,Q),onDismiss:()=>this.resolveInputDialog(A,void 0)})];case"confirm":return[new AA1({key:new RW(A),options:A.options,onConfirm:()=>this.resolveConfirmDialog(A,!0),onCancel:()=>this.resolveConfirmDialog(A,!1)})];case"select":return[new QA1({key:new RW(A),options:A.options,onSelect:(Q)=>this.resolveSelectDialog(A,Q),onCancel:()=>this.resolveSelectDialog(A,void 0)})]}}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;if(id(B.errorMessage))continue;let $=`${B.uri.toString()}
|
|
5733
|
-
${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}zl();w2();import{readFile as vy5}from"node:fs/promises";import $A1 from"node:os";async function On4(A,Q){try{return{path:Q,contents:hh0(await vy5(A,"utf8"))}}catch{return null}}async function jn4(A,Q){let B=[],$=await YA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(e$(J),null,2)});let Y=await On4(Dx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await On4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let F=await tN()??"unknown",X=await YA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778158028-g39bfa2",clientOS:`${$A1.platform()} ${$A1.release()} ${$A1.arch()}`,installMethod:F}},{config:A.configService});if(!X.ok)throw Error(`Failed to submit report: ${X.error.message}`);return X.result.reportID}class JA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}c0();G9();w2();async function Rn4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await YA.setThreadMeta({thread:Q,meta:nY(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=MB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new aQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class kG0 extends z5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new YA1(this.offstage)}updateRenderObject(A){if(A instanceof YA1)A.offstage=this.offstage}}class YA1 extends $4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class ZA1{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class FA1 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Pn4}}class Pn4 extends S0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new Mj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new Mj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new kG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new i4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new kG0({key:$.key,offstage:!J,child:Y}))}return new e4({fit:"expand",children:Q})}}class DA1 extends N1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=yy5(Q);return new SA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:W0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new g6({items:Q,showBorder:!1,getLabel:($)=>{let J=XA1($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=pj($.item.verb.toLowerCase(),Y),F=pj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=pj(XA1($.item),Y),D=pj(XA1(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=T0.of(J);return new p({text:new M($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new _n4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class _n4 extends N1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=T0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new M(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:xy5(Q.shortcut,Z,$)});return new Tn4({columns:W,padding:W0.horizontal(1),backgroundColor:D})}}function XA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function yy5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,d4(B.noun)):Q},0)}function xy5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Tn4 extends N1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new t0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class GA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class sY extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sY.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sY)?.commandRegistry??null}}class VA1 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Sn4}}class Sn4 extends S0{modalStack=new ZA1;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sY.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sY.of(A).commands,B=new DA1({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new FA1({root:B,controller:this.modalStack})}}var UA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],KA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class vG0 extends N1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=t1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:W0.only({left:4}),child:X})]});else D=new t0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new f0({padding:W0.horizontal(6),child:D}))}return new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class EA1 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new kn4}}class kn4 extends S0{scrollController;initState(){this.scrollController=new rA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=T0.of(A).app,Y=t1.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,z=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let R=O.noun?.toLowerCase();return R!=="dev"&&R!=="debug"&&!O.id.startsWith("debug-")&&!H.has(O.id)})].sort((O,R)=>{let S=(O.noun??"").toLowerCase(),T=(R.noun??"").toLowerCase(),f=S.localeCompare(T);if(f!==0)return f;let h=O.verb.toLowerCase(),x=R.verb.toLowerCase(),k=h.localeCompare(x);if(k!==0)return k;return O.id.localeCompare(R.id)}),I=new TA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new M1(z,z,0,Number.POSITIVE_INFINITY),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new r1({child:new p({text:new M(`Amp CLI - Help & Keyboard Shortcuts
|
|
5733
|
+
${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"input",options:A,resolve:Q})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(!1);return}this.enqueueDialog({kind:"confirm",options:A,resolve:Q})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(this.disposed||!this.options.state.mounted){Q(void 0);return}this.enqueueDialog({kind:"select",options:A,resolve:Q})})};cancelPendingDialogs(){let A=[];if(this.activeDialog)A.push(this.activeDialog);A.push(...this.queuedDialogs),this.activeDialog=null,this.queuedDialogs=[];for(let Q of A)this.cancelDialog(Q)}cancelDialog(A){switch(A.kind){case"input":A.resolve(void 0);return;case"confirm":A.resolve(!1);return;case"select":A.resolve(void 0);return}}enqueueDialog(A){if(this.activeDialog){this.queuedDialogs.push(A);return}this.options.commandPalette.disable(),this.options.state.setState(()=>{this.activeDialog=A})}resolveInputDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveConfirmDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}resolveSelectDialog(A,Q){if(this.activeDialog!==A)return;this.advanceDialog(),A.resolve(Q)}advanceDialog(){this.updateDialogState(()=>{this.activeDialog=this.queuedDialogs.shift()??null})}updateDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}zl();w2();import{readFile as vy5}from"node:fs/promises";import $A1 from"node:os";async function On4(A,Q){try{return{path:Q,contents:hh0(await vy5(A,"utf8"))}}catch{return null}}async function jn4(A,Q){let B=[],$=await YA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(e$(J),null,2)});let Y=await On4(Dx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await On4(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let F=await tN()??"unknown",X=await YA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778171486-g3e6a89",clientOS:`${$A1.platform()} ${$A1.release()} ${$A1.arch()}`,installMethod:F}},{config:A.configService});if(!X.ok)throw Error(`Failed to submit report: ${X.error.message}`);return X.result.reportID}class JA1{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}c0();G9();w2();async function Rn4(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await YA.setThreadMeta({thread:Q,meta:nY(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let F=MB(new URL(A.ampURL),Q).toString();try{await C4.instance.tuiInstance.clipboard.writeText(F),Y=!0}catch(X){j.error("Failed to copy thread URL after visibility update",{error:X})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new aQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class kG0 extends z5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new YA1(this.offstage)}updateRenderObject(A){if(A instanceof YA1)A.offstage=this.offstage}}class YA1 extends $4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class ZA1{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class FA1 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new Pn4}}class Pn4 extends S0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new Mj,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new Mj,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new kG0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new i4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new kG0({key:$.key,offstage:!J,child:Y}))}return new e4({fit:"expand",children:Q})}}class DA1 extends N1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=yy5(Q);return new SA({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:W0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new g6({items:Q,showBorder:!1,getLabel:($)=>{let J=XA1($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=pj($.item.verb.toLowerCase(),Y),F=pj(J.item.verb.toLowerCase(),Y);if(Z!==F)return F-Z;let X=pj(XA1($.item),Y),D=pj(XA1(J.item),Y);if(X!==D)return D-X;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=T0.of(J);return new p({text:new M($.status.reason,new v({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new _n4({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class _n4 extends N1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=T0.of(Y),{colors:F,app:X}=Z,D=B?X.selectionBackground:void 0,G=B?X.selectionForeground:F.foreground,V=B?G:F.mutedForeground,U=new p({text:new M(Q.noun?.toLowerCase()??"",new v({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new v({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new v({color:G,dim:!0})));let E=p.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:xy5(Q.shortcut,Z,$)});return new Tn4({columns:W,padding:W0.horizontal(1),backgroundColor:D})}}function XA1(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function yy5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,d4(B.noun)):Q},0)}function xy5(A,Q,B){let{colors:$,app:J}=Q,Y=new v({color:$.mutedForeground,dim:B}),Z=[];for(let F of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(F,new v({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new v({color:J.keybind,bold:!0,dim:B}))),p.spans(Z)}class Tn4 extends N1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let F=0;F<Q.length;F++){let X=Q[F];if(F>0&&B>0)Y.push(new U0({width:B}));if(X.fixedWidth!==void 0)Y.push(new U0({width:X.fixedWidth,child:X.child}));else if(X.expanded)Y.push(new _1({child:X.child}));else Y.push(X.child)}let Z=new t0({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new g0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class GA1{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class sY extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=sY.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(sY)?.commandRegistry??null}}class VA1 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new Sn4}}class Sn4 extends S0{modalStack=new ZA1;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=sY.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=sY.of(A).commands,B=new DA1({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new FA1({root:B,controller:this.modalStack})}}var UA1=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],KA1=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class vG0 extends N1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=t1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[F,X]=this.renderRow(Z),D;if(J)D=new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[F,new f0({padding:W0.only({left:4}),child:X})]});else D=new t0({crossAxisAlignment:"start",children:[new _1({flex:1,child:F}),new U0({width:1}),new _1({flex:1,child:X})]});Y.push(new f0({padding:W0.horizontal(6),child:D}))}return new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class EA1 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new kn4}}class kn4 extends S0{scrollController;initState(){this.scrollController=new rA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=R1.of(A).colorScheme,J=T0.of(A).app,Y=t1.of(A),Z=new v({color:B.primary,bold:!0}),F=new v({color:B.secondary,bold:!0}),X=new v({color:J.keybind}),D=new v({color:J.command}),G=new v({color:B.foreground}),V=new v({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,z=Math.max(40,Math.min(80,E)),H=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let R=O.noun?.toLowerCase();return R!=="dev"&&R!=="debug"&&!O.id.startsWith("debug-")&&!H.has(O.id)})].sort((O,R)=>{let S=(O.noun??"").toLowerCase(),T=(R.noun??"").toLowerCase(),f=S.localeCompare(T);if(f!==0)return f;let h=O.verb.toLowerCase(),x=R.verb.toLowerCase(),k=h.localeCompare(x);if(k!==0)return k;return O.id.localeCompare(R.id)}),I=new TA({autofocus:!0,controller:this.scrollController,child:new g0({constraints:new M1(z,z,0,Number.POSITIVE_INFINITY),child:new x0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new r1({child:new p({text:new M(`Amp CLI - Help & Keyboard Shortcuts
|
|
5734
5734
|
`,Z)})}),new U0({height:1}),new f0({padding:W0.horizontal(2),child:new p({text:new M(`Editor Shortcuts
|
|
5735
5735
|
`,F)})}),new vG0({items:UA1.filter((O)=>O.submitOnEnterOnly===void 0||O.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(O)=>{let R=[];for(let T of O.methods){let f=this.buildCleanKeyCombination(T);R.push(f)}let S=R.join(", ");return[new p({text:new M(S,X)}),new p({text:new M(O.description,G)})]}}),new U0({height:1}),new f0({padding:W0.horizontal(2),child:new p({text:new M(`Scrolling & Navigation
|
|
5736
5736
|
`,F)})}),new vG0({items:KA1,renderRow:(O)=>{let R=[];for(let T of O.methods){let f=this.buildCleanKeyCombination(T);R.push(f)}let S=R.join(", ");return[new p({text:new M(S,X)}),new p({text:new M(O.description,G)})]}}),new U0({height:1}),new f0({padding:W0.horizontal(2),child:new p({text:new M(`Command Palette Commands
|
|
@@ -5830,10 +5830,10 @@ Ctrl-X, Y, Z to unlock`;if(E){let a=G.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
5830
5830
|
`))}function kh5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function $s4(A,Q){let B=A.replace(/\s+/g," ").trim();if(d4(B)<=Q)return B;let $="...",J=d4($);if(Q<=J)return hF($,Q);return`${hF(B,Q-J,!0,"")}${$}`}var a61="https://ampcode.com/news/neo",o61=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:[{text:"Amp now has a ",linkText:"complete plugin API",href:"https://ampcode.com/manual/plugin-api",textAfter:"."},"Add tools, commands, control UI, and hook into events."]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:a61,href:a61},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}];function vh5(A){return[{title:"Upgrade your Amp CLI",body:[{text:"This npm-based distribution of Amp CLI has been deprecated. To use the ",linkText:"new Amp CLI",href:a61,textAfter:" you'll need to switch to the binary install:",linkWidget:!0},"",{codeBlock:["npm uninstall -g @sourcegraph/amp",A]}]}]}function yh5(){if(process.platform==="win32")return'powershell -c "irm https://ampcode.com/install.ps1 | iex"';return"curl -fsSL https://ampcode.com/install.sh | bash"}var uf=50,VR=40,i61=1000,xh5=420,fh5=760,bh5=-250,uh5=1100,GV0=33,Fs4=0.999,hh5=2.1,gh5=720,mh5=420,Ws4="Meet the new",zs4="Amp",Hs4="CLI",r61=L4(Ws4).length,ph5=L4(zs4).length,dh5=L4(Hs4).length,VV0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},Xs4={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},Ds4={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},Gs4=[VV0,Xs4,Ds4,VV0,Xs4,Ds4,VV0],ch5=VV0;class s61 extends v0{onDismiss;onQuit;animationProgress;variant;binaryInstallCommand;introStages;dismissible;constructor(A){super();this.onDismiss=A.onDismiss,this.onQuit=A.onQuit,this.animationProgress=A.animationProgress,this.variant=A.variant??"intro",this.binaryInstallCommand=A.binaryInstallCommand??yh5(),this.introStages=this.variant==="npm-migration"?vh5(this.binaryInstallCommand):o61,this.dismissible=this.variant!=="npm-migration"}createState(){return new qs4}}class qs4 extends S0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=i61;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new j9(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=tY(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=Fs4,this.firstStageHintVisible=this.animationProgress>=Fs4,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}if(this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:i61,onComplete:()=>{if(!this.widget.dismissible)this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageHintVisible=!0,this.firstStageTitleRevealProgress=1,this.firstStageHintRevealProgress=1})}}),this.widget.dismissible)this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=tY(A/fh5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},GV0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.isFinalIntroStage()){if(this.widget.dismissible)this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.widget.dismissible||!this.canNavigateIntroStage()||!this.isFinalIntroStage())return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.isFinalIntroStage())return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}isFinalIntroStage(){return this.introStage>=this.widget.introStages.length-1}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let B=performance.now()-this.stageTransitionStartedAt,$=tY(B/xh5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},GV0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=tY(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*hf(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},GV0)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){this.stopFirstStageRevealTimers(),this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,i61+bh5),Q=A+uh5;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?tY((A-this.firstStageTitleRevealStartedAt)/gh5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?tY((A-this.firstStageHintRevealStartedAt)/mh5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},GV0)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=Vs4(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:Us4(Vs4(this.previousIntroStage),A,hf(this.stageTransitionProgress));return this.dismissProgress>0?Us4(Q,ch5,hf(this.dismissProgress)):Q}build(A){let Q=R1.of(A).colorScheme,B=T0.of(A),$=this.currentOrbPalette(),J=nQ(1,"frontier",$),Y=t1.of(A).size,F=this.widget.animationProgress??this.animationProgress,X=Math.max(Y.width/uf,Y.height/VR)*hh5,D=X+(1-X)*F,G=hf(this.dismissProgress),V=Math.max(uf,Math.round(uf*D)),U=Math.max(VR,Math.round(VR*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),W=Math.max(0,Math.floor((Y.width-uf)/2)),z=-Math.floor(VR/2),H=Math.round(K+(W-K)*F),q=Math.round(E+(z-E)*F),N=H+V/2,I=q+U/2,w=lh5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),C=Math.max(uf,Math.round(uf*w.orbScale)),O=Math.max(VR,Math.round(VR*w.orbScale)),R=w.orbCenterX,S=w.orbCenterY,T=Math.round(R-C/2),f=Math.round(S-O/2),h=Math.max(3,Math.min(Y.height-5,Math.floor(VR/2)+2)),x=Math.max(h+3,Y.height-3),k=w.textDissolveProgress,b=this.isFinalIntroStage()?w.backdropDissolveProgress:0,c=this.firstStageTitleVisible&&k<1,l=c&&this.firstStageHintVisible,g=l&&this.widget.dismissible&&this.introStage>0&&!this.isFinalIntroStage(),i=this.introStage===0?this.firstStageTitleRevealProgress:1,d=this.introStage===0?this.firstStageHintRevealProgress:1,Q0=Math.max(24,Math.min(74,Y.width-4)),H0=Math.min(12,Math.max(8,Y.height-h-6)),a=Math.max(0,Math.floor((Y.width-Q0)/2)),I0=Math.max(0,Math.min(Y.height-H0,Math.floor(Y.height*0.55-H0/2))),_0=this.widget.animationProgress!==void 0?new kx({width:C,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new kx({width:C,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new i4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(B0)=>{if(B0.key==="Enter")return this.advanceIntroStage(),"handled";if(!this.widget.dismissible&&B0.key==="c"&&B0.ctrlKey)return this.widget.onQuit?.(),"handled";if(!this.widget.dismissible&&B0.key==="q")return this.widget.onQuit?.(),"handled";if((B0.key===" "||B0.key==="Space")&&!this.isFinalIntroStage())return this.advanceIntroStage(),"handled";if(B0.key==="Escape"||B0.key==="Esc"){if(!this.widget.dismissible)return this.widget.onQuit?.(),"handled";return this.dismissFromFinalIntroStage()?"handled":"ignored"}if(B0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(B0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new e4({fit:"expand",children:[new Ns4({color:Q.background,dissolveProgress:b}),new e4({fit:"expand",children:[new v1({onClick:()=>{},child:U0.expand()}),new WA({left:T,top:f,width:C,height:O,child:_0}),...c?[new WA({left:a,top:I0,width:Q0,height:H0,child:nh5({introStages:this.widget.introStages,stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:Q0,height:H0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:i,dissolveProgress:k,context:A})})]:[],...l?[...g?[new WA({left:a,top:Math.max(0,x-1),width:Q0,height:1,child:new p({text:eh5({stage:this.introStage,featureStageCount:Math.max(0,this.widget.introStages.length-2),foreground:Q.mutedForeground,dissolveProgress:k}),textAlign:"center"})})]:[],new WA({left:a,top:x,width:Q0,height:1,child:Qg5({finalStage:this.isFinalIntroStage(),dismissible:this.widget.dismissible,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:d,dissolveProgress:k,context:A})})]:[]]})]})})}}class Ns4 extends $8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new Is4(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class Is4 extends $4{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),F={bg:this.color},X=tY(this.dissolveProgress);if(X<=0){A.fill($,J,Y,Z," ",F);return}if(X>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!ih5(G,D,Y,Z,X))A.fill($+G,J+D,1,1," ",F)}}function tY(A){return Math.min(1,Math.max(0,A))}function hf(A){return 1-(1-A)**3}function Vs4(A){return Gs4[A]??Gs4[0]}function Us4(A,Q,B){return{primary:Lj(A.primary,Q.primary,B),secondary:Lj(A.secondary,Q.secondary,B)}}function lh5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:tY(A/0.52),backdropDissolveProgress:hf(tY((A-0.12)/0.88))}}function ih5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=ws4(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function nh5({introStages:A,stage:Q,previousStage:B,progress:$,direction:J,width:Y,height:Z,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E}){if(B===null||$>=1)return n61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E});let W=hf($),z=J*Math.round((1-W)*Y),H=-J*Math.round(W*Y);return new SW(new e4({fit:"expand",children:[new WA({left:H,top:0,width:Y,height:Z,child:n61({introStages:A,stage:B,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:B===0?1:U,dissolveProgress:K,context:E})}),new WA({left:z,top:0,width:Y,height:Z,child:n61({introStages:A,stage:Q,foreground:F,mutedForeground:X,accent:D,link:G,keybind:V,titleRevealProgress:U,dissolveProgress:K,context:E})})]}))}function n61({introStages:A,stage:Q,foreground:B,mutedForeground:$,accent:J,link:Y,keybind:Z,titleRevealProgress:F,dissolveProgress:X,context:D}){let G=A[Q]??A[0]??o61[0],V=new v({color:J,bold:!0}),U=new v({color:B}),K=A===o61&&Q===0,E=[...G.title===null?[]:[new p({text:K?UV0(rh5({progress:F,foreground:J,pulseColor:J}),X):new M(Q$(G.title,X),V),textAlign:"center"})],...G.body.length>0?[ah5()]:[],...G.body.map((W)=>oh5(W,U,$,Y,Z,X,D))];return new r1({child:new f0({padding:W0.horizontal(1),child:new x0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:E})})})}function ah5(){return U0.height(1)}function oh5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new p({text:new M(Q$(A,Y),Q),textAlign:"center"});if("codeBlock"in A)return new Q3({onCopy:(F,X)=>{if(X)J5.success(Z,"Copied to clipboard",2000)},child:new x0({mainAxisSize:"min",children:A.codeBlock.map((F)=>new p({text:new M(Q$(F,Y),new v({color:J})),textAlign:"center",selectable:!0}))})});if("keybind"in A){let F=new p({text:new M("",void 0,[new M(Q$(A.text,Y),new v({color:B,dim:!0})),new M(Q$(A.keybind,Y,L4(A.text).length),new v({color:J}))]),textAlign:"center",selectable:"selectable"in A?A.selectable:!1});if("selectable"in A)return new r1({child:new Q3({child:F})});return F}if("highlightText"in A){let F=GA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=mD.of(Z),D=new M("",void 0,[new M(A.text,Q),new M(A.highlightText,new v({color:J})),new M(A.textAfterHighlight,Q),new M(F.text,F.style,F.children,F.hyperlink,()=>{dA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new M(A.textAfter,Q)]);return new p({text:UV0(D,Y),textAlign:"center"})}if("linkText"in A){if(A.linkWidget)return new x0({mainAxisSize:"min",children:[new p({text:new M(Q$(A.text,Y),Q),textAlign:"center"}),new r1({child:new t0({mainAxisSize:"min",children:[GA.createWidget(Z,A.href,Q$(A.linkText,Y),new v({color:$,underline:!0})),new p({text:new M(Q$(A.textAfter,Y),Q)})]})})]});let F=GA.createSpan(A.href,A.linkText,new v({color:$,underline:!0})),X=mD.of(Z),D=new M("",void 0,[new M(A.text,Q),new M(F.text,F.style,F.children,F.hyperlink,()=>{dA(Z,A.href,{forceExternal:!1,onShowImagePreview:X})}),new M(A.textAfter,Q)]);return new p({text:UV0(D,Y),textAlign:"center"})}if(Y>0)return new p({text:new M(Q$(A.text,Y),new v({color:$,underline:!0})),textAlign:"center"});return new r1({child:GA.createWidget(Z,A.href,A.text,new v({color:$,underline:!0}))})}function rh5({progress:A,foreground:Q,pulseColor:B}){let $=new v({color:Q,bold:!0}),J=new v({color:th5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new M("",void 0,[new M(sh5(A).padEnd(r61," "),$),new M(" ",$),new M(Ks4(zs4,ph5,A,0.72),$),new M(" ",$),new M(Ks4(Hs4,dh5,A,0.88),J)])}function sh5(A){let Q=L4(Ws4),B=Math.min(r61,Math.ceil(tY(A/0.62)*r61));return Q.slice(0,B).join("")}function Ks4(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function th5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=tY((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function eh5({stage:A,featureStageCount:Q,foreground:B,dissolveProgress:$}){return new M(Q$(`${A}/${Q}`,$),new v({color:B,dim:!0}))}function Ag5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}){let Z=new v({color:$}),F=new v({color:B,dim:!0}),X=Q?A?"Enter":"Space":"Esc",D=Q?A?" to get started":" to continue":" to quit, or use ",G=Q?"":"amp --take-me-back",V=Q?"":" to use the old version",U=`${D}${G}${V}`;if(!Q)return new M("",void 0,[new M(X,Z),new M(D,F),new M(G,Z),new M(V,F)]);let K=Es4(X,J),E=Es4(U,tY((J*(L4(X).length+L4(U).length)-L4(X).length)/L4(U).length));return new M("",void 0,[new M(Q$(K,Y),Z),new M(Q$(E.slice(0,D.length),Y),F),new M(Q$(E.slice(D.length,D.length+G.length),Y),Z),new M(Q$(E.slice(D.length+G.length),Y),F)])}function Qg5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y,context:Z}){if(Q)return new p({text:Ag5({finalStage:A,dismissible:Q,foreground:B,keybind:$,revealProgress:J,dissolveProgress:Y}),textAlign:"center"});let F=new v({color:$}),X=new v({color:B,dim:!0});return new Q3({onCopy:(D,G)=>{if(G)J5.success(Z,"Copied to clipboard",2000)},child:new p({text:new M("",void 0,[new M("q",F),new M(" to quit, or use ",X),new M("amp --take-me-back",F),new M(" to use the old version",X)]),textAlign:"center",selectable:!0})})}function Es4(A,Q){let B=L4(A),$=Math.min(B.length,Math.ceil(tY(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function UV0(A,Q,B=0){if(Q<=0)return A;let $=B+L4(A.text??"").length,J=A.children?.map((Y)=>{let Z=UV0(Y,Q,$);return $+=L4(Y.toPlainText()).length,Z});return new M(A.text?Q$(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function Q$(A,Q,B=0){if(Q<=0)return A;return L4(A).map((J,Y)=>{if(J.trim()==="")return J;return ws4(B+Y)<Q?" ":J}).join("")}function ws4(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}c0();w2();function mI(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,F=Y?.paidUSD??0;if(Z===0&&F===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(F===0)J.push(new M(mU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new M(" (free)",new v({color:B.foreground,dim:$})));else if(Z>0)J.push(new M(mU(Z,D),new v({color:B.foreground,dim:$}))),J.push(new M(" (free)",new v({color:B.foreground,dim:$}))),J.push(new M(" + ",new v({color:B.foreground,dim:$}))),J.push(new M(mU(F,D),new v({color:B.foreground,dim:$,bold:!$})));else J.push(new M(mU(F,D),new v({color:B.foreground,dim:$,bold:!$})));return J}class t61 extends l4{}class e61 extends l4{}function Bg5(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 $g5(A,Q){let B=T0.of(Q),{colors:$}=B,J=mI(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new M("Total: ",new v({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(`
|
|
5831
5831
|
|
|
5832
5832
|
`)),Y.push(new M("Details: ",new v({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new v({color:B.app.link})));return new p({text:new M("",void 0,Y)})}function Jg5(A,Q,B){let $=$g5(A,Q);if(!A.costBreakdownURL)return new SA({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new D4(()=>{return t4.maybeInvoke(Q,new AQ(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new D4(()=>{return dA(Q,J),"handled"});return new SA({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 t4({actions:new Map([[t61,Y],[e61,Z]]),child:new m5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[T1.key("o"),new e61],[T1.key("y"),new t61]]),child:new m4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function Cs4(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 YA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(Bg5(J,Y.error),"error",5000),$();return}Q.push(Jg5(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 Yg5=250,Zg5=2000;function Fg5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${MB(new URL(A),Q).toString()} (cli log: ${B}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
|
|
5833
|
-
`)}class A51 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;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.neoWelcomeVariant=A.neoWelcomeVariant??"intro",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 Ls4}}class Ls4 extends S0{editorController=new M8;commandPalette=new Jr(this);commandRegistry=new GA1;toastController=new le0;exitHintTimer=new ox(this,1000);ideStatus=new u8(this,{});threadNavigationHistory=new JA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=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})};sendFeedbackReport=async(A)=>jn4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return Rn4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await Rd4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Pd4({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 _d4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(nB.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(this.applySessionDefaultsToThreadSettings(v30(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 BA1({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=C4.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()},Yg5),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<Zg5)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?Cn4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,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((F)=>eA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,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()}},Cs4({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 jA1({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 l61({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 dA(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:()=>{zJ(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((F)=>new LA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),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 WA1({commands:sY.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the 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 SA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new M(ue0({version:"0.0.1778158028-g39bfa2",buildTimestamp:"2026-05-07T12:50:51.788Z",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:T1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{t4.maybeInvoke(Y,new Rf)}},...Q,...Gn4(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 c61({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=t1.of(A),Z=[new g0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new i4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new VA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(eA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new i4({debugLabel:"NeoWelcomeDialogOverlay",child:new s61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),variant:this.widget.neoWelcomeVariant})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new CA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:ys.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new MA1);return new _3({neoContext:this.widget.neoContext,child:new sY({commandRegistry:this.commandRegistry,child:new SI({completionBuilder:this.widget.completionBuilder,child:new J5({controller:this.toastController,child:new t4({actions:this.buildActions(),child:new m5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[T1.ctrl("c"),new OG0],[T1.ctrl("o"),new jG0],[T1.alt("i"),new PG0],[T1.alt("p"),new VI],[T1.ctrl("t"),new _G0]]),child:new m4({debugLabel:"AppShellFocus",child:new ie0({controller:this.toastController,child:new e4({children:Z})})})})})})})})})}buildActions(){let A=new D4(()=>{if(WJ.hasAnyCopyableSelection())return WJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new D4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new D4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new D4(()=>{return this.startNewDraftThread(),"handled"}),J=new D4(()=>{return C4.instance.stop(),"handled"}),Y=new D4((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new D4(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new D4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new D4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Dx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new D4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new D4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new D4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[OG0,A],[Qs,$],[Rf,J],[AQ,Y],[Js,B],[jG0,Q],[PG0,F],[Ys,X],[Zs,D],[Fs,G],[VI,Z],[_G0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Fg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Dx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}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=this.applySessionDefaultsToThreadSettings(await hx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=aB(Q),J=fX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return xX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ms4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(bZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ms4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TI);if(this.exitHintTimer.isActive())A.add(wf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.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 J=this.activeThreadContext?.client.getThreadId(),Y=A.find((F)=>F.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,ys.cwd()),this.widget.history.reset();let Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?nY(B):void 0);this.sendUserMessage(Z,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=aB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};EJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=OY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}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{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","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{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","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.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=wA1(Q);if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=ys.cwd().replace(ys.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,ys.stdout.write(BI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}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.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;if(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 Ms4(A,Q,B){let $={...A};for(let J of Xg5(Q,B)){if(!bZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Xg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}c4();function Os4(A,Q,B,$){let J=rT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\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 pY(G,V),K=new j9(42),E=new YI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),z=0;for(let R=0;R<V;R++)if(W[R].some((S)=>S.char!==" ")){z=R;break}let H=V-1;for(let R=V-1;R>=0;R--)if(W[R].some((S)=>S.char!==" ")){H=R;break}function q(R,S){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:h}=R.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${f};${h}m`;let x=wj(T,f,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(H>=z)for(let R=z;R<=H;R++){let S="";for(let T=0;T<G;T++){let f=W[R][T],h=f.char,x=q(f.style.fg,!0);S+=x+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 R=0;R<w;R++){let S=" ".repeat(G);if(R>=C&&R<C+I)S=N[R-C];let T=" ",f="";if(R>=O&&R<O+D.length)f=D[R-O];B.write(S+T+f+`
|
|
5833
|
+
`)}class A51 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;neoWelcomeVariant;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.neoWelcomeVariant=A.neoWelcomeVariant??"intro",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 Ls4}}class Ls4 extends S0{editorController=new M8;commandPalette=new Jr(this);commandRegistry=new GA1;toastController=new le0;exitHintTimer=new ox(this,1000);ideStatus=new u8(this,{});threadNavigationHistory=new JA1;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new H6;terminalTitleSpinnerTimer=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})};sendFeedbackReport=async(A)=>jn4({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return Rn4({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await Rd4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Pd4({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 _d4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(nB.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(this.applySessionDefaultsToThreadSettings(v30(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 BA1({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=C4.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()},Yg5),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<Zg5)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?Cn4({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,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((F)=>eA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:F,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()}},Cs4({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 jA1({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 l61({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 dA(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:()=>{zJ(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((F)=>new LA1({onCancel:F,onSelect:(X)=>{this.handleIdeSelection(X),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 WA1({commands:sY.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the 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 SA({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new p({text:new M(ue0({version:"0.0.1778171486-g3e6a89",buildTimestamp:"2026-05-07T16:34:46.143Z",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:T1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{t4.maybeInvoke(Y,new Rf)}},...Q,...Gn4(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 c61({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,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=t1.of(A),Z=[new g0({constraints:M1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new i4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new VA1({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(eA1({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new i4({debugLabel:"NeoWelcomeDialogOverlay",child:new s61({onDismiss:this.dismissNeoWelcome,onQuit:()=>C4.instance.stop(),variant:this.widget.neoWelcomeVariant})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new CA1({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:ys.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new MA1);return new _3({neoContext:this.widget.neoContext,child:new sY({commandRegistry:this.commandRegistry,child:new SI({completionBuilder:this.widget.completionBuilder,child:new J5({controller:this.toastController,child:new t4({actions:this.buildActions(),child:new m5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[T1.ctrl("c"),new OG0],[T1.ctrl("o"),new jG0],[T1.alt("i"),new PG0],[T1.alt("p"),new VI],[T1.ctrl("t"),new _G0]]),child:new m4({debugLabel:"AppShellFocus",child:new ie0({controller:this.toastController,child:new e4({children:Z})})})})})})})})})}buildActions(){let A=new D4(()=>{if(WJ.hasAnyCopyableSelection())return WJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new D4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new D4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new D4(()=>{return this.startNewDraftThread(),"handled"}),J=new D4(()=>{return C4.instance.stop(),"handled"}),Y=new D4((U)=>{if(!U.text)return"ignored";return C4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new D4(()=>{return C4.instance.toggleFrameStatsOverlay(),"handled"}),F=new D4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),X=new D4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=Dx(U);return C4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new D4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new D4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await C4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new D4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[OG0,A],[Qs,$],[Rf,J],[AQ,Y],[Js,B],[jG0,Q],[PG0,F],[Ys,X],[Zs,D],[Fs,G],[VI,Z],[_G0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:Fg5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:Dx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}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=this.applySessionDefaultsToThreadSettings(await hx(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=aB(Q),J=fX0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return xX0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=Ms4(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(bZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=Ms4(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(TI);if(this.exitHintTimer.isActive())A.add(wf);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),C4.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 J=this.activeThreadContext?.client.getThreadId(),Y=A.find((F)=>F.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,ys.cwd()),this.widget.history.reset();let Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?nY(B):void 0);this.sendUserMessage(Z,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=aB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};EJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=OY0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}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{await A.client.reconnect(),this.toastController.update(B,Q?`Reconnected ${Q}`:"Reconnected thread","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{await A.client.disconnectAndWait(),this.toastController.update(B,Q?`Disconnected ${Q}`:"Disconnected thread","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.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=wA1(Q);if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=ys.cwd().replace(ys.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,ys.stdout.write(BI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}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.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;if(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 Ms4(A,Q,B){let $={...A};for(let J of Xg5(Q,B)){if(!bZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Xg5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}c4();function Os4(A,Q,B,$){let J=rT(A),Y="\x1B[0m",Z="\x1B[34m",F="\x1B[90m",X="\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 pY(G,V),K=new j9(42),E=new YI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,E0.default(),K);E.layout(M1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),z=0;for(let R=0;R<V;R++)if(W[R].some((S)=>S.char!==" ")){z=R;break}let H=V-1;for(let R=V-1;R>=0;R--)if(W[R].some((S)=>S.char!==" ")){H=R;break}function q(R,S){if(!R)return"";if(R.type==="rgb"){let{r:T,g:f,b:h}=R.value;if(B.getColorDepth()>=24)return`\x1B[${S?38:48};2;${T};${f};${h}m`;let x=wj(T,f,h);return`\x1B[${S?38:48};5;${x}m`}return""}let N=[];if(H>=z)for(let R=z;R<=H;R++){let S="";for(let T=0;T<G;T++){let f=W[R][T],h=f.char,x=q(f.style.fg,!0);S+=x+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 R=0;R<w;R++){let S=" ".repeat(G);if(R>=C&&R<C+I)S=N[R-C];let T=" ",f="";if(R>=O&&R<O+D.length)f=D[R-O];B.write(S+T+f+`
|
|
5834
5834
|
`)}if($)B.write(`
|
|
5835
5835
|
\x1B[90m${$}\x1B[0m
|
|
5836
|
-
`)}c0();iX0();var Dg5=2000;function js4(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<Dg5)return;if(J=U,Pj())return;if(nF0())aF0();else GZ0(V)},Z=(V)=>{if(!Q||!B)return;if(Pj()&&!oo()&&!_x())return;process.stdout.write(SD(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&cB(X),E=X==="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{X=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Gg5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeVariant:B,neoWelcomeDismissed:$}){if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let J=!A&&!$;return{show:J,markDismissedOnDismiss:J}}async function Vg5(A){await EJ((Q)=>hX0(Q,A,"interactive"))}async function Rs4(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:F,showNeoWelcome:X=!1,neoWelcomeVariant:D="intro"}=Q,G=D==="npm-migration",V=async(C)=>{let O=await A.getThreadFromServer(C);if(!O)return null;return kF0(O)},U=async(C)=>{let O=await A.getThreadFromServer(C);if(!O)throw Error(`Thread ${C} not found`);let R=await hY(C,A.configService,A.apiKey,{usesThreadActors:!0}),f=await HU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([C],{params:{wsToken:R.wsToken},createWithInput:{threadId:R.threadId,threadVersion:R.threadVersion,ownerUserId:R.ownerUserId,...R.agentMode?{agentMode:R.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Bx4(O)}),skipReadyWait:!0});if(!f.ok&&f.status!==409)throw Error(`Thread import failed (${f.status}): ${await f.text()}`);try{await Tx4(C,A.configService,A.apiKey,{executorType:"local-client"})}catch(h){j.warn("failed to mark thread as imported on server",{threadID:C,error:h instanceof Error?h.message:String(h)})}},K=new He0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:lN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(C)=>A.pluginService.event.toolCall(C),requestPluginToolResult:(C)=>A.pluginService.event.toolResult(C),pluginService:A.pluginService,invokeTool:async(C,O)=>{let R=typeof O.args==="object"&&O.args!==null?O.args:{},S=await aN({toolName:O.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:O.toolCallId,
|
|
5836
|
+
`)}c0();iX0();var Dg5=2000;function js4(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<Dg5)return;if(J=U,Pj())return;if(nF0())aF0();else GZ0(V)},Z=(V)=>{if(!Q||!B)return;if(Pj()&&!oo()&&!_x())return;process.stdout.write(SD(`\x1B]777;notify;Amp;${V}\x1B\\`))},F=null,X=null,D=()=>{F?.unsubscribe(),F=null,X=null};return{attach:(V)=>{D(),F=V.subscribe({next:(U)=>{try{let K=X!==null&&cB(X),E=X==="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{X=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Gg5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeVariant:B,neoWelcomeDismissed:$}){if(B==="npm-migration")return{show:!0,markDismissedOnDismiss:!1};if(Q)return{show:!0,markDismissedOnDismiss:!0};let J=!A&&!$;return{show:J,markDismissedOnDismiss:J}}async function Vg5(A){await EJ((Q)=>hX0(Q,A,"interactive"))}async function Rs4(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:F,showNeoWelcome:X=!1,neoWelcomeVariant:D="intro"}=Q,G=D==="npm-migration",V=async(C)=>{let O=await A.getThreadFromServer(C);if(!O)return null;return kF0(O)},U=async(C)=>{let O=await A.getThreadFromServer(C);if(!O)throw Error(`Thread ${C} not found`);let R=await hY(C,A.configService,A.apiKey,{usesThreadActors:!0}),f=await HU({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([C],{params:{wsToken:R.wsToken},createWithInput:{threadId:R.threadId,threadVersion:R.threadVersion,ownerUserId:R.ownerUserId,...R.agentMode?{agentMode:R.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Bx4(O)}),skipReadyWait:!0});if(!f.ok&&f.status!==409)throw Error(`Thread import failed (${f.status}): ${await f.text()}`);try{await Tx4(C,A.configService,A.apiKey,{executorType:"local-client"})}catch(h){j.warn("failed to mark thread as imported on server",{threadID:C,error:h instanceof Error?h.message:String(h)})}},K=new He0(A.rivetEndpoint,A.apiKey,A.configService,{clientID:lN.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(C)=>A.pluginService.event.toolCall(C),requestPluginToolResult:(C)=>A.pluginService.event.toolResult(C),pluginService:A.pluginService,invokeTool:async(C,O)=>{let R=typeof O.args==="object"&&O.args!==null?O.args:{},S=await aN({toolName:O.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:O.toolCallId,threadId:C});return A.toolService.invokeTool(O.toolName,{args:R},S)},persistLastThreadID:Vg5,readFileSystemDirectory:A.readFileSystemDirectory},V,U),E=await DI(),W=Gg5({initialUserInput:$,showNeoWelcome:X,neoWelcomeVariant:D,neoWelcomeDismissed:E.neoWelcomeDismissed}),z={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(C)=>{let O=await A.getThreadFromServer(C);return O?LV(O):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:la,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:G?!1:Y,sessionAgentMode:Z??E.agentMode,explicitReasoningEffort:F,lastReasoningEffortByMode:E.lastReasoningEffortByMode,lastSpeedByMode:E.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},H=(C,O)=>{return Yx({ampURL:A.ampURL,configService:A.configService,threadID:C,signal:O})},q=(C,O)=>{return _h4({ampURL:A.ampURL,configService:A.configService,threadID:C,signal:O})},N=new be0,I=js4({configService:A.configService}),w=new Set;try{await ro(new A51({clientPool:K,analyzeContextForThread:H,listSkillsForThread:q,completionBuilder:A.completionBuilder,history:new Jo,ideManager:N,configService:A.configService,initialThreadID:G?void 0:B,notificationService:I,initialUserInput:G?void 0:$,openThreadPickerOnStart:G?!1:J,neoContext:z,showNeoWelcome:W.show,neoWelcomeVariant:D,onNeoWelcomeDismissed:W.markDismissedOnDismiss?()=>{EJ(vh4).catch((O)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:O})})}:void 0,onThreadArchived:(O)=>{w.add(O)}}));let C=K.lastActiveObservingClient;if(C){let{client:O,observer:R}=C,S=O.getThreadId();if(S){let T={id:S,title:R.title().getValue(),agentMode:R.agentMode,archived:w.has(S)},f=`${A.ampURL.replace(/\/$/,"")}/threads/${S}`;Os4(T,f,process.stdout)}}}finally{process.stdout.write(BI("")),I.unsubscribe(),K.dispose(),await A.dispose?.()}process.exit(0)}mp();nK();async function Ug5(A,Q,B){let $=N80(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=PH($.data);if(!J.success){let X=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${X}`)}let Y=await Q.get("permissions",B)??[],F=[$.data[0],...Y];await Q.set("permissions",F,B)}async function Ps4(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await Ug5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
|
|
5837
5837
|
`),A.exit(1)}}H80();mp();async function _s4(A){let Q=A.builtinOnly?IS:await A.settings.get("permissions",A.scope)??[];if(A.json)A.stdout.write(JSON.stringify(Q,null,2));else{let B=gp(Q);A.stdout.write(B),A.stdout.write(`
|
|
5838
5838
|
`)}A.exit(0)}H80();NS();wS();nK();var Kg5={outputResult(A,Q,B){let $={tool:A.toolName,arguments:Q,...A.context&&{context:A.context},...A.threadId&&{threadId:A.threadId},...B};A.stdout.write(JSON.stringify($,null,2))},outputError(A,Q,B){let $={tool:A.toolName,arguments:Q,...A.context&&{context:A.context},...A.threadId&&{threadId:A.threadId},...B};A.stdout.write(JSON.stringify($,null,2))}},Eg5={outputResult(A,Q,B){if(A.stdout.write(`tool: ${A.toolName}
|
|
5839
5839
|
`),A.stdout.write(`arguments: ${JSON.stringify(Q)}
|
|
@@ -7468,7 +7468,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
|
|
|
7468
7468
|
`),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 v({color:$.app.keybind,bold:!0})));else Y.push(new M(G,new v({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new M(`
|
|
7469
7469
|
`))}return new g0({decoration:{color:B.colorScheme.background,border:c1.all(new l1($.app.keybind,1,"rounded"))},child:new f0({padding:W0.symmetric(0,1),child:new p({text:new M(void 0,void 0,Y)})})})}}class F31 extends $8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=OU0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new Y31({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 i0A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let F=B;return F>=0&&F<Y?F:null}case"bar":case"stacked-bar":{let F=Z?m8:0,X=$-F;if(X<=0)return null;let D=Q-F;if(D<0||D>=X)return null;let G=Math.max(1,Math.floor(X/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let F=Z?m8:0,X=$-F;if(X<=0)return null;let D=Math.max(0,Math.min(X-1,Q-F));if(Y===1)return 0;let G=X/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function Ii5(A,Q,B,$,J,Y,Z,F){if(J<=0||Q<0||Q>=J)return null;let X=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?m8:0,G=B-D,V=$-(Y?X: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=F>0?Z/F:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?m8:0,G=B-D,V=$-(Y?X: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=F>0?Z/F:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function wi5(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function Ci5(A,Q,B,$,J){if(B.length<=1){let F=$(A.value),X=A.meta?` (${A.meta})`:"";return A.label.length+2+F.length+X.length}let Y=A.label.length,Z=0;for(let F of B){let X=F.points[Q];if(!X)continue;Z+=X.value;let D=2+F.name.length+2+$(X.value).length;Y=Math.max(Y,D)}if(J){let F=9+$(Z).length;Y=Math.max(Y,F)}return Y}function Mi5(A,Q,B,$,J,Y,Z){let F;try{let E=R1.of(A),W=T0.of(A);F={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{F={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let X=new v({color:F.foreground,bold:!0}),D=new v({color:F.foreground}),G=new v({color:F.foreground,dim:!0}),V=[],U=new v({color:F.foreground,underline:!0}),K=(E,W)=>new M(W,U,void 0,OW(E),()=>{dA(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,X)),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}
|
|
7470
7470
|
`,X));let W=0;for(let z=0;z<$.length;z++){let H=$[z],q=H.points[B];if(!q)continue;W+=q.value;let N=H.color??J[z%J.length]??F.foreground;if(V.push(new M("● ",new v({color:N}))),V.push(new M(`${H.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(z<$.length-1||E)V.push(new M(`
|
|
7471
|
-
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new g0({decoration:{color:F.background,border:c1.all(new l1(F.border,1,"rounded"))},child:new p({text:new M(void 0,void 0,V)})})}c0();C3();K8();t5();y7();R7();G9();w2();jB();MV();c4();dk();zT();L1();c0();G9();class X31{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.1778158028-g39bfa2"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await _30(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 Aw extends v0{props;constructor(A){super();this.props=A}createState(){return new n0A}}class n0A extends S0{_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 a0A extends S0{controller=new M8;focusNode=new X6({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=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=c1.all(new l1(B.foreground,1,"solid")),X=new oB({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 t0({children:[new g0({decoration:{color:B.background},child:new p({text:new M(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new g0({padding:W0.symmetric(1,0),child:new p({text:this.widget.props.title?new M(this.widget.props.title,new v({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new v({color:B.foreground})),new M(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new v({color:$.keybind}))),V.push(new M(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new M("Esc",new v({color:$.keybind}))),V.push(new M(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:W0.symmetric(1,0),child:new p({text:new M("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:W0.all(1),child:new x0({children:[G,new U0({height:1}),D,new $5,U]})})}}class ss extends v0{props;constructor(A){super();this.props=A}createState(){return new a0A}}jB();class o0A extends S0{controller=new M8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new X6({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>=n9)return!1;let Q=await iF(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=T0.of(A),{colors:B,app:$}=Q,Y=t1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new dD({controller:this.controller,triggers:[new wJ],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:C4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new M1({maxHeight:Z}),padding:W0.symmetric(1,0),child:X}),G=new g0({padding:W0.symmetric(1,0),child:new p({text:new M("",void 0,[new M("Command: ",new v({color:B.foreground})),new M(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:W0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new v({color:$.keybind})),new M(" again to clear input",new v({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new v({color:B.foreground,dim:!0})),new M("Enter",new v({color:$.keybind})),new M(" to submit, ",new v({color:B.foreground,dim:!0})),new M("Esc",new v({color:$.keybind})),new M(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:c1.all(new l1(B.foreground,1,"solid")),color:B.background},padding:W0.all(1),child:new x0({children:U})})}}class D31 extends v0{props;constructor(A){super();this.props=A}createState(){return new o0A}}function r0A(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 G31 extends N1{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)=>r0A(J.pubDate).length));return new g6({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,F)=>{let X=T0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,z)=>new U0({width:z,child:t0.end([new p({text:new M(W,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:W0.symmetric(2,0),child:new t0({children:[new _1({child:new p({text:new M(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(r0A(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()}}c0();class s0A extends S0{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=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new g6({title:"Add Label",items:X,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 z=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:W0.symmetric(2,0),child:new p({text:new M("",void 0,[new M("Create new label: ",new v({color:E})),new M(z,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:W0.symmetric(2,0),child:new p({text:new M(D.name,new v({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 V31 extends v0{props;constructor(A){super();this.props=A}createState(){return new s0A}}class iD extends v0{props;constructor(A){super();this.props=A}createState(){return new t0A}}class t0A extends S0{_spinner=new H6;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=T0.of(A),{colors:B,app:$}=Q,J=c1.all(new l1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new M("",void 0,[new M(Y,new v({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:W0.symmetric(2,0),child:new p({text:new M("",new v({dim:!0}),[new M("Press ",new v({color:B.foreground})),new M("Esc",new v({color:B.info})),new M(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new f4(B.background,J),child:new U0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new i4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class cU extends v0{props;constructor(A){super();this.props=A}createState(){return new e0A}}class e0A extends S0{scrollController=new rA;scrollAreaKey=new J2("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 S2}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=T0.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=OD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=c1.all(new l1(Q.colors.border,1,"solid")),Z=new g0({padding:W0.symmetric(1,0),child:new p({text:new M($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new M($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new Q3({child:new g0({padding:W0.symmetric(1,0),child:new t0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new TA({controller:this.scrollController,autofocus:!0,child:F})}),new X2({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 g0({padding:W0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new v({color:Q.colors.foreground,dim:!0})),new M("R",new v({color:Q.app.keybind})),new M(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new M("Esc",new v({color:Q.app.keybind})),new M(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({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 v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new i4({debugLabel:"MessageDialog",child:new e4({fit:"expand",children:[new v1({onClick:()=>{},child:new U0}),new m4({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 g0({decoration:{border:Y,color:Q.colors.background},padding:W0.all(1),child:new x0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}C3();s1();class A1A extends v0{props;constructor(A){super();this.props=A}createState(){return new Q1A}}class Q1A extends S0{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=s0.file(this.widget.props.cwd),B=X1.relativePath(Q,OA(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return R5(A)}statusIcon(A){let Q=h8.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=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new M("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${W4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${F} ${W4(F,"tool")})`,new v({dim:!0})));$.push(new M(`
|
|
7471
|
+
`))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new g0({decoration:{color:F.background,border:c1.all(new l1(F.border,1,"rounded"))},child:new p({text:new M(void 0,void 0,V)})})}c0();C3();K8();t5();y7();R7();G9();w2();jB();MV();c4();dk();zT();L1();c0();G9();class X31{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.1778171486-g3e6a89"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await _30(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 Aw extends v0{props;constructor(A){super();this.props=A}createState(){return new n0A}}class n0A extends S0{_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 a0A extends S0{controller=new M8;focusNode=new X6({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=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,F=c1.all(new l1(B.foreground,1,"solid")),X=new oB({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 t0({children:[new g0({decoration:{color:B.background},child:new p({text:new M(">",new v({color:B.foreground}))})}),new _1({child:X})]}),G=new g0({padding:W0.symmetric(1,0),child:new p({text:this.widget.props.title?new M(this.widget.props.title,new v({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new v({color:B.foreground})),new M(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new v({color:$.keybind}))),V.push(new M(" to submit, ",new v({color:B.foreground,dim:!0})));V.push(new M("Esc",new v({color:$.keybind}))),V.push(new M(" to cancel",new v({color:B.foreground,dim:!0})));let U=new g0({padding:W0.symmetric(1,0),child:new p({text:new M("",void 0,V)})});return new g0({decoration:{border:F,color:B.background},padding:W0.all(1),child:new x0({children:[G,new U0({height:1}),D,new $5,U]})})}}class ss extends v0{props;constructor(A){super();this.props=A}createState(){return new a0A}}jB();class o0A extends S0{controller=new M8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new X6({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>=n9)return!1;let Q=await iF(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=T0.of(A),{colors:B,app:$}=Q,Y=t1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),F=new dD({controller:this.controller,triggers:[new wJ],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:C4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),X=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:F}),D=new g0({constraints:new M1({maxHeight:Z}),padding:W0.symmetric(1,0),child:X}),G=new g0({padding:W0.symmetric(1,0),child:new p({text:new M("",void 0,[new M("Command: ",new v({color:B.foreground})),new M(this.widget.props.commandName,new v({color:$.command,bold:!0}))])})}),V=new g0({padding:W0.symmetric(1,0),child:new p({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new v({color:$.keybind})),new M(" again to clear input",new v({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new v({color:B.foreground,dim:!0})),new M("Enter",new v({color:$.keybind})),new M(" to submit, ",new v({color:B.foreground,dim:!0})),new M("Esc",new v({color:$.keybind})),new M(" to clear",new v({color:B.foreground,dim:!0}))])})}),U=[G,new U0({height:1}),new _1({child:D}),new U0({height:1}),V];return new g0({decoration:{border:c1.all(new l1(B.foreground,1,"solid")),color:B.background},padding:W0.all(1),child:new x0({children:U})})}}class D31 extends v0{props;constructor(A){super();this.props=A}createState(){return new o0A}}function r0A(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 G31 extends N1{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)=>r0A(J.pubDate).length));return new g6({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,F)=>{let X=T0.of(F),{colors:D}=X,G=X.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,z)=>new U0({width:z,child:t0.end([new p({text:new M(W,new v({color:K}))})])});return new g0({decoration:V?{color:V}:void 0,padding:W0.symmetric(2,0),child:new t0({children:[new _1({child:new p({text:new M(J.title,new v({color:U})),overflow:"ellipsis",maxLines:1})}),new U0({width:2}),E(r0A(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()}}c0();class s0A extends S0{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=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),X=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new g6({title:"Add Label",items:X,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 z=this.currentQuery.trim().toLowerCase();return new g0({decoration:K?{color:K}:void 0,padding:W0.symmetric(2,0),child:new p({text:new M("",void 0,[new M("Create new label: ",new v({color:E})),new M(z,new v({color:E,bold:!0}))])})})}return new g0({decoration:K?{color:K}:void 0,padding:W0.symmetric(2,0),child:new p({text:new M(D.name,new v({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 V31 extends v0{props;constructor(A){super();this.props=A}createState(){return new s0A}}class iD extends v0{props;constructor(A){super();this.props=A}createState(){return new t0A}}class t0A extends S0{_spinner=new H6;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=T0.of(A),{colors:B,app:$}=Q,J=c1.all(new l1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new p({textAlign:"center",text:new M("",void 0,[new M(Y,new v({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new v({color:B.foreground}))])}),X=[new _1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)X.push(new U0({height:2,child:new g0({padding:W0.symmetric(2,0),child:new p({text:new M("",new v({dim:!0}),[new M("Press ",new v({color:B.foreground})),new M("Esc",new v({color:B.info})),new M(" to cancel",new v({color:B.foreground}))])})})}));let D=new g0({decoration:new f4(B.background,J),child:new U0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:X})})});if(this.widget.props.onAbort)return new i4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class cU extends v0{props;constructor(A){super();this.props=A}createState(){return new e0A}}class e0A extends S0{scrollController=new rA;scrollAreaKey=new J2("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 S2}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=T0.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=OD0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=c1.all(new l1(Q.colors.border,1,"solid")),Z=new g0({padding:W0.symmetric(1,0),child:new p({text:new M($.title,new v({color:J,bold:!0}))})}),F=this.isWidgetMessage(B)?B.widget:new p({text:new M($.description,new v({color:Q.colors.foreground})),selectable:!0}),X=new _1({child:new Q3({child:new g0({padding:W0.symmetric(1,0),child:new t0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new _1({child:new TA({controller:this.scrollController,autofocus:!0,child:F})}),new X2({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 g0({padding:W0.symmetric(1,0),child:new p({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new v({color:Q.colors.foreground,dim:!0})),new M("R",new v({color:Q.app.keybind})),new M(" to retry, ",new v({color:Q.colors.foreground,dim:!0})),new M("Esc",new v({color:Q.app.keybind})),new M(" to cancel",new v({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new v({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new v({color:Q.app.keybind}),U=new v({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 v({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new i4({debugLabel:"MessageDialog",child:new e4({fit:"expand",children:[new v1({onClick:()=>{},child:new U0}),new m4({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 g0({decoration:{border:Y,color:Q.colors.background},padding:W0.all(1),child:new x0({mainAxisAlignment:"center",children:[Z,new U0({height:1}),X,D]})})})]})})}}C3();s1();class A1A extends v0{props;constructor(A){super();this.props=A}createState(){return new Q1A}}class Q1A extends S0{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=s0.file(this.widget.props.cwd),B=X1.relativePath(Q,OA(A));if(B!==null&&B!==""&&B!==".."&&!B.startsWith("../"))return B;return R5(A)}statusIcon(A){let Q=h8.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=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new p({text:new M("No plugins found.",new v({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((X)=>X.status==="active").length,Z=this.plugins.reduce((X,D)=>X+D.registeredCommands.length,0),F=this.plugins.reduce((X,D)=>X+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${W4(J,"plugin")} active`,new v({bold:!0}))),Z>0||F>0)$.push(new M(` (${Z} ${W4(Z,"command")}, ${F} ${W4(F,"tool")})`,new v({dim:!0})));$.push(new M(`
|
|
7472
7472
|
|
|
7473
7473
|
`));for(let X of this.plugins){let{icon:D,color:G}=this.statusIcon(X.status),V=this.getRelativePath(X.uri);if($.push(new M(`${D} `,new v({color:G}))),$.push(new M(V,new v({bold:!0}))),$.push(new M(` ${X.status}`,new v({dim:!0}))),$.push(new M(`
|
|
7474
7474
|
`)),X.status==="active"&&X.registeredEvents.length>0)$.push(new M(" Events: ",new v({dim:!0}))),$.push(new M(X.registeredEvents.join(", "),new v({color:B.link}))),$.push(new M(`
|
|
@@ -7646,7 +7646,7 @@ ${t.content||""}`:t.content||"",b0=[],h0=t.baseDir.startsWith("file://")?AK0(t.b
|
|
|
7646
7646
|
`)}function fAA(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"),F=H04({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),X=await YA.userDisplayBalanceInfo({},{config:F});if(!X.ok){if(X.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: ")+X.error.message+`
|
|
7647
7647
|
`),process.exit(1)}process.stdout.write(await mo5(X.result.displayText)+`
|
|
7648
7648
|
`),process.exit(0)})}var D03=xt.join(S$,"logs","headless.log"),E91=xt.join(jx,"device-id.json"),G03=`cli-tui-${D8A(16).toString("hex")}`;async function V03(){for(let A of kM)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(() => T4(_b(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){_J.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
|
|
7649
|
-
`)}function U03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function f2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")AY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")AY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)AY("internal.model",W03(Q.model))}function $8A(A){let Q=A.indexOf(":");if(Q===-1)throw new J4(`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 J4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function K03(A){if(A===void 0)return;let Q=A.trim();if(J04(Q))return Q;throw new J4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function E03(A,Q){if(kX(A,Q))return;let B=u$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new J4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function W03(A){if(!A.includes("="))return $8A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new J4(`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 J4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new J4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);$8A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new J4("No valid model overrides found in --model flag value.",1);return Q}function z03(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 H03(A){try{return await G8A(A,"utf-8")}catch{return A}}async function W91(A,Q,B){let $=z03(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!iK0(J,IB.HARNESS_SYSTEM_PROMPT)&&!(Y&&O7(Y)))throw new J4("You are not allowed to do this.",1);AY("systemPrompt",await H03($))}function iK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function q03(A){return A!=="pending"}function kR(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function N03(A){let Q=kR(A);if(Q)return Q.id;if(SX(A))throw Error(A.error.message);throw Error("unreachable")}function I03(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 w03(A){let $=I03(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 J4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function ft(A,Q){let B=or0(Error(A.error.message));if(B.message===Y7.networkOffline||B.message===Y7.networkTimeout)return w03(Q);if(B.message!==Y7.internalBug)return new J4(B.message,1,B.suggestion);return new J4(A.error.message.replace(/^Error: /,""),1)}async function C03(){if(process.versions.bun)return!1;try{return await tN()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var J8A=[{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??bF,description:`Custom settings file path (overrides the default location ${bF})`},{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 ${la})`},{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:TM.SMART.key,description:`Set the agent mode (${f$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(f$().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:"showWelcome",long:"show-welcome",type:"switch",description:"Show the 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}],Y8A=(A)=>("deprecated"in A)&&A.deprecated===!0,M03=(A)=>("hidden"in A)&&A.hidden===!0,L03=(A)=>("default"in A),O03=(A)=>("default"in A)?A.default:void 0;function dK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=K03(Q.effort);if(B!==void 0)E03(Q.mode,B);return B}function j03(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((F)=>B.includes(F)||F.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 J4(Y7.unknownCommand(B),1,Z)}}async function nK0(A){return{...A,getThreadEnvironment:EW,getEnvironmentData:(Q,B)=>tX({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new EL(A.fileSystem),generateThreadTitle:WF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>IQ(A.configService),pluginService:A.pluginService}}function V8A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:EW,getEnvironmentData:(Q,B)=>tX({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var cK0=s0.file(X03.homedir()),z91=process.env.XDG_CONFIG_HOME?s0.file(process.env.XDG_CONFIG_HOME):X1.joinPath(cK0,".config");function R03(A){return dR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(nF0())aF0();else GZ0(Q);let B=Pj(),$=oo();if((!B||$||_x())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(Pj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function p8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;oe1("0.0.
|
|
7649
|
+
`)}function U03(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",F=!1;A.warn(Y,{name:Z,code:$})}}function f2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")AY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")AY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)AY("internal.model",W03(Q.model))}function $8A(A){let Q=A.indexOf(":");if(Q===-1)throw new J4(`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 J4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function K03(A){if(A===void 0)return;let Q=A.trim();if(J04(Q))return Q;throw new J4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function E03(A,Q){if(kX(A,Q))return;let B=u$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new J4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function W03(A){if(!A.includes("="))return $8A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new J4(`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 J4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new J4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);$8A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new J4("No valid model overrides found in --model flag value.",1);return Q}function z03(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 H03(A){try{return await G8A(A,"utf-8")}catch{return A}}async function W91(A,Q,B){let $=z03(A,Q);if(!$)return;let J=bA(B)?B.features:[],Y=bA(B)?B.user.email:void 0;if(!iK0(J,IB.HARNESS_SYSTEM_PROMPT)&&!(Y&&O7(Y)))throw new J4("You are not allowed to do this.",1);AY("systemPrompt",await H03($))}function iK0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function q03(A){return A!=="pending"}function kR(A){if(!bA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function N03(A){let Q=kR(A);if(Q)return Q.id;if(SX(A))throw Error(A.error.message);throw Error("unreachable")}function I03(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 w03(A){let $=I03(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 J4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function ft(A,Q){let B=or0(Error(A.error.message));if(B.message===Y7.networkOffline||B.message===Y7.networkTimeout)return w03(Q);if(B.message!==Y7.internalBug)return new J4(B.message,1,B.suggestion);return new J4(A.error.message.replace(/^Error: /,""),1)}async function C03(){if(process.versions.bun)return!1;try{return await tN()==="npm"}catch(A){return j.debug("Failed to detect package manager for Neo npm migration welcome",{error:A}),!1}}var J8A=[{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??bF,description:`Custom settings file path (overrides the default location ${bF})`},{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 ${la})`},{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:TM.SMART.key,description:`Set the agent mode (${f$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(f$().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:"showWelcome",long:"show-welcome",type:"switch",description:"Show the 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}],Y8A=(A)=>("deprecated"in A)&&A.deprecated===!0,M03=(A)=>("hidden"in A)&&A.hidden===!0,L03=(A)=>("default"in A),O03=(A)=>("default"in A)?A.default:void 0;function dK0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=K03(Q.effort);if(B!==void 0)E03(Q.mode,B);return B}function j03(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((F)=>B.includes(F)||F.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 J4(Y7.unknownCommand(B),1,Z)}}async function nK0(A){return{...A,getThreadEnvironment:EW,getEnvironmentData:(Q,B)=>tX({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new EL(A.fileSystem),generateThreadTitle:WF4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>IQ(A.configService),pluginService:A.pluginService}}function V8A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:EW,getEnvironmentData:(Q,B)=>tX({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var cK0=s0.file(X03.homedir()),z91=process.env.XDG_CONFIG_HOME?s0.file(process.env.XDG_CONFIG_HOME):X1.joinPath(cK0,".config");function R03(A){return dR4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(nF0())aF0();else GZ0(Q);let B=Pj(),$=oo();if((!B||$||_x())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(SD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(SD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(Pj()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function p8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;oe1("0.0.1778171486-g3e6a89");let Y=x30({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(s0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:cK0,userConfigDir:z91});ts4(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let F=!1;{let g=await A.secrets.get("apiKey",A.ampURL);if(F=Boolean(g),j.info("API key lookup before login",{found:Boolean(g),ampURL:A.ampURL,deferAuth:$}),!g)if($)j.info("No API key found, continuing startup with deferred auth");else{X5.write(`No API key found. Starting login flow...
|
|
7650
7650
|
`);let i=await P03(A),d=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:i,storedKeyPresent:Boolean(d),ampURL:A.ampURL}),!i)await IW(),process.exit(1);F=!0}}{let g=await Y.getLatest(),i=g.settings.url,d=g.secrets.isSet?.[i];j.info("Config secrets state after login",{configURL:i,apiKeySet:d?.apiKey??!1})}let X=y1(IQ(Y).pipe(P5(q03))),D=$?"pending":await X;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:bA(D),isError:SX(D),errorMessage:SX(D)?D.error.message:void 0});let G=X.then((g)=>N03(g));G.catch(()=>{return});let U=!Q.takeMeBack&&bA(D)&&iK0(D.features,IB.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=uR4({configService:Y}),W=new Map,z=()=>W.clear(),H=new uf0(Y,A.settings.getWorkspaceRootPath()),q=lJ4({configService:Y,filesystem:O3}),N=f74({configService:Y,trustStore:H,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(g,i,d)=>{let Q0=`${g}:${i}`,H0=W.get(Q0);if(H0)return j.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:i}),H0;j.debug("Creating OAuth provider for server",{serverName:g,serverUrl:i});let a=(async()=>{let I0=new uM(A.secrets),F0=await I0.getClientInfo(g,i),_0=d?.scopes??F0?.scopes,B0=Wf4();j.info("OAuth headless mode check",{useHeadless:B0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:X5.isTTY});let K0;if(B0)K0=A.executeMode?Ef4():Kf4(g);let o=new ok0({storage:I0,serverName:g,serverUrl:i,clientId:d?.clientId??F0?.clientId,clientSecret:d?.clientSecret??F0?.clientSecret,authUrl:d?.authUrl??F0?.authUrl,tokenUrl:d?.tokenUrl??F0?.tokenUrl,scopes:_0,headlessAuthHandler:K0});return j.debug("OAuth provider created",{serverName:g,serverUrl:i,hasManualClientId:!!(d?.clientId??F0?.clientId),willUseDCR:!(d?.clientId??F0?.clientId),scopes:_0,headlessMode:B0,executeMode:A.executeMode}),o})();return W.set(Q0,a),a}}),I=un0({configService:Y,filesystem:O3,spawn:TY0}),w=Q.headless?ys4():void 0,C=w??new KV0({configService:Y}),O=C instanceof KV0?C:void 0;if(O)O.pluginExecutorKind="local";let R=Bb0({configService:Y,fileSystem:O3,platform:C,loadGlobalPlugins:es0(Y),pluginFilter:U}),S=yQ4(R),T=[N,I,S],f;if(J)f=new Map;else if(A.executeMode){let g=await EO4({toolService:K,providers:T,initialTimeout:15000});f=g.registrations;for(let[i,d]of g.initErrors)j.warn(`${i} provider initialization slow or failed:`,d)}else f=hn0({toolService:K,providers:T});if(Q.jetbrains)jM("JetBrains");else if(Q.ide&&ef4())jM("VS Code");else if(Q.ide&&Ab4())jM("Neovim");else if(Q.ide){let g=await V03();if(g){let i=l30(g.ideName);if(i)jM(i)}}if(A.executeMode)re1(!0);let h,x=u3.status.pipe(C1((g)=>Boolean(g.connected&&g.authenticated&&g.ideName&&n04(g.ideName))),P4()).subscribe((g)=>{if(g){if(!h)h=K.registerTool(KO4)}else h?.dispose(),h=void 0}),k;if(!A.executeMode){let g=await A.settings.get("fuzzy.alwaysIncludePaths")??[];k=new cF0(process.cwd(),{alwaysIncludePaths:g},!0)}else k=new class extends cF0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let b=new Qg0(Ll(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let c=new F51,l={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:H,threadService:b,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:k,fileSystem:O3,terminal:c,pluginService:R,pluginPlatform:O,headlessPluginPlatform:w,serverStatus:D,serverStatusPromise:X,viewerUserIDPromise:G,hasAPIKeyAtStartup:F};return{...l,async asyncDispose(){if(l.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await l.mcpService.waitForAuthentication();for(let g of f.values())g.dispose();await l.mcpService.dispose(),z(),await l.threadService.asyncDispose(),l.configService.unsubscribe(),E(),l.fuzzyServer.dispose(),l.settingsStorage[Symbol.dispose](),x.unsubscribe(),h?.dispose(),await l.pluginService.dispose()}}}async function P03(A){if(!A.executeMode){if(!await vX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return X5.write(`Login cancelled. Run the command again to retry.
|
|
7651
7651
|
`),!1}return await U8A(A)}async function U8A(A){let Q=D8A(32).toString("hex"),B=await ux(A.ampURL,Q),$=new AbortController;try{await PX(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await ux(A.ampURL,Q,!1);X5.write(`If your browser does not open automatically, visit:
|
|
7652
7652
|
|
|
@@ -7654,7 +7654,7 @@ ${o0.blue.bold(J)}
|
|
|
7654
7654
|
|
|
7655
7655
|
`);try{return await Hh4(A.ampURL,Q,A.secrets,$),X5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),_J.write(`
|
|
7656
7656
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
7657
|
-
`),!1}}async function _03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new J4("No Amp API key found. Run `amp login` first.",1);let J=Y03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function T03(A){let Q=new yN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)Zj(),process.exit(0);let H=z.originalError??z;Iv4(H)}),Mg4(Q,{version:"0.0.
|
|
7657
|
+
`),!1}}async function _03(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new J4("No Amp API key found. Run `amp login` first.",1);let J=Y03("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(F)=>Y(F??1))})}function T03(A){let Q=new yN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((z)=>{if(z.code==="commander.help"||z.code==="commander.version"||z.exitCode===0)Zj(),process.exit(0);let H=z.originalError??z;Iv4(H)}),Mg4(Q,{version:"0.0.1778171486-g3e6a89",buildTimestamp:"2026-05-07T16:34:46.143Z",buildType:"'release'"}),Q.addHelpText("after",rf4()),Q.configureHelp({formatHelp:sf4}),Q.command("logout").description("Log out by removing stored API key").action(async(z,H)=>{let q=H.optsWithGlobals(),N=await p5(q);await h03(N)}),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(z,H)=>{let q=H.optsWithGlobals(),N=await p5(q);await u03(N,await Vt0(q,N.settings))}),Hv4(Q,p5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let H=z.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=z.filter((w)=>w!==H).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=H.optsWithGlobals(),I=await p5(N);await _03(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});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(z,H,q)=>{let N=q.optsWithGlobals(),I=await p5(N);await Yf4(z??"get",I.ampURL,I.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(z,H)=>{let q=H.optsWithGlobals(),N=await p5(q);await Zf4(N.ampURL,N.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(z)=>{await zu4({raw:z.raw===!0}),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(`
|
|
7658
7658
|
`)).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(z,H,q)=>{if(z&&H.apply)throw new J4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=H.apply??z;if(!N||N.trim().length===0)X5.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.
|
|
7659
7659
|
|
|
7660
7660
|
`),q.outputHelp(),process.exit(0);let I=N2(N)??VJ(N),w=q.optsWithGlobals(),C=await p5(w);f2(q,w);let O=await p8(C,w),R=!1;try{if(H.checkout&&H.skipCheckout)throw new J4("Choose either --checkout or --skip-checkout, not both.",1);if(SX(O.serverStatus))throw ft(O.serverStatus,C.ampURL);let S=bA(O.serverStatus)?O.serverStatus.features:void 0;if(!iK0(S,IB.V2))throw new J4("live-sync is not enabled for your user",1);await Zh4({ampURL:C.ampURL,threadId:I,configService:O.configService,threadService:O.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof H.apply==="string",checkoutMode:H.checkout?"always":H.skipCheckout?"never":"prompt",promptForYesNo:vX0}),R=!0}finally{if(await O.asyncDispose(),R)process.exit(0)}});let J=async(z,H,q)=>{x30({storage:H.settings,secretStorage:H.secrets,workspaceRoot:m0.of(s0.file(process.cwd())),defaultAmpURL:H.ampURL,homeDir:cK0,userConfigDir:z91});let N={...H,executeMode:!1};await lK0(N,{...z,openThreadSwitcher:!0},q,A)},Y=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(z,H)=>{let q=H.optsWithGlobals(),N=await p5(q);await X8A(q,N,H)});Y.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(z,H)=>{let q=H.optsWithGlobals(),N=await p5(q);await r03(q,N,H)}),Y.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(z,H,q)=>{let N=q.optsWithGlobals(),I=await p5(N);if(H.pick)_J.write(`${o0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -7687,8 +7687,8 @@ ${C}
|
|
|
7687
7687
|
`))}),H.args.length>0)j03(N,H);await lK0(N,q,H,A)}),kb4(Q),Q}async function Tb(A,Q){await EJ((B)=>hX0(B,A,Q))}async function Z8A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([YA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.getChild("fetchAndStartThread").info(`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 J4(`Cannot resume thread created by another user.
|
|
7688
7688
|
|
|
7689
7689
|
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 K8A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await WV0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await WV0()).trimEnd(),stdinInput:null}}function E8A(A,Q,B){if(A.streamJson&&!Q)throw new J4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new J4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new J4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new J4("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 J4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new J4("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 J4("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 J4("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"
|
|
7690
|
-
Or pipe via stdin: echo "your message" | amp --execute`)}function S03(A,Q){if(IA4([i50.parse({tool:"*",action:"allow"})]),GA4({bypass:!0}),fs4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:B51})}async function lK0(A,Q,B,$){if(Q.headless)return k03(A,Q,B);let J=await p8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=bA(Y)&&iK0(Y.features,IB.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&!F)throw await J.asyncDispose(),new J4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await C03();return S03(Z,J.pluginService),v03(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&HQ(Q.threadId)){let D=await YA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new J4(`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 y03(A,Q,B,$,{dependencies:J})}}async function k03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gr0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};f2(B,Q);let J=process.hrtime.bigint(),Y=await p8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(SX(Z))throw ft(Z,A.ampURL);let F=bA(Z)?Z:null,X=F?.user.email;await W91(B,Q,Z);let D=kR(Z),G=$r(Q,D);if(G instanceof Error)f5(G.message);if(F&&!QS(Q.mode,X))throw new J4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!O7(X)))throw new J4("Headless executor mode is only available for Amp employees",1);VF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new J4("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&&!HQ(K))throw new J4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await a03({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new J4("Failed to resolve headless thread ID",1);let z=await Nf4(W);if(z.status==="already-running")await Y.asyncDispose(),await IW(),process.exit(0);try{await Gf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.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 z.release(),await Y.asyncDispose()}await IW(),process.exit(0)}async function v03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await K8A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;E8A({...Q,streamJson:F},A.executeMode,Y),f2(B,Q),Gv4(),VF0();let X=Q.threadId&&HQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?N2(Q.observe)??VJ(Q.observe):void 0,G=await $.serverStatusPromise;if(SX(G))throw ft(G,A.ampURL);let V=await $.secretStorage.get("apiKey",A.ampURL);if(!V)throw new J4("API key required. Please run `amp login` first.",1);let U=bA(G)&&O7(G.user.email);if(A.executeMode){Ke0($.mcpService,A.settings);try{let K=dK0(B,Q),E=await DI(),W=X?K:yX0({agentMode:Q.mode,explicitEffort:K,sessionState:E}),z=X?void 0:xX0(await hx($.configService),{agentMode:Q.mode,explicitEffort:K,sessionState:E}),H=await bx4({apiKey:V,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:W,labels:Q.label,initialThreadID:X,initialSettings:z});if(await Tb(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await IW(),process.exit(0)}else{let K=dK0(B,Q),E=J.showNpmMigrationWelcome?"npm-migration":"intro",W=Ll($.configService),z=new ts($.fuzzyServer),H=process.cwd();await Rs4({ampURL:A.ampURL,apiKey:V,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??yF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:q})=>qx({fileSystem:$.fileSystem,workspaceRoot:H},q),completionBuilder:z,workspaceRoot:H,listThreads:()=>W.listThreads(),getThreadFromServer:(q)=>W.getThread(q),toolboxes:$.toolboxService.toolboxes,isInternalUser:U,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:D??X,initialUserInput:Y||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,neoWelcomeVariant:E,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:K}),process.exit(0)}}async function y03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(F0,_0)=>{let B0=Number(process.hrtime.bigint()-_0)/1e6,K0=gr0();j.info("Startup phase",{phase:F0,phaseMs:Math.round(B0),sinceMainMs:K0===null?void 0:Math.round(K0)})},{userInput:F,stdinInput:X}=await K8A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;E8A({...Q,streamJson:D},A.executeMode,F),f2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await p8(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&&SX(E))throw ft(E,A.ampURL);let W=bA(E)?E:null,z=W?.user.email,H=!!(z&&O7(z));if(H)VF0();if(!K)await W91(B,Q,E);let q=kR(E),N=q?.features??[],I=q?.team??null,w=$r(Q,q);if(w instanceof Error)f5(w.message);if(W&&!QS(Q.mode,z))throw new J4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&HQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await nK0(V);Z("runMainThread:createWorkerDeps",G);let R=A.executeMode?void 0:async(F0)=>Tb(F0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(F0)=>{let _0=K?await V.serverStatusPromise:E,B0=await UF0(A.settings,process.cwd(),kR(_0),w);if(B0 instanceof Error)f5(B0.message);return m81(O,{threadMeta:B0?nY(B0):void 0,agentMode:F0??Q.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(F0,_0)=>{if(_0?.nonBlockingOwnershipCheck){Z8A(F0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof J4){if(_0.onOwnershipError){_0.onOwnershipError(B0,F0);return}wW(B0,F0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await Z8A(F0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof J4)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:R,handleError:wW},T=async()=>{try{return kAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(F0){if(F0 instanceof J4)throw F0;throw await wW(F0,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 F0=await V.configService.getLatest(),_0=ym(F0),B0=await YA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(_0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(F0){j.error("Failed to fetch free tier status:",F0);return}})(),x=!A.executeMode?new U51:null,k,b=null;if(x)k=x,b=(async()=>{let F0=K?await V.serverStatusPromise:V.serverStatus;if(SX(F0))throw ft(F0,A.ampURL);await W91(B,Q,F0);let _0=process.hrtime.bigint(),B0=await T();if(Z("runMainThread:createThreadPool",_0),x.attach(B0),F){let K0=await y1(B0.threadHandles$);if(!K0)throw new J4("No active thread is available yet.",1);await K0.sendMessage({content:[{type:"text",text:F}]})}})(),b.catch(async(F0)=>{let _0=F0 instanceof Error?F0:Error(String(F0));x.setInitError(_0),await wW(F0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let l=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),R03({configService:V.configService,threadService:V.threadService,config:l,useNotificationsForService:c,threadViewStates$:()=>k.threadHandles$.pipe(u4((F0)=>{if(!F0)return m0.of({});return P6(F0.thread$,F0.threadViewState$).pipe(C1(([_0,B0])=>({[_0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){Ke0(V.mcpService,A.settings);let F0=dK0(B,Q),_0=await DI(),B0=C?F0:yX0({agentMode:Q.mode,explicitEffort:F0,sessionState:_0}),K0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},o=await mv4({threadPool:k,...K0});if(await Tb(o,"execute"),Q.archive)await V.threadService.archive(o,!0);await V.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await i30();let F0=await yX({jetbrainsOnly:Q.jetbrains});if(F0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let _0=F0[0];if(_0)u3.selectConfig(_0)}else i=!0}G=process.hrtime.bigint();let d=vt0("0.0.1778158028-g39bfa2",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let Q0=new Ee0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let F0=await y1(k.threadHandles$);if(!F0)throw new J4("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let H0=await DI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",H0);let a=dK0(B,Q),I0={...H0,launchCount:H0.launchCount+1,lastReasoningEffortByMode:a?{...H0.lastReasoningEffortByMode,[Q.mode]:a}:H0.lastReasoningEffortByMode};EJ((F0)=>({...F0,launchCount:F0.launchCount+1}));try{if(G=process.hrtime.bigint(),await it4({history:new Jo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:YA,threadPool:k,createSystemPromptDeps:async()=>V8A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:Q0,updateService:d,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:G03,logFile:{path:$},sessionState:I0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-07T12:50:51.788Z"},(F0)=>new N51({...F0,threadPool:F0.threadPool},(_0)=>new h81({..._0,threadState:_0.threadState}))),Z("runMainThread:mountApp-returned",G),b)await b}finally{await k.dispose().catch((F0)=>{j.error("Failed to dispose thread pool during shutdown",F0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function p5(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)_J.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7691
|
-
`);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 m74({get:async(F)=>{if(F!==bd)return;try{let X=await G8A(E91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==bd)return;await Z03(xt.dirname(E91),{recursive:!0}),await F03(E91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:z90()});se1($);let J=await kf4({...A,workspaceTrust:{current:!0,changes:iT0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Rh4(A.mcpConfig);J=Ph4(J,F)}let Y=xt.dirname(J.getSettingsFilePath());pR4(jx,Y),J=_s1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=j7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!RH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:as4(await Vt0(A,J))}}function x03(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function f03(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=xt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?D03:la));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function b03(){Jv4();let A=x03(process.argv),Q=f03(process.argv,A),B=Vv4(Q);fZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(U03(j),j.info("Starting Amp CLI.",{version:"0.0.
|
|
7690
|
+
Or pipe via stdin: echo "your message" | amp --execute`)}function S03(A,Q){if(IA4([i50.parse({tool:"*",action:"allow"})]),GA4({bypass:!0}),fs4(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:B51})}async function lK0(A,Q,B,$){if(Q.headless)return k03(A,Q,B);let J=await p8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),F=bA(Y)&&iK0(Y.features,IB.THREAD_ACTORS_TUI),X=F&&!Q.takeMeBack;if(Q.showWelcome&&!F)throw await J.asyncDispose(),new J4("--show-welcome is only available with the new Amp CLI feature flag",1);if(X){let D=!A.executeMode&&await C03();return S03(Z,J.pluginService),v03(A,Q,B,J,{showNpmMigrationWelcome:D})}else{if(Q.threadId&&HQ(Q.threadId)){let D=await YA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new J4(`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 y03(A,Q,B,$,{dependencies:J})}}async function k03(A,Q,B){let $=(H,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=gr0();j.info("Startup phase",{phase:H,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};f2(B,Q);let J=process.hrtime.bigint(),Y=await p8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(SX(Z))throw ft(Z,A.ampURL);let F=bA(Z)?Z:null,X=F?.user.email;await W91(B,Q,Z);let D=kR(Z),G=$r(Q,D);if(G instanceof Error)f5(G.message);if(F&&!QS(Q.mode,X))throw new J4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!X||!O7(X)))throw new J4("Headless executor mode is only available for Amp employees",1);VF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new J4("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&&!HQ(K))throw new J4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await a03({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new J4("Failed to resolve headless thread ID",1);let z=await Nf4(W);if(z.status==="already-running")await Y.asyncDispose(),await IW(),process.exit(0);try{await Gf4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.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 z.release(),await Y.asyncDispose()}await IW(),process.exit(0)}async function v03(A,Q,B,$,J){let{userInput:Y,stdinInput:Z}=await K8A(Q),F=!!Q.streamJson||!!Q.streamJsonThinking;E8A({...Q,streamJson:F},A.executeMode,Y),f2(B,Q),Gv4(),VF0();let X=Q.threadId&&HQ(Q.threadId)?Q.threadId:void 0,D=Q.observe?N2(Q.observe)??VJ(Q.observe):void 0,G=await $.serverStatusPromise;if(SX(G))throw ft(G,A.ampURL);let V=await $.secretStorage.get("apiKey",A.ampURL);if(!V)throw new J4("API key required. Please run `amp login` first.",1);let U=bA(G)&&O7(G.user.email);if(A.executeMode){Ke0($.mcpService,A.settings);try{let K=dK0(B,Q),E=await DI(),W=X?K:yX0({agentMode:Q.mode,explicitEffort:K,sessionState:E}),z=X?void 0:xX0(await hx($.configService),{agentMode:Q.mode,explicitEffort:K,sessionState:E}),H=await bx4({apiKey:V,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:Y,stdinInput:Z,stats:!!Q.stats,streamJson:F,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:W,labels:Q.label,initialThreadID:X,initialSettings:z});if(await Tb(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await IW(),process.exit(0)}else{let K=dK0(B,Q),E=J.showNpmMigrationWelcome?"npm-migration":"intro",W=Ll($.configService),z=new ts($.fuzzyServer),H=process.cwd();await Rs4({ampURL:A.ampURL,apiKey:V,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??yF(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:q})=>qx({fileSystem:$.fileSystem,workspaceRoot:H},q),completionBuilder:z,workspaceRoot:H,listThreads:()=>W.listThreads(),getThreadFromServer:(q)=>W.getThread(q),toolboxes:$.toolboxService.toolboxes,isInternalUser:U,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:D??X,initialUserInput:Y||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!D,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,neoWelcomeVariant:E,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:K}),process.exit(0)}}async function y03(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(F0,_0)=>{let B0=Number(process.hrtime.bigint()-_0)/1e6,K0=gr0();j.info("Startup phase",{phase:F0,phaseMs:Math.round(B0),sinceMainMs:K0===null?void 0:Math.round(K0)})},{userInput:F,stdinInput:X}=await K8A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;E8A({...Q,streamJson:D},A.executeMode,F),f2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await p8(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&&SX(E))throw ft(E,A.ampURL);let W=bA(E)?E:null,z=W?.user.email,H=!!(z&&O7(z));if(H)VF0();if(!K)await W91(B,Q,E);let q=kR(E),N=q?.features??[],I=q?.team??null,w=$r(Q,q);if(w instanceof Error)f5(w.message);if(W&&!QS(Q.mode,z))throw new J4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&HQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await nK0(V);Z("runMainThread:createWorkerDeps",G);let R=A.executeMode?void 0:async(F0)=>Tb(F0,"interactive"),S={threadService:V.threadService,workerDeps:O,createThread:async(F0)=>{let _0=K?await V.serverStatusPromise:E,B0=await UF0(A.settings,process.cwd(),kR(_0),w);if(B0 instanceof Error)f5(B0.message);return m81(O,{threadMeta:B0?nY(B0):void 0,agentMode:F0??Q.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(F0,_0)=>{if(_0?.nonBlockingOwnershipCheck){Z8A(F0,V.configService,V.viewerUserIDPromise).catch((B0)=>{if(B0 instanceof J4){if(_0.onOwnershipError){_0.onOwnershipError(B0,F0);return}wW(B0,F0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})});return}try{await Z8A(F0,V.configService,V.viewerUserIDPromise)}catch(B0){if(B0 instanceof J4)throw B0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:B0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:R,handleError:wW},T=async()=>{try{return kAA(S,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(F0){if(F0 instanceof J4)throw F0;throw await wW(F0,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 F0=await V.configService.getLatest(),_0=ym(F0),B0=await YA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(_0)});if(B0.ok)return j.info("User free tier status:",B0),B0.result;return}catch(F0){j.error("Failed to fetch free tier status:",F0);return}})(),x=!A.executeMode?new U51:null,k,b=null;if(x)k=x,b=(async()=>{let F0=K?await V.serverStatusPromise:V.serverStatus;if(SX(F0))throw ft(F0,A.ampURL);await W91(B,Q,F0);let _0=process.hrtime.bigint(),B0=await T();if(Z("runMainThread:createThreadPool",_0),x.attach(B0),F){let K0=await y1(B0.threadHandles$);if(!K0)throw new J4("No active thread is available yet.",1);await K0.sendMessage({content:[{type:"text",text:F}]})}})(),b.catch(async(F0)=>{let _0=F0 instanceof Error?F0:Error(String(F0));x.setInitError(_0),await wW(F0,Q.threadId)});else G=process.hrtime.bigint(),k=await T(),Z("runMainThread:createThreadPool",G);let c=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let l=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),R03({configService:V.configService,threadService:V.threadService,config:l,useNotificationsForService:c,threadViewStates$:()=>k.threadHandles$.pipe(u4((F0)=>{if(!F0)return m0.of({});return P6(F0.thread$,F0.threadViewState$).pipe(C1(([_0,B0])=>({[_0.id]:B0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){Ke0(V.mcpService,A.settings);let F0=dK0(B,Q),_0=await DI(),B0=C?F0:yX0({agentMode:Q.mode,explicitEffort:F0,sessionState:_0}),K0={userInput:F,stdinInput:X,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:H,agentMode:Q.mode,reasoningEffort:B0,labels:Q.label},o=await mv4({threadPool:k,...K0});if(await Tb(o,"execute"),Q.archive)await V.threadService.archive(o,!0);await V.asyncDispose(),process.exit(0)}let g=!1,i=!1;if(Q.jetbrains||Q.ide){await i30();let F0=await yX({jetbrainsOnly:Q.jetbrains});if(F0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let _0=F0[0];if(_0)u3.selectConfig(_0)}else i=!0}G=process.hrtime.bigint();let d=vt0("0.0.1778171486-g3e6a89",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let Q0=new Ee0(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),F&&A.executeMode){let F0=await y1(k.threadHandles$);if(!F0)throw new J4("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:F}]})}G=process.hrtime.bigint();let H0=await DI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",H0);let a=dK0(B,Q),I0={...H0,launchCount:H0.launchCount+1,lastReasoningEffortByMode:a?{...H0.lastReasoningEffortByMode,[Q.mode]:a}:H0.lastReasoningEffortByMode};EJ((F0)=>({...F0,launchCount:F0.launchCount+1}));try{if(G=process.hrtime.bigint(),await it4({history:new Jo,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:YA,threadPool:k,createSystemPromptDeps:async()=>V8A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:Q0,updateService:d,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:g,showIdePickerHint:i,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:G03,logFile:{path:$},sessionState:I0,freeTierStatusPromise:f,workspace:I??null,features:N,isInternalUser:H,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-07T16:34:46.143Z"},(F0)=>new N51({...F0,threadPool:F0.threadPool},(_0)=>new h81({..._0,threadState:_0.threadState}))),Z("runMainThread:mountApp-returned",G),b)await b}finally{await k.dispose().catch((F0)=>{j.error("Failed to dispose thread pool during shutdown",F0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function p5(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)_J.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7691
|
+
`);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 m74({get:async(F)=>{if(F!==bd)return;try{let X=await G8A(E91,"utf-8");return JSON.parse(X).installationID}catch{return}},set:async(F,X)=>{if(F!==bd)return;await Z03(xt.dirname(E91),{recursive:!0}),await F03(E91,JSON.stringify({installationID:X},null,2),{mode:384})}},{clientType:"cli",platform:z90()});se1($);let J=await kf4({...A,workspaceTrust:{current:!0,changes:iT0},getHook:process.env.AMP_URL?(F,X)=>{if(F==="url")return Promise.resolve(process.env.AMP_URL);return X()}:void 0});if(A.mcpConfig){let F=await Rh4(A.mcpConfig);J=Ph4(J,F)}let Y=xt.dirname(J.getSettingsFilePath());pR4(jx,Y),J=_s1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=j7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!RH(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:as4(await Vt0(A,J))}}function x03(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(F,X)=>X.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function f03(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=xt.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?D03:la));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function b03(){Jv4();let A=x03(process.argv),Q=f03(process.argv,A),B=Vv4(Q);fZ0("silent");let $=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(U03(j),j.info("Starting Amp CLI.",{version:"0.0.1778171486-g3e6a89",buildTimestamp:"2026-05-07T16:34:46.143Z"}),process.platform==="win32"&&zj())Nb4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new J4(Y7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await T03(B).parseAsync(process.argv)}gR4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await b03().catch(wW)});async function u03(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"),X5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7692
7692
|
`);else if(!RH(A.ampURL))X5.write(`Logging in to ${new URL(A.ampURL).hostname}
|
|
7693
7693
|
`);let $=process.env.AMP_API_KEY;if($)X5.write(`API key found in environment variable, storing...
|
|
7694
7694
|
`),await Q.set("apiKey",$,A.ampURL),X5.write(`API key successfully stored.
|