@sourcegraph/amp 0.0.1776946513-g63e052 → 0.0.1776949187-g6c0bed
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 +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4282,7 +4282,7 @@ ${RR4("\t",h??"(unknown)")}
|
|
|
4282
4282
|
`)}else if(h)process.stdout.write(h+`
|
|
4283
4283
|
`);await C()}}})})}function jR4(J){return J.filter((Z)=>Z.role==="assistant"&&Z.state.type!=="streaming").length}function IR4(J){if(J instanceof Error)if(iS(J))return"Unauthorized. Check your access token.";else if(hz(J))return"Context window limit reached.";else if(OA(J))return"Model provider overloaded. Try again in a few seconds.";else if(EA(J))return"Model stream timed out. Try again in a few seconds.";else if(lS(J))return"Insufficient credit balance.";else return J.message;if(typeof J==="object"&&J&&"message"in J&&typeof J.message==="string")return J.message;return String(J)}function RR4(J,Z){if(!Z)return Z;return J+Z.split(`
|
|
4284
4284
|
`).join(`
|
|
4285
|
-
`+J)}a0();import{randomUUID as RY3}from"node:crypto";v4();I1();class GX0 extends Error{constructor(J){super(J);this.name="ThreadClientError"}}class N9 extends GX0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}class LJ extends GX0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="ThreadClientConnectionError"}}a0();I1();D$();function CR4(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}t3();D4();vI0();D$();var J8=v.string().min(1),pw=J8.brand(),ma0=v.string().regex(/^[0-9A-Za-z]{22}$/),P$3=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),qn=v.templateLiteral(["T-",P$3]),C$3=v.enum(["fork","handoff","mention"]),_$3=v.enum(["parent","child"]),_R4=v.object({threadID:qn,type:C$3,role:_$3,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),B3=v.templateLiteral(["M-",ma0]);function FX0(){return`M-${CR4(Xh())}`}var F7=v.templateLiteral(["TU-",ma0]);var Wn=v.templateLiteral(["E-",ma0]);var T$3=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),S$3=v.union([v.literal("builtin"),v.object({toolbox:J8}).strict(),v.object({mcp:J8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:J8}).strict(),v.object({remote:J8}).strict()]),k$3=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(J8).optional()}),TR4=v.looseObject({name:J8,description:v.string(),inputSchema:T$3,source:S$3,meta:k$3.optional()}),_X9=v.object({id:J8,category:J8,title:J8,description:v.string().optional(),pluginName:J8}),zX0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),SR4=v.object({workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),kR4=v.enum(["sandbox","local-client"]),Hn=v.any().and(v.object({status:v.string()})),vR4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),_q=J8,yR4=30000,xv=hW,v$3=v.enum(["file","directory"]),y$3=v.object({mtimeMs:v.number().nonnegative().optional()}),Un=v.tuple([v.string(),v$3,y$3.nullish()]),x$3=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),dw=v.object({code:x$3,message:v.string()}),f$3=v.object({ok:v.literal(!0),entries:v.array(Un)}),u$3=v.object({ok:v.literal(!1),error:dw}),TX9=v.discriminatedUnion("ok",[f$3,u$3]),b$3=v.object({ok:v.literal(!0),contentBase64:v.string()}),h$3=v.object({ok:v.literal(!1),error:dw}),SX9=v.discriminatedUnion("ok",[b$3,h$3]),g$3=J8,pa0=v.object({key:J8,dataType:g$3,contentBase64:v.string()}),da0=pa0.extend({toolCallId:F7.optional(),updatedAt:v.string()}),ca0=v.looseObject({uri:hW,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),xR4=v.object({name:J8,description:v.string(),baseDir:hW,frontmatter:v.object({name:J8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),la0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),fR4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),fv=v.array(v.discriminatedUnion("type",[la0,fR4])),yv=v.record(v.string(),v.unknown()),uR4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),m$3=uR4.extend({complete:v.literal(!0),input:yv,normalizedInput:yv.optional()}),p$3=uR4.extend({complete:v.literal(!1),input:yv,inputIncomplete:yv,inputPartialJSON:v.object({json:v.string()}),normalizedInput:yv.optional()}),d$3=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),c$3=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:Hn,userInput:d$3.optional()}),l$3=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),i$3=v.object({type:v.literal("redacted_thinking"),data:v.string()}),n$3=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:yv}),a$3=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:Hn,hidden:v.boolean().optional()}),ia0=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:qn.optional()}),o$3=v.union([la0,fR4,c$3]),r$3=v.union([la0,l$3,i$3,m$3,p$3,n$3]),na0=v.array(o$3),aa0=v.array(r$3),s$3=v.array(a$3),ga0=v.looseObject({line:v.number().int(),column:v.number().int()}),t$3=v.looseObject({start:ga0,end:ga0}),e$3=v.looseObject({name:v.string(),repositoryURL:v.string()}),$J3=v.looseObject({currentURL:v.string(),availableProjects:v.array(e$3).optional()}),oa0=v.looseObject({currentlyVisibleFiles:v.array(hW),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:ga0.optional(),cursorLocationLine:v.string().optional(),selectionRange:t$3.optional(),aggmanContext:$J3.optional()}),oj=v.custom((J)=>typeof J==="string"&&r7(J)!==void 0),JJ3=v.object({threadId:qn,role:v.literal("user"),content:na0,agentMode:oj.optional(),meta:ia0.optional(),userState:oa0.optional(),readAt:v.string().nullable().optional(),messageId:B3,createdAt:v.string().optional()}),ra0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),ZJ3=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),QJ3=v.object({threadId:qn,role:v.literal("assistant"),content:aa0,state:ZJ3.optional(),usage:ra0.optional(),readAt:v.string().nullable().optional(),messageId:B3,createdAt:v.string().optional()}),YJ3=v.object({threadId:qn,role:v.literal("info"),content:s$3,messageId:B3,createdAt:v.string().optional()}),bR4=v.discriminatedUnion("role",[JJ3,QJ3,YJ3]),Dn=v.object({workspaceRoot:hW.optional(),workingDirectory:hW.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),git:v.object({branch:v.string().optional()}).optional(),updatedAt:v.string().optional()}),XJ3=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),KJ3=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:XJ3}),VJ3=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),hR4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(VJ3).optional(),diffHash:v.string().optional(),files:v.array(KJ3),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),qX0=v.object({id:v.string(),toolCallId:F7,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:F7.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),GJ3=v.object({type:v.literal("request"),id:J8,method:J8,params:v.unknown()}),FJ3=v.object({type:v.literal("response"),id:J8,result:v.unknown().optional(),error:v.string().optional()}),zJ3=v.object({type:v.literal("event"),event:J8,data:v.unknown(),span:v.string().optional()}),WX0=v.discriminatedUnion("type",[GJ3,FJ3,zJ3]);var qJ3=v.object({type:v.literal("executor_connect"),clientId:pw,capabilities:SR4,executorType:kR4.optional()}),WJ3=v.object({type:v.literal("client_update_thread_settings"),settings:zX0}),HJ3=v.object({type:v.literal("executor_tools_register"),tools:v.array(TR4)}),UJ3=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(J8)}),DJ3=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),BJ3=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:F7}),sa0=v.object({type:v.literal("tool_progress"),toolCallId:F7,progress:v.union([vR4,v.unknown()]).optional(),parentToolCallId:F7.optional()}),NJ3=v.object({type:v.literal("executor_tool_result"),toolCallId:F7,run:Hn}),wJ3=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:J8,files:v.array(ca0),isLast:v.boolean(),userConfigDir:v.any().optional()}),LJ3=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:F7,files:v.array(ca0),isLast:v.boolean()}),OJ3=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:J8,skills:v.array(xR4),isLast:v.boolean()}),EJ3=v.object({type:v.literal("executor_rollback_ack"),editId:Wn,ok:v.boolean(),error:v.string().optional()}),MJ3=v.object({type:v.literal("executor_environment_snapshot"),environment:Dn}),AJ3=v.object({type:v.literal("executor_environment_update"),environment:Dn}),jJ3=v.object({type:v.literal("executor_artifact_upsert"),artifact:pa0,toolCallId:F7.optional()}),IJ3=v.object({type:v.literal("executor_artifact_delete"),key:J8}),RJ3=v.object({type:v.literal("executor_tool_approval_request"),approval:qX0}),PJ3=v.object({type:v.literal("executor_plugin_message"),message:WX0}),CJ3=v.object({type:v.literal("client_append_user_msg"),content:fv,userState:oa0.optional(),agentMode:oj.optional(),messageId:B3}),_J3=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:B3}),TJ3=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:B3}),SJ3=v.object({type:v.literal("client_edit_message"),messageId:B3,editId:Wn,content:fv,agentMode:oj.optional()}),kJ3=v.object({type:v.literal("client_mark_message_read"),messageId:B3}),vJ3=v.object({type:v.literal("client_mark_message_unread"),messageId:B3}),yJ3=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),xJ3=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),fJ3=v.object({endpoint:v.string().url(),keys:xJ3}),uJ3=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:fJ3,threadURL:v.string().min(1)}),bJ3=v.object({type:v.literal("client_filesystem_read_directory"),requestId:_q,uri:xv}),hJ3=v.object({type:v.literal("client_filesystem_read_file"),requestId:_q,uri:xv}),gJ3=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:_q,ok:v.boolean(),entries:v.array(Un).optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),mJ3=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:_q,ok:v.boolean(),contentBase64:v.string().optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),pJ3=v.object({type:v.literal("client_resume"),version:v.number()}),dJ3=v.object({type:v.literal("client_retry")}),cJ3=v.object({type:v.literal("client_dismiss_active_error"),seq:v.number().optional()}),lJ3=v.object({type:v.literal("client_cancel")}),iJ3=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:Hn,hidden:v.boolean().optional()}),nJ3=v.object({type:v.literal("client_tool_approval_response"),toolCallId:F7,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),aJ3=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),gR4=v.discriminatedUnion("type",[qJ3,WJ3,HJ3,UJ3,DJ3,BJ3,sa0,NJ3,wJ3,LJ3,OJ3,EJ3,MJ3,AJ3,jJ3,IJ3,RJ3,PJ3,CJ3,_J3,TJ3,SJ3,kJ3,vJ3,yJ3,uJ3,bJ3,hJ3,gJ3,mJ3,pJ3,dJ3,cJ3,lJ3,iJ3,nJ3,aJ3]);D$();var HX0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)});D$();D$();var ta0=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],bX9=new Set(ta0);var oJ3=["working","streaming","tool_use","running_tools"],rJ3=new Set(oJ3);function rj(J){if(typeof J!=="string")return!1;return rJ3.has(J)}function UX0(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}var sJ3=v.enum(ta0),tJ3=v.enum(["start","generating","tool_use","complete","error"]),eJ3=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),$Z3=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),JZ3=v.enum(["starting","running","failed"]),ZZ3=v.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),QZ3=v.enum(["pending","ready","failed"]).nullable(),YZ3=v.enum(["allocating_environment","configuring_workspace","starting_headless"]).nullable(),XZ3=v.enum(["idle","creating","recovering"]),KZ3=v.enum(["unknown","running","paused","missing"]),VZ3=v.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"]),GZ3=v.object({environmentId:v.string().nullable().optional(),stage:ZZ3.optional(),setupState:QZ3.optional(),setupPhase:YZ3.optional(),operation:XZ3.optional(),providerState:KZ3.optional(),restartAttempts:v.number().optional()}),FZ3=v.object({reasonCode:VZ3.optional(),executionEnvironment:GZ3.optional()}),zZ3=v.object({cutMessageId:B3,createdAt:v.string()}),mR4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:B3,content:fv,userState:v.any().optional(),meta:ia0.optional(),createdAt:v.string().optional()})}),qZ3=v.object({type:v.literal("agent_state"),state:sJ3,messageId:B3.optional(),agentMode:oj.optional()}),WZ3=v.object({type:v.literal("thread_settings"),settings:zX0}),HZ3=v.object({type:v.literal("error"),message:v.string(),code:v.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()}),UZ3=v.object({type:v.literal("error_set"),seq:v.number(),error:eJ3}),DZ3=v.object({type:v.literal("error_cleared"),seq:v.number()}),BZ3=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:B3.optional()}),NZ3=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),wZ3=v.object({type:v.literal("retry_started")}),LZ3=v.object({type:v.literal("retry_cancelled")}),OZ3=v.object({type:v.literal("executor_connected"),executorId:pw,registeredToolCount:v.number(),resumeBootstrap:v.boolean().optional(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),EZ3=v.object({type:v.literal("tool_lease"),toolCallId:F7,toolName:v.string(),args:v.unknown(),messageId:B3,parentToolCallId:F7.optional()}),MZ3=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:_q,uri:xv}),AZ3=v.object({type:v.literal("executor_filesystem_read_file"),requestId:_q,uri:xv}),jZ3=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:_q,ok:v.boolean(),entries:v.array(Un).optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),IZ3=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:_q,ok:v.boolean(),contentBase64:v.string().optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),RZ3=v.object({type:v.literal("tool_approval_queue"),approvals:v.array(qX0)}),PZ3=v.object({type:v.literal("executor_rollback_request"),editId:Wn,messageId:B3,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(F7)}),CZ3=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:F7,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),_Z3=v.object({type:v.literal("plugin_message"),message:WX0}),TZ3=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:F7,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),SZ3=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),kZ3=v.object({type:v.literal("delta"),messageId:B3,role:v.literal("assistant"),blocks:aa0.optional(),blockIndex:v.number().int().nonnegative().optional(),state:tJ3,usage:ra0.optional(),parentToolCallId:F7.optional()}),vZ3=v.object({type:v.literal("delta"),messageId:B3,role:v.literal("user"),blocks:na0.optional(),state:v.literal("complete"),parentToolCallId:F7.optional()}),yZ3=v.discriminatedUnion("role",[kZ3,vZ3]),xZ3=v.object({type:v.literal("queued_messages"),messages:v.array(mR4)}),fZ3=v.object({type:v.literal("queued_message_added"),message:mR4,seq:v.number()}),uZ3=v.object({type:v.literal("queued_message_removed"),queuedMessageId:B3,seq:v.number()}),bZ3=v.object({type:v.literal("message_added"),message:bR4,seq:v.number(),parentToolUseId:J8.optional()}),hZ3=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),gZ3=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:B3,content:fv,truncateToMessageId:B3,reason:v.literal("message_edit"),agentMode:oj.optional()}),mZ3=v.object({type:v.literal("observers"),count:v.number(),observers:v.array($Z3),hasExecutor:v.boolean().optional()}),pZ3=v.object({type:v.literal("executor_status"),spawnId:v.string().optional(),status:JZ3,message:v.string().optional(),executorId:v.string().optional(),details:FZ3.optional()}),dZ3=v.object({type:v.literal("environment_update"),environment:Dn}),cZ3=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(da0)}),lZ3=v.object({type:v.literal("artifact_upserted"),artifact:da0}),iZ3=v.object({type:v.literal("artifact_deleted"),key:J8}),nZ3=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),aZ3=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),oZ3=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(_R4)}),rZ3=v.object({type:v.literal("compaction_started")}),sZ3=v.object({type:v.literal("compaction_complete"),cutMessageId:B3}),tZ3=v.object({type:v.literal("compaction_records"),records:v.array(zZ3)}),DX0=v.discriminatedUnion("type",[qZ3,WZ3,HZ3,UZ3,DZ3,BZ3,NZ3,wZ3,LZ3,OZ3,EZ3,MZ3,AZ3,jZ3,IZ3,RZ3,PZ3,CZ3,_Z3,TZ3,sa0,SZ3,yZ3,xZ3,fZ3,uZ3,bZ3,hZ3,gZ3,mZ3,pZ3,dZ3,cZ3,lZ3,iZ3,nZ3,aZ3,oZ3,rZ3,sZ3,tZ3]);var pR4=HX0(gR4),eZ3=v.union([DX0,v.array(DX0)]),dR4=HX0(DX0),cR4=HX0(eZ3);D4();function lR4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let G;try{G=n1(K1.parse(V.uri))}catch{if(Y)return null;continue}let F={uri:G};if(typeof V.content==="string")F.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))F.lineCount=V.lineCount;if(typeof V.hash==="string")F.hash=V.hash;X.push(F)}return X}var iR4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function ea0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function $Q3(J){return J.replace(/\s+/g," ").trim()}function JQ3(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function ZQ3(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return ea0(JSON.stringify(J),120)}catch{return ea0(String(J),120)}}function nR4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function QQ3(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=nR4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function aR4(J){for(let Z of J){let Q=QQ3(Z);if(Q)return Q}return null}function YQ3(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||nR4(Q.path)==="type")})}function XQ3(J,Z){let Q=aR4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function oR4(J,Z,Q){let Y=JQ3(Z),X=(()=>{let z=$Q3(J);if(z.length===0)return null;return ea0(z,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let z=aR4(Y);return{failureType:"invalid_json",summary:z?`malformed JSON: ${z}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let G=V.type,F=ZQ3(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:X,issues:Y};if(YQ3(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:F,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:XQ3(G,Y),messageType:G,typePreview:F,payloadPreview:X,issues:Y}}function $o0(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}a0();I1();var KQ3=1000,VQ3=30000,GQ3=5,FQ3=30000,zQ3=15000,qQ3=1000,WQ3=200,HQ3=30000,rR4=["online","focus","pageshow","keydown","pointerdown"],sR4=["visibilitychange"];function Zo0(){return globalThis}function eR4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function tR4(){return eR4(Zo0().window)}function Jo0(){let J=Zo0().document;if(!eR4(J))return null;return J}function UQ3(){let J=Zo0().navigator;if(!J||typeof J!=="object")return null;return J}function DQ3(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}class Qo0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new P4({state:"disconnected",role:null,clientId:null});lifecycleEventSubject=new P4([]);config;threadIDSubject=new P4(null);_currentThreadID=null;get currentThreadID(){return this._currentThreadID}set currentThreadID(J){if(J!==null&&J!==this._currentThreadID)this._currentThreadID=J,this.threadIDSubject.next(J);else this._currentThreadID=J}constructor(J){this.config={threadId:J.threadId,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??KQ3,maxReconnectDelayMs:J.maxReconnectDelayMs??VQ3,maxReconnectAttempts:J.maxReconnectAttempts??GQ3,pingIntervalMs:J.pingIntervalMs??FQ3,connectTimeoutMs:J.connectTimeoutMs??zQ3},this.currentThreadID=J.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(J){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||J<=0)return Promise.resolve(!1);return new Promise((Z)=>{let Q=!1,Y=null,X=null,K=(V)=>{if(Q)return;if(Q=!0,Y)clearTimeout(Y),Y=null;X?.unsubscribe(),X=null,Z(V)};Y=setTimeout(()=>{K(!1)},J),X=this.connectionSubject.subscribe({next:(V)=>{if(V.state==="connected")K(!0)},error:()=>{K(!1)},complete:()=>{K(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=WQ3,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new N9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Z,threadId:Q}=await this.config.webSocketProvider();this.currentThreadID=Q;try{Z.binaryType="arraybuffer"}catch{}await this.waitForOpen(Z),this.ws=Z,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Z),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J){if(this.ws=null,this.intentionallyClosedSockets.add(J),J.readyState===WebSocket.OPEN)J.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(J){let Z=this.ws;if(!Z)return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${J}`),this.reconnectCause={type:"error",at:Date.now(),error:J},Z.readyState===WebSocket.OPEN)Z.close(4000,J)}async disconnectAndWait(J){let Z=this.ws;if(!Z||Z.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let Q=this.waitForSocketClose(Z,J?.waitForCloseTimeoutMs??qQ3);return this.disconnect(),Q}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new N9("WebSocket is not connected");this.ws?.send(J),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}waitForSocketClose(J,Z){return new Promise((Q)=>{let Y=!1,X=null,K=(G)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);J.removeEventListener("close",V),Q(G)},V=(G)=>{let F=G;K({status:F.code===1000?"server_acknowledged":"timeout",...typeof F.code==="number"?{closeCode:F.code}:{},...typeof F.reason==="string"?{closeReason:F.reason}:{}})};if(X=setTimeout(()=>{K({status:"timeout"})},Z),J.addEventListener("close",V),J.readyState===WebSocket.CLOSED)K({status:"timeout"})})}updateConnectionState(J){let Z={...this.connectionInfo};if(J==="disconnected"||J==="reconnecting"){let Y={state:J,role:null,clientId:null};if(this.reconnectCause)Y.reconnectCause=this.reconnectCause;this.connectionInfo=Y}else if(this.connectionInfo.state=J,J==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let Q={...this.connectionInfo};this.connectionSubject.next(Q),S.info("[thread-client] Transport connection state changed",{previousState:Z.state,nextState:Q.state,previousRole:Z.role,nextRole:Q.role,clientId:Q.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${DQ3(this.reconnectCause)}`)}onRawMessage(J){}onMaxReconnectExceeded(J){}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=setTimeout(()=>{X(),this.updateConnectionState("disconnected");try{if(J.readyState===WebSocket.CONNECTING)J.close()}catch{}Q(new N9(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),X=()=>{clearTimeout(Y),J.removeEventListener("open",K),J.removeEventListener("error",V),J.removeEventListener("close",G)},K=()=>{X(),Z()},V=(F)=>{X(),this.updateConnectionState("disconnected");let z="message"in F?F.message:("error"in F)&&F.error instanceof Error?F.error.message:F.type;Q(new N9(`WebSocket connection failed: ${z}`))},G=(F)=>{X(),this.updateConnectionState("disconnected"),Q(new N9(`WebSocket closed during connect: code=${F.code} reason=${F.reason||"none"}`))};if(J.addEventListener("open",K),J.addEventListener("error",V),J.addEventListener("close",G),J.readyState===WebSocket.OPEN)return K();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return G({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now(),this.startPingIntervalOnce();return}this.startPingIntervalOnce(),this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.startPingIntervalOnce(),this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)})}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(S.info("[thread-client] Transport socket close observed",{code:Z,reason:Q||void 0,intentional:Y,isCurrentSocket:J===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,threadId:this.currentThreadID,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};this.reconnectCause=K,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==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(J){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(!J?.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 Z=J?.immediate?0:this.getReconnectDelayMs();S.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Z),immediate:J?.immediate===!0,bypassActivityGate:J?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,threadId:this.currentThreadID,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=tR4(),Z=Jo0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=UQ3();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Jo0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=tR4(),Z=Jo0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of rR4)J?.addEventListener(Y,Q);for(let Y of sR4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of rR4)J?.removeEventListener(Y,Q);for(let Y of sR4)Z?.removeEventListener(Y,Q)}}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},HQ3)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},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}}D$();var $P4="dtw-parse-error",KK9=v.object({kind:v.literal($P4),failureType:v.enum(iR4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),VK9=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function BQ3(J){return{kind:$P4,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function NQ3(J){let Z=BQ3(J);return JSON.stringify(Z)}function JP4(J,Z){let Q=oR4(J,Z);return NQ3({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}var wQ3=3000,LQ3=30000,OQ3=5,EQ3="T-00000000-0000-0000-0000-000000000000";function ZP4(J){if(J instanceof LJ)return J;if(J instanceof Error){let Z=J.message||"Unknown thread-client connection error";return new LJ(Z,J)}if(typeof J==="string"&&J.length>0)return new LJ(J,J);return new LJ("Unknown thread-client connection error",J)}function MQ3(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}function Xo0(J,Z){return{...J,pendingOptimisticUserMessages:Z}}function QP4(){return{latestAgentLoopState:null,pendingOptimisticUserMessages:new Map}}function AQ3(J,Z){if(J.latestAgentLoopState===Z)return J;return{...J,latestAgentLoopState:Z}}function jQ3(J){if(J.latestAgentLoopState===null||J.latestAgentLoopState==="idle")return"message_added";return"queued_message_added"}function IQ3(J,Z,Q){if(Z==="message_added")return{type:"message_added",message:{type:"message_added",message:{role:"user",messageId:J.messageId,content:J.content,agentMode:J.agentMode,threadId:Q??EQ3},seq:0}};return{type:"queued_message_added",message:{type:"queued_message_added",message:{interrupt:!1,queuedMessage:{role:"user",messageId:J.messageId,content:J.content,userState:J.userState}},seq:0}}}function RQ3(J,Z,Q){let Y=new Map(J.pendingOptimisticUserMessages);return Y.set(Z,Q),Xo0(J,Y)}function Yo0(J,Z){if(!J.pendingOptimisticUserMessages.has(Z))return J;let Q=new Map(J.pendingOptimisticUserMessages);return Q.delete(Z),Xo0(J,Q)}function PQ3(J,Z){let Q=J.pendingOptimisticUserMessages.get(Z);if(!Q)return{state:J,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:null};let Y=Yo0(J,Z);if(Q==="message_added")return{state:Y,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:null};return{state:Y,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:{type:"queued_message_removed",queuedMessageId:Z,seq:0}}}function YP4(J,Z){let Q=J.pendingOptimisticUserMessages.get(Z);if(Q==="queued_message_added")return{state:J,suppressQueuedMessageAdded:!0};if(Q!=="message_added")return{state:J,suppressQueuedMessageAdded:!1};let Y=new Map(J.pendingOptimisticUserMessages);return Y.set(Z,"queued_message_added"),{state:Xo0(J,Y),suppressQueuedMessageAdded:!1}}function CQ3(J,Z){let Q=J;for(let Y of Z)Q=YP4(Q,Y).state;return Q}function _Q3(J,Z){let Q=new Set(Z.map((Y)=>Y.queuedMessage.messageId));for(let[Y,X]of J.pendingOptimisticUserMessages){if(X!=="queued_message_added")continue;if(!Q.has(Y))return!0}return!1}function TQ3(J,Z,Q){let Y=jQ3(J);return{state:RQ3(J,Z.messageId,Y),event:IQ3(Z,Y,Q)}}function SQ3(J){return{type:"error",message:`Failed to send user message: ${J}`,code:"MESSAGE_ERROR"}}class Tq extends Qo0{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outboundUserMessages=[];pendingCancelAgentLoop=!1;pendingDismissActiveError=null;optimisticReconciliationState=QP4();fileSystemRequestCounter=0;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=$o0(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new P4(null);threadIDSubscription;constructor(J){super(J.transport);if(this.threadHistoryLoader=J.threadHistoryLoader,this.threadIDSubscription=this.threadIDSubject.subscribe((Z)=>{if(Z!==null)this.dispatchObserverCallbacks((Q)=>{Q.onThreadId?.(Z)})}),J.observerCallbacks)this.setObserverCallbacks(J.observerCallbacks);if(J.executorCallbacks)this.setExecutorCallbacks(J.executorCallbacks)}setObserverCallbacks(J){if(this.observerCallbacks&&this.observerCallbacks!==J)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===J)return;if(this.observerCallbacks=J,this.pendingObserverDispatches.length===0)return;for(let Z of this.pendingObserverDispatches)Z(J);this.pendingObserverDispatches.length=0}setExecutorCallbacks(J){if(this.executorCallbacks&&this.executorCallbacks!==J)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===J)return;if(this.executorCallbacks=J,this.pendingExecutorDispatches.length===0)return;for(let Z of this.pendingExecutorDispatches)Z(J);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(J){throw ZP4(J)}}async ensureConnected(J){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(J);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(J){let Z=J?.baseDelayMs??wQ3,Q=J?.maxDelayMs??LQ3,Y=J?.maxAttempts??OQ3;if(J?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let X=0;X<Y;X++){try{await this.connect()}catch(F){let z=ZP4(F);if(this.getConnectionInfo().state!=="reconnecting")throw z;J?.onRetryableConnectError?.(z)}let K=J?.waitForConnectedTimeoutMs??Math.min(Z*2**X,Q);if(await this.waitForConnected(K))return!0;let G=X+1<Y?Math.min(Z*2**(X+1),Q):null;J?.onAttemptTimeout?.({attempt:X+1,maxAttempts:Y,nextDelayMs:G})}return!1}async loadThreadHistory(J){let Z=await this.threadHistoryLoader(J);if(!Z)return null;let Q=Z.title;if(Q!==void 0)this.dispatchObserverCallbacks((Y)=>{Y.onThreadTitle?.({type:"thread_title",title:Q})});for(let[Y,X]of Z.messages.entries())this.dispatchObserverCallbacks((K)=>{K.onMessageAdded?.({type:"message_added",message:X,seq:Y})});return Z}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??FX0(),X={type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState},K=TQ3(this.optimisticReconciliationState,X,this.getThreadId());if(this.optimisticReconciliationState=K.state,this.emitOptimisticUserMessage(K.event),this.trySendMessage(X))return Y;return this.outboundUserMessages.push(X),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J}),this.resumeCursor.reset(J)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(J){let Z=J===void 0?{}:{seq:J};if(!this.hasOpenSocket()){this.pendingDismissActiveError=Z;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Z})}cancelAgentLoop(){if(!this.hasOpenSocket()){this.pendingCancelAgentLoop=!0;return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}executorHandshake(J,Z,Q){if(this.disposed)throw new N9("Transport is disposed");if(!this.hasOpenSocket())throw new N9("WebSocket is not connected. Call connect() first.");let Y=performance.now(),X=60000,K={clientId:J,threadId:this.getThreadId(),executorType:Q?.executorType,timeoutMs:X};return S.info("[thread-client] Starting executor handshake",{...K,connectionState:this.getConnectionInfo().state}),new Promise((V,G)=>{let F=!1,z=null,q=null,W=()=>Math.round(performance.now()-Y),H=(N,w,L)=>{let O=this.getConnectionInfo();S.error(N,{...K,durationMs:W(),connectionState:O.state,role:O.role,reconnectCauseType:O.reconnectCause?.type,reconnectCode:O.reconnectCause?.code,reconnectReason:O.reconnectCause?.reason,error:w,...L})},U=(N)=>{S.info("[thread-client] Executor handshake completed",{...K,durationMs:W(),executorId:N.executorId,registeredToolCount:N.registeredToolCount,resumeBootstrap:N.resumeBootstrap}),B(()=>V(N))},D=(N)=>{let w=Error(N.message);H("[thread-client] Executor handshake rejected by server",w,{code:N.code}),B(()=>G(w))},B=(N)=>{if(F)return;if(F=!0,z)clearTimeout(z),z=null;this.executorConnectedListeners.delete(U),this.executorErrorListeners.delete(D),q?.unsubscribe(),N()};this.executorConnectedListeners.add(U),this.executorErrorListeners.add(D),q=this.connectionChanges().subscribe({next:(N)=>{if(N.state==="connected")return;let w=new N9(N.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");H("[thread-client] Executor handshake interrupted",w),B(()=>G(w))}}),this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),z=setTimeout(()=>{let N=Error("Executor connect timeout");H("[thread-client] Executor handshake timed out",N),B(()=>G(N))},X)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=UX0(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendClientUpdateThreadSettings(J){if(!this.hasOpenSocket()){this.pendingThreadSettings=J;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:J})}catch(Z){if(!this.hasOpenSocket()){this.pendingThreadSettings=J;return}throw Z}}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J}),this.environmentSubject.next(J)}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J}),this.environmentSubject.next(J)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outboundUserMessages.length=0,this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.optimisticReconciliationState=QP4(),this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=$o0(0),this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(J){if(super.updateConnectionState(J),J==="connected")this.flushPendingThreadSettings(),this.flushOutboundUserMessages(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError();if(this.emitConnectionChanged(),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(J){let Z=cR4.safeDecode(J);if(!Z.success){let Y=dR4.safeDecode(J),X=Y.success?Z.error:Y.error,K={type:"error",message:JP4(J,X),code:"PARSE_ERROR"};this.dispatchObserverCallbacks((V)=>{V.onErrorNotice?.(K)});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}onMaxReconnectExceeded(J){this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(J){switch(this.advanceResumeCursor(J),J.type){case"agent_state":this.optimisticReconciliationState=AQ3(this.optimisticReconciliationState,J.state),this.dispatchObserverCallbacks((Z)=>{Z.onAgentState?.(J)});break;case"thread_settings":this.dispatchObserverCallbacks((Z)=>{Z.onThreadSettings?.(J)});break;case"error":this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.(J)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Z)=>{Z.onActiveError?.(J)});break;case"cancelled":this.dispatchObserverCallbacks((Z)=>{Z.onCancelled?.(J)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Z)=>{Z.onRetryEvent?.(J)});break;case"delta":this.dispatchObserverCallbacks((Z)=>{Z.onDelta?.(J)});break;case"message_added":{let Z=PQ3(this.optimisticReconciliationState,J.message.messageId);if(this.optimisticReconciliationState=Z.state,Z.suppressMessageAdded)break;let Q=Z.syntheticQueuedMessageRemoved;if(Q)this.dispatchObserverCallbacks((Y)=>{Y.onQueuedMessages?.(Q)});this.dispatchObserverCallbacks((Y)=>{Y.onMessageAdded?.(J)});break}case"edit_rejected":this.dispatchObserverCallbacks((Z)=>{Z.onEditRejected?.(J)});break;case"message_edited":this.dispatchObserverCallbacks((Z)=>{Z.onMessageEdited?.(J)});break;case"queued_messages":if(this.optimisticReconciliationState=CQ3(this.optimisticReconciliationState,J.messages.map((Z)=>Z.queuedMessage.messageId)),_Q3(this.optimisticReconciliationState,J.messages))break;this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J)});break;case"queued_message_added":{let Z=YP4(this.optimisticReconciliationState,J.message.queuedMessage.messageId);if(this.optimisticReconciliationState=Z.state,Z.suppressQueuedMessageAdded)break;this.dispatchObserverCallbacks((Q)=>{Q.onQueuedMessages?.(J)});break}case"queued_message_removed":this.optimisticReconciliationState=Yo0(this.optimisticReconciliationState,J.queuedMessageId),this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Z)=>{Z.onExecutorConnected?.(J)});for(let Z of this.executorConnectedListeners)Z(J);break;case"tool_lease":this.dispatchExecutorCallbacks((Z)=>{Z.onToolLease?.(J)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Z)=>{Z.onFileSystemReadDirectoryRequest?.(J)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Z)=>{Z.onFileSystemReadFileRequest?.(J)});break;case"executor_rollback_request":this.dispatchExecutorCallbacks((Z)=>{Z.onExecutorRollbackRequest?.(J)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Z)=>{Z.onToolLeaseRevoked?.(J)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Z)=>{Z.onToolApprovalQueue?.(J)});break;case"plugin_message":this.dispatchObserverCallbacks((Z)=>{Z.onPluginMessage?.(J)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorToolApprovalResponse?.(J)});break;case"tool_progress":this.dispatchObserverCallbacks((Z)=>{Z.onToolProgress?.(J)});break;case"executor_error":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorError?.(J)});for(let Z of this.executorErrorListeners)Z(J);break;case"observers":this.dispatchObserverCallbacks((Z)=>{Z.onObservers?.(J)});break;case"executor_status":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorStatus?.(J)});break;case"environment_update":this.environmentSubject.next(J.environment),this.dispatchObserverCallbacks((Z)=>{Z.onEnvironmentUpdate?.(J)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Z)=>{Z.onArtifactEvent?.(J)});break;case"thread_title":this.dispatchObserverCallbacks((Z)=>{Z.onThreadTitle?.(J)});break;case"thread_relationships":this.dispatchObserverCallbacks((Z)=>{Z.onThreadRelationships?.(J)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Z)=>{Z.onCompactionEvent?.(J)});break;case"thread_status":break}}flushOutboundUserMessages(){while(this.outboundUserMessages.length>0){let J=this.outboundUserMessages[0];if(!J)return;if(!this.trySendMessage(J))return;this.outboundUserMessages.shift()}}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.hasOpenSocket())return;let J=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:J})}catch{if(!this.hasOpenSocket())this.pendingThreadSettings=J}}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}}trySendMessage(J){if(!this.hasOpenSocket())return!1;try{return this.send(J),!0}catch(Z){if(!this.hasOpenSocket())return!1;this.optimisticReconciliationState=Yo0(this.optimisticReconciliationState,J.messageId);let Q=Z instanceof Error?Z.message:String(Z);return this.dispatchObserverCallbacks((Y)=>{Y.onErrorNotice?.(SQ3(Q))}),!0}}emitConnectionChanged(){let J=this.getConnectionInfo();S.info("[thread-client] Emitting connection change callbacks",{state:J.state,role:J.role,clientId:J.clientId,reconnectCauseType:J.reconnectCause?.type,reconnectCode:J.reconnectCause?.code,reconnectReason:J.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Z)=>{Z.onConnectionChange?.(J)}),this.dispatchObserverCallbacks((Z)=>{Z.onConnectionChanged?.(J)})}emitOptimisticUserMessage(J){if(J.type==="message_added")this.dispatchObserverCallbacks((Z)=>{Z.onMessageAdded?.(J.message)});else this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J.message)})}dispatchObserverCallbacks(J){let Z=this.observerCallbacks;if(!Z){this.pendingObserverDispatches.push(J);return}J(Z)}dispatchExecutorCallbacks(J){let Z=this.executorCallbacks;if(!Z){this.pendingExecutorDispatches.push(J);return}J(Z)}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new N9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new N9(`Filesystem request timed out: ${Z}`))},yR4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve(MQ3(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new N9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new N9(J)),this.pendingReadFileRequests.delete(Z)}advanceResumeCursor(J){let Z=J.seq;if(typeof Z!=="number"||!Number.isFinite(Z))return;this.resumeCursor.advanceFromSeq(Z)}send(J){try{this.sendRaw(pR4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new N9(`Failed to encode thread-protocol message "${J.type}": ${Q}`,Z)}}}function uv(J,Z){let Q=Z;return async()=>{let Y=await J(Q);return Q=Y.threadId,Y}}function bv(J){let Z=Lv({endpoint:J.rivetEndpoint});return{...J.initialThreadID?{threadId:J.initialThreadID}:{},...J.maxReconnectAttempts!==void 0?{maxReconnectAttempts:J.maxReconnectAttempts}:{},pingIntervalMs:J.pingIntervalMs??5000,webSocketProvider:async()=>{let Q=await J.credentialsProvider({forceRefresh:!0});return{webSocket:await Z.threadActor.getOrCreate([Q.threadId],{params:{wsToken:Q.wsToken},createWithInput:{threadId:Q.threadId,threadVersion:Q.threadVersion,ownerUserId:Q.ownerUserId,...Q.agentMode?{agentMode:Q.agentMode}:{}}}).webSocket("/"),threadId:Q.threadId}}}}s4();function BX0(J){return{version:J.v,title:J.title??null,messages:J.messages.map((Z)=>kQ3(J,Z)),agentMode:J.agentMode||x40(J)}}function kQ3(J,Z){let Q=vQ3(Z);switch(Z.role){case"user":return{threadId:J.id,role:"user",content:[...Z.content],meta:du1(Z.meta),userState:yQ3(Z.userState),readAt:Z.readAt,messageId:Q};case"assistant":return{threadId:J.id,role:"assistant",content:[...Z.content],state:Z.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Z.usage,readAt:Z.readAt,messageId:Q};case"info":return{threadId:J.id,role:"info",content:Z.content.filter(xQ3),messageId:Q}}}function vQ3(J){let Z=XP4(J.protocolMessageID);if(Z)return Z;let Q=J.messageId;if(typeof Q==="string"){let Y=XP4(Q);if(Y)return Y}return FX0()}function XP4(J){if(!J)return null;let Z=B3.safeParse(J);return Z.success?Z.data:null}function yQ3(J){if(!J)return;return{...J,currentlyVisibleFiles:[...J.currentlyVisibleFiles],runningTerminalCommands:J.runningTerminalCommands?[...J.runningTerminalCommands]:void 0,aggmanContext:J.aggmanContext?{...J.aggmanContext,availableProjects:J.aggmanContext.availableProjects?J.aggmanContext.availableProjects.map((Z)=>({...Z})):void 0,recentUnreadThreads:J.aggmanContext.recentUnreadThreads?J.aggmanContext.recentUnreadThreads.map((Z)=>({...Z})):void 0}:void 0}}function xQ3(J){return J.type==="manual_bash_invocation"}YJ();D4();import Bn from"node:path";class sj extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function VP4(J,Z){let Q=K1.parse(J);if(Q.scheme!=="file")throw new sj("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new sj("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((F)=>F===".."))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");let X=Bn.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");let K=Bn.resolve(Z),V=X.length>0?Bn.resolve(K,X):K,G=Bn.relative(K,V);if(G.startsWith("..")||Bn.isAbsolute(G))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function cw(J,Z){try{let Q=VP4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(K1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",G=V==="file"?await fQ3(J.fileSystem,K.uri):void 0;return[F1.basename(K.uri),V,G]}))}}catch(Q){return{ok:!1,error:FP4(Q,"read_directory")}}}async function fQ3(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function GP4(J,Z){try{let Q=VP4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(K1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:FP4(Q,"read_file")}}}function FP4(J,Z){if(J instanceof sj)return{code:J.code,message:J.message};if(W9(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(NX0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(NX0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":KP4(J)};if(NX0(J,"EACCES")||NX0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:KP4(J)}}function NX0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function KP4(J){if(J instanceof Error)return J.message;return String(J)}a0();j3();s4();D4();I1();import{exec as uQ3}from"node:child_process";import{promisify as bQ3}from"node:util";tA();s4();D4();var hQ3=bQ3(uQ3);async function zP4(J){let Z=await qU(),Q=sZ(J)?J:I7(),Y=await bm0({filesystem:q8},Z,Q),X=await gQ3(Y.workingDirectory??Y.workspaceRoot);return{...Z,...Y,...X?{git:{branch:X}}:{},updatedAt:new Date().toISOString()}}async function gQ3(J){if(!J)return;let Z;try{Z=K1.parse(J).fsPath}catch{return}try{let{stdout:Q}=await hQ3("git symbolic-ref --quiet --short HEAD",{cwd:Z});return Q.trim()||void 0}catch{return}}function mQ3(J){return new TextEncoder().encode(JSON.stringify(J)).length}function hv(J,Z,Q){if(J.length===0)return[];let Y=[],X=[];for(let K of J){let V=[...X,K],G=mQ3(Q(V));if(X.length>0&&G>Z){Y.push(X),X=[K];continue}X=V}if(X.length>0)Y.push(X);return Y}var WP4=1048576;function qP4(J){let Z=new Map;for(let Q of J)Z.set(Q.name,{schema:Q,serializedSchema:JSON.stringify(Q)});return Z}function pQ3(J){let Z={...J.executionProfile?.serial!==void 0?{serial:J.executionProfile.serial}:{},...J.meta?.deferred!==void 0?{deferred:J.meta.deferred}:{},...J.meta?.skillNames!==void 0?{skillNames:[...J.meta.skillNames]}:{}};return Object.keys(Z).length>0?Z:void 0}function dQ3(J){return{name:J.name,description:J.description??"",inputSchema:{type:"object",properties:J.inputSchema.properties??{},required:J.inputSchema.required,additionalProperties:J.inputSchema.additionalProperties},source:J.source,meta:pQ3(J)}}function wX0(J){return J.map((Z)=>dQ3(Z.spec))}function HP4(J,Z){let Q=qP4(J),Y=qP4(Z);return{toolsToRegister:Z.filter((X)=>{let K=Q.get(X.name),V=Y.get(X.name);return K?.serializedSchema!==V?.serializedSchema}),toolNamesToUnregister:[...Q.keys()].filter((X)=>!Y.has(X))}}function UP4(J,Z=WP4){return hv(J,Z,(Q)=>({type:"executor_tools_register",tools:Q}))}function DP4(J,Z=WP4){return hv(J,Z,(Q)=>({type:"executor_tools_unregister",toolNames:Q}))}import{execFile as aQ3}from"node:child_process";import{createHash as oQ3}from"node:crypto";import{readFile as rQ3,stat as sQ3}from"node:fs/promises";import{basename as tQ3,join as eQ3}from"node:path";import AP4 from"node:process";import{promisify as $Y3}from"node:util";async function BP4(J,Z,Q){let Y=[];for(let X=0;X<J.length;X+=Z){let K=J.slice(X,X+Z);Y.push(...await Promise.all(K.map(Q)))}return Y}var NP4=2097152,lw="(Content omitted — git status artifact exceeds size limit)";function cQ3(J){return(J.fullFileDiff?.length??0)+(J.oldContent?.length??0)+(J.newContent?.length??0)}function lQ3(J){let Z=!1;if(J.fullFileDiff!==void 0&&J.fullFileDiff!==J.diff)J.fullFileDiff=J.diff,Z=!0;if(J.oldContent!==void 0&&J.oldContent!==lw)J.oldContent=lw,Z=!0;if(J.newContent!==void 0&&J.newContent!==lw)J.newContent=lw,Z=!0;return Z}function iQ3(J){let Z=!1;if(J.oldContent!==void 0)J.oldContent=void 0,Z=!0;if(J.newContent!==void 0)J.newContent=void 0,Z=!0;if(J.fullFileDiff!==void 0)J.fullFileDiff=void 0,Z=!0;return Z}function nQ3(J){let Z=!1;if(J.diff!==lw)J.diff=lw,Z=!0;if(J.fullFileDiff!==void 0&&J.fullFileDiff!==lw)J.fullFileDiff=lw,Z=!0;return Z}function gv(J){let Z=Buffer.from(JSON.stringify(J),"utf8").toString("base64"),Q=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:Lk,dataType:"application/json",contentBase64:Z}})).length;return{contentBase64:Z,messageSizeBytes:Q}}function wP4(J,Z){let Q={...J,aheadCommits:[...J.aheadCommits],files:J.files.map((V)=>({...V}))},Y=gv(Q);if(Y.messageSizeBytes<=Z)return Y.contentBase64;let X=Q.files.map((V,G)=>({index:G,weight:cQ3(V)})).filter((V)=>V.weight>0).sort((V,G)=>G.weight-V.weight);for(let{index:V}of X){let G=Q.files[V];if(!G||!lQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}for(let{index:V}of X){let G=Q.files[V];if(!G||!iQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}let K=Q.files.map((V,G)=>({index:G,weight:V.diff.length+(V.fullFileDiff?.length??0)})).filter((V)=>V.weight>0).sort((V,G)=>G.weight-V.weight);for(let{index:V}of K){let G=Q.files[V];if(!G||!nQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}if(Q.aheadCommits.length>0){if(Q.aheadCommits=[],Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}while(Q.files.length>0)if(Q.files.pop(),Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64;return Y.contentBase64}var JY3=$Y3(aQ3),pv=20971520,ZY3=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],LX0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],QY3=999999,LP4="refs/remotes/origin/",YY3=20,XY3=10;function OX0(J){return J.replace(/\n+$/,"")}var Ko0=AP4.platform==="win32"?"NUL":"/dev/null";function KY3(J=AP4.env,Z={}){let{isolateGitConfig:Q=!0}=Z,Y={...J};if(Q){for(let X of Object.keys(Y))if(ZY3.includes(X)||X.startsWith("GIT_CONFIG_KEY_")||X.startsWith("GIT_CONFIG_VALUE_"))delete Y[X];Y.GIT_CONFIG_NOSYSTEM="1",Y.GIT_CONFIG_SYSTEM=Ko0,Y.GIT_CONFIG_GLOBAL=Ko0}return Y}function OP4(J,Z){return{provider:"git",capturedAt:J,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Z}}function VY3(J){return J instanceof Error}async function mv(J,Z,Q={}){try{let{stdout:Y}=await JY3("git",Z,{cwd:J,env:KY3(),maxBuffer:Q.maxBufferBytes??pv});return Y}catch(Y){if(Q?.allowExitCodeOne&&VY3(Y)&&(Y.code===1||Y.code==="1")&&typeof Y.stdout==="string")return Y.stdout;throw Y}}async function CU(J,Z){try{return await mv(J,Z)}catch{return null}}function GY3(J){if(J==="??")return"untracked";let Z=J[0]??" ",Q=J[1]??" ";if(Z==="U"||Q==="U"||J==="AA"||J==="DD")return"unmerged";if(Z==="R"||Q==="R")return"renamed";if(Z==="C"||Q==="C")return"copied";if(Z==="A"||Q==="A")return"added";if(Z==="D"||Q==="D")return"deleted";if(Z==="T"||Q==="T")return"type_changed";return"modified"}function Vo0(J){let Z=[],Q=J.split("\x00");for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X||X.length<4)continue;let K=X.slice(0,2),V=X.slice(3);if(!V)continue;let G=GY3(K);if(G==="renamed"||G==="copied"){let F=Q[Y+1];if(F){Z.push({path:V,previousPath:F,changeType:G}),Y+=1;continue}}Z.push({path:V,changeType:G})}return Z.sort((Y,X)=>Y.path.localeCompare(X.path))}function FY3(J){let Z=0,Q=0,Y=0,X=0,K=0,V=()=>{if(X===0&&K===0)return;Y+=Math.min(X,K),X=0,K=0};for(let G of J.split(`
|
|
4285
|
+
`+J)}a0();import{randomUUID as RY3}from"node:crypto";v4();I1();class GX0 extends Error{constructor(J){super(J);this.name="ThreadClientError"}}class N9 extends GX0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}class LJ extends GX0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="ThreadClientConnectionError"}}a0();I1();D$();function CR4(J){let Z=J.replace(/-/g,"");if(Z.length!==32)throw Error(`Invalid UUID hex length: ${Z.length}`);let Q=BigInt("0x"+Z),Y="";while(Q>0n)Y="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[Number(Q%62n)]+Y,Q=Q/62n;return Y.padStart(22,"0")}t3();D4();vI0();D$();var J8=v.string().min(1),pw=J8.brand(),ma0=v.string().regex(/^[0-9A-Za-z]{22}$/),P$3=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),qn=v.templateLiteral(["T-",P$3]),C$3=v.enum(["fork","handoff","mention"]),_$3=v.enum(["parent","child"]),_R4=v.object({threadID:qn,type:C$3,role:_$3,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),B3=v.templateLiteral(["M-",ma0]);function FX0(){return`M-${CR4(Xh())}`}var F7=v.templateLiteral(["TU-",ma0]);var Wn=v.templateLiteral(["E-",ma0]);var T$3=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),S$3=v.union([v.literal("builtin"),v.object({toolbox:J8}).strict(),v.object({mcp:J8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:J8}).strict(),v.object({remote:J8}).strict()]),k$3=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(J8).optional()}),TR4=v.looseObject({name:J8,description:v.string(),inputSchema:T$3,source:S$3,meta:k$3.optional()}),_X9=v.object({id:J8,category:J8,title:J8,description:v.string().optional(),pluginName:J8}),zX0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),SR4=v.object({workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),kR4=v.enum(["sandbox","local-client"]),Hn=v.any().and(v.object({status:v.string()})),vR4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error","aborted"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),_q=J8,yR4=30000,xv=hW,v$3=v.enum(["file","directory"]),y$3=v.object({mtimeMs:v.number().nonnegative().optional()}),Un=v.tuple([v.string(),v$3,y$3.nullish()]),x$3=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),dw=v.object({code:x$3,message:v.string()}),f$3=v.object({ok:v.literal(!0),entries:v.array(Un)}),u$3=v.object({ok:v.literal(!1),error:dw}),TX9=v.discriminatedUnion("ok",[f$3,u$3]),b$3=v.object({ok:v.literal(!0),contentBase64:v.string()}),h$3=v.object({ok:v.literal(!1),error:dw}),SX9=v.discriminatedUnion("ok",[b$3,h$3]),g$3=J8,pa0=v.object({key:J8,dataType:g$3,contentBase64:v.string()}),da0=pa0.extend({toolCallId:F7.optional(),updatedAt:v.string()}),ca0=v.looseObject({uri:hW,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),xR4=v.object({name:J8,description:v.string(),baseDir:hW,frontmatter:v.object({name:J8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),la0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),fR4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),fv=v.array(v.discriminatedUnion("type",[la0,fR4])),yv=v.record(v.string(),v.unknown()),uR4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),m$3=uR4.extend({complete:v.literal(!0),input:yv,normalizedInput:yv.optional()}),p$3=uR4.extend({complete:v.literal(!1),input:yv,inputIncomplete:yv,inputPartialJSON:v.object({json:v.string()}),normalizedInput:yv.optional()}),d$3=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),c$3=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:Hn,userInput:d$3.optional()}),l$3=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),i$3=v.object({type:v.literal("redacted_thinking"),data:v.string()}),n$3=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:yv}),a$3=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:Hn,hidden:v.boolean().optional()}),ia0=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:qn.optional()}),o$3=v.union([la0,fR4,c$3]),r$3=v.union([la0,l$3,i$3,m$3,p$3,n$3]),na0=v.array(o$3),aa0=v.array(r$3),s$3=v.array(a$3),ga0=v.looseObject({line:v.number().int(),column:v.number().int()}),t$3=v.looseObject({start:ga0,end:ga0}),e$3=v.looseObject({name:v.string(),repositoryURL:v.string()}),$J3=v.looseObject({currentURL:v.string(),availableProjects:v.array(e$3).optional()}),oa0=v.looseObject({currentlyVisibleFiles:v.array(hW),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:ga0.optional(),cursorLocationLine:v.string().optional(),selectionRange:t$3.optional(),aggmanContext:$J3.optional()}),oj=v.custom((J)=>typeof J==="string"&&r7(J)!==void 0),JJ3=v.object({threadId:qn,role:v.literal("user"),content:na0,agentMode:oj.optional(),meta:ia0.optional(),userState:oa0.optional(),readAt:v.string().nullable().optional(),messageId:B3,createdAt:v.string().optional()}),ra0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),ZJ3=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),QJ3=v.object({threadId:qn,role:v.literal("assistant"),content:aa0,state:ZJ3.optional(),usage:ra0.optional(),readAt:v.string().nullable().optional(),messageId:B3,createdAt:v.string().optional()}),YJ3=v.object({threadId:qn,role:v.literal("info"),content:s$3,messageId:B3,createdAt:v.string().optional()}),bR4=v.discriminatedUnion("role",[JJ3,QJ3,YJ3]),Dn=v.object({workspaceRoot:hW.optional(),workingDirectory:hW.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),git:v.object({branch:v.string().optional()}).optional(),updatedAt:v.string().optional()}),XJ3=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),KJ3=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:XJ3}),VJ3=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),hR4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(VJ3).optional(),diffHash:v.string().optional(),files:v.array(KJ3),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),qX0=v.object({id:v.string(),toolCallId:F7,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:F7.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),GJ3=v.object({type:v.literal("request"),id:J8,method:J8,params:v.unknown()}),FJ3=v.object({type:v.literal("response"),id:J8,result:v.unknown().optional(),error:v.string().optional()}),zJ3=v.object({type:v.literal("event"),event:J8,data:v.unknown(),span:v.string().optional()}),WX0=v.discriminatedUnion("type",[GJ3,FJ3,zJ3]);var qJ3=v.object({type:v.literal("executor_connect"),clientId:pw,capabilities:SR4,executorType:kR4.optional()}),WJ3=v.object({type:v.literal("client_update_thread_settings"),settings:zX0}),HJ3=v.object({type:v.literal("executor_tools_register"),tools:v.array(TR4)}),UJ3=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(J8)}),DJ3=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),BJ3=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:F7}),sa0=v.object({type:v.literal("tool_progress"),toolCallId:F7,progress:v.union([vR4,v.unknown()]).optional(),parentToolCallId:F7.optional()}),NJ3=v.object({type:v.literal("executor_tool_result"),toolCallId:F7,run:Hn}),wJ3=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:J8,files:v.array(ca0),isLast:v.boolean(),userConfigDir:v.any().optional()}),LJ3=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:F7,files:v.array(ca0),isLast:v.boolean()}),OJ3=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:J8,skills:v.array(xR4),isLast:v.boolean()}),EJ3=v.object({type:v.literal("executor_rollback_ack"),editId:Wn,ok:v.boolean(),error:v.string().optional()}),MJ3=v.object({type:v.literal("executor_environment_snapshot"),environment:Dn}),AJ3=v.object({type:v.literal("executor_environment_update"),environment:Dn}),jJ3=v.object({type:v.literal("executor_artifact_upsert"),artifact:pa0,toolCallId:F7.optional()}),IJ3=v.object({type:v.literal("executor_artifact_delete"),key:J8}),RJ3=v.object({type:v.literal("executor_tool_approval_request"),approval:qX0}),PJ3=v.object({type:v.literal("executor_plugin_message"),message:WX0}),CJ3=v.object({type:v.literal("client_append_user_msg"),content:fv,userState:oa0.optional(),agentMode:oj.optional(),messageId:B3}),_J3=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:B3}),TJ3=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:B3}),SJ3=v.object({type:v.literal("client_edit_message"),messageId:B3,editId:Wn,content:fv,agentMode:oj.optional()}),kJ3=v.object({type:v.literal("client_mark_message_read"),messageId:B3}),vJ3=v.object({type:v.literal("client_mark_message_unread"),messageId:B3}),yJ3=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),xJ3=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),fJ3=v.object({endpoint:v.string().url(),keys:xJ3}),uJ3=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:fJ3,threadURL:v.string().min(1)}),bJ3=v.object({type:v.literal("client_filesystem_read_directory"),requestId:_q,uri:xv}),hJ3=v.object({type:v.literal("client_filesystem_read_file"),requestId:_q,uri:xv}),gJ3=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:_q,ok:v.boolean(),entries:v.array(Un).optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),mJ3=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:_q,ok:v.boolean(),contentBase64:v.string().optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),pJ3=v.object({type:v.literal("client_resume"),version:v.number()}),dJ3=v.object({type:v.literal("client_retry")}),cJ3=v.object({type:v.literal("client_dismiss_active_error"),seq:v.number().optional()}),lJ3=v.object({type:v.literal("client_cancel")}),iJ3=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:Hn,hidden:v.boolean().optional()}),nJ3=v.object({type:v.literal("client_tool_approval_response"),toolCallId:F7,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),aJ3=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),gR4=v.discriminatedUnion("type",[qJ3,WJ3,HJ3,UJ3,DJ3,BJ3,sa0,NJ3,wJ3,LJ3,OJ3,EJ3,MJ3,AJ3,jJ3,IJ3,RJ3,PJ3,CJ3,_J3,TJ3,SJ3,kJ3,vJ3,yJ3,uJ3,bJ3,hJ3,gJ3,mJ3,pJ3,dJ3,cJ3,lJ3,iJ3,nJ3,aJ3]);D$();var HX0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)});D$();D$();var ta0=["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"],bX9=new Set(ta0);var oJ3=["working","streaming","tool_use","running_tools"],rJ3=new Set(oJ3);function rj(J){if(typeof J!=="string")return!1;return rJ3.has(J)}function UX0(J,Z){if(J&&typeof J==="object"&&"type"in J){let Y=J;if(Y.type==="delta"||Y.type==="snapshot")return Y}if(Z==="snapshot")return{type:"snapshot",value:J};let Q=typeof J==="string"?J:J!==void 0?JSON.stringify(J):"";return{type:"delta",blocks:Q?[{type:"text",text:Q}]:void 0,state:"generating"}}var sJ3=v.enum(ta0),tJ3=v.enum(["start","generating","tool_use","complete","error","aborted"]),eJ3=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),$Z3=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),JZ3=v.enum(["starting","running","failed"]),ZZ3=v.enum(["missing","allocating_environment","configuring_workspace","starting_headless","headless_ready","paused","failed"]),QZ3=v.enum(["pending","ready","failed"]).nullable(),YZ3=v.enum(["allocating_environment","configuring_workspace","starting_headless"]).nullable(),XZ3=v.enum(["idle","creating","recovering"]),KZ3=v.enum(["unknown","running","paused","missing"]),VZ3=v.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"]),GZ3=v.object({environmentId:v.string().nullable().optional(),stage:ZZ3.optional(),setupState:QZ3.optional(),setupPhase:YZ3.optional(),operation:XZ3.optional(),providerState:KZ3.optional(),restartAttempts:v.number().optional()}),FZ3=v.object({reasonCode:VZ3.optional(),executionEnvironment:GZ3.optional()}),zZ3=v.object({cutMessageId:B3,createdAt:v.string()}),mR4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:B3,content:fv,userState:v.any().optional(),meta:ia0.optional(),createdAt:v.string().optional()})}),qZ3=v.object({type:v.literal("agent_state"),state:sJ3,messageId:B3.optional(),agentMode:oj.optional()}),WZ3=v.object({type:v.literal("thread_settings"),settings:zX0}),HZ3=v.object({type:v.literal("error"),message:v.string(),code:v.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()}),UZ3=v.object({type:v.literal("error_set"),seq:v.number(),error:eJ3}),DZ3=v.object({type:v.literal("error_cleared"),seq:v.number()}),BZ3=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:B3.optional()}),NZ3=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),wZ3=v.object({type:v.literal("retry_started")}),LZ3=v.object({type:v.literal("retry_cancelled")}),OZ3=v.object({type:v.literal("executor_connected"),executorId:pw,registeredToolCount:v.number(),resumeBootstrap:v.boolean().optional(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),EZ3=v.object({type:v.literal("tool_lease"),toolCallId:F7,toolName:v.string(),args:v.unknown(),messageId:B3,parentToolCallId:F7.optional()}),MZ3=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:_q,uri:xv}),AZ3=v.object({type:v.literal("executor_filesystem_read_file"),requestId:_q,uri:xv}),jZ3=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:_q,ok:v.boolean(),entries:v.array(Un).optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),IZ3=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:_q,ok:v.boolean(),contentBase64:v.string().optional(),error:dw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),RZ3=v.object({type:v.literal("tool_approval_queue"),approvals:v.array(qX0)}),PZ3=v.object({type:v.literal("executor_rollback_request"),editId:Wn,messageId:B3,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(F7)}),CZ3=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:F7,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),_Z3=v.object({type:v.literal("plugin_message"),message:WX0}),TZ3=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:F7,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),SZ3=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),kZ3=v.object({type:v.literal("delta"),messageId:B3,role:v.literal("assistant"),blocks:aa0.optional(),blockIndex:v.number().int().nonnegative().optional(),state:tJ3,usage:ra0.optional(),parentToolCallId:F7.optional()}),vZ3=v.object({type:v.literal("delta"),messageId:B3,role:v.literal("user"),blocks:na0.optional(),state:v.literal("complete"),parentToolCallId:F7.optional()}),yZ3=v.discriminatedUnion("role",[kZ3,vZ3]),xZ3=v.object({type:v.literal("queued_messages"),messages:v.array(mR4)}),fZ3=v.object({type:v.literal("queued_message_added"),message:mR4,seq:v.number()}),uZ3=v.object({type:v.literal("queued_message_removed"),queuedMessageId:B3,seq:v.number()}),bZ3=v.object({type:v.literal("message_added"),message:bR4,seq:v.number(),parentToolUseId:J8.optional()}),hZ3=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),gZ3=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:B3,content:fv,truncateToMessageId:B3,reason:v.literal("message_edit"),agentMode:oj.optional()}),mZ3=v.object({type:v.literal("observers"),count:v.number(),observers:v.array($Z3),hasExecutor:v.boolean().optional()}),pZ3=v.object({type:v.literal("executor_status"),spawnId:v.string().optional(),status:JZ3,message:v.string().optional(),executorId:v.string().optional(),details:FZ3.optional()}),dZ3=v.object({type:v.literal("environment_update"),environment:Dn}),cZ3=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(da0)}),lZ3=v.object({type:v.literal("artifact_upserted"),artifact:da0}),iZ3=v.object({type:v.literal("artifact_deleted"),key:J8}),nZ3=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),aZ3=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),oZ3=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(_R4)}),rZ3=v.object({type:v.literal("compaction_started")}),sZ3=v.object({type:v.literal("compaction_complete"),cutMessageId:B3}),tZ3=v.object({type:v.literal("compaction_records"),records:v.array(zZ3)}),DX0=v.discriminatedUnion("type",[qZ3,WZ3,HZ3,UZ3,DZ3,BZ3,NZ3,wZ3,LZ3,OZ3,EZ3,MZ3,AZ3,jZ3,IZ3,RZ3,PZ3,CZ3,_Z3,TZ3,sa0,SZ3,yZ3,xZ3,fZ3,uZ3,bZ3,hZ3,gZ3,mZ3,pZ3,dZ3,cZ3,lZ3,iZ3,nZ3,aZ3,oZ3,rZ3,sZ3,tZ3]);var pR4=HX0(gR4),eZ3=v.union([DX0,v.array(DX0)]),dR4=HX0(DX0),cR4=HX0(eZ3);D4();function lR4(J,Z={}){let Y=(Z.mode??"lenient")==="strict";if(!Array.isArray(J))return Y?null:[];let X=[];for(let K of J){if(typeof K!=="object"||K===null){if(Y)return null;continue}let V=K;if(typeof V.uri!=="string"||V.uri.length===0){if(Y)return null;continue}let G;try{G=n1(K1.parse(V.uri))}catch{if(Y)return null;continue}let F={uri:G};if(typeof V.content==="string")F.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))F.lineCount=V.lineCount;if(typeof V.hash==="string")F.hash=V.hash;X.push(F)}return X}var iR4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function ea0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function $Q3(J){return J.replace(/\s+/g," ").trim()}function JQ3(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function ZQ3(J){if(J===void 0)return null;if(typeof J==="string")return JSON.stringify(J);if(typeof J==="number"||typeof J==="boolean"||J===null)return JSON.stringify(J);try{return ea0(JSON.stringify(J),120)}catch{return ea0(String(J),120)}}function nR4(J){if(!Array.isArray(J)||J.length===0)return null;let Z=J.map((Q)=>typeof Q==="number"?`[${Q}]`:String(Q)).join(".").replace(/\.\[/g,"[");return Z.length>0?Z:null}function QQ3(J){if(!J||typeof J!=="object")return null;let Z=J,Q=typeof Z.message==="string"?Z.message:null,Y=typeof Z.note==="string"?Z.note:null,X=nR4(Z.path);if(X&&Q&&Q!=="Invalid input")return`${X}: ${Q}`;if(X&&Y)return`${X}: ${Y}`;if(X&&Q)return`invalid value at ${X}`;return Y??Q}function aR4(J){for(let Z of J){let Q=QQ3(Z);if(Q)return Q}return null}function YQ3(J){return J.some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;return Q.code==="invalid_union"&&(Q.note==="No matching discriminator"||Q.discriminator==="type"||nR4(Q.path)==="type")})}function XQ3(J,Z){let Q=aR4(Z);if(J&&Q)return`type ${JSON.stringify(J)} failed validation: ${Q}`;if(J)return`type ${JSON.stringify(J)} failed validation`;if(Q)return`message payload failed validation: ${Q}`;return"message payload failed validation"}function oR4(J,Z,Q){let Y=JQ3(Z),X=(()=>{let z=$Q3(J);if(z.length===0)return null;return ea0(z,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let z=aR4(Y);return{failureType:"invalid_json",summary:z?`malformed JSON: ${z}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let G=V.type,F=ZQ3(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:X,issues:Y};if(YQ3(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:F,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:XQ3(G,Y),messageType:G,typePreview:F,payloadPreview:X,issues:Y}}function $o0(J){let Z=Number.isFinite(J)?J:0,Q=0,Y=Z;function X(V=Z){if(Number.isFinite(V))Z=V;return Q=0,Y=Z,Z}function K(V){if(!Number.isFinite(V)||V<1)return Z;if(V<=Q)return Z;if(Q===0)Y=Z-(V-1);return Z=Math.max(Z,Y+V),Q=V,Z}return{getVersion:()=>Z,reset:X,advanceFromSeq:K}}a0();I1();var KQ3=1000,VQ3=30000,GQ3=5,FQ3=30000,zQ3=15000,qQ3=1000,WQ3=200,HQ3=30000,rR4=["online","focus","pageshow","keydown","pointerdown"],sR4=["visibilitychange"];function Zo0(){return globalThis}function eR4(J){if(!J||typeof J!=="object")return null;let Z=J;if(typeof Z.addEventListener!=="function"||typeof Z.removeEventListener!=="function")return null;return Z}function tR4(){return eR4(Zo0().window)}function Jo0(){let J=Zo0().document;if(!eR4(J))return null;return J}function UQ3(){let J=Zo0().navigator;if(!J||typeof J!=="object")return null;return J}function DQ3(J){if(!J)return"none";let Z=[J.type];if(J.code!==void 0)Z.push(`code=${J.code}`);if(J.reason!==void 0)Z.push(`reason=${J.reason}`);if(J.error!==void 0)Z.push(`error=${J.error}`);return Z.join(" ")}class Qo0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null};reconnectCause=null;reconnectAttempts=0;reconnectTimeoutID=null;reconnectResetTimeoutID=null;pingIntervalID=null;disposed=!1;lastPongAt=Date.now();intentionallyClosedSockets=new WeakSet;reconnectActivityCleanup=null;lifecycleEventID=0;lifecycleEvents=[];connectionSubject=new P4({state:"disconnected",role:null,clientId:null});lifecycleEventSubject=new P4([]);config;threadIDSubject=new P4(null);_currentThreadID=null;get currentThreadID(){return this._currentThreadID}set currentThreadID(J){if(J!==null&&J!==this._currentThreadID)this._currentThreadID=J,this.threadIDSubject.next(J);else this._currentThreadID=J}constructor(J){this.config={threadId:J.threadId,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??KQ3,maxReconnectDelayMs:J.maxReconnectDelayMs??VQ3,maxReconnectAttempts:J.maxReconnectAttempts??GQ3,pingIntervalMs:J.pingIntervalMs??FQ3,connectTimeoutMs:J.connectTimeoutMs??zQ3},this.currentThreadID=J.threadId??null,this.recordLifecycleEvent("transport_initialized",`threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(J){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||J<=0)return Promise.resolve(!1);return new Promise((Z)=>{let Q=!1,Y=null,X=null,K=(V)=>{if(Q)return;if(Q=!0,Y)clearTimeout(Y),Y=null;X?.unsubscribe(),X=null,Z(V)};Y=setTimeout(()=>{K(!1)},J),X=this.connectionSubject.subscribe({next:(V)=>{if(V.state==="connected")K(!0)},error:()=>{K(!1)},complete:()=>{K(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=WQ3,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new N9("Transport is disposed");if(this.ws)return;this.recordLifecycleEvent("connect_requested",J.fromReconnect?`mode=reconnect attempt=${this.reconnectAttempts}`:"mode=initial"),this.updateConnectionState("connecting");try{let{webSocket:Z,threadId:Q}=await this.config.webSocketProvider();this.currentThreadID=Q;try{Z.binaryType="arraybuffer"}catch{}await this.waitForOpen(Z),this.ws=Z,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Z),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);if(this.recordLifecycleEvent("connect_failed",`mode=${J.fromReconnect?"reconnect":"initial"} error=${Q}`),!J.fromReconnect&&!this.disposed)this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q},this.scheduleReconnect();throw Z}}disconnect(){this.recordLifecycleEvent("disconnect_requested"),this.stopPingInterval(),this.cancelReconnect(),this.reconnectCause=null;let J=this.ws;if(J){if(this.ws=null,this.intentionallyClosedSockets.add(J),J.readyState===WebSocket.OPEN)J.close(1000,"Client disconnect")}this.updateConnectionState("disconnected")}forceReconnect(J){let Z=this.ws;if(!Z)return;if(this.recordLifecycleEvent("force_reconnect_requested",`reason=${J}`),this.reconnectCause={type:"error",at:Date.now(),error:J},Z.readyState===WebSocket.OPEN)Z.close(4000,J)}async disconnectAndWait(J){let Z=this.ws;if(!Z||Z.readyState!==WebSocket.OPEN)return this.disconnect(),{status:"not_connected"};let Q=this.waitForSocketClose(Z,J?.waitForCloseTimeoutMs??qQ3);return this.disconnect(),Q}dispose(){if(this.disposed)return;this.recordLifecycleEvent("disposed"),this.disposed=!0,this.disconnect(),this.connectionSubject.complete(),this.lifecycleEventSubject.complete()}sendRaw(J){if(!this.hasOpenSocket())throw new N9("WebSocket is not connected");this.ws?.send(J),this.startPingIntervalOnce()}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}waitForSocketClose(J,Z){return new Promise((Q)=>{let Y=!1,X=null,K=(G)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);J.removeEventListener("close",V),Q(G)},V=(G)=>{let F=G;K({status:F.code===1000?"server_acknowledged":"timeout",...typeof F.code==="number"?{closeCode:F.code}:{},...typeof F.reason==="string"?{closeReason:F.reason}:{}})};if(X=setTimeout(()=>{K({status:"timeout"})},Z),J.addEventListener("close",V),J.readyState===WebSocket.CLOSED)K({status:"timeout"})})}updateConnectionState(J){let Z={...this.connectionInfo};if(J==="disconnected"||J==="reconnecting"){let Y={state:J,role:null,clientId:null};if(this.reconnectCause)Y.reconnectCause=this.reconnectCause;this.connectionInfo=Y}else if(this.connectionInfo.state=J,J==="connected")this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;let Q={...this.connectionInfo};this.connectionSubject.next(Q),S.info("[thread-client] Transport connection state changed",{previousState:Z.state,nextState:Q.state,previousRole:Z.role,nextRole:Q.role,clientId:Q.clientId,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${DQ3(this.reconnectCause)}`)}onRawMessage(J){}onMaxReconnectExceeded(J){}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=setTimeout(()=>{X(),this.updateConnectionState("disconnected");try{if(J.readyState===WebSocket.CONNECTING)J.close()}catch{}Q(new N9(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),X=()=>{clearTimeout(Y),J.removeEventListener("open",K),J.removeEventListener("error",V),J.removeEventListener("close",G)},K=()=>{X(),Z()},V=(F)=>{X(),this.updateConnectionState("disconnected");let z="message"in F?F.message:("error"in F)&&F.error instanceof Error?F.error.message:F.type;Q(new N9(`WebSocket connection failed: ${z}`))},G=(F)=>{X(),this.updateConnectionState("disconnected"),Q(new N9(`WebSocket closed during connect: code=${F.code} reason=${F.reason||"none"}`))};if(J.addEventListener("open",K),J.addEventListener("error",V),J.addEventListener("close",G),J.readyState===WebSocket.OPEN)return K();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return G({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now(),this.startPingIntervalOnce();return}this.startPingIntervalOnce(),this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.startPingIntervalOnce(),this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)})}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(S.info("[thread-client] Transport socket close observed",{code:Z,reason:Q||void 0,intentional:Y,isCurrentSocket:J===this.ws,stateBeforeClose:this.connectionInfo.state,roleBeforeClose:this.connectionInfo.role,clientIdBeforeClose:this.connectionInfo.clientId,threadId:this.currentThreadID,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};this.reconnectCause=K,this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==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(J){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(!J?.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 Z=J?.immediate?0:this.getReconnectDelayMs();S.info("[thread-client] Scheduling transport reconnect",{attempt:this.reconnectAttempts,delayMs:Math.round(Z),immediate:J?.immediate===!0,bypassActivityGate:J?.bypassActivityGate===!0,state:this.connectionInfo.state,role:this.connectionInfo.role,clientId:this.connectionInfo.clientId,threadId:this.currentThreadID,reconnectCauseType:this.reconnectCause?.type,reconnectCode:this.reconnectCause?.code,reconnectReason:this.reconnectCause?.reason}),this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=tR4(),Z=Jo0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=UQ3();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Jo0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=tR4(),Z=Jo0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of rR4)J?.addEventListener(Y,Q);for(let Y of sR4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of rR4)J?.removeEventListener(Y,Q);for(let Y of sR4)Z?.removeEventListener(Y,Q)}}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},HQ3)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},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}}D$();var $P4="dtw-parse-error",KK9=v.object({kind:v.literal($P4),failureType:v.enum(iR4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),VK9=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function BQ3(J){return{kind:$P4,failureType:J.failureType??null,source:J.source??null,direction:J.direction??null,stage:J.stage??null,summary:J.summary??null,messageType:J.messageType??null,typePreview:J.typePreview??null,payloadPreview:J.payloadPreview??null,issues:J.issues??[]}}function NQ3(J){let Z=BQ3(J);return JSON.stringify(Z)}function JP4(J,Z){let Q=oR4(J,Z);return NQ3({failureType:Q.failureType,source:"dtw-transport",direction:"server->client",stage:"decode-server-message",summary:Q.summary,messageType:Q.messageType,typePreview:Q.typePreview,payloadPreview:Q.payloadPreview,issues:Q.issues})}var wQ3=3000,LQ3=30000,OQ3=5,EQ3="T-00000000-0000-0000-0000-000000000000";function ZP4(J){if(J instanceof LJ)return J;if(J instanceof Error){let Z=J.message||"Unknown thread-client connection error";return new LJ(Z,J)}if(typeof J==="string"&&J.length>0)return new LJ(J,J);return new LJ("Unknown thread-client connection error",J)}function MQ3(J){let Z=atob(J),Q=new Uint8Array(Z.length);for(let Y=0;Y<Z.length;Y++)Q[Y]=Z.charCodeAt(Y);return Q}function Xo0(J,Z){return{...J,pendingOptimisticUserMessages:Z}}function QP4(){return{latestAgentLoopState:null,pendingOptimisticUserMessages:new Map}}function AQ3(J,Z){if(J.latestAgentLoopState===Z)return J;return{...J,latestAgentLoopState:Z}}function jQ3(J){if(J.latestAgentLoopState===null||J.latestAgentLoopState==="idle")return"message_added";return"queued_message_added"}function IQ3(J,Z,Q){if(Z==="message_added")return{type:"message_added",message:{type:"message_added",message:{role:"user",messageId:J.messageId,content:J.content,agentMode:J.agentMode,threadId:Q??EQ3},seq:0}};return{type:"queued_message_added",message:{type:"queued_message_added",message:{interrupt:!1,queuedMessage:{role:"user",messageId:J.messageId,content:J.content,userState:J.userState}},seq:0}}}function RQ3(J,Z,Q){let Y=new Map(J.pendingOptimisticUserMessages);return Y.set(Z,Q),Xo0(J,Y)}function Yo0(J,Z){if(!J.pendingOptimisticUserMessages.has(Z))return J;let Q=new Map(J.pendingOptimisticUserMessages);return Q.delete(Z),Xo0(J,Q)}function PQ3(J,Z){let Q=J.pendingOptimisticUserMessages.get(Z);if(!Q)return{state:J,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:null};let Y=Yo0(J,Z);if(Q==="message_added")return{state:Y,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:null};return{state:Y,suppressMessageAdded:!1,syntheticQueuedMessageRemoved:{type:"queued_message_removed",queuedMessageId:Z,seq:0}}}function YP4(J,Z){let Q=J.pendingOptimisticUserMessages.get(Z);if(Q==="queued_message_added")return{state:J,suppressQueuedMessageAdded:!0};if(Q!=="message_added")return{state:J,suppressQueuedMessageAdded:!1};let Y=new Map(J.pendingOptimisticUserMessages);return Y.set(Z,"queued_message_added"),{state:Xo0(J,Y),suppressQueuedMessageAdded:!1}}function CQ3(J,Z){let Q=J;for(let Y of Z)Q=YP4(Q,Y).state;return Q}function _Q3(J,Z){let Q=new Set(Z.map((Y)=>Y.queuedMessage.messageId));for(let[Y,X]of J.pendingOptimisticUserMessages){if(X!=="queued_message_added")continue;if(!Q.has(Y))return!0}return!1}function TQ3(J,Z,Q){let Y=jQ3(J);return{state:RQ3(J,Z.messageId,Y),event:IQ3(Z,Y,Q)}}function SQ3(J){return{type:"error",message:`Failed to send user message: ${J}`,code:"MESSAGE_ERROR"}}class Tq extends Qo0{ensureConnectedPromise=null;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;pendingThreadSettings=null;outboundUserMessages=[];pendingCancelAgentLoop=!1;pendingDismissActiveError=null;optimisticReconciliationState=QP4();fileSystemRequestCounter=0;observerCallbacks=null;executorCallbacks=null;pendingObserverDispatches=[];pendingExecutorDispatches=[];resumeCursor=$o0(0);threadHistoryLoader;executorConnectedListeners=new Set;executorErrorListeners=new Set;environmentSubject=new P4(null);threadIDSubscription;constructor(J){super(J.transport);if(this.threadHistoryLoader=J.threadHistoryLoader,this.threadIDSubscription=this.threadIDSubject.subscribe((Z)=>{if(Z!==null)this.dispatchObserverCallbacks((Q)=>{Q.onThreadId?.(Z)})}),J.observerCallbacks)this.setObserverCallbacks(J.observerCallbacks);if(J.executorCallbacks)this.setExecutorCallbacks(J.executorCallbacks)}setObserverCallbacks(J){if(this.observerCallbacks&&this.observerCallbacks!==J)throw Error("Observer callbacks are already set and cannot be replaced");if(this.observerCallbacks===J)return;if(this.observerCallbacks=J,this.pendingObserverDispatches.length===0)return;for(let Z of this.pendingObserverDispatches)Z(J);this.pendingObserverDispatches.length=0}setExecutorCallbacks(J){if(this.executorCallbacks&&this.executorCallbacks!==J)throw Error("Executor callbacks are already set and cannot be replaced");if(this.executorCallbacks===J)return;if(this.executorCallbacks=J,this.pendingExecutorDispatches.length===0)return;for(let Z of this.pendingExecutorDispatches)Z(J);this.pendingExecutorDispatches.length=0}async connect(){try{await super.connect()}catch(J){throw ZP4(J)}}async ensureConnected(J){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(J);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(J){let Z=J?.baseDelayMs??wQ3,Q=J?.maxDelayMs??LQ3,Y=J?.maxAttempts??OQ3;if(J?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let X=0;X<Y;X++){try{await this.connect()}catch(F){let z=ZP4(F);if(this.getConnectionInfo().state!=="reconnecting")throw z;J?.onRetryableConnectError?.(z)}let K=J?.waitForConnectedTimeoutMs??Math.min(Z*2**X,Q);if(await this.waitForConnected(K))return!0;let G=X+1<Y?Math.min(Z*2**(X+1),Q):null;J?.onAttemptTimeout?.({attempt:X+1,maxAttempts:Y,nextDelayMs:G})}return!1}async loadThreadHistory(J){let Z=await this.threadHistoryLoader(J);if(!Z)return null;let Q=Z.title;if(Q!==void 0)this.dispatchObserverCallbacks((Y)=>{Y.onThreadTitle?.({type:"thread_title",title:Q})});for(let[Y,X]of Z.messages.entries())this.dispatchObserverCallbacks((K)=>{K.onMessageAdded?.({type:"message_added",message:X,seq:Y})});return Z}getResumeVersion(){return this.resumeCursor.getVersion()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??FX0(),X={type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState},K=TQ3(this.optimisticReconciliationState,X,this.getThreadId());if(this.optimisticReconciliationState=K.state,this.emitOptimisticUserMessage(K.event),this.trySendMessage(X))return Y;return this.outboundUserMessages.push(X),Y}removeQueuedMessage(J){this.send({type:"client_remove_queued_msg",queuedMessageId:J})}interruptQueuedMessage(J){this.send({type:"client_interrupt_queued_msg",queuedMessageId:J})}editUserMessage(J,Z,Q,Y){this.send({type:"client_edit_message",messageId:J,editId:Q,content:Z,agentMode:Y})}markMessageRead(J){this.send({type:"client_mark_message_read",messageId:J})}markMessageUnread(J){this.send({type:"client_mark_message_unread",messageId:J})}setThreadTitle(J){this.send({type:"client_set_thread_title",title:J})}upsertNotificationSubscription(J,Z){this.send({type:"client_upsert_notification_subscription",subscription:J,threadURL:Z})}readDirectory(J){return this.requestReadDirectory(J)}readFile(J){return this.requestReadFile(J)}resumeFromVersion(J){this.send({type:"client_resume",version:J}),this.resumeCursor.reset(J)}retryAgentLoop(){this.send({type:"client_retry"})}dismissActiveError(J){let Z=J===void 0?{}:{seq:J};if(!this.hasOpenSocket()){this.pendingDismissActiveError=Z;return}this.pendingDismissActiveError=null,this.send({type:"client_dismiss_active_error",...Z})}cancelAgentLoop(){if(!this.hasOpenSocket()){this.pendingCancelAgentLoop=!0;return}this.pendingCancelAgentLoop=!1,this.send({type:"client_cancel"})}appendManualBashInvocation(J){this.send({type:"client_append_manual_bash_invocation",args:J.args,run:J.run,hidden:J.hidden})}resolveToolApproval(J,Z,Q){this.send({type:"client_tool_approval_response",toolCallId:J,accepted:Z,input:Q})}requestExecutorSpawn(J,Z){this.send({type:"client_spawn_executor",requestId:J,repositoryURL:Z?.repositoryURL,projectID:Z?.projectID,additionalRepositories:Z?.additionalRepositories})}executePluginCommand(J,Z,Q,Y){this.sendPluginMessage({type:"request",id:J,method:"command.execute",params:{pluginName:Z,commandId:Q,threadID:Y}})}executorHandshake(J,Z,Q){if(this.disposed)throw new N9("Transport is disposed");if(!this.hasOpenSocket())throw new N9("WebSocket is not connected. Call connect() first.");let Y=performance.now(),X=60000,K={clientId:J,threadId:this.getThreadId(),executorType:Q?.executorType,timeoutMs:X};return S.info("[thread-client] Starting executor handshake",{...K,connectionState:this.getConnectionInfo().state}),new Promise((V,G)=>{let F=!1,z=null,q=null,W=()=>Math.round(performance.now()-Y),H=(N,w,L)=>{let O=this.getConnectionInfo();S.error(N,{...K,durationMs:W(),connectionState:O.state,role:O.role,reconnectCauseType:O.reconnectCause?.type,reconnectCode:O.reconnectCause?.code,reconnectReason:O.reconnectCause?.reason,error:w,...L})},U=(N)=>{S.info("[thread-client] Executor handshake completed",{...K,durationMs:W(),executorId:N.executorId,registeredToolCount:N.registeredToolCount,resumeBootstrap:N.resumeBootstrap}),B(()=>V(N))},D=(N)=>{let w=Error(N.message);H("[thread-client] Executor handshake rejected by server",w,{code:N.code}),B(()=>G(w))},B=(N)=>{if(F)return;if(F=!0,z)clearTimeout(z),z=null;this.executorConnectedListeners.delete(U),this.executorErrorListeners.delete(D),q?.unsubscribe(),N()};this.executorConnectedListeners.add(U),this.executorErrorListeners.add(D),q=this.connectionChanges().subscribe({next:(N)=>{if(N.state==="connected")return;let w=new N9(N.state==="reconnecting"?"Executor handshake interrupted by reconnect":"Executor handshake interrupted by disconnect");H("[thread-client] Executor handshake interrupted",w),B(()=>G(w))}}),this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),z=setTimeout(()=>{let N=Error("Executor connect timeout");H("[thread-client] Executor handshake timed out",N),B(()=>G(N))},X)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=UX0(Z,"snapshot");this.send({type:"tool_progress",toolCallId:J,progress:Q})}sendExecutorToolResult(J,Z){this.send({type:"executor_tool_result",toolCallId:J,run:Z})}sendExecutorFileSystemReadDirectoryResult(J,Z){this.send({type:"executor_filesystem_read_directory_result",requestId:J,...Z})}sendExecutorFileSystemReadFileResult(J,Z){this.send({type:"executor_filesystem_read_file_result",requestId:J,...Z})}sendExecutorToolApprovalRequest(J){this.send({type:"executor_tool_approval_request",approval:J})}sendPluginMessage(J){this.send({type:"executor_plugin_message",message:J})}sendExecutorGuidanceSnapshot(J){this.send({type:"executor_guidance_snapshot",...J})}sendExecutorGuidanceDiscovery(J){this.send({type:"executor_guidance_discovery",...J})}sendExecutorSkillSnapshot(J){this.send({type:"executor_skill_snapshot",...J})}sendClientUpdateThreadSettings(J){if(!this.hasOpenSocket()){this.pendingThreadSettings=J;return}try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:J})}catch(Z){if(!this.hasOpenSocket()){this.pendingThreadSettings=J;return}throw Z}}sendExecutorRollbackAck(J,Z,Q){this.send({type:"executor_rollback_ack",editId:J,ok:Z,error:Q})}registerTools(J){this.send({type:"executor_tools_register",tools:J})}sendExecutorToolsBootstrapComplete(J,Z){this.send({type:"executor_tools_bootstrap_complete",ok:J,error:Z})}sendEnvironmentSnapshot(J){this.send({type:"executor_environment_snapshot",environment:J}),this.environmentSubject.next(J)}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J}),this.environmentSubject.next(J)}environmentChanges(){return this.environmentSubject}getEnvironmentSnapshot(){return this.environmentSubject.getValue()}sendExecutorArtifactUpsert(J,Z){this.send({type:"executor_artifact_upsert",artifact:J,toolCallId:Z})}sendExecutorArtifactDelete(J){this.send({type:"executor_artifact_delete",key:J})}unregisterTools(J){this.send({type:"executor_tools_unregister",toolNames:J})}dispose(){if(this.disposed)return;super.dispose(),this.threadIDSubscription.unsubscribe(),this.pendingThreadSettings=null,this.outboundUserMessages.length=0,this.pendingCancelAgentLoop=!1,this.pendingDismissActiveError=null,this.optimisticReconciliationState=QP4(),this.pendingObserverDispatches.length=0,this.pendingExecutorDispatches.length=0,this.resumeCursor=$o0(0),this.environmentSubject.complete(),this.rejectPendingFileSystemRequests("Transport disposed")}updateConnectionState(J){if(super.updateConnectionState(J),J==="connected")this.flushPendingThreadSettings(),this.flushOutboundUserMessages(),this.flushPendingCancelAgentLoop(),this.flushPendingDismissActiveError();if(this.emitConnectionChanged(),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}onRawMessage(J){let Z=cR4.safeDecode(J);if(!Z.success){let Y=dR4.safeDecode(J),X=Y.success?Z.error:Y.error,K={type:"error",message:JP4(J,X),code:"PARSE_ERROR"};this.dispatchObserverCallbacks((V)=>{V.onErrorNotice?.(K)});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}onMaxReconnectExceeded(J){this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})})}handleServerMessage(J){switch(this.advanceResumeCursor(J),J.type){case"agent_state":this.optimisticReconciliationState=AQ3(this.optimisticReconciliationState,J.state),this.dispatchObserverCallbacks((Z)=>{Z.onAgentState?.(J)});break;case"thread_settings":this.dispatchObserverCallbacks((Z)=>{Z.onThreadSettings?.(J)});break;case"error":this.dispatchObserverCallbacks((Z)=>{Z.onErrorNotice?.(J)});break;case"error_set":case"error_cleared":this.dispatchObserverCallbacks((Z)=>{Z.onActiveError?.(J)});break;case"cancelled":this.dispatchObserverCallbacks((Z)=>{Z.onCancelled?.(J)});break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.dispatchObserverCallbacks((Z)=>{Z.onRetryEvent?.(J)});break;case"delta":this.dispatchObserverCallbacks((Z)=>{Z.onDelta?.(J)});break;case"message_added":{let Z=PQ3(this.optimisticReconciliationState,J.message.messageId);if(this.optimisticReconciliationState=Z.state,Z.suppressMessageAdded)break;let Q=Z.syntheticQueuedMessageRemoved;if(Q)this.dispatchObserverCallbacks((Y)=>{Y.onQueuedMessages?.(Q)});this.dispatchObserverCallbacks((Y)=>{Y.onMessageAdded?.(J)});break}case"edit_rejected":this.dispatchObserverCallbacks((Z)=>{Z.onEditRejected?.(J)});break;case"message_edited":this.dispatchObserverCallbacks((Z)=>{Z.onMessageEdited?.(J)});break;case"queued_messages":if(this.optimisticReconciliationState=CQ3(this.optimisticReconciliationState,J.messages.map((Z)=>Z.queuedMessage.messageId)),_Q3(this.optimisticReconciliationState,J.messages))break;this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J)});break;case"queued_message_added":{let Z=YP4(this.optimisticReconciliationState,J.message.queuedMessage.messageId);if(this.optimisticReconciliationState=Z.state,Z.suppressQueuedMessageAdded)break;this.dispatchObserverCallbacks((Q)=>{Q.onQueuedMessages?.(J)});break}case"queued_message_removed":this.optimisticReconciliationState=Yo0(this.optimisticReconciliationState,J.queuedMessageId),this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J)});break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.emitConnectionChanged(),this.dispatchObserverCallbacks((Z)=>{Z.onExecutorConnected?.(J)});for(let Z of this.executorConnectedListeners)Z(J);break;case"tool_lease":this.dispatchExecutorCallbacks((Z)=>{Z.onToolLease?.(J)});break;case"executor_filesystem_read_directory":this.dispatchExecutorCallbacks((Z)=>{Z.onFileSystemReadDirectoryRequest?.(J)});break;case"executor_filesystem_read_file":this.dispatchExecutorCallbacks((Z)=>{Z.onFileSystemReadFileRequest?.(J)});break;case"executor_rollback_request":this.dispatchExecutorCallbacks((Z)=>{Z.onExecutorRollbackRequest?.(J)});break;case"executor_tool_lease_revoked":this.dispatchExecutorCallbacks((Z)=>{Z.onToolLeaseRevoked?.(J)});break;case"tool_approval_queue":this.dispatchObserverCallbacks((Z)=>{Z.onToolApprovalQueue?.(J)});break;case"plugin_message":this.dispatchObserverCallbacks((Z)=>{Z.onPluginMessage?.(J)});break;case"executor_tool_approval_response":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorToolApprovalResponse?.(J)});break;case"tool_progress":this.dispatchObserverCallbacks((Z)=>{Z.onToolProgress?.(J)});break;case"executor_error":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorError?.(J)});for(let Z of this.executorErrorListeners)Z(J);break;case"observers":this.dispatchObserverCallbacks((Z)=>{Z.onObservers?.(J)});break;case"executor_status":this.dispatchObserverCallbacks((Z)=>{Z.onExecutorStatus?.(J)});break;case"environment_update":this.environmentSubject.next(J.environment),this.dispatchObserverCallbacks((Z)=>{Z.onEnvironmentUpdate?.(J)});break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.dispatchObserverCallbacks((Z)=>{Z.onArtifactEvent?.(J)});break;case"thread_title":this.dispatchObserverCallbacks((Z)=>{Z.onThreadTitle?.(J)});break;case"thread_relationships":this.dispatchObserverCallbacks((Z)=>{Z.onThreadRelationships?.(J)});break;case"client_filesystem_read_directory_result":this.handleReadDirectoryResult(J);break;case"client_filesystem_read_file_result":this.handleReadFileResult(J);break;case"compaction_started":case"compaction_complete":case"compaction_records":this.dispatchObserverCallbacks((Z)=>{Z.onCompactionEvent?.(J)});break;case"thread_status":break}}flushOutboundUserMessages(){while(this.outboundUserMessages.length>0){let J=this.outboundUserMessages[0];if(!J)return;if(!this.trySendMessage(J))return;this.outboundUserMessages.shift()}}flushPendingThreadSettings(){if(!this.pendingThreadSettings||!this.hasOpenSocket())return;let J=this.pendingThreadSettings;try{this.pendingThreadSettings=null,this.send({type:"client_update_thread_settings",settings:J})}catch{if(!this.hasOpenSocket())this.pendingThreadSettings=J}}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}}trySendMessage(J){if(!this.hasOpenSocket())return!1;try{return this.send(J),!0}catch(Z){if(!this.hasOpenSocket())return!1;this.optimisticReconciliationState=Yo0(this.optimisticReconciliationState,J.messageId);let Q=Z instanceof Error?Z.message:String(Z);return this.dispatchObserverCallbacks((Y)=>{Y.onErrorNotice?.(SQ3(Q))}),!0}}emitConnectionChanged(){let J=this.getConnectionInfo();S.info("[thread-client] Emitting connection change callbacks",{state:J.state,role:J.role,clientId:J.clientId,reconnectCauseType:J.reconnectCause?.type,reconnectCode:J.reconnectCause?.code,reconnectReason:J.reconnectCause?.reason,hasExecutorCallbacks:this.executorCallbacks!==null,hasObserverCallbacks:this.observerCallbacks!==null,pendingExecutorDispatches:this.pendingExecutorDispatches.length,pendingObserverDispatches:this.pendingObserverDispatches.length}),this.dispatchExecutorCallbacks((Z)=>{Z.onConnectionChange?.(J)}),this.dispatchObserverCallbacks((Z)=>{Z.onConnectionChanged?.(J)})}emitOptimisticUserMessage(J){if(J.type==="message_added")this.dispatchObserverCallbacks((Z)=>{Z.onMessageAdded?.(J.message)});else this.dispatchObserverCallbacks((Z)=>{Z.onQueuedMessages?.(J.message)})}dispatchObserverCallbacks(J){let Z=this.observerCallbacks;if(!Z){this.pendingObserverDispatches.push(J);return}J(Z)}dispatchExecutorCallbacks(J){let Z=this.executorCallbacks;if(!Z){this.pendingExecutorDispatches.push(J);return}J(Z)}requestReadDirectory(J){let Z=this.nextFileSystemRequestID("read-directory");return this.createPendingReadRequest(this.pendingReadDirectoryRequests,Z,()=>{this.send({type:"client_filesystem_read_directory",requestId:Z,uri:J})})}requestReadFile(J){let Z=this.nextFileSystemRequestID("read-file");return this.createPendingReadRequest(this.pendingReadFileRequests,Z,()=>{this.send({type:"client_filesystem_read_file",requestId:Z,uri:J})})}createPendingReadRequest(J,Z,Q){if(!this.hasOpenSocket())return Promise.reject(new N9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new N9(`Filesystem request timed out: ${Z}`))},yR4);J.set(Z,{resolve:Y,reject:X,timeoutID:K});try{Q()}catch(V){clearTimeout(K),J.delete(Z),X(V instanceof Error?V:Error(String(V)))}})}nextFileSystemRequestID(J){let Z=this.fileSystemRequestCounter++;return`${J}-${Date.now()}-${Z}`}handleReadDirectoryResult(J){let Z=this.pendingReadDirectoryRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadDirectoryRequests.delete(J.requestId),J.ok&&J.entries){Z.resolve(J.entries);return}if(J.ok){Z.reject(Error("Invalid filesystem read_directory response: missing entries"));return}if(!J.error){Z.reject(Error("Invalid filesystem read_directory response: missing error"));return}Z.reject(this.createFileSystemError(J.error))}handleReadFileResult(J){let Z=this.pendingReadFileRequests.get(J.requestId);if(!Z)return;if(clearTimeout(Z.timeoutID),this.pendingReadFileRequests.delete(J.requestId),!J.ok&&J.error){Z.reject(this.createFileSystemError(J.error));return}if(!J.ok){Z.reject(Error("Invalid filesystem read_file response: missing error"));return}if(J.contentBase64===void 0){Z.reject(Error("Invalid filesystem read_file response: missing content"));return}try{Z.resolve(MQ3(J.contentBase64))}catch{Z.reject(Error("Invalid base64 payload in filesystem read_file response"))}}createFileSystemError(J){return Error(`Filesystem error (${J.code}): ${J.message}`)}rejectPendingFileSystemRequests(J){for(let[Z,Q]of this.pendingReadDirectoryRequests)clearTimeout(Q.timeoutID),Q.reject(new N9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new N9(J)),this.pendingReadFileRequests.delete(Z)}advanceResumeCursor(J){let Z=J.seq;if(typeof Z!=="number"||!Number.isFinite(Z))return;this.resumeCursor.advanceFromSeq(Z)}send(J){try{this.sendRaw(pR4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new N9(`Failed to encode thread-protocol message "${J.type}": ${Q}`,Z)}}}function uv(J,Z){let Q=Z;return async()=>{let Y=await J(Q);return Q=Y.threadId,Y}}function bv(J){let Z=Lv({endpoint:J.rivetEndpoint});return{...J.initialThreadID?{threadId:J.initialThreadID}:{},...J.maxReconnectAttempts!==void 0?{maxReconnectAttempts:J.maxReconnectAttempts}:{},pingIntervalMs:J.pingIntervalMs??5000,webSocketProvider:async()=>{let Q=await J.credentialsProvider({forceRefresh:!0});return{webSocket:await Z.threadActor.getOrCreate([Q.threadId],{params:{wsToken:Q.wsToken},createWithInput:{threadId:Q.threadId,threadVersion:Q.threadVersion,ownerUserId:Q.ownerUserId,...Q.agentMode?{agentMode:Q.agentMode}:{}}}).webSocket("/"),threadId:Q.threadId}}}}s4();function BX0(J){return{version:J.v,title:J.title??null,messages:J.messages.map((Z)=>kQ3(J,Z)),agentMode:J.agentMode||x40(J)}}function kQ3(J,Z){let Q=vQ3(Z);switch(Z.role){case"user":return{threadId:J.id,role:"user",content:[...Z.content],meta:du1(Z.meta),userState:yQ3(Z.userState),readAt:Z.readAt,messageId:Q};case"assistant":return{threadId:J.id,role:"assistant",content:[...Z.content],state:Z.state?.type==="cancelled"?{type:"cancelled"}:void 0,usage:Z.usage,readAt:Z.readAt,messageId:Q};case"info":return{threadId:J.id,role:"info",content:Z.content.filter(xQ3),messageId:Q}}}function vQ3(J){let Z=XP4(J.protocolMessageID);if(Z)return Z;let Q=J.messageId;if(typeof Q==="string"){let Y=XP4(Q);if(Y)return Y}return FX0()}function XP4(J){if(!J)return null;let Z=B3.safeParse(J);return Z.success?Z.data:null}function yQ3(J){if(!J)return;return{...J,currentlyVisibleFiles:[...J.currentlyVisibleFiles],runningTerminalCommands:J.runningTerminalCommands?[...J.runningTerminalCommands]:void 0,aggmanContext:J.aggmanContext?{...J.aggmanContext,availableProjects:J.aggmanContext.availableProjects?J.aggmanContext.availableProjects.map((Z)=>({...Z})):void 0,recentUnreadThreads:J.aggmanContext.recentUnreadThreads?J.aggmanContext.recentUnreadThreads.map((Z)=>({...Z})):void 0}:void 0}}function xQ3(J){return J.type==="manual_bash_invocation"}YJ();D4();import Bn from"node:path";class sj extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function VP4(J,Z){let Q=K1.parse(J);if(Q.scheme!=="file")throw new sj("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new sj("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((F)=>F===".."))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");let X=Bn.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");let K=Bn.resolve(Z),V=X.length>0?Bn.resolve(K,X):K,G=Bn.relative(K,V);if(G.startsWith("..")||Bn.isAbsolute(G))throw new sj("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function cw(J,Z){try{let Q=VP4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(K1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",G=V==="file"?await fQ3(J.fileSystem,K.uri):void 0;return[F1.basename(K.uri),V,G]}))}}catch(Q){return{ok:!1,error:FP4(Q,"read_directory")}}}async function fQ3(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function GP4(J,Z){try{let Q=VP4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(K1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:FP4(Q,"read_file")}}}function FP4(J,Z){if(J instanceof sj)return{code:J.code,message:J.message};if(W9(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(NX0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(NX0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":KP4(J)};if(NX0(J,"EACCES")||NX0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:KP4(J)}}function NX0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function KP4(J){if(J instanceof Error)return J.message;return String(J)}a0();j3();s4();D4();I1();import{exec as uQ3}from"node:child_process";import{promisify as bQ3}from"node:util";tA();s4();D4();var hQ3=bQ3(uQ3);async function zP4(J){let Z=await qU(),Q=sZ(J)?J:I7(),Y=await bm0({filesystem:q8},Z,Q),X=await gQ3(Y.workingDirectory??Y.workspaceRoot);return{...Z,...Y,...X?{git:{branch:X}}:{},updatedAt:new Date().toISOString()}}async function gQ3(J){if(!J)return;let Z;try{Z=K1.parse(J).fsPath}catch{return}try{let{stdout:Q}=await hQ3("git symbolic-ref --quiet --short HEAD",{cwd:Z});return Q.trim()||void 0}catch{return}}function mQ3(J){return new TextEncoder().encode(JSON.stringify(J)).length}function hv(J,Z,Q){if(J.length===0)return[];let Y=[],X=[];for(let K of J){let V=[...X,K],G=mQ3(Q(V));if(X.length>0&&G>Z){Y.push(X),X=[K];continue}X=V}if(X.length>0)Y.push(X);return Y}var WP4=1048576;function qP4(J){let Z=new Map;for(let Q of J)Z.set(Q.name,{schema:Q,serializedSchema:JSON.stringify(Q)});return Z}function pQ3(J){let Z={...J.executionProfile?.serial!==void 0?{serial:J.executionProfile.serial}:{},...J.meta?.deferred!==void 0?{deferred:J.meta.deferred}:{},...J.meta?.skillNames!==void 0?{skillNames:[...J.meta.skillNames]}:{}};return Object.keys(Z).length>0?Z:void 0}function dQ3(J){return{name:J.name,description:J.description??"",inputSchema:{type:"object",properties:J.inputSchema.properties??{},required:J.inputSchema.required,additionalProperties:J.inputSchema.additionalProperties},source:J.source,meta:pQ3(J)}}function wX0(J){return J.map((Z)=>dQ3(Z.spec))}function HP4(J,Z){let Q=qP4(J),Y=qP4(Z);return{toolsToRegister:Z.filter((X)=>{let K=Q.get(X.name),V=Y.get(X.name);return K?.serializedSchema!==V?.serializedSchema}),toolNamesToUnregister:[...Q.keys()].filter((X)=>!Y.has(X))}}function UP4(J,Z=WP4){return hv(J,Z,(Q)=>({type:"executor_tools_register",tools:Q}))}function DP4(J,Z=WP4){return hv(J,Z,(Q)=>({type:"executor_tools_unregister",toolNames:Q}))}import{execFile as aQ3}from"node:child_process";import{createHash as oQ3}from"node:crypto";import{readFile as rQ3,stat as sQ3}from"node:fs/promises";import{basename as tQ3,join as eQ3}from"node:path";import AP4 from"node:process";import{promisify as $Y3}from"node:util";async function BP4(J,Z,Q){let Y=[];for(let X=0;X<J.length;X+=Z){let K=J.slice(X,X+Z);Y.push(...await Promise.all(K.map(Q)))}return Y}var NP4=2097152,lw="(Content omitted — git status artifact exceeds size limit)";function cQ3(J){return(J.fullFileDiff?.length??0)+(J.oldContent?.length??0)+(J.newContent?.length??0)}function lQ3(J){let Z=!1;if(J.fullFileDiff!==void 0&&J.fullFileDiff!==J.diff)J.fullFileDiff=J.diff,Z=!0;if(J.oldContent!==void 0&&J.oldContent!==lw)J.oldContent=lw,Z=!0;if(J.newContent!==void 0&&J.newContent!==lw)J.newContent=lw,Z=!0;return Z}function iQ3(J){let Z=!1;if(J.oldContent!==void 0)J.oldContent=void 0,Z=!0;if(J.newContent!==void 0)J.newContent=void 0,Z=!0;if(J.fullFileDiff!==void 0)J.fullFileDiff=void 0,Z=!0;return Z}function nQ3(J){let Z=!1;if(J.diff!==lw)J.diff=lw,Z=!0;if(J.fullFileDiff!==void 0&&J.fullFileDiff!==lw)J.fullFileDiff=lw,Z=!0;return Z}function gv(J){let Z=Buffer.from(JSON.stringify(J),"utf8").toString("base64"),Q=new TextEncoder().encode(JSON.stringify({type:"executor_artifact_upsert",artifact:{key:Lk,dataType:"application/json",contentBase64:Z}})).length;return{contentBase64:Z,messageSizeBytes:Q}}function wP4(J,Z){let Q={...J,aheadCommits:[...J.aheadCommits],files:J.files.map((V)=>({...V}))},Y=gv(Q);if(Y.messageSizeBytes<=Z)return Y.contentBase64;let X=Q.files.map((V,G)=>({index:G,weight:cQ3(V)})).filter((V)=>V.weight>0).sort((V,G)=>G.weight-V.weight);for(let{index:V}of X){let G=Q.files[V];if(!G||!lQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}for(let{index:V}of X){let G=Q.files[V];if(!G||!iQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}let K=Q.files.map((V,G)=>({index:G,weight:V.diff.length+(V.fullFileDiff?.length??0)})).filter((V)=>V.weight>0).sort((V,G)=>G.weight-V.weight);for(let{index:V}of K){let G=Q.files[V];if(!G||!nQ3(G))continue;if(Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}if(Q.aheadCommits.length>0){if(Q.aheadCommits=[],Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64}while(Q.files.length>0)if(Q.files.pop(),Y=gv(Q),Y.messageSizeBytes<=Z)return Y.contentBase64;return Y.contentBase64}var JY3=$Y3(aQ3),pv=20971520,ZY3=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],LX0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],QY3=999999,LP4="refs/remotes/origin/",YY3=20,XY3=10;function OX0(J){return J.replace(/\n+$/,"")}var Ko0=AP4.platform==="win32"?"NUL":"/dev/null";function KY3(J=AP4.env,Z={}){let{isolateGitConfig:Q=!0}=Z,Y={...J};if(Q){for(let X of Object.keys(Y))if(ZY3.includes(X)||X.startsWith("GIT_CONFIG_KEY_")||X.startsWith("GIT_CONFIG_VALUE_"))delete Y[X];Y.GIT_CONFIG_NOSYSTEM="1",Y.GIT_CONFIG_SYSTEM=Ko0,Y.GIT_CONFIG_GLOBAL=Ko0}return Y}function OP4(J,Z){return{provider:"git",capturedAt:J,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Z}}function VY3(J){return J instanceof Error}async function mv(J,Z,Q={}){try{let{stdout:Y}=await JY3("git",Z,{cwd:J,env:KY3(),maxBuffer:Q.maxBufferBytes??pv});return Y}catch(Y){if(Q?.allowExitCodeOne&&VY3(Y)&&(Y.code===1||Y.code==="1")&&typeof Y.stdout==="string")return Y.stdout;throw Y}}async function CU(J,Z){try{return await mv(J,Z)}catch{return null}}function GY3(J){if(J==="??")return"untracked";let Z=J[0]??" ",Q=J[1]??" ";if(Z==="U"||Q==="U"||J==="AA"||J==="DD")return"unmerged";if(Z==="R"||Q==="R")return"renamed";if(Z==="C"||Q==="C")return"copied";if(Z==="A"||Q==="A")return"added";if(Z==="D"||Q==="D")return"deleted";if(Z==="T"||Q==="T")return"type_changed";return"modified"}function Vo0(J){let Z=[],Q=J.split("\x00");for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X||X.length<4)continue;let K=X.slice(0,2),V=X.slice(3);if(!V)continue;let G=GY3(K);if(G==="renamed"||G==="copied"){let F=Q[Y+1];if(F){Z.push({path:V,previousPath:F,changeType:G}),Y+=1;continue}}Z.push({path:V,changeType:G})}return Z.sort((Y,X)=>Y.path.localeCompare(X.path))}function FY3(J){let Z=0,Q=0,Y=0,X=0,K=0,V=()=>{if(X===0&&K===0)return;Y+=Math.min(X,K),X=0,K=0};for(let G of J.split(`
|
|
4286
4286
|
`)){if(G.startsWith("+")&&!G.startsWith("+++")){Z+=1,X+=1;continue}if(G.startsWith("-")&&!G.startsWith("---")){Q+=1,K+=1;continue}V()}return V(),{added:Z,deleted:Q,changed:Y}}function zY3(J){let Z=oQ3("sha256");for(let Q of J)Z.update(Q.path),Z.update("\x00"),Z.update(Q.diff),Z.update("\x00");return Z.digest("hex")}async function EP4(J,Z,Q,Y,X=pv){let K=Y!==void 0?[`--unified=${Y}`]:[];if(Q)return mv(J,[...LX0,...K,"HEAD","--",Z],{maxBufferBytes:X});let[V,G]=await Promise.all([mv(J,[...LX0,...K,"--cached","--",Z],{maxBufferBytes:X}).catch(()=>""),mv(J,[...LX0,...K,"--",Z],{maxBufferBytes:X}).catch(()=>"")]);return[OX0(V),OX0(G)].filter(Boolean).join(`
|
|
4287
4287
|
`)}async function qY3(J,Z,Q=pv){return mv(J,[...LX0,"--no-index","--",Ko0,Z],{allowExitCodeOne:!0,maxBufferBytes:Q})}async function WY3(J,Z,Q,Y=pv){let X=Q??"HEAD";try{return await mv(J,["show",`${X}:${Z}`],{maxBufferBytes:Y})}catch{return}}async function HY3(J,Z,Q=pv){try{let Y=eQ3(J,Z);if((await sQ3(Y)).size>Q)return;return await rQ3(Y,"utf-8")}catch{return}}function MP4(J){let Z=Number.parseInt(J.trim(),10);if(!Number.isFinite(Z))return null;return Z}async function UY3(J){let Z=(await CU(J,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Z?.startsWith(LP4))return null;let Q=Z.slice(LP4.length);if(!Q)return null;let Y=`origin/${Q}`,K=(await CU(J,["rev-parse","--verify","--quiet",`${Y}^{commit}`]))?.trim();if(!K)return null;return{baseRef:Q,comparisonRef:Y,baseRefHead:K}}function DY3(J){let Z=J.split("\x00"),Q=[];for(let Y=0;Y+1<Z.length;Y+=2){let X=Z[Y],K=Z[Y+1]??"";if(!X)continue;Q.push({hash:X,shortHash:X.slice(0,12),subject:K})}return Q}async function BY3(J,Z){let Q=await CU(J,["log","-z",`--max-count=${YY3}`,"--format=%H%x00%s",`${Z}..HEAD`]);if(!Q)return[];return DY3(Q)}async function NY3(J,Z){if(!Z)return null;let Q=await UY3(J);if(!Q)return null;let Y=await CU(J,["rev-list","--count",`${Q.comparisonRef}..HEAD`]);if(!Y)return null;let X=await CU(J,["rev-list","--count",`HEAD..${Q.comparisonRef}`]);if(!X)return null;let K=MP4(Y);if(K===null)return null;let V=MP4(X);if(V===null)return null;return{baseRef:Q.baseRef,comparisonRef:Q.comparisonRef,baseRefHead:Q.baseRefHead,aheadCount:K,behindCount:V}}async function EX0(J,Z={}){let{maxDiffBufferBytes:Q=pv}=Z,Y=Date.now(),X=await CU(J,["rev-parse","--show-toplevel"]);if(!X)return OP4(Y,"not a git repository");let K=X.trim(),V=tQ3(K),[G,F,z]=await Promise.all([CU(K,["rev-parse","--verify","HEAD"]),CU(K,["symbolic-ref","--short","HEAD"]),CU(K,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(z===null)return OP4(Y,"failed to read git status");let q=G?.trim()||null,W=F?.trim()||null,H=Vo0(z),U=await NY3(K,q),D=U?.aheadCount&&U.aheadCount>0?await BY3(K,U.comparisonRef):[],B=await BP4(H,XY3,async(N)=>{let w=OX0(N.changeType==="untracked"?await qY3(K,N.path,Q).catch(()=>""):await EP4(K,N.path,q,void 0,Q).catch(()=>"")),L=OX0(N.changeType==="modified"?await EP4(K,N.path,q,QY3,Q).catch(()=>""):w),O=N.changeType!=="added"&&N.changeType!=="untracked"?await WY3(K,N.previousPath??N.path,q,Q):void 0,E=N.changeType!=="deleted"?await HY3(K,N.path,Q):void 0;return{path:N.path,previousPath:N.previousPath,changeType:N.changeType,created:N.changeType==="added"||N.changeType==="untracked",diff:w,fullFileDiff:L,oldContent:O,newContent:E,diffStat:FY3(w)}});return{provider:"git",capturedAt:Y,available:!0,repositoryRoot:K,repositoryName:V,branch:W,head:q,diffHash:zY3(B),baseRef:U?.baseRef??null,baseRefHead:U?.baseRefHead??null,aheadCount:U?.aheadCount??0,behindCount:U?.behindCount,aheadCommits:D,files:B}}function wY3(J){return{provider:J.provider,capturedAt:J.capturedAt,available:J.available,repositoryRoot:J.repositoryRoot,repositoryName:J.repositoryName,branch:J.branch,head:J.head,diffHash:J.diffHash,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,behindCount:J.behindCount,...J.unavailableReason!==void 0?{unavailableReason:J.unavailableReason}:{},aheadCommits:J.aheadCommits??[],files:J.files.map((Z)=>({path:Z.path,previousPath:Z.previousPath,changeType:Z.changeType,created:Z.created,diff:Z.diff,fullFileDiff:Z.fullFileDiff,oldContent:Z.oldContent,newContent:Z.newContent,diffStat:Z.diffStat}))}}function Go0(J){let Z=wP4(wY3(J),NP4);return{key:Lk,dataType:"application/json",contentBase64:Z}}var jP4=1048576;function IP4(J,Z,Q,Y=jP4){return hv(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function RP4(J,Z,Q=jP4){return hv(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}var dv={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function MX0(J,Z){if(J>=Z.maxAttempts)return null;let Q=Math.max(1,J);return Math.min(Z.baseDelayMs*2**(Q-1),Z.maxDelayMs)}function LY3(J){return typeof J==="object"&&J!==null&&"output"in J&&J.output===""}function OY3(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}function EY3(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}function PP4(J){let Z=J.previouslyAdvertisedTools??[],{toolsToRegister:Q,toolNamesToUnregister:Y}=HP4(Z,J.nextTools),X=J.forceRegisterAll?[...J.nextTools]:Q;for(let K of UP4(X))J.logMessage?.("SEND",{type:"executor_tools_register",tools:K.map((V)=>V.name)}),J.transport.registerTools(K);for(let K of DP4(Y))J.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:K}),J.transport.unregisterTools(K);return[...J.nextTools]}async function MY3(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:K}=J,V=J.fileSystem??q8,G=performance.now(),F={clientID:J.executorClientID,threadID:Q,executorType:J.executorType,allowResumeBootstrap:J.allowResumeBootstrap===!0},z={},q="executorHandshake",W=!1,H=performance.now(),U=(N)=>{z[`${N}Ms`]=Math.round(performance.now()-H)};S.info("[executor] Starting executor bootstrap",F);let D={workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:EY3(process.platform)},tags:[]};K?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:D,executorType:J.executorType}),q="executorHandshake",H=performance.now();let B=await Z.executorHandshake(J.executorClientID,D,{executorType:J.executorType});U(q),K?.("RECV",B),W=J.allowResumeBootstrap===!0&&B.resumeBootstrap===!0;try{if(!W){J.onBootstrapProgress?.("environment"),q="buildEnvironmentSnapshot",H=performance.now();let O=await zP4(Q);U(q),K?.("SEND",{type:"executor_environment_snapshot",environment:O}),Z.sendEnvironmentSnapshot(O);let M={trees:O.workspaceRoot?[{uri:O.workspaceRoot}]:[],platform:O.platform,tags:O.tags};if(J.onBootstrapProgress?.("guidance"),q="sendGuidanceSnapshot",H=performance.now(),await AY3(Z,V,Y,M,K),U(q),J.onBootstrapProgress?.("skills"),q="sendSkillSnapshot",H=performance.now(),await jY3(Z,X,K),U(q),J.sendGitSnapshot!==!1){J.onBootstrapProgress?.("git");try{q="sendGitSnapshot",H=performance.now();let A=await EX0(J.workspaceRoot);K?.("SEND",{type:"executor_artifact_upsert",available:A.available,fileCount:A.files.length,branch:A.branch,head:A.head}),Z.sendExecutorArtifactUpsert(Go0(A)),U(q)}catch{}}}J.onBootstrapProgress?.("tools"),q="initialToolDiscovery",H=performance.now(),await J.initialToolDiscovery,U(q),q="loadToolStatuses",H=performance.now();let N=await v1(J.toolService.tools);U(q);let w=wX0(N);q="syncExecutorToolRegistrations",H=performance.now();let L=PP4({transport:Z,nextTools:w,previouslyAdvertisedTools:J.previouslyAdvertisedTools,forceRegisterAll:!W,logMessage:K});return U(q),K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0),S.info("[executor] Executor bootstrap completed",{...F,resumeBootstrap:W,toolCount:w.length,advertisedToolCount:L.length,totalMs:Math.round(performance.now()-G),...z}),{advertisedTools:L}}catch(N){let w=N instanceof Error?N.message:String(N);throw K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:w}),Z.sendExecutorToolsBootstrapComplete(!1,w),S.error("[executor] Executor bootstrap failed",{...F,currentPhase:q,resumeBootstrap:W,totalMs:Math.round(performance.now()-G),...z,error:N}),N}}async function AY3(J,Z,Q,Y,X){let V=(await eB({filesystem:Z,configService:Q,threadService:{observe:()=>h0.of({id:I7(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
|
|
4288
4288
|
`).length})),G=crypto.randomUUID(),F=Q.userConfigDir?n1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:[],isLast:!0,userConfigDir:F});return}let z=IP4(V,G,F);for(let q=0;q<z.length;q++){let W=z[q];if(!W)continue;let H=q===z.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:W.length,isLast:H}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:W,isLast:H,userConfigDir:F})}}async function jY3(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((G)=>({name:G.name,description:G.description,baseDir:G.baseDir,frontmatter:G.frontmatter,files:G.files}));if(V.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let G=0;G<V.length;G+=20){let F=V.slice(G,G+20),z=G+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:F.length,isLast:z}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:F,isLast:z})}}class CP4{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;pollDelayMs;constructor(J){this.options=J;this.baseDelayMs=J.baseDelayMs??dv.baseDelayMs,this.maxDelayMs=J.maxDelayMs??dv.maxDelayMs,this.maxAttempts=J.maxAttempts??dv.maxAttempts,this.pollDelayMs=J.pollDelayMs??30000}ensureHandshake(J){return this.tryHandshake(J)}ensureReady(J){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=OY3();this.tryHandshake("connect");let Z=this.readyWaiter.promise;if(!J?.timeoutMs)return Z;let Q=J.timeoutMessage??`Timed out waiting for handshake after ${J.timeoutMs}ms`;return this.withTimeout(Z,J.timeoutMs,Q)}handleConnectionChange(J){this.lastInfo=J;let Z=J.state!=="connected"?"reset_disconnected":J.role==="executor"?"mark_ready":"ensure_handshake";if(S.info("[executor] Handshake manager handling connection change",{action:Z,state:J.state,role:J.role,clientId:J.clientId,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,attempt:this.attempt,hasInFlightHandshake:this.inFlight!==null,hasRetryTimer:this.retryTimer!==null}),J.state!=="connected"){this.reset("disconnected");return}if(J.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let J=this.readyWaiter;if(!J)return;this.readyWaiter=null,J.resolve()}rejectReadyWaiter(J){let Z=this.readyWaiter;if(!Z)return;this.readyWaiter=null,Z.reject(J)}reset(J){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}async withTimeout(J,Z,Q){let Y=null;try{return await Promise.race([J,new Promise((X,K)=>{Y=setTimeout(()=>{K(Error(Q))},Z)})])}finally{if(Y)clearTimeout(Y)}}tryHandshake(J){if(this.disposed)return S.info("[executor] Handshake manager ignored trigger while disposed",{trigger:J}),this.inFlight;if(this.inFlight)return S.info("[executor] Handshake manager reused in-flight handshake",{trigger:J,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role}),this.inFlight;let Z=this.generation;S.info("[executor] Handshake manager starting handshake",{trigger:J,generation:Z,attempt:this.attempt,state:this.lastInfo?.state,role:this.lastInfo?.role});let Q=this.options.handshake(J);return this.inFlight=Q,Q.then(()=>{if(this.disposed||Z!==this.generation)return;S.info("[executor] Handshake manager handshake succeeded",{trigger:J,generation:Z}),this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch((Y)=>{if(this.disposed||Z!==this.generation)return;this.scheduleRetry(J,Y)}).finally(()=>{if(this.inFlight===Q)this.inFlight=null}),Q}scheduleRetry(J,Z){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let Q=MX0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts}),Y=Q===null;if(Y)S.error("[executor] Handshake manager exhausted fast retries",{trigger:J,attempt:this.attempt,maxAttempts:this.maxAttempts,pollDelayMs:this.pollDelayMs,error:Z}),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Z}),this.rejectReadyWaiter(Z instanceof Error?Z:Error("Executor handshake failed and exhausted retries")),this.options.forceReconnect?.("executor handshake exhausted");let X=Q??this.pollDelayMs;this.clearRetryTimer(),S.info("[executor] Handshake manager scheduled retry",{trigger:J,attempt:this.attempt,delayMs:X,state:this.lastInfo.state,role:this.lastInfo.role,mode:Y?"poll":"fast",error:Z instanceof Error?Z.message:String(Z)}),this.options.onError?.({trigger:J,attempt:this.attempt,delayMs:X,error:Z}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},X)}}class _P4{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(J){this.options=J;this.clientID=J.clientID,this.transport=J.transport}async handleToolLease(J){if(this.disposing)return;let{toolCallId:Z,toolName:Q}=J;if(this.activeTools.has(Z)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Z,toolName:Q});return}let Y=this.pendingTerminalResults.get(Z);if(Y){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Z,toolName:Q}),this.sendTerminalResult(Z,Y,"flush");return}let X=Date.now();this.options.log.info(`${this.clientID} executing tool: ${Q}`,{toolCallId:Z}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Z}),this.transport.ackToolLease(Z);let K=new AbortController,V={subscription:{unsubscribe:()=>{}},abortController:K};this.activeTools.set(Z,V);let G=()=>{this.activeTools.delete(Z)};try{let F=await this.options.invokeTool(J);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Z,toolName:Q,elapsedMs:Date.now()-X});let z=F.subscribe({next:(q)=>{if(K.signal.aborted)return;let W=q.status==="in-progress"?q.progress??q.result:void 0;if(W!==void 0&&!LY3(W))this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,W),{toolCallId:Z});if(h3(q.status))this.sendToolResult(Z,q),G(),z.unsubscribe();if(q.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(q)=>{if(K.signal.aborted){G();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,q);let W={status:"error",error:{message:q instanceof Error?q.message:"Unknown error"}};this.sendToolResult(Z,W),G()}});V.subscription=z}catch(F){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,F);let z={status:"error",error:{message:F instanceof Error?F.message:String(F)}};this.sendToolResult(Z,z),G()}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[J,Z]of this.pendingTerminalResults)this.sendTerminalResult(J,Z,"flush")}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z)}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}sendToolResult(J,Z){let Q=Date.now(),Y=this.toToolRun(Z),{run:X,files:K}=this.extractGuidanceFromRun(Y);if(K.length>0)this.sendGuidanceDiscovery(J,K);this.sendTerminalResult(J,X,"live",{guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendTerminalResult(J,Z,Q,Y){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:Z});let X=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,Z),{toolCallId:J,source:Q});if(X)this.pendingTerminalResults.delete(J);else this.pendingTerminalResults.set(J,Z);return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:Z.status,sent:X,source:Q,...Y}),X}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let K=Y===Q.length-1;if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:J,fileCount:X.length,isLast:K}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:J,files:X,isLast:K}),{toolCallId:J,isLast:K,fileCount:X.length}))return}}queueGitStatusSnapshot(J){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,J)this.gitStatusQueue.queuedToolCallId=J;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(J).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Z=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Z)})}async sendGitStatusSnapshot(J){try{if(!this.options.captureGitStatus)return;let Z=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Z.available,fileCount:Z.files.length,toolCallId:J,branch:Z.branch,head:Z.head}),this.transport.sendExecutorArtifactUpsert(Go0(Z),J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}toToolRun(J){switch(J.status){case"done":return{status:"done",result:J.result,progress:J.progress,trackFiles:J.trackFiles?[...J.trackFiles]:void 0};case"error":return{status:"error",error:{message:J.error?this.options.renderToolRunError(J.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:J.reason};case"cancelled":return{status:"cancelled",reason:J.reason};default:return{status:"error",error:{message:`Unexpected status: ${J.status}`}}}}extractGuidanceFromRun(J){if(J.status!=="done")return{run:J,files:[]};if(!J.result||typeof J.result!=="object"||Array.isArray(J.result))return{run:J,files:[]};let Z=J.result;if(!("discoveredGuidanceFiles"in Z))return{run:J,files:[]};let Q=lR4(Z.discoveredGuidanceFiles),{discoveredGuidanceFiles:Y,...X}=Z;return{run:{...J,result:X},files:Q}}sendTransportMessage(J,Z,Q){try{return Z(),!0}catch(Y){if(Y instanceof N9)return this.options.log.info(`${this.clientID} dropped ${J} while reconnecting`,{messageType:J,...Q}),this.options.onTransportSendFailure?.(this.clientID,J,Y,Q),!1;return this.options.log.error(`${this.clientID} failed to send ${J}`,Y),!1}}}class tj{options;toolRunner;sentApprovalRequests;discoveredGuidanceFileURIs;handshakeManager;runtimeLog;advertisedExecutorTools=[];hasCompletedBootstrap=!1;executorCallbacksAttached=!1;constructor(J){this.options=J;this.runtimeLog=this.options.log??{info:(Z,Q)=>S.info(`[executor] ${Z}`,{...Q,threadID:this.options.threadID}),error:(Z,Q)=>S.error(`[executor] ${Z}`,{error:Q,threadID:this.options.threadID}),wsMessage:(Z,Q,Y)=>{S.info("[executor] websocket message",{direction:Z,clientID:Q,threadID:this.options.threadID,...typeof Y==="object"&&Y!==null?Y:{message:Y}})}},this.handshakeManager=new CP4({handshake:this.options.handshake,forceReconnect:(Z)=>this.options.transport.forceReconnect(Z),...this.options.handshakeManagerOptions}),this.toolRunner=new _P4({clientID:this.options.clientID,transport:this.options.transport,log:this.runtimeLog,invokeTool:(Z)=>this.invokeTool(Z),captureGitStatus:this.options.captureGitStatus,batchGuidanceFiles:this.options.batchGuidanceFiles??((Z)=>[Z]),renderToolRunError:this.options.renderToolRunError??((Z)=>Z?.message??"Tool run failed"),onTransportSendFailure:this.options.onTransportSendFailure}),this.sentApprovalRequests=this.toolRunner.sentApprovalRequests,this.discoveredGuidanceFileURIs=this.toolRunner.discoveredGuidanceFileURIs}async connect(J){if(!this.executorCallbacksAttached)this.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),this.handleConnectionChange(this.options.transport.getConnectionInfo());await this.bootstrapExecutor({executorType:J,trigger:"connect"})}ensureHandshake(J){return this.handshakeManager.ensureHandshake(J)}ensureReady(J){return this.handshakeManager.ensureReady(J)}async bootstrapExecutor(J){await this.connectAsExecutor(J.executorType,J.workspaceRoot??this.options.workspaceRoot??"",J.threadID??this.options.threadID,J.trigger,J.suppressConnectLog)}syncExecutorToolRegistrations(J,Z){let Q=this.options.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;this.advertisedExecutorTools=PP4({transport:this.options.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools,logMessage:Z?.logMessage})}handleConnectionChange(J){this.runtimeLog.info(`${this.options.clientID} handling connection change`,{state:J.state,role:J.role,transportClientId:J.clientId,reconnectCauseType:J.reconnectCause?.type,reconnectCauseCode:J.reconnectCause?.code,reconnectCauseReason:J.reconnectCause?.reason,hasCompletedBootstrap:this.hasCompletedBootstrap,executorCallbacksAttached:this.executorCallbacksAttached}),this.handshakeManager.handleConnectionChange(J)}onToolLeaseMessage(J){this.handleToolLease(J)}onToolLeaseRevokedMessage(J){this.handleToolLeaseRevoked(J)}onExecutorRollbackRequestMessage(J){this.handleExecutorRollbackRequest(J)}onExecutorFileSystemReadDirectoryRequestMessage(J){this.handleExecutorFileSystemReadDirectoryRequest(J)}onExecutorFileSystemReadFileRequestMessage(J){this.handleExecutorFileSystemReadFileRequest(J)}attachTransportExecutorCallbacks(J){if(!this.options.transport.setExecutorCallbacks){this.executorCallbacksAttached=!0;return}let Z=J?.includeConnectionChanges??!1,Q=this.getInboundExecutorHandlers(),Y={onToolLease:(X)=>{this.runtimeLog.info("onToolLease",{data:X}),Q.onToolLease(X)},onToolLeaseRevoked:(X)=>{this.runtimeLog.info("onToolLeaseRevoked",{data:X}),Q.onToolLeaseRevoked(X)},onFileSystemReadFileRequest:(X)=>{this.runtimeLog.info("onFileSystemReadFileRequest",{data:X}),Q.onFileSystemReadFileRequest(X)}};if(Z)Y.onConnectionChange=(X)=>{this.runtimeLog.info("onConnectionChange",{data:X}),this.handleConnectionChange(X)};if(Q.onExecutorRollbackRequest){let X=Q.onExecutorRollbackRequest;Y.onExecutorRollbackRequest=(K)=>{this.runtimeLog.info("onExecutorRollbackRequest",{data:K}),X(K)}}if(Q.onFileSystemReadDirectoryRequest){let X=Q.onFileSystemReadDirectoryRequest;Y.onFileSystemReadDirectoryRequest=(K)=>{this.runtimeLog.info("onFileSystemReadDirectoryRequest",{data:K}),X(K)}}this.options.transport.setExecutorCallbacks(Y),this.executorCallbacksAttached=!0}clearTransportExecutorCallbacks(){if(!this.executorCallbacksAttached)return;this.executorCallbacksAttached=!1}dispose(){this.clearTransportExecutorCallbacks(),this.toolRunner.dispose(),this.handshakeManager.dispose()}async invokeTool(J){return this.options.invokeTool(J)}async connectAsExecutor(J,Z,Q,Y,X=!1){if(!X)S.info(`Connecting ${this.options.clientID} as executor...`);try{let{advertisedTools:K}=await MY3({transport:this.options.transport,executorClientID:this.options.executorClientID??this.options.clientID,workspaceRoot:Z,threadId:Q,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,logMessage:this.options.bootstrapLogMessage,executorType:J,initialToolDiscovery:this.options.initialToolDiscovery,sendGitSnapshot:this.options.sendGitSnapshot??!1,previouslyAdvertisedTools:this.advertisedExecutorTools,allowResumeBootstrap:this.hasCompletedBootstrap,onBootstrapProgress:this.options.onBootstrapProgress});if(this.advertisedExecutorTools=K,this.hasCompletedBootstrap=!0,this.toolRunner.flushBufferedTerminalResults(),this.options.onBootstrapSuccess)await this.options.onBootstrapSuccess(Y)}catch(K){throw S.error(`executor ${this.options.clientID} bootstrap failed`,K),K}}getInboundExecutorHandlers(){let J={onToolLease:(Z)=>{this.handleToolLease(Z)},onToolLeaseRevoked:(Z)=>{this.handleToolLeaseRevoked(Z)},onFileSystemReadFileRequest:(Z)=>{this.handleExecutorFileSystemReadFileRequest(Z)}};if(this.options.handleExecutorRollbackRequest)J.onExecutorRollbackRequest=(Z)=>{this.handleExecutorRollbackRequest(Z)};if(this.options.handleExecutorFileSystemReadDirectoryRequest||this.options.readFileSystemDirectory)J.onFileSystemReadDirectoryRequest=(Z)=>{this.handleExecutorFileSystemReadDirectoryRequest(Z)};return J}maybeLogInboundExecutorMessage(J){if(!this.options.logInboundExecutorMessages)return;this.runtimeLog.wsMessage("RECV",this.options.clientID,J)}handleToolLease(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolLease(J)}handleToolLeaseRevoked(J){this.maybeLogInboundExecutorMessage(J),this.toolRunner.handleToolRevocation(J)}handleExecutorRollbackRequest(J){if(this.maybeLogInboundExecutorMessage(J),!this.options.handleExecutorRollbackRequest)return;this.options.handleExecutorRollbackRequest(J)}async handleExecutorFileSystemReadDirectoryRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadDirectoryRequest){await this.options.handleExecutorFileSystemReadDirectoryRequest(J);return}if(!this.options.readFileSystemDirectory)throw Error("Method not implemented.");let Z=await this.options.readFileSystemDirectory(J);this.options.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}handleExecutorFileSystemReadFileRequest(J){if(this.maybeLogInboundExecutorMessage(J),this.options.handleExecutorFileSystemReadFileRequest){this.options.handleExecutorFileSystemReadFileRequest(J);return}throw Error("Method not implemented.")}}A$();async function oG(J,Z,Q,Y={}){let X={...J?{threadId:J}:{},...Y.repositoryURL?{repositoryURL:Y.repositoryURL}:{},...!J&&Y.executorType?{executorType:Y.executorType}:{},...Y.agentMode?{agentMode:Y.agentMode}:{},...Y.relationship?{relationship:Y.relationship}:{},...Y.usesThreadActors?{usesThreadActors:!0}:{}},K=await v2("/api/thread-actors",IY3({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X),signal:Y.signal},Q),Z);if(!K.ok)throw Error(`Failed to create DTW thread: ${K.status} ${await K.text()}`);let V=await K.json();if(!V.threadId||!V.wsToken)throw Error("DTW thread creation response missing threadId or wsToken");if(!V.ownerUserId||typeof V.threadVersion!=="number")throw Error("DTW thread creation response missing ownerUserId or threadVersion");return{threadId:V.threadId,wsToken:V.wsToken,usesDtw:V.usesDtw??!0,usesThreadActors:V.usesThreadActors??!1,executorType:V.executorType??null,ownerUserId:V.ownerUserId,threadVersion:V.threadVersion,...V.agentMode?{agentMode:V.agentMode}:{}}}function IY3(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}YG();yJ0();km();Sm0();s4();D4();I1();async function Sq(J){let{toolName:Z,dtwArtifactSyncService:Q,configService:Y,toolService:X,mcpService:K,skillService:V,fsTracker:G,toolUseID:F,discoveredGuidanceFileURIs:z,threadID:q}=J,W={id:q??I7(),created:Date.now(),v:0,messages:[]},H=K1.file(process.cwd()),U=F??aX(),D=await Y.getLatest(),B,N;if(G)B=G.trackedFileSystem(U),N=G.tracker;else N=kJ0(hk0,W.id,async()=>{}),B=km0(q8,N,U);return{dir:H,tool:Z,thread:W,dtwArtifactSyncService:Q,trackedFiles:new VJ,toolUseID:U,todos:void 0,configService:Y,toolService:X,mcpService:K,config:D,filesystem:B,fileChangeTracker:N,getAllTrackedChanges:async()=>N.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>h0.of(W),get:()=>Promise.resolve(W),getPrimitiveProperty:(w,L)=>Promise.resolve(W[L]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:q8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:hk0,discoveredGuidanceFileURIs:z??new Set,skillService:V??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}var TP4=45000;async function SP4(J){let{apiKey:Z,ampURL:Q,workspaceRoot:Y,dependencies:X,userInput:K,stdinInput:V,stats:G,agentMode:F,labels:z,initialThreadID:q}=J,W=process.env.RIVET_PUBLIC_ENDPOINT??lK(Q),H=vM(X.configService),U=async(O)=>{let E=await H.getThread(O);return E?BX0(E):null},D=new kP4,B=uv((O)=>oG(O,X.configService,Z,{...F?{agentMode:F}:{},executorType:"local-client"}),q),N=new Tq({transport:bv({rivetEndpoint:W,credentialsProvider:B,initialThreadID:q,pingIntervalMs:5000}),threadHistoryLoader:U,observerCallbacks:D}),w=pw.parse(`amp-x-${RY3()}`),L=null;try{let O=q?(await N.loadThreadHistory(q))?.version??0:0;await N.connect();let E=N.getThreadId();if(!E)throw new LJ("Thread client connected without a thread ID");L=new tj({transport:N,toolService:X.toolService,configService:X.configService,clientID:w,threadID:E,invokeTool:async(A)=>{let j=typeof A.args==="object"&&A.args!==null?A.args:{},R=await Sq({toolName:A.toolName,configService:X.configService,toolService:X.toolService,mcpService:X.mcpService,skillService:X.skillService,toolUseID:A.toolCallId,threadID:E});return X.toolService.invokeTool(A.toolName,{args:j},R)},readFileSystemDirectory:({uri:A})=>cw({fileSystem:X.fileSystem,workspaceRoot:Y},A),skillService:X.skillService,sendGitSnapshot:!1,handshake:async(A)=>{if(!L)throw Error("Executor not initialized");await L.bootstrapExecutor({executorType:"local-client",trigger:A,workspaceRoot:Y,threadID:E,suppressConnectLog:!0})}}),L.attachTransportExecutorCallbacks({includeConnectionChanges:!0}),L.handleConnectionChange(N.getConnectionInfo()),await L.ensureReady({timeoutMs:TP4,timeoutMessage:`Timed out waiting for executor handshake after ${TP4}ms`}),N.resumeFromVersion(O);let M=await PY3(N,D,X,K,V,F,G,E);if(z&&z.length>0)await kv(M,z,X.configService);return M}finally{if(L)L.dispose();N.dispose()}}function PY3(J,Z,Q,Y,X,K,V,G){return new Promise((F,z)=>{let q=!1,W=!1,H=[],U=new Set,D=[],B=setInterval(()=>{},1000),N=()=>{if(q)return;q=!0,L.remove(),clearInterval(B);for(let E of D)E.unsubscribe()},L=Sv(()=>{if(q)return;S.debug("User cancelled (SIGINT/SIGTERM); cancelling remote agent loop");try{J.cancelAgentLoop()}catch(E){S.warn("Failed to cancel remote agent loop on signal",{error:E})}N(),F(G)});L.install(),D.push(Z.activeError$.subscribe((E)=>{if(E)S.error("error",{error:E}),process.stderr.write(`Error: ${E.message}
|
|
@@ -4453,12 +4453,12 @@ ${D}`))}},error:(U)=>{if(!H)H=!0,F(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
4453
4453
|
${D}`;if(K==="pnpm"&&D.includes("Unable to find the global bin directory"))B+=`
|
|
4454
4454
|
|
|
4455
4455
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4456
|
-
npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();mN();async function pX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=bn(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return S.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var NV3="https://static.ampcode.com/cli/cli-version.txt";async function dX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${NV3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=bn(J,X),V=K<0;return S.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return S.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var wV3=604800000;function S_4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>wV3)return{ageMs:Q};return null}function bn(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ao0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?bz(Q):void 0;return{sha:Y,age:X}}catch{return null}}I1();a0();import{readFile as LV3,realpath as OV3}from"node:fs/promises";import{homedir as EV3}from"node:os";import{dirname as k_4,join as oo0}from"node:path";async function v_4(J){switch(J){case"binary":case"brew":return MV3(yn());case"npm":case"pnpm":case"yarn":case"bun":return AV3();case"bootstrap":return jV3()}}async function MV3(J){let Z=await sG(J,["--version"],5000);if(Z.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:J,result:Z}),null;return Z.output.trim().split(/\s+/)[0]||null}async function AV3(){try{let J=process.argv[1];if(!J)return null;let Z=await OV3(J),Q=k_4(k_4(Z));return await y_4(oo0(Q,"package.json"))}catch(J){return S.debug("failed to read installed version from package.json",{error:J}),null}}async function jV3(){try{let J=process.env.AMP_HOME??oo0(EV3(),".amp");return await y_4(oo0(J,"package","package.json"))}catch(J){return S.debug("failed to read installed version from bootstrap package.json",{error:J}),null}}async function y_4(J){let Z=await LV3(J,"utf8"),Q=JSON.parse(Z);if(Q.name!=="@sourcegraph/amp")return S.debug("package.json name mismatch",{pkgJsonPath:J,name:Q.name}),null;return Q.version||null}var IV3=3600000,RV3=5000;function ro0(J,Z,Q={}){let Y=new W6,X=Y.pipe(h6({shouldCountRefs:!1})),K=Q.startDelayMs??0,V=Q.checkIntervalMs??IV3,G=!1,F=()=>{G=!0};return setImmediate(async()=>{let z=new uV().scoped("update");if(K>0){if(await uz(K),G)return}let q=X.subscribe({next:(H)=>{z.debug("emit new state",H)}}),W=J;try{while(!G){let H=await PV3(W,Z,z,Y);if(H.stop)return;if(H.updatedTo)W=H.updatedTo;if(H.emittedVisibleState){if(await uz(RV3),G)return;Y.next("hidden")}if(V<=0)return;let U=1000,D=V;while(D>0&&!G){let B=Math.min(U,D);await uz(B),D-=B}}}finally{q.unsubscribe(),Y.complete()}}),{state:X,dispose:F}}async function PV3(J,Z,Q,Y){let X={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return Q.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),X.stop=!0,X;let K=await Z.get("updates.mode");if(K==="disabled")return Q.debug("checking disabled"),X.stop=!0,X;let V=await gX0(),G=V==="binary"||V==="brew";Q.debug("checking",{currentVersion:J,mode:K,packageManager:V,isBinaryDistribution:G});let F;if(G)F=await dX0(J);else{let W=await YI();F=await pX0(J,W)}if(!(F.latestVersion&&F.hasUpdate))return Q.debug("no update available"),X;let z=(W)=>{Y.next(W),X.emittedVisibleState=!0};if(V){let W=await v_4(V);if(W&&bn(W,F.latestVersion)>=0){if(Q.debug("on-disk version already up to date",{currentVersion:J,installedVersion:W,latestVersion:F.latestVersion}),X.updatedTo=W,bn(J,W)<0){let H=await TU(W),U={from:J,to:W,externallyUpdated:!0,...H};if(H.status==="same")Q.info("on-disk already updated by another instance",U),z("updated");else Q.warn("on-disk already updated by another instance, with PATH warning",U),z("updated-with-warning")}return X}}let q=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let W=F.currentVersionAge-F.latestVersionAge,H=0.5;if(Math.abs(W)<0.5)return Q.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:W}),!0}return!1};if(!K)K=V==="pnpm"?"warn":"auto",Q.debug("no configured update mode; selected default based on package manager",{packageManager:V,mode:K});if(V==="brew"){if(!q())z("update-available-brew");return X}if(V==="binary"&&process.execPath!==yn()){if(Q.debug("non-standard binary path, showing warning"),!q())z("update-available-unrecognized-path");return X}if(K==="warn"){if(!q())z("update-available");return X}if(!V){if(Q.debug("auto-update not supported, falling back to warn mode"),!q())z("update-available");return X}if(V==="binary"&&process.platform==="win32"){if(Q.debug("binary auto-update not supported on Windows, falling back to warn mode"),!q())z("update-available");return X}try{await un(F.latestVersion,V),X.updatedTo=F.latestVersion;let W=await TU(F.latestVersion),H={from:F.currentVersion,to:F.latestVersion,...W};if(W.status==="same")Q.info("success",H),z("updated");else Q.warn("success with warning",H),z("updated-with-warning")}catch(W){z("update-error")}return X}catch(K){return Q.debug("check failed",{error:K}),X}}mN();import{stderr as tG}from"node:process";function x_4(J){let Z=new qw().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(Y)=>{await fo0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
4456
|
+
npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();mN();async function pX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=bn(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return S.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return S.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var NV3="https://static.ampcode.com/cli/cli-version.txt";async function dX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${NV3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=bn(J,X),V=K<0;return S.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return S.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var wV3=604800000;function S_4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>wV3)return{ageMs:Q};return null}function bn(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ao0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?bz(Q):void 0;return{sha:Y,age:X}}catch{return null}}I1();a0();import{readFile as LV3,realpath as OV3}from"node:fs/promises";import{homedir as EV3}from"node:os";import{dirname as k_4,join as oo0}from"node:path";async function v_4(J){switch(J){case"binary":case"brew":return MV3(yn());case"npm":case"pnpm":case"yarn":case"bun":return AV3();case"bootstrap":return jV3()}}async function MV3(J){let Z=await sG(J,["--version"],5000);if(Z.reason!=="success")return S.debug("failed to read version from binary",{binaryPath:J,result:Z}),null;return Z.output.trim().split(/\s+/)[0]||null}async function AV3(){try{let J=process.argv[1];if(!J)return null;let Z=await OV3(J),Q=k_4(k_4(Z));return await y_4(oo0(Q,"package.json"))}catch(J){return S.debug("failed to read installed version from package.json",{error:J}),null}}async function jV3(){try{let J=process.env.AMP_HOME??oo0(EV3(),".amp");return await y_4(oo0(J,"package","package.json"))}catch(J){return S.debug("failed to read installed version from bootstrap package.json",{error:J}),null}}async function y_4(J){let Z=await LV3(J,"utf8"),Q=JSON.parse(Z);if(Q.name!=="@sourcegraph/amp")return S.debug("package.json name mismatch",{pkgJsonPath:J,name:Q.name}),null;return Q.version||null}var IV3=3600000,RV3=5000;function ro0(J,Z,Q={}){let Y=new W6,X=Y.pipe(h6({shouldCountRefs:!1})),K=Q.startDelayMs??0,V=Q.checkIntervalMs??IV3,G=!1,F=()=>{G=!0};return setImmediate(async()=>{let z=new uV().scoped("update");if(K>0){if(await uz(K),G)return}let q=X.subscribe({next:(H)=>{z.debug("emit new state",H)}}),W=J;try{while(!G){let H=await PV3(W,Z,z,Y);if(H.stop)return;if(H.updatedTo)W=H.updatedTo;if(H.emittedVisibleState){if(await uz(RV3),G)return;Y.next("hidden")}if(V<=0)return;let U=1000,D=V;while(D>0&&!G){let B=Math.min(U,D);await uz(B),D-=B}}}finally{q.unsubscribe(),Y.complete()}}),{state:X,dispose:F}}async function PV3(J,Z,Q,Y){let X={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return Q.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),X.stop=!0,X;let K=await Z.get("updates.mode");if(K==="disabled")return Q.debug("checking disabled"),X.stop=!0,X;let V=await gX0(),G=V==="binary"||V==="brew";Q.debug("checking",{currentVersion:J,mode:K,packageManager:V,isBinaryDistribution:G});let F;if(G)F=await dX0(J);else{let W=await YI();F=await pX0(J,W)}if(!(F.latestVersion&&F.hasUpdate))return Q.debug("no update available"),X;let z=(W)=>{Y.next(W),X.emittedVisibleState=!0};if(V){let W=await v_4(V);if(W&&bn(W,F.latestVersion)>=0){if(Q.debug("on-disk version already up to date",{currentVersion:J,installedVersion:W,latestVersion:F.latestVersion}),X.updatedTo=W,bn(J,W)<0){let H=await TU(W),U={from:J,to:W,externallyUpdated:!0,...H};if(H.status==="same")Q.info("on-disk already updated by another instance",U),z("updated");else Q.warn("on-disk already updated by another instance, with PATH warning",U),z("updated-with-warning")}return X}}let q=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let W=F.currentVersionAge-F.latestVersionAge,H=0.5;if(Math.abs(W)<0.5)return Q.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:W}),!0}return!1};if(!K)K=V==="pnpm"?"warn":"auto",Q.debug("no configured update mode; selected default based on package manager",{packageManager:V,mode:K});if(V==="brew"){if(!q())z("update-available-brew");return X}if(V==="binary"&&process.execPath!==yn()){if(Q.debug("non-standard binary path, showing warning"),!q())z("update-available-unrecognized-path");return X}if(K==="warn"){if(!q())z("update-available");return X}if(!V){if(Q.debug("auto-update not supported, falling back to warn mode"),!q())z("update-available");return X}if(V==="binary"&&process.platform==="win32"){if(Q.debug("binary auto-update not supported on Windows, falling back to warn mode"),!q())z("update-available");return X}try{await un(F.latestVersion,V),X.updatedTo=F.latestVersion;let W=await TU(F.latestVersion),H={from:F.currentVersion,to:F.latestVersion,...W};if(W.status==="same")Q.info("success",H),z("updated");else Q.warn("success with warning",H),z("updated-with-warning")}catch(W){z("update-error")}return X}catch(K){return Q.debug("check failed",{error:K}),X}}mN();import{stderr as tG}from"node:process";function x_4(J){let Z=new qw().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(Y)=>{await fo0(Y.force||!1,Y.verbose||!1,"0.0.1776949187-g6c0bed"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new qw("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(Y)=>{await _V3(Y.targetVersion)});J.addCommand(Q)}function CV3(J){let Z=Boolean(J.isTTY),Q=0,Y=!1;function X(){if(!Z||!Y)return;J.write(`
|
|
4457
4457
|
`),Y=!1,Q=0}function K(V){if(!Z)return;let G=V.padEnd(Q," ");J.write(`\r${G}`),Y=!0,Q=G.length}return{flushProgressLine:X,renderProgress:K}}async function _V3(J){let Q=process.platform==="win32"&&QI()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:Y,renderProgress:X}=CV3(tG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")tG.write(n0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4458
4458
|
|
|
4459
4459
|
`));try{if(!J){tG.write(n0.blue(`Checking for updates...
|
|
4460
|
-
`));let G=!1,F;if(QI()){let z=await dX0("0.0.
|
|
4461
|
-
`));let W=await TU("0.0.
|
|
4460
|
+
`));let G=!1,F;if(QI()){let z=await dX0("0.0.1776949187-g6c0bed");G=z.hasUpdate,F=z.latestVersion}else{let z=await YI(),q=await pX0("0.0.1776949187-g6c0bed",z);G=q.hasUpdate,F=q.latestVersion}if(!G){let z=ao0("0.0.1776949187-g6c0bed"),q=z?.age?`released ${z.age} ago`:`built ${bz(new Date("2026-04-23T13:03:36.797Z"))} ago`;tG.write(n0.green(`✓ Amp is already up to date on version ${"0.0.1776949187-g6c0bed"} (${q})
|
|
4461
|
+
`));let W=await TU("0.0.1776949187-g6c0bed",Q);if(W.warning)tG.write(`
|
|
4462
4462
|
`+n0.yellow(W.warning)+`
|
|
4463
4463
|
`);process.exit(0)}if(!F)tG.write(n0.yellow("[WARN] could not find latest version")),process.exit(0);J=F}tG.write(n0.blue(`Updating to version ${J}...
|
|
4464
4464
|
`)),await un(J,void 0,(G)=>{Y(),tG.write(n0.dim(`Running: ${G}
|
|
@@ -4935,7 +4935,7 @@ ${Y}`).join(`
|
|
|
4935
4935
|
|
|
4936
4936
|
`)}copyErrorToClipboard(J,Z){let Q=this.buildClipboardText(Z);D5.maybeInvoke(J,new rq(Q)),this.setState(()=>{this.didCopy=!0})}build(J){let Z=y0.of(J),Q=this.widget.presentationOptions.ampURL??l$.of(J).ampURL,Y=Fw(_h4(this.widget.error),this.widget.presentationOptions),X=this.hideAddCreditsActionForCurrentError?Y.actions.filter((F)=>F!=="add-credits"):Y.actions,K=this.computeRetryCountdown(),V=X.filter((F)=>F!=="dismiss"&&F!=="handoff"&&F!=="new-thread").map((F)=>({value:F,label:Mk(F,{ampURL:Q,retryCountdown:K})}));V.push({value:"copy",label:this.didCopy?"Copy to Clipboard ✓":"Copy to Clipboard"}),V.push({value:"dismiss",label:Mk("dismiss")});let G=this.buildBodyWithLinks(J,Y.description);return new l7({title:Y.title,body:G,options:V,onSelect:(F)=>{let z=F??"dismiss";if(z==="copy"){this.copyErrorToClipboard(J,Y);return}if(z==="add-credits"){if(N3(J,new URL("/pay",Q)),!this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!0});this.widget.onResponse(z);return}if(this.hideAddCreditsActionForCurrentError)this.setState(()=>{this.hideAddCreditsActionForCurrentError=!1});this.widget.onResponse(z)},borderColor:Z.colors.destructive,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1})}buildBodyWithLinks(J,Z){if(!Z)return;let Q=/(https?:\/\/[^\s]+)/g,Y=[],X=0;for(let K of Z.matchAll(Q)){let V=K[0],G=K.index??0;if(G>X)Y.push(new P(Z.slice(X,G)));let F=Y5.createSpan(V,V);Y.push(new P(F.text,F.style,F.children,F.hyperlink,()=>{N3(J,V)})),X=G+V.length}if(Y.length===0)return Z;if(X<Z.length)Y.push(new P(Z.slice(X)));return new $0({text:new P(void 0,void 0,Y),selectable:!0})}}function _h4(J){return{message:J.message}}D4();import{homedir as $j3}from"node:os";import IL from"node:path";function Jj3(J,Z,Q){if(!J)return null;let Y=J.workingDirectory??J.workspaceRoot;if(!Y)return null;let X;try{X=K1.parse(Y).fsPath}catch{return null}let K=Zj3(X),V=Qj3(K),G=J.git?.branch;return Yj3(V,G,Z,Q)}function Zj3(J){let Z=$j3();if(J===Z)return"~";if(J.startsWith(Z+IL.sep))return"~"+J.slice(Z.length);return J}function Qj3(J){let Z=J.split(IL.sep).filter(Boolean);if(Z.length<=5)return J;return[Z.slice(0,2).join(IL.sep),"…",Z.slice(-2).join(IL.sep)].join(IL.sep)}function Yj3(J,Z,Q,Y){if(Q<=0)return"";let X=Z?` (${Z})`:"",K=J+X;if(Q5(K,Y)<=Q)return K;let V=J.split(IL.sep);if(V.length>2){let F=[V[0],"…",V[V.length-1]].join(IL.sep)+X;if(Q5(F,Y)<=Q)return F}return SU(K,Q,Y)}function Sh4(J,Z){let Q=G4.of(J),Y=k1.of(J),X=Math.max(0,Q.size.width-6),K=Jj3(Z,X,Q.supportsEmojiWidth);if(!K)return;return new $0({text:new P(K,new g({color:Y.colorScheme.foreground,dim:!0}))})}var Xj3=!1;class p01 extends S1{build(J){if(!Xj3)return new I0;let Z=y0.of(J);return new l0({decoration:new e4(Z.app.smartModeColor),child:new m0({padding:R0.horizontal(1),child:new $0({text:new P("DEVELOPMENT BUILD (neo)",new g({color:Z.app.selectionForeground,bold:!0})),textAlign:"center"})})})}}a0();tJ();a0();tJ();import{randomBytes as Kj3}from"node:crypto";import Vj3 from"node:fs";import{writeFile as Gj3}from"node:fs/promises";import{tmpdir as Fj3}from"node:os";import jG0 from"node:path";function zj3(J){let Z=J.trim().replace(/^["']|["']$/g,"");if(Z=Z.replace(/\\(.)/g,"$1"),Z=Z.replace(/u\{([0-9a-fA-F]+)\}/g,(Y,X)=>String.fromCodePoint(parseInt(X,16))),!/\.(png|jpe?g|gif|webp)$/i.test(Z))return null;if(!jG0.isAbsolute(Z))return null;return S.debug("Extracted image path",{original:J,extracted:Z}),Z}function kh4(J){let Z=J.trim().replace(/^["']|["']$/g,""),Q=Z.split(`
|
|
4937
4937
|
`).filter(Boolean);if(Q.length===1)Q=Z.split(/(?<=\.(?:png|jpe?g|gif|webp))\s+(?=["']?\/)/i);return Q.map((Y)=>zj3(Y)).filter((Y)=>Y!==null)}async function qj3(J,Z){let Q=jG0.extname(J).toLowerCase()||".png",Y=`amp-img-${Kj3(8).toString("hex")}${Q}`,X=jG0.join(Fj3(),Y);return await Gj3(X,Z),X}async function sq(J){try{let Z;try{Z=Vj3.readFileSync(J)}catch(K){return S.error(`Failed to read image file ${J}:`,K),`Failed to read image file: ${K instanceof Error?K.message:"unknown error"}`}let Q=B_(Z);if(!Q){let K=jG0.extname(J).toLowerCase();if(Q=Jg(K),!Q)return S.warn("Unsupported image format",{imagePath:J}),"Unsupported image format"}let Y=sJ({source:{type:"file",path:J,data:Z}});if(Y!==null)return S.warn("Image validation failed",{error:Y}),Y;let X=await qj3(J,Z);return Wj3(Z,Q,X)}catch(Z){return S.error("Error handling image file path",{imagePath:J,error:Z}),`Error handling image file: ${Z instanceof Error?Z.message:"unknown error"}`}}function Wj3(J,Z,Q){return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Z},sourcePath:Q}}a0();A$();var Hj3=dv,Uj3=["unable to connect","failed to connect","connection refused","econnrefused","enotfound","fetch failed","networkerror"];function vh4(J){if(!(J instanceof Error))return!1;let Z=J.message.toLowerCase();return Uj3.some((Q)=>Z.includes(Q))}function yh4(J){return MX0(J,Hj3)}function Dj3(J){if(typeof J!=="object"||J===null)return!1;return typeof Reflect.get(J,"url")==="string"}function Bj3(J){if(typeof J!=="object"||J===null)return!1;return typeof Reflect.get(J,"error")==="string"}function xh4(J){try{let Z=new URL(J);if(Z.protocol!=="http:"&&Z.protocol!=="https:")return!1;let Q=Z.hostname.toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"||Q.endsWith(".localhost")}catch{return!1}}async function Nj3(J,Z){let Q=await v2("/api/attachments",{method:"POST",body:JSON.stringify({data:J.data,mediaType:J.mediaType})},Z),Y=null;try{Y=await Q.json()}catch{Y=null}if(!Q.ok){if(Bj3(Y))throw Error(Y.error);throw Error(`Failed to upload image (HTTP ${Q.status})`)}if(!Dj3(Y))throw Error("Failed to upload image: invalid response from server");return Y.url}async function fh4(J,Z){let Q=0;while(!0)try{return await Nj3(J,Z)}catch(Y){Q+=1;let X=yh4(Q);if(!vh4(Y)||X===null)throw Y;S.warn(`Attachment upload attempt ${Q} failed; retrying in ${X}ms`,Y),await new Promise((K)=>setTimeout(K,X))}}import{mkdtemp as Oj3,readFile as Ej3,rmdir as Mj3,unlink as Aj3,writeFile as jj3}from"node:fs/promises";import{tmpdir as Ij3}from"node:os";import ch4 from"node:path";a0();a0();class IG0{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class rI extends IG0{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function uh4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class d01 extends R3{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new uq(this)}createRenderObject(){return new bh4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class bh4 extends q4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}getParentGlobalOffset(){let J=0,Z=0,Q=this.parent;while(Q&&Q instanceof q4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(h4(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z){let Q=this.getParentGlobalOffset();this.setOffset(Z.x-Q.x,Z.y-Q.y)}if(this.children.length>0){let Q=this.children[0];Q.layout(J.loosen());let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}class c01 extends R3{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new uq(this)}createRenderObject(){return new hh4(this.link)}updateRenderObject(J){J.link=this.link}}class hh4 extends q4{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Z=this.offset.y,Q=this.parent;while(Q&&Q instanceof q4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(h4(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}a0();class l01{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Z){S.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}a0();var wj3=500;class i01{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new rI(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let F=G.detect(Z,Y);if(F&&(!X||F.start>X.start))X=F}if(!this.currentState.isActive&&X&&X.query.length>0){let G=f6(Z),F=Y,z=F;while(z<G.length){let q=G[z];if(q&&/[\s)\]}@]/.test(q))break;z++}if(z>F){let W=[...G.slice(0,F),...G.slice(z)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(S.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},wj3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class Ro{}class Po{}class Co{}class RG0{}class PG0 extends u0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new gh4(this.props)}}class gh4 extends f0{props;controller;stateListener=null;overlayEntry=null;layerLink=new l01;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new O6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new i01,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=uh4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss()}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Ro)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Po)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Co)return this.controller.acceptSelected(),"handled";if(J instanceof RG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new zX({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0}),Q=new w9({shortcuts:new Map([[new t1("ArrowDown"),new Ro],[new t1("ArrowUp"),new Po],[new t1("n",{ctrl:!0}),new Ro],[new t1("p",{ctrl:!0}),new Po],[new t1("Enter"),new Co],[new t1("Escape"),new RG0],[new t1("Tab"),new Co]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new D5({actions:new Map([[Ro,new d4(this.invoke)],[Po,new d4(this.invoke)],[Co,new d4(this.invoke)],[RG0,new d4(this.invoke)]]),child:Q});return new c01({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new jL((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{pQ.of(this.context).insert(this.overlayEntry)}catch(J){S.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new P(Q,new g({color:y0.of(J).app.command})),new P(" ",new g({color:Z})));return X.push(new P(Y,new g({color:Z}))),[{child:new $0({text:new P(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=k1.maybeOf(J),Y=Q?.colorScheme.background??E0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??E0.default(),K=Z.options.length,V=G4.sizeOf(J).height,G=0;try{let R=this.layerLink.getTargetTransform();if(R)G=R.position.y}catch{}let F=this.props.autoOverlayPosition?G<V/3:!1,z=2,q;if(F){let R=this.props.controller.getCursorVisualRow(),_=G+R+1;q=V-_-z}else q=G-z;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,H=Math.min(Z.options.length,W+K),U=[],D=0;for(let R=W;R<H;R++){let _=Z.options[R];if(!_)continue;let C=R===Z.selectedIndex,b,d;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(J,_,C);let x=this.props.displayStringForOption?.(_)??String(_),m="",p=x,h=_;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":m="@",p=h.path||x;break;case"artifact":m="",p=h.label||x;break}d=m+p}else{let x=this.props.displayStringForOption?.(_)??String(_),m=Q?.colorScheme.selection??E0.default(),p=Q?.colorScheme.foreground??E0.default();b=new $0({text:new P(x,new g({color:p,backgroundColor:C?m:void 0}))}),d=x}let f=G4.of(J),y=Q5(d,f.supportsEmojiWidth);D=Math.max(D,y),U.push(b)}let B=G4.sizeOf(J).width,N=D+4,w=Math.floor(B*0.9),L=Math.max(Math.min(N,w),Math.min(30,w)),M=U.length+2,A;if(F)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({width:L,child:new l0({height:M,decoration:new e4(Y),child:new H7({decoration:{border:K4.all(new Y4(X,1,"rounded"))},padding:R0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new p0({crossAxisAlignment:"start",children:U})})})});return new d01({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function mh4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function ph4(J){switch(J.type){case"file":return J.path;case"hint":return`${Lj3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function dh4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function Lj3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class KV{detect(J,Z){if(!J||Z<1)return null;let Q=f6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
|
|
4938
|
-
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class oU extends u0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new lh4(this.props)}}var Rj3=":";class lh4 extends f0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new A5;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new KV().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let G=X.query.toLowerCase().startsWith(Rj3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",F=K+G+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,F=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new O6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=kh4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if((this.props.uploadingImageIndices?.size??0)>0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await Oj3(ch4.join(Ij3(),"amp-edit-")),Q=ch4.join(Z,"message.amp.md");await jj3(Q,J,"utf-8"),await eK(Q);try{let Y=await Ej3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")S.error("Failed to read temporary file",Y)}try{await Aj3(Q),await Mj3(Z)}catch(Y){S.warn("Failed to clean up temporary file",Y)}}catch(Z){S.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new q1({mainAxisSize:"min",children:[new $0({text:new P("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((F,z)=>{let q=new o1({onClick:()=>{this.props.onSkillClick?.(z)},cursor:"pointer",child:new $0({text:new P(F.name,new g({color:Z.success,underline:!0}))})});if(z<Q.length-1)return[q,new $0({text:new P(" ")})];return[q]})]}):null,K=Y?new q1({mainAxisSize:"min",children:[new $0({text:new P("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((F,z)=>{let q=this.props.uploadingImageIndices?.has(z)===!0,W=this.props.onImageClick!==void 0&&!q,H=q?`[Image ${this._imageUploadSpinner.toBraille()}]`:`[Image ${z+1}]`,U=new o1({onClick:W?()=>{this.props.onImageClick?.(z)}:void 0,cursor:W?"pointer":void 0,child:new $0({text:new P(H,new g({color:q?Z.foreground:Z.success,underline:!q,dim:q}))})});if(z<this.props.imageAttachments.length-1)return[U,new $0({text:new P(" ")})];return[U]})]}):null,V=new PG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(F)=>ph4(F),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:R0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(F,z,q)=>{let W=q?Z.selection:void 0,H=Z.secondary,U=Z.foreground,D=Z.foreground,B=Z.warning;if(z.type==="commit")return new l0({decoration:new e4(W),child:new q1({children:[new b1({child:new $0({text:new P("",void 0,[new P(z.shortHash,new g({color:Z.secondary})),new P(" ",new g({})),new P(z.message,new g({color:U}))]),maxLines:1,overflow:"ellipsis"})}),new $0({text:new P(` ${z.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(z.type){case"file":N.push(new P("@",new g({color:H}))),N.push(new P(z.path,new g({color:U})));break;case"hint":N.push(new P(z.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new P(" ",new g({}))),N.push(new P(z.message,new g({color:B})));break}let w=dh4(z);if(w)N.push(new P(" - ",new g({color:D,dim:!0}))),N.push(new P(w,new g({color:D,dim:!0})));return new l0({decoration:new e4(W),child:new $0({text:new P("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let F=[];if(X)F.push(X);if(X&&K)F.push(new $0({text:new P(" ")}));if(K)F.push(K);let z=new l0({padding:R0.only({bottom:1}),child:new q1({mainAxisSize:"min",children:F})});G.push(z)}if(G.push(new W7({fit:this.props.fillAvailableHeight===!1?"loose":"tight",child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new p0({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class nh4 extends q7{color;constructor({color:J,key:Z}){super({key:Z});this.color=J}createRenderObject(){return new ah4(this.color)}updateRenderObject(J){J.color=this.color}}class ah4 extends q4{color;constructor(J){super();this.color=J}performLayout(){let J=this._lastConstraints;if(J)this.setSize(J.maxWidth,1)}paint(J,Z,Q){let Y=Math.floor(this.size.width);for(let X=0;X<Y;X++)J.setChar(Z+X,Q,"─",{fg:this.color},1)}}var Pj3=30,ih4=[{left:{keys:"Ctrl+O",description:"command palette"},right:{keys:"Ctrl+R",description:"prompt history"}},{left:{keys:"$ or $$",description:"shell commands"},right:{keys:"Ctrl+V",description:"paste images"}},{left:{keys:"Shift+Enter",description:"newline"},right:{keys:"Ctrl+S",description:"switch modes"}},{left:{keys:"Alt+D",description:"toggle deep reasoning"},right:{keys:"Alt+T",description:"toggle thinking/dense view"}},{left:{keys:"Ctrl+G",description:"edit in $EDITOR"},right:{keys:"Tab/Shift+Tab",description:"navigate messages"}},{left:{keys:"@ / @@",description:"mention files/threads"},right:{keys:"?",description:"toggle this help"}}];class _o extends S1{submitOnEnter;constructor(J={}){super(J.key?{key:J.key}:{});this.submitOnEnter=J.submitOnEnter??!0}build(J){let Q=k1.of(J).colorScheme,X=y0.of(J).app,K=new g({color:X.keybind}),V=new g({color:Q.foreground,dim:!0}),G=eG()&&!Jr0,z=(this.submitOnEnter?ih4:ih4.map((W)=>W.left.keys==="Shift+Enter"?{left:{keys:"Ctrl/Cmd+Enter",description:"submit"},right:W.right}:W)).map((W)=>{let H=W.left.keys==="Shift+Enter"&&G?"Alt+Enter":W.left.keys,U=W.left.description,D=H.length+1+U.length,B=" ".repeat(Math.max(0,Pj3-D)),N=W.right.keys,w=W.right.description;return new $0({text:new P("",void 0,[new P(H,K),new P(" ",V),new P(U,V),new P(B+" ",V),new P(N,K),new P(" ",V),new P(w,V)])})});if(G)z.push(new I0({height:1})),z.push(new o1({onClick:()=>N3(J,"https://ampcode.com/manual/appendix#amp-cli-tmux"),cursor:"pointer",child:new $0({text:new P("",void 0,[new P("Enable ",V),new P("extended-keys",new g({color:X.command})),new P(" in tmux to use ",V),new P("Shift+Enter",K),new P(". See ",V),Y5.createSpan("https://ampcode.com/manual/appendix#amp-cli-tmux","https://ampcode.com/manual/appendix#amp-cli-tmux",new g({color:X.link,underline:!0}))])})}));let q=new q1({children:[new b1({child:new nh4({color:Q.border})})]});return new p0({crossAxisAlignment:"start",mainAxisSize:"min",children:[...z,q]})}}class n01 extends IG0{_mode="auto";_isResizing=!1;_isHandleHovered=!1;get mode(){return this._mode}get isResizing(){return this._isResizing}get isHandleHovered(){return this._isHandleHovered}_update(J,Z,Q){let Y=this._mode!==J||this._isResizing!==Z||this._isHandleHovered!==Q;if(this._mode=J,this._isResizing=Z,this._isHandleHovered=Q,Y)this.notifyListeners()}}class a01 extends u0{child;minRows;maxRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;controller;constructor({key:J,child:Z,minRows:Q=3,maxRows:Y=12,initialRows:X=null,initialMode:K="auto",dragThresholdRows:V=0,onHandleDoubleClick:G,controller:F}){super(J?{key:J}:{});if(Q>Y)throw Error("minRows must be <= maxRows");if(V<0)throw Error("dragThresholdRows must be >= 0");this.child=Z,this.minRows=Q,this.maxRows=Y,this.initialRows=X,this.initialMode=K,this.dragThresholdRows=V,this.onHandleDoubleClick=G,this.controller=F}createState(){return new oh4}}class oh4 extends f0{_mode="auto";_heightRows=3;_dragSession=null;_isHandleHovered=!1;initState(){super.initState(),this._syncToInitialProps()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.initialMode!==this.widget.initialMode||J.initialRows!==this.widget.initialRows){this._syncToInitialProps();return}this._heightRows=this._clampRows(this._heightRows)}build(J){let Z=this._mode==="manual"?new l0({height:this._heightRows,child:this.widget.child}):new l0({constraints:new E1(0,Number.POSITIVE_INFINITY,this.widget.minRows,this.widget.maxRows),child:this.widget.child});return new d6({children:[Z,this._buildHandleOverlay()]})}get _effectiveMinRows(){return this.widget.minRows}_buildHandleOverlay(){return new r5({top:0,left:0,right:0,height:1,child:new o1({cursor:G3.NS_RESIZE,onClick:this._handleHandlePress,onDrag:this._handleHandleDrag,onRelease:this._handleHandleRelease,onEnter:()=>this._setHandleHovered(!0),onExit:()=>this._setHandleHovered(!1),child:new I0({height:1})})})}_notifyController(){this.widget.controller?._update(this._mode,!!this._dragSession,this._isHandleHovered)}_setHandleHovered(J){if(this._isHandleHovered===J)return;this.setState(()=>{this._isHandleHovered=J,this._notifyController()})}_handleHandlePress=(J)=>{if(J.button!=="left")return;let Z=this._currentRenderedHeightRows(),Q=this._toTerminalRow(J.position.y),Y=J.clickCount===2?this.widget.onHandleDoubleClick?.({mode:this._mode,currentRows:Z,minRows:this._effectiveMinRows,maxRows:this.widget.maxRows}):void 0,X=this._mode==="manual"&&J.clickCount===2&&Y===void 0;this.setState(()=>{this._dragSession={modeAtStart:this._mode,baseHeightRows:Z,startRow:Q,currentRow:Q,resetToAutoOnRelease:X,doubleClickOverride:Y},this._notifyController()})};_handleHandleDrag=(J)=>{if(J.button!=="left"||!this._dragSession)return;let Z=this._toTerminalRow(J.position.y),Q=this._dragSession,Y=Z-Q.startRow,X=Q.modeAtStart==="manual"||Math.abs(Y)>=this.widget.dragThresholdRows;this.setState(()=>{if(Q.currentRow=Z,Y!==0)Q.resetToAutoOnRelease=!1,Q.doubleClickOverride=void 0;if(X)this._mode="manual",this._heightRows=this._clampRows(Q.baseHeightRows-Y);this._notifyController()})};_handleHandleRelease=(J)=>{if(J.button!=="left"||!this._dragSession)return;let Z=this._dragSession,Q=Z.currentRow-Z.startRow,Y=Z.doubleClickOverride==="auto-min"&&Q===0,X=Z.doubleClickOverride==="manual-max"&&Q===0,K=Z.resetToAutoOnRelease&&Q===0,V=Z.modeAtStart==="auto"&&this._mode==="auto"&&this.widget.dragThresholdRows===0&&Q===0;this.setState(()=>{if(Y)this._mode="auto",this._heightRows=this._clampRows(this._effectiveMinRows);else if(X)this._mode="manual",this._heightRows=this._clampRows(this.widget.maxRows);else if(K)this._mode="auto";else if(V)this._mode="manual",this._heightRows=this._clampRows(Z.baseHeightRows);this._dragSession=null,this._notifyController()})};_syncToInitialProps(){this._mode=this.widget.initialMode,this._heightRows=this._resolveInitialRows(),this._dragSession=null,this._notifyController()}_resolveInitialRows(){return this._clampRows(this.widget.initialRows??this._effectiveMinRows)}_clampRows(J){return Math.max(this._effectiveMinRows,Math.min(J,this.widget.maxRows))}_currentRenderedHeightRows(){return this.context.findRenderObject()?.size.height??this._heightRows}_toTerminalRow(J){return Math.floor(J)}}class o01 extends u0{childBuilder;minBodyRows;maxBodyRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;bottomRightLabel;constructor(J){let{key:Z,minBodyRows:Q=3,maxBodyRows:Y=12,initialRows:X=null,initialMode:K="auto",dragThresholdRows:V=0,onHandleDoubleClick:G,bottomRightLabel:F}=J;super(Z?{key:Z}:{});this.childBuilder="childBuilder"in J&&J.childBuilder?J.childBuilder:()=>J.child,this.minBodyRows=Q,this.maxBodyRows=Y,this.initialRows=X,this.initialMode=K,this.dragThresholdRows=V,this.onHandleDoubleClick=G,this.bottomRightLabel=F}createState(){return new rh4}}class rh4 extends f0{_controller=new n01;_onControllerChanged=()=>{this.setState(()=>{})};initState(){super.initState(),this._controller.addListener(this._onControllerChanged)}dispose(){this._controller.removeListener(this._onControllerChanged),this._controller.dispose(),super.dispose()}build(J){let Z=k1.of(J),Q=Z.colorScheme.border,X=this._controller.isResizing||this._controller.isHandleHovered?2:1,K=[];if(this.widget.bottomRightLabel)K.push({child:this.widget.bottomRightLabel,position:"bottom",alignment:"right"});return new a01({controller:this._controller,minRows:this.widget.minBodyRows+2,maxRows:this.widget.maxBodyRows+2,initialRows:this.widget.initialRows,initialMode:this.widget.initialMode,dragThresholdRows:this.widget.dragThresholdRows,onHandleDoubleClick:this.widget.onHandleDoubleClick,child:new H7({decoration:new e4(Z.colorScheme.background,new K4(new Y4(Q,X,"rounded"),new Y4(Q,1,"rounded"),new Y4(Q,1,"rounded"),new Y4(Q,1,"rounded"))),overlays:K,child:this.widget.childBuilder(this._controller.mode)})})}}a0();D4();qB();class r01 extends u0{createState(){return new sh4}}class sh4 extends f0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=y0.of(J).colors;return new $0({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function Cj3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return MG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function s01(J,Z,Q){return new $0({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function _j3(J,Z,Q,Y){return[s01("+",J,Y.success),B5.horizontal(1),s01("~",Z,Y.warning),B5.horizontal(1),s01("-",Q,Y.destructive)]}function Tj3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}var t01=["Alt+W","Ctrl+T"];function e01(J){return J?"all workspaces":"filter by workspace"}class ly extends u0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new th4}}class th4 extends f0{spinner=new A5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=Cj3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=y0.of(J),U=new m0({padding:R0.symmetric(0,1),child:new s1({child:new $0({text:new P("",new g({color:H.colors.foreground,dim:!0}),[new P(t01.join("/"),new g({color:H.colors.primary,dim:!0})),new P(` ${Z.filterByWorkspace?"for":"to"} ${e01(Z.filterByWorkspace===!0)}`,new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=I9(L);return B};return new p3({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!Tj3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,showBorder:Z.showBorder,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError||Z.showInlineWorkspaceFilterHint===!1?void 0:U,renderItem:(L,O,E,M)=>{let A=y0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,C=O?j.selectionForeground:R.foreground,b=R.mutedForeground,d=(t,B0)=>new I0({width:B0,child:q1.end([new $0({text:new P(t,new g({color:b}))})])}),f=Z.threadViewStates[L.id],y=[],x=L.relationshipType==="handoff",m=new jo({connectorColor:R.mutedForeground});if(L.depth>0){let t=[],B0=L.ancestorsAreLast.slice(1);for(let q0 of B0)t.push(new P(m.getAncestorPrefix(q0),new g({color:m.connectorColor,dim:m.connectorDim})));let a=L.isLast?m.elbow:m.tee,J0=m.getConnectorText(a);t.push(new P(J0,new g({color:m.connectorColor,dim:m.connectorDim}))),y.push(new $0({text:new P("",void 0,t)}))}let p=[],h=F===L.id?new P("(current) ",new g({color:R.success})):G.has(L.id)?new P("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new $0({text:h}));if(LA(f))p.push(new r01),p.push(new I0({width:1}));let o=L.title;if(L.relationshipType==="fork"){let t=o.match(/^Forked\((\d+)\): /);if(t)o=o.slice(t[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);p.push(new $0({text:new P("[fork] ",new g({color:R.primary}))}))}else if(x)p.push(new $0({text:new P("[handoff] ",new g({color:R.accent}))}));if(p.push(new b1({child:new $0({text:new P(o,new g({color:C})),overflow:"ellipsis",maxLines:1})})),p.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let t=O?{success:b,warning:b,destructive:b}:R;p.push(..._j3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,t)),p.push(new I0({width:2}))}return p.push(d(L.description.timeAgo,W)),new l0({decoration:_?{color:_}:void 0,padding:R0.symmetric(2,0),child:new q1({children:[...y,...p]})})}})}}I1();function $11(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),K=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(K<=4)return`${K}w ago`;return`${V}mo ago`}class J11{threadService;constructor(J){this.threadService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y,X)=>{let K=this.threadService.observeThreadList(Z).subscribe({next:(V)=>{K.unsubscribe(),Y(V)},error:X})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadService.observeThreadList({includeArchived:Z.includeArchived??!1}).pipe(M1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let K=X.title?.toLowerCase()||"untitled",V=X.id.toLowerCase(),G=Z.toLowerCase();return K.includes(G)||V.includes(G)}).map((X)=>{let K=new Date(X.userLastInteractedAt),V=$11(K),G=X.id.slice(-8),F=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:V,title:X.title||"Untitled",shortThreadID:G},diffStats:X.summaryStats?.diffStats,workspaceURI:F,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}function Sj3(J){return J.filter((Z)=>!Z.mainThreadID&&!Z.archived).sort((Z,Q)=>new Date(Q.userLastInteractedAt).getTime()-new Date(Z.userLastInteractedAt).getTime()).map((Z)=>{let Q=Z.title||"Untitled",Y=new Date(Z.userLastInteractedAt),X=Z.env?.initial.trees?.[0]?.uri;return{id:Z.id,title:Q,updatedAt:Y.toISOString(),description:{timeAgo:$11(Y),title:Q,shortThreadID:Z.id.slice(-8)},diffStats:Z.summaryStats?.diffStats,workspaceURI:X,relationships:Z.relationships,agentMode:Z.agentMode,details:{messageCount:Z.summaryStats?.messageCount},archived:Z.archived}})}class eh4 extends u0{props;constructor(J){super();this.props=J}createState(){return new $g4}}class $g4 extends f0{threadViewStates={};currentWorkspaceURI=n1(K1.file(process.cwd()));threads=[];isLoading=!0;hasError=!1;filterByWorkspace=!0;handleKeyEvent=(J)=>{if(J.ctrlKey&&J.key.toLowerCase()==="t"||J.altKey&&J.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace}),"handled";return"ignored"};initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let J=await this.widget.props.loadThreads(),Z=Sj3(J);if(!this.mounted)return;this.setState(()=>{this.threads=Z,this.isLoading=!1,this.hasError=!1})}catch(J){if(S.error("Failed to load threads for Neo command palette",{error:J}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}build(J){let Z=[{keys:t01,label:e01(this.filterByWorkspace)},{keys:["Esc"],label:"close"}];return new RZ({header:this.widget.props.title,autofocus:!1,chromePadding:R0.symmetric(1,0),footer:Z,onDismiss:this.widget.props.onDismiss,child:new n4({onKey:this.handleKeyEvent,debugLabel:"ThreadSwitchPicker",child:new ly({threads:this.threads,showBorder:!1,showInlineWorkspaceFilterHint:!1,onSelect:this.widget.props.onSelect,onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,hasError:this.hasError,currentWorkspaceURI:this.currentWorkspaceURI,filterByWorkspace:this.filterByWorkspace,threadViewStates:this.threadViewStates,currentThreadID:this.widget.props.activeThreadID??void 0,excludeCurrentThread:this.widget.props.excludeCurrentThread})})})}}function Jg4(J,Z){return new eh4({title:Z.title,activeThreadID:J.activeThreadID,loadThreads:J.loadThreads,excludeCurrentThread:Z.excludeCurrentThread,onSelect:async(Q)=>{try{await J.onSelectThread(Q),J.onThreadSelected()}catch(Y){Z.logFailure(Q,Y)}},onDismiss:J.onDismiss})}function Z11(J){return Jg4(J,{title:"Switch Thread",excludeCurrentThread:!1,logFailure:(Z,Q)=>{S.error("Failed to switch thread",{error:Q,threadID:Z})}})}function Q11(J){return Jg4(J,{title:"Mention Thread",excludeCurrentThread:!0,logFailure:(Z,Q)=>{S.error("Failed to mention thread",{error:Q,threadID:Z})}})}class Y11 extends u0{props;constructor(J){super();this.props=J}createState(){return new Zg4}}var kj3=0;class Zg4 extends f0{imageEntries=[];pendingUploads=new Map;isShowingShortcutsHelp=!1;removeKeyInterceptor=null;imagePreviewOverlay=null;mentionPickerOverlay=null;unregisterCommands=null;initState(){super.initState(),this.isShowingShortcutsHelp=this.widget.props.showShortcutsHelp??!1,this.unregisterCommands=this.registerCommands(),this.removeKeyInterceptor=l4.instance.addKeyInterceptor((J)=>{let Z=this.widget.props.editorController;if(J.key==="?"){if(Z.text===""&&Z.cursorPosition===0)return this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!0}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),J.key==="Escape")return!0;return!1}return!1})}dispose(){this.dismissImagePreview(),this.dismissMentionPicker(),this.unregisterCommands?.(),this.unregisterCommands=null,this.removeKeyInterceptor?.(),this.removeKeyInterceptor=null,super.dispose()}registerCommands(){let J=YV.of(this.context),Z={noun:"thread",verb:"mention",description:"Mention a thread",keywords:["reference","link","attach","cite"],status:{type:"enabled"},run:(Q,Y,X)=>{Q.pushWithDismiss((K)=>Q11({activeThreadID:this.widget.props.activeThreadID,loadThreads:()=>l$.of(this.context).listThreads(),onSelectThread:(V)=>{this.insertThreadMention(V)},onDismiss:K,onThreadSelected:X}))}};return J.register(Z)}handleDoubleAtTrigger=()=>{this.showMentionPicker()};showMentionPicker(){this.dismissMentionPicker();let J=new jL(()=>Q11({activeThreadID:this.widget.props.activeThreadID,loadThreads:()=>l$.of(this.context).listThreads(),onSelectThread:(Z)=>{this.insertThreadMention(Z)},onDismiss:()=>this.dismissMentionPicker(),onThreadSelected:()=>this.dismissMentionPicker()}));this.mentionPickerOverlay=J,pQ.of(this.context).insert(J)}dismissMentionPicker(){if(this.mentionPickerOverlay)this.mentionPickerOverlay.remove(),this.mentionPickerOverlay=null}insertThreadMention(J){let Z=this.widget.props.editorController,Q=Z.text,Y=Z.cursorPosition,K=Q.slice(0,Y).lastIndexOf("@@");if(K!==-1){let V=Q.slice(Y),G=V.length===0,F=`@${J}${G?" ":""}`,z=Q.slice(0,K)+F+V;Z.text=z,Z.cursorPosition=K+F.length;return}Z.insertText(`@${J} `)}handleInsertImage=async(J)=>{if(this.imageEntries.length>=wY)return!1;let Z=await sq(J);if(typeof Z==="string")return!1;let Q=kj3++,Y={id:Q,image:Z,uploading:!1};if(Z.source.type==="base64")Y.uploading=!0,this.setState(()=>{this.imageEntries=[...this.imageEntries,Y]}),this.uploadEntryInBackground(Q,Z.source);else this.setState(()=>{this.imageEntries=[...this.imageEntries,Y]});return!1};async uploadEntryInBackground(J,Z){let Q=(async()=>{try{let{configService:Y}=l$.of(this.context),X=await fh4(Z,Y);if(!this.mounted)return;let K=this.imageEntries.find((G)=>G.id===J);if(!K)return;let V=xh4(X)?K.image:{type:"image",source:{type:"url",url:X},sourcePath:K.image.sourcePath};this.setState(()=>{this.imageEntries=this.imageEntries.map((G)=>G.id===J?{...G,image:V,uploading:!1}:G)})}catch(Y){if(S.error("Failed to upload image attachment",{error:Y}),!this.mounted)return;this.setState(()=>{this.imageEntries=this.imageEntries.map((X)=>X.id===J?{...X,uploading:!1}:X)})}finally{this.pendingUploads.delete(J)}})();this.pendingUploads.set(J,Q)}handlePopImage=()=>{if(this.imageEntries.length===0)return;let J=this.imageEntries[this.imageEntries.length-1];if(J)this.pendingUploads.delete(J.id);this.setState(()=>{this.imageEntries=this.imageEntries.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageEntries[J];if(!Z||Z.uploading)return;this.dismissImagePreview();let Q=new jL(()=>new oI({image:Z.image,imageIndex:J,onDismiss:()=>this.dismissImagePreview(),onRemove:()=>{this.dismissImagePreview();let Y=this.imageEntries[J];if(Y)this.pendingUploads.delete(Y.id);this.setState(()=>{this.imageEntries=this.imageEntries.filter((X,K)=>K!==J)})}}));this.imagePreviewOverlay=Q,pQ.of(this.context).insert(Q)};dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}handleSubmitted=(J)=>{if(this.pendingUploads.size>0)this.waitAndSubmit(J);else{let Z=this.imageEntries.map((Q)=>Q.image);this.setState(()=>{this.imageEntries=[]}),this.widget.props.onSubmitted(J,Z)}};async waitAndSubmit(J){if(await Promise.all(this.pendingUploads.values()),!this.mounted)return;let Z=this.imageEntries.map((Q)=>Q.image);this.setState(()=>{this.imageEntries=[]}),this.widget.props.onSubmitted(J,Z)}uploadingIndices(){let J=new Set;for(let Z=0;Z<this.imageEntries.length;Z++)if(this.imageEntries[Z]?.uploading)J.add(Z);return J}build(J){let{editorController:Z,queuedMessages:Q,selectedQueuedMessageIndex:Y,maxBodyRows:X}=this.widget.props,K=Q.length>0,V=k1.of(J),G=[];if(K)G.push(new m0({padding:R0.horizontal(1),child:new dy({queuedMessages:Q,selectedIndex:Y})}));return G.push(new o01({initialRows:3,minBodyRows:3,maxBodyRows:X,bottomRightLabel:this.widget.props.bottomRightLabel,onHandleDoubleClick:({currentRows:F,maxRows:z})=>F>=z?"auto-min":"manual-max",childBuilder:(F)=>new m0({padding:R0.horizontal(1),child:new oU({controller:Z,triggers:[new KV],completionBuilder:gy.of(J),autoOverlayPosition:!0,theme:V.colorScheme,onInsertImage:this.handleInsertImage,imageAttachments:this.imageEntries.map((z)=>z.image),popImage:this.handlePopImage,onImageClick:this.handleImageClick,uploadingImageIndices:this.uploadingIndices(),enabled:this.widget.props.editorEnabled,onDoubleAtTrigger:this.handleDoubleAtTrigger,onSubmitted:this.handleSubmitted,fillAvailableHeight:F==="manual",topWidget:this.isShowingShortcutsHelp?new _o:void 0})})})),new o1({onClick:!this.widget.props.editorEnabled?()=>D5.maybeInvoke(this.context,new Bo):void 0,child:new uK0({children:G})})}}k8();UB();import vj3 from"node:path";function yj3(J){try{return decodeURIComponent(J)}catch{return J}}function Qg4(J,Z){if(!J?.enabled||!J.authenticated)return null;let Q=J.selections?.[0],Y=!cC(Q)&&Q?Q.range.endLine-Q.range.startLine+1:0,X=[];if(J.openFile)X.push(vj3.basename(yj3(J.openFile)));else if(J.ideName)X.push(J.ideName);if(Q&&Y>0)X.push(`${Y} selected ${j4(Y,"line")}`);if(X.length===0)return null;let K=`✓ ${X.join(" • ")}`;return new $0({text:new P(K,new g({color:Z.app.ideConnected})),textAlign:"right",maxLines:1,overflow:"clip"})}var Yg4=[fy,Ho,Wo];class X11 extends S1{hints;agentLoopState;compactionState;connectionState;pendingSend;statusMessageOverride;ideStatus;constructor(J){super();this.hints=J.hints,this.agentLoopState=J.agentLoopState,this.compactionState=J.compactionState,this.connectionState=J.connectionState,this.pendingSend=J.pendingSend,this.statusMessageOverride=J.statusMessageOverride??null,this.ideStatus=J.ideStatus}build(J){let Z=y0.of(J),Q=[],Y=mj3(this.agentLoopState,this.compactionState,this.connectionState,this.pendingSend),X=xj3(this.hints),K=this.statusMessageOverride;if(X){if(Y||X===fy)Xg4(Z,Q);bj3(Q,hj3(X,J))}else if(K)uj3(Z,K,Q);else if(Y)Xg4(Z,Q),fj3(Z,Y,Q);let V=Qg4(this.ideStatus,Z);if(!V&&Q.length===0)return new I0({width:0,height:0});let G=[...Q];if(V)G.push(B5.flexible()),G.push(V);return new q1({children:G,mainAxisSize:"max",mainAxisAlignment:"start"})}}function xj3(J){for(let Z=Yg4.length-1;Z>=0;Z--){let Q=Yg4[Z];if(J.has(Q))return Q}return}function Xg4(J,Z){Z.push(new Eo({color:J.colors.primary})),Z.push(B5.horizontal(1))}function fj3(J,Z,Q){Q.push(new $0({text:new P(Z,new g({color:J.colors.foreground,dim:!0})),textAlign:"left",maxLines:1,overflow:"clip"}))}function uj3(J,Z,Q){Q.push(new $0({text:new P(Z,new g({color:J.colors.destructive})),textAlign:"left",maxLines:1,overflow:"clip"}))}function bj3(J,Z){J.push(new $0({text:Z,textAlign:"left",maxLines:1,overflow:"clip"}))}function hj3(J,Z){let Q=y0.of(Z),Y=new g({color:Q.app.keybind}),X=new g({color:Q.colors.foreground,dim:!0});switch(J){case Wo:return new P("",void 0,[new P("Ctrl+C",Y),new P(" again to exit",X)]);case Ho:return new P("",void 0,[new P("Esc",Y),new P(" again to cancel",X)]);case fy:return new P("Loading thread…",X)}}function gj3(J){switch(J){case"connected":return null;case"authenticating":return"Authenticating...";default:return"Connecting..."}}function mj3(J,Z,Q,Y){if(Z==="compacting")return"Auto-compacting...";if(Y&&J==="idle")return gj3(Q)??"Sending message...";switch(J){case"working":return"Waiting for response...";case"streaming":return"Streaming response...";case"tool_use":case"running_tools":return"Running tools...";case"awaiting_approval":return"Waiting for approval...";case"error":return"Error";case"idle":return null}}class K11 extends S1{props;constructor(J){super();this.props=J}build(J){if(!l$.of(J).isInternalUser)return new I0;let Q=k1.of(J),Y=this.props.connectionInfo?.state??"disconnected",X=this.props.connectionInfo?.role??null,K=Y==="connected"?X??"connected":Y;return new m0({padding:R0.horizontal(1),child:new $0({text:new P(`(neo: ${K})`,new g({color:Q.colorScheme.mutedForeground,dim:!0})),textAlign:"left"})})}}class To extends S1{props;constructor(J){super();this.props=J}onSubmitted=(J,Z)=>{let Q=J.trim();if(Q.length===0&&Z.length===0)return;let Y=[];if(Q.length>0)Y.push({type:"text",text:Q});Y.push(...Z),this.props.onSubmit(Y),this.props.editorController.clear()};build(J){let{child:Z,editorController:Q,hints:Y,agentState:X,compactionState:K,connectionInfo:V,pendingSend:G,agentMode:F,deepReasoningEffort:z,speedSuffix:q,queuedMessages:W,selectedQueuedMessageIndex:H,editorEnabled:U,statusMessageOverride:D,activeError:B,onErrorResponse:N}=this.props,w=G4.of(J),{width:L,height:O}=w.size,E=Sh4(J,this.props.environment),M=new Map([[t1.key("ArrowUp"),new by],[t1.key("Tab"),new by],[t1.key("ArrowDown"),new uy],[t1.shift("Tab"),new uy],[t1.key("Enter"),new Do],[t1.key("Backspace"),new Uo],[t1.key("PageUp"),new wo],[t1.key("PageDown"),new Lo]]),A=B?new m01({error:B,onResponse:(R)=>N?.(R)}):new Y11({editorController:Q,activeThreadID:this.props.activeThreadID,queuedMessages:W,selectedQueuedMessageIndex:H,editorEnabled:U,maxBodyRows:Math.floor(w.size.height/3),onSubmitted:this.onSubmitted,showShortcutsHelp:this.props.showShortcutsHelp,bottomRightLabel:E}),j=[new p01,new b1({child:Z}),new I0({height:1,child:new q1({mainAxisAlignment:"end",children:[new K11({connectionInfo:V}),B5.flexible(),new m0({padding:R0.horizontal(1),child:new g01({agentMode:F,deepReasoningEffort:z,speedSuffix:q})})]})}),A,new I0({width:L,height:1,child:new X11({hints:Y,agentLoopState:X==="error"?"idle":X,compactionState:K,connectionState:V?.state??"disconnected",pendingSend:G,statusMessageOverride:D,ideStatus:this.props.ideStatus})})];return new w9({shortcuts:M,child:new pQ({child:new l0({constraints:E1.tight(L,O),child:new p0({mainAxisSize:"max",crossAxisAlignment:"stretch",children:j})})})})}}class V11 extends u0{editorController;client;observer;hints;ideStatus;onPromptSubmitted;constructor(J){super({key:new V5(J.observingClient.client.getThreadId())});this.editorController=J.editorController,this.client=J.observingClient.client,this.observer=J.observingClient.observer,this.hints=J.hints,this.ideStatus=J.ideStatus,this.onPromptSubmitted=J.onPromptSubmitted}createState(){return new Kg4}}class Kg4 extends f0{agentState=new EZ(this,"idle");connectionInfo=new EZ(this,null);pendingSend=new EZ(this,!1);compactionState=new EZ(this,"idle");queuedMessages=new EZ(this,[]);activeError=new EZ(this,null);threadSettings=new EZ(this,null);environment=new EZ(this,null);cancelHintTimer=new Oa(this,1000);threadController=null;controllerUnsubscription=null;imagePreviewOverlay=null;initState(){this.recreateThreadController(),this.subscribeToObserver()}didUpdateWidget(J){if(J.client!==this.widget.client||J.observer!==this.widget.observer)this.recreateThreadController(),this.resetThreadClientState(),this.subscribeToObserver()}resetThreadClientState(){this.agentState.dispose(),this.connectionInfo.dispose(),this.pendingSend.dispose(),this.compactionState.dispose(),this.queuedMessages.dispose(),this.activeError.dispose(),this.threadSettings.dispose(),this.environment.dispose()}subscribeToObserver(){this.agentState.subscribe(this.widget.observer.agentState()),this.connectionInfo.subscribe(this.widget.observer.connectionInfo()),this.pendingSend.subscribe(this.widget.observer.pendingSend()),this.compactionState.subscribe(this.widget.observer.compactionState()),this.queuedMessages.subscribe(this.widget.observer.queuedMessages()),this.activeError.subscribe(this.widget.observer.activeError()),this.threadSettings.subscribe(this.widget.observer.threadSettings()),this.environment.subscribe(this.widget.client.environmentChanges())}subscribeToThreadController(){let J=this.threadController;if(!J)return;this.controllerUnsubscription=J.subscribe(()=>{this.setState()})}recreateThreadController(){this.controllerUnsubscription?.(),this.threadController?.dispose(),this.threadController=new I01(this.widget.observer.reader(),this.widget.observer.groupedReader(),this.widget.observer.agentMode),this.subscribeToThreadController()}onEscPressed=()=>{if(this.threadController?.hasSelection)return this.threadController.clearSelection(),"handled";if(!rj(this.agentState.getValue()))return"ignored";if(this.cancelHintTimer.isActive())this.cancelHintTimer.clear(),this.widget.client.cancelAgentLoop();else this.cancelHintTimer.activate();return"handled"};buildHints(){let J=new Set(this.widget.hints);if(this.cancelHintTimer.isActive())J.add(Ho);return J}dispose(){this.dismissImagePreview(),this.controllerUnsubscription?.(),this.threadController?.dispose(),super.dispose()}onShowImagePreview=(J,Z,Q)=>{this.showOverlay(J,()=>new oI({image:Z,imageIndex:Q,onDismiss:()=>this.dismissImagePreview()}))};onShowFileImagePreview=(J)=>{this.showOverlay(this.context,()=>new TI({filePath:J,onDismiss:()=>this.dismissImagePreview()}))};showOverlay(J,Z){this.dismissImagePreview();let Q=new jL(Z);this.imagePreviewOverlay=Q,pQ.of(J).insert(Q)}dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}onErrorResponse=(J)=>{let{client:Z,observer:Q}=this.widget;switch(J){case"retry":Q.dismissActiveError(),Z.retryAgentLoop();break;case"dismiss":Z.dismissActiveError(Q.getActiveErrorSeq()??void 0),Q.dismissActiveError();break;case"add-credits":break}};getSelectedQueuedMessage(){let J=this.threadController?.selectedQueuedMessageIndex;if(J===null||J===void 0)return null;return this.queuedMessages.getValue()[J]??null}build(J){let{editorController:Z,client:Q}=this.widget,Y=this.threadController,X=this.widget.observer.agentMode,K=this.queuedMessages.getValue();Y.setQueuedMessageCount(K.length);let{deepReasoningEffort:V,speedSuffix:G}=EG0(X,this.threadSettings.getValue()),F=new d4(()=>{return this.onEscPressed()}),z=new d4(()=>{let w=this.getSelectedQueuedMessage();if(!w)return"ignored";return Q.interruptQueuedMessage(w.queuedMessage.messageId),"handled"}),q=new d4(()=>{let w=this.getSelectedQueuedMessage();if(!w)return"ignored";return Q.removeQueuedMessage(w.queuedMessage.messageId),Z.text=dy.rowText(w),Y.clearSelection(),"handled"}),W=new d4(()=>{return Y.selectPrevious()?"handled":"ignored"}),H=new d4(()=>{return Y.selectNext()?"handled":"ignored"}),U=new d4(()=>{return Y.onPageUp?.(),"handled"}),D=new d4(()=>{return Y.onPageDown?.(),"handled"}),B=new d4(()=>{return Y.clearSelection(),"handled"});return new D5({actions:new Map([[zG0,F],[Bo,B],[Do,z],[Uo,q],[by,W],[uy,H],[wo,U],[Lo,D]]),child:new w9({shortcuts:new Map([[t1.key("Escape"),new zG0]]),child:new XL({onShowImagePreview:this.onShowFileImagePreview,child:new To({child:new f01({threadController:Y,subagentReaderProvider:(w)=>this.widget.observer.subagentReader(w),onShowImagePreview:this.onShowImagePreview}),editorController:Z,activeThreadID:Q.getThreadId()??null,queuedMessages:K,selectedQueuedMessageIndex:Y.selectedQueuedMessageIndex,editorEnabled:!Y.hasSelection,hints:this.buildHints(),agentState:this.agentState.getValue(),compactionState:this.compactionState.getValue(),connectionInfo:this.connectionInfo.getValue(),pendingSend:this.pendingSend.getValue(),agentMode:X,deepReasoningEffort:V,speedSuffix:G,activeError:this.activeError.getValue(),onErrorResponse:this.onErrorResponse,ideStatus:this.widget.ideStatus,environment:this.environment.getValue(),onSubmit:(w)=>{let L=w.find((E)=>E.type==="text");if(L&&L.type==="text")this.widget.onPromptSubmitted(L.text);this.widget.observer.markMessageSent();let O=xJ0(this.widget.ideStatus);Q.sendUserMessage(w,void 0,{userState:O}),Y.onScrollToBottom?.()}})})})})}}function Vg4(J,Z){return{noun:"thread",verb:"archive and exit",description:"Archive thread and exit",keywords:["close","done","finish","quit"],get status(){return Z()?{type:"enabled"}:{type:"disabled",reason:"Cannot archive an empty thread"}},run:(Q,Y,X)=>{let K=Z()?.client.getThreadId();if(!K)return;(async()=>{let V=await J.archiveThread(K);if(X(),V===null)D5.maybeInvoke(Y,new hy)})()}}}_2();var rU=" .:-=+*#%@",iy=0.5,RL=64,pj3=30,So=0.9,Fg4=1.4,G11=So+Fg4,F11=6,Gg4=0.5,dj3=1.6,cj3=28;class z11 extends u0{originX;originY;agentMode;primaryColor;secondaryColor;fps;onComplete;constructor({originX:J,originY:Z,agentMode:Q,primaryColor:Y,secondaryColor:X,fps:K=pj3,onComplete:V,key:G}){super(G?{key:G}:{});this.originX=J,this.originY=Z,this.agentMode=Q,this.primaryColor=Y,this.secondaryColor=X,this.fps=K,this.onComplete=V}createState(){return new zg4}}class zg4 extends f0{elapsed=0;timer=null;startMs=0;completed=!1;glow=new bQ;initState(){if(super.initState(),this.startMs=performance.now(),this.widget.fps<=0){this.elapsed=G11,this.complete();return}let J=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsed=(performance.now()-this.startMs)/1000,this.elapsed>=G11){this.elapsed=G11,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},J)}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(J){let Z=k1.of(J);return new qg4({originX:this.widget.originX,originY:this.widget.originY,elapsed:this.elapsed,agentMode:this.widget.agentMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Z.colorScheme.background,glow:this.glow})}}class qg4 extends q7{props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new IJ(this)}createRenderObject(){return new Wg4(this.props)}updateRenderObject(J){J.update(this.props)}}function lj3(J){let Z=J>>>0;return()=>{Z=Z+1831565813>>>0;let Q=Z;return Q=Math.imul(Q^Q>>>15,Q|1),Q^=Q+Math.imul(Q^Q>>>7,Q|61),((Q^Q>>>14)>>>0)/4294967296}}class Wg4 extends q4{_props;_palette=[];_paletteSignature="";_fragments=null;_fragmentRadius=0;constructor(J){super();this._props=J,this.rebuildPalette()}update(J){let Z=J.agentMode!==this._props.agentMode||J.primaryColor!==this._props.primaryColor||J.secondaryColor!==this._props.secondaryColor;if(this._props=J,Z)this.rebuildPalette();this.markNeedsPaint()}rebuildPalette(){let J=this._props.primaryColor&&this._props.secondaryColor?{primary:this._props.primaryColor,secondary:this._props.secondaryColor}:void 0;this._palette=Array.from({length:RL},(Z,Q)=>{let Y=Q/(RL-1);return $a(Y,this._props.agentMode,J)}),this._paletteSignature=`${this._props.agentMode??"smart"}|${this._props.primaryColor?`${this._props.primaryColor.r},${this._props.primaryColor.g},${this._props.primaryColor.b}`:""}|${this._props.secondaryColor?`${this._props.secondaryColor.r},${this._props.secondaryColor.g},${this._props.secondaryColor.b}`:""}`}performLayout(){let J=this._lastConstraints,Z=J.constrain(J.biggest.width,J.biggest.height);this.setSize(Z.width,Z.height),super.performLayout()}getMaxRadius(J,Z){let Q=J*Gg4,Y=Z*Gg4*(1/iy);return Math.max(F11+1,Math.min(Q,Y))}buildFragments(J){let Z=lj3(2654435761),Q=[],Y=Math.min(600,Math.max(120,Math.floor(J*J*0.45)));for(let X=0;X<Y;X++){let K=Math.sqrt(Z()),V=Z()*Math.PI*2,G=Math.cos(V)*K*J,F=Math.sin(V)*K*J*iy,z=(0.5+K*0.9)*dj3*J,q=0.7+Z()*0.6,W=Math.cos(V)*z*q,H=Math.sin(V)*z*q*iy-Z()*J*0.6,U=0.4+Z()*0.6,D=Math.min(rU.length-1,Math.floor(U*rU.length));Q.push({x:G,y:F,vx:W,vy:H,glyph:rU[D]||"*",intensity:U})}return Q}paint(J,Z=0,Q=0){let{elapsed:Y,originX:X,originY:K,backgroundColor:V,glow:G}=this._props,F=Z+this.offset.x,z=Q+this.offset.y,q=Math.floor(this.size.width),W=Math.floor(this.size.height),H=J.getSize(),U=H.width,D=H.height,B=this._palette;this._paletteSignature;let N=this.getMaxRadius(q,W),w=X-F,L=K-z;if(Y<So){let j=1-(1-Y/So)**3,R=F11+(N-F11)*j;this.paintOrb(J,F,z,w,L,R,1,Y,G,B,V,U,D);return}if(!this._fragments||this._fragmentRadius!==N)this._fragments=this.buildFragments(N),this._fragmentRadius=N;let O=Math.min(1,(Y-So)/Fg4);if(O<0.2){let A=1-O/0.2;this.paintOrb(J,F,z,w,L,N,A,Y,G,B,V,U,D)}let E=Y-So,M=1-O;for(let A of this._fragments){let j=A.x+A.vx*E,R=A.y+A.vy*E+0.5*cj3*E*E,_=Math.round(F+w+j),C=Math.round(z+L+R);if(_<0||_>=U||C<0||C>=D)continue;let b=Math.max(0.05,A.intensity*M),d=Math.min(rU.length-1,Math.floor(b*rU.length)),f=O>0.7?".":rU[d]||A.glyph,y=Math.min(RL-1,Math.floor(b*RL)),x=B[y]||B[RL-1];if(!x)continue;J.setCell(_,C,{char:f,width:1,style:{fg:x,bg:V,dim:O>0.55,bold:O<0.15}})}}paintOrb(J,Z,Q,Y,X,K,V,G,F,z,q,W,H){let U=Math.max(1,K),D=U*U,B=1/D,N=1/iy,w=Math.max(0,Math.floor(X-U*iy)),L=Math.min(H-Q-1,Math.ceil(X+U*iy));for(let O=w;O<=L;O++){let E=Q+O;if(E<0||E>=H)continue;let M=(O-X)*N,A=M*M;if(A>=D)continue;let j=Math.sqrt(D-A),R=Math.max(0,Math.floor(Y-j)),_=Math.min(W-Z-1,Math.ceil(Y+j));for(let C=R;C<=_;C++){let b=C-Y,d=b*b+A;if(d>=D)continue;let f=1-d*B,x=F.sample(C,O,G,1)*f*V;if(x<=0)continue;let m=Math.min(rU.length-1,Math.floor(x*rU.length)),p=rU[m]||" ",h=Math.min(RL-1,Math.floor(x*RL)),o=z[h]||z[RL-1];if(!o)continue;let l=Z+C;if(l<0||l>=W)continue;J.setCell(l,E,{char:p,width:1,style:{fg:o,bg:q}})}}}}var CG0=5,Hg4=3.8,Ug4=280;var ij3=["*","+",".",":","'"];function Dg4(J,Z,Q=Date.now()){return Math.floor(J)*73856093^Math.floor(Z)*19349663^Q}function Bg4(J,Z,Q={}){let{burstParticleCount:Y=72,burstSpeedMin:X=10,burstSpeedRange:K=16,rainSpeedMin:V=4,rainSpeedRange:G=9,burstDelayMax:F=0.18,rainDelayMax:z=1,burstLifetimeMin:q=1.4,burstLifetimeRange:W=1.2,rainLifetimeMin:H=2.8,rainLifetimeRange:U=1.8,burstDriftMin:D=0.3,burstDriftRange:B=0.9,rainDriftMin:N=0.8,rainDriftRange:w=1.8,rainAngleCenter:L=Math.PI/2,rainAngleSpread:O=1.4,colorIndexCount:E=6,sparkleGlyphs:M=ij3}=Q,A=nj3(J),j=[];for(let R=0;R<Z;R++){let _=R<Y,C=_?A()*Math.PI*2:L+(A()-0.5)*O,b=_?X+A()*K:V+A()*G,d=_?A()*F:A()*z,f=_?q+A()*W:H+A()*U,y=_?D+A()*B:N+A()*w,x=A()*Math.PI*2,m=M[Math.floor(A()*M.length)]??"*";j.push({kind:_?"burst":"rain",angle:C,speed:b,delay:d,lifetime:f,drift:y,phase:x,glyph:m,colorIndex:Math.floor(A()*E)})}return j}function Ng4(J,Z){let{elapsedSeconds:Q,originX:Y,originY:X,unitScale:K=1}=Z,V=Q-J.delay;if(V<0||V>J.lifetime)return null;let G=J.kind==="burst"?9:12,F=J.speed*K,z=Math.cos(J.angle)*F,q=Math.sin(J.angle)*F,W=Math.sin((V+J.phase)*8)*J.drift*K;return{x:Y+z*V+W,y:X+q*V+G*K*V*V,progress:V/J.lifetime}}function nj3(J){let Z=J>>>0;if(Z===0)Z=2654435769;return()=>{return Z=Z*1664525+1013904223>>>0,Z/4294967296}}class _G0 extends q7{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:J,text:Z,baseColor:Q,backgroundColor:Y,glow:X,time:K,agentMode:V,orbWidth:G=40,orbHeight:F=40,glowIntensity:z=0.4,shockwaves:q=[]}){super(J?{key:J}:{});this.text=Z,this.baseColor=Q,this.backgroundColor=Y,this.glow=X,this.time=K,this.agentMode=V,this.orbWidth=G,this.orbHeight=F,this.glowIntensity=z,this.shockwaves=q}createElement(){return new IJ(this)}createRenderObject(){return new wg4(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(J){J.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var aj3=0.5;class wg4 extends q4{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(J,Z,Q,Y,X,K,V,G,F,z){super();this._text=J;this._baseColor=Z;this._backgroundColor=Q;this._glow=Y;this._time=X;this._agentMode=K;this._orbWidth=V;this._orbHeight=G;this._glowIntensity=F;this._shockwaves=z}update(J,Z,Q,Y,X,K,V,G,F,z){let q=J!==this._text;if(this._text=J,this._baseColor=Z,this._backgroundColor=Q,this._glow=Y,this._time=X,this._agentMode=K,this._orbWidth=V,this._orbHeight=G,this._glowIntensity=F,this._shockwaves=z,q)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(J){return Q5(this._text,!1)}getMaxIntrinsicWidth(J){return Q5(this._text,!1)}getMinIntrinsicHeight(J){return 1}getMaxIntrinsicHeight(J){return 1}performLayout(){let J=this._lastConstraints;h4(!!J,"performLayout called without constraints");let Z=Q5(this._text,!1),Q=J.constrain(Z,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=f6(this._text),V=this._agentMode==="rush"?2.5:1,{primary:G,secondary:F}=Nr0(this._agentMode),z=Y;for(let q=0;q<K.length;q++){let W=K[q],H=V3(W,!1),D=(1-q/Math.max(K.length-1,1)*0.7)**1.2,B=this._glow.sample(this._orbWidth-2+q*0.5,this._orbHeight/2,this._time,V),N=0;for(let E of this._shockwaves){let M=this._time-E.startTime;if(M<0||M>$L)continue;let A=this._orbWidth*0.7+q,j=this._orbHeight/2,R=A-E.x,_=(j-E.y)/aj3,C=Math.sqrt(R*R+_*_),b=M*Lr0,d=Math.abs(C-b);if(d<WI){let f=1-M/$L,y=(1-d/WI)*f;N=Math.max(N,y*0.6)}}let w=B**0.7,L=Math.min(1,w*D+N),O=this.blendWithGlow(this._baseColor,L,G,F);J.setCell(z,X,{char:W,width:H,style:{fg:O,bg:this._backgroundColor}}),z+=H}}blendWithGlow(J,Z,Q,Y){let X=YK0(Q,Y,Z),K=Z*this._glowIntensity;if(J.type==="rgb"){let V=J.value,G=Math.round(V.r*(1-K)+X.r*K),F=Math.round(V.g*(1-K)+X.g*K),z=Math.round(V.b*(1-K)+X.b*K);return{type:"rgb",value:{r:G,g:F,b:z}}}if(K>0.15)return{type:"rgb",value:{r:X.r,g:X.g,b:X.b}};return J}}var Lg4=["ctrl+x","y","z"],Og4=1.5,TG0="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789";function oj3(J,Z,Q){let Y=Math.max(J.length,Z.length),X=[];for(let K=0;K<Y;K++){let V=J[K]??" ",G=Z[K]??" ",F=V===" "||V===`
|
|
4938
|
+
`))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class oU extends u0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new lh4(this.props)}}var Rj3=":";class lh4 extends f0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new A5;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new KV().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let G=X.query.toLowerCase().startsWith(Rj3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",F=K+G+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,F=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(F),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new O6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=kh4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if((this.props.uploadingImageIndices?.size??0)>0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await Oj3(ch4.join(Ij3(),"amp-edit-")),Q=ch4.join(Z,"message.amp.md");await jj3(Q,J,"utf-8"),await eK(Q);try{let Y=await Ej3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")S.error("Failed to read temporary file",Y)}try{await Aj3(Q),await Mj3(Z)}catch(Y){S.warn("Failed to clean up temporary file",Y)}}catch(Z){S.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new q1({mainAxisSize:"min",children:[new $0({text:new P("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((F,z)=>{let q=new o1({onClick:()=>{this.props.onSkillClick?.(z)},cursor:"pointer",child:new $0({text:new P(F.name,new g({color:Z.success,underline:!0}))})});if(z<Q.length-1)return[q,new $0({text:new P(" ")})];return[q]})]}):null,K=Y?new q1({mainAxisSize:"min",children:[new $0({text:new P("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((F,z)=>{let q=this.props.uploadingImageIndices?.has(z)===!0,W=this.props.onImageClick!==void 0&&!q,H=q?`[Image ${this._imageUploadSpinner.toBraille()}]`:`[Image ${z+1}]`,U=new o1({onClick:W?()=>{this.props.onImageClick?.(z)}:void 0,cursor:W?"pointer":void 0,child:new $0({text:new P(H,new g({color:q?Z.foreground:Z.success,underline:!q,dim:q}))})});if(z<this.props.imageAttachments.length-1)return[U,new $0({text:new P(" ")})];return[U]})]}):null,V=new PG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(F)=>ph4(F),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:R0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(F,z,q)=>{let W=q?Z.selection:void 0,H=Z.secondary,U=Z.foreground,D=Z.foreground,B=Z.warning;if(z.type==="commit")return new l0({decoration:new e4(W),child:new q1({children:[new b1({child:new $0({text:new P("",void 0,[new P(z.shortHash,new g({color:Z.secondary})),new P(" ",new g({})),new P(z.message,new g({color:U}))]),maxLines:1,overflow:"ellipsis"})}),new $0({text:new P(` ${z.relativeDate}`,new g({color:D,dim:!0}))})]})});let N=[];switch(z.type){case"file":N.push(new P("@",new g({color:H}))),N.push(new P(z.path,new g({color:U})));break;case"hint":N.push(new P(z.kind==="commit"?"@:":"@@",new g({color:B}))),N.push(new P(" ",new g({}))),N.push(new P(z.message,new g({color:B})));break}let w=dh4(z);if(w)N.push(new P(" - ",new g({color:D,dim:!0}))),N.push(new P(w,new g({color:D,dim:!0})));return new l0({decoration:new e4(W),child:new $0({text:new P("",void 0,N),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let F=[];if(X)F.push(X);if(X&&K)F.push(new $0({text:new P(" ")}));if(K)F.push(K);let z=new l0({padding:R0.only({bottom:1}),child:new q1({mainAxisSize:"min",children:F})});G.push(z)}if(G.push(new W7({fit:this.props.fillAvailableHeight===!1?"loose":"tight",child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new p0({mainAxisSize:"min",crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class nh4 extends q7{color;constructor({color:J,key:Z}){super({key:Z});this.color=J}createRenderObject(){return new ah4(this.color)}updateRenderObject(J){J.color=this.color}}class ah4 extends q4{color;constructor(J){super();this.color=J}performLayout(){let J=this._lastConstraints;if(J)this.setSize(J.maxWidth,1)}paint(J,Z,Q){let Y=Math.floor(this.size.width);for(let X=0;X<Y;X++)J.setChar(Z+X,Q,"─",{fg:this.color},1)}}var Pj3=30,ih4=[{left:{keys:"Ctrl+O",description:"command palette"},right:{keys:"Ctrl+R",description:"prompt history"}},{left:{keys:"$ or $$",description:"shell commands"},right:{keys:"Ctrl+V",description:"paste images"}},{left:{keys:"Shift+Enter",description:"newline"},right:{keys:"Ctrl+S",description:"switch modes"}},{left:{keys:"Alt+D",description:"toggle deep reasoning"},right:{keys:"Alt+T",description:"toggle thinking/dense view"}},{left:{keys:"Ctrl+G",description:"edit in $EDITOR"},right:{keys:"Tab/Shift+Tab",description:"navigate messages"}},{left:{keys:"@ / @@",description:"mention files/threads"},right:{keys:"?",description:"toggle this help"}}];class _o extends S1{submitOnEnter;constructor(J={}){super(J.key?{key:J.key}:{});this.submitOnEnter=J.submitOnEnter??!0}build(J){let Q=k1.of(J).colorScheme,X=y0.of(J).app,K=new g({color:X.keybind}),V=new g({color:Q.foreground,dim:!0}),G=eG()&&!Jr0,z=(this.submitOnEnter?ih4:ih4.map((W)=>W.left.keys==="Shift+Enter"?{left:{keys:"Ctrl/Cmd+Enter",description:"submit"},right:W.right}:W)).map((W)=>{let H=W.left.keys==="Shift+Enter"&&G?"Alt+Enter":W.left.keys,U=W.left.description,D=H.length+1+U.length,B=" ".repeat(Math.max(0,Pj3-D)),N=W.right.keys,w=W.right.description;return new $0({text:new P("",void 0,[new P(H,K),new P(" ",V),new P(U,V),new P(B+" ",V),new P(N,K),new P(" ",V),new P(w,V)])})});if(G)z.push(new I0({height:1})),z.push(new o1({onClick:()=>N3(J,"https://ampcode.com/manual/appendix#amp-cli-tmux"),cursor:"pointer",child:new $0({text:new P("",void 0,[new P("Enable ",V),new P("extended-keys",new g({color:X.command})),new P(" in tmux to use ",V),new P("Shift+Enter",K),new P(". See ",V),Y5.createSpan("https://ampcode.com/manual/appendix#amp-cli-tmux","https://ampcode.com/manual/appendix#amp-cli-tmux",new g({color:X.link,underline:!0}))])})}));let q=new q1({children:[new b1({child:new nh4({color:Q.border})})]});return new p0({crossAxisAlignment:"start",mainAxisSize:"min",children:[...z,q]})}}class n01 extends IG0{_mode="auto";_isResizing=!1;_isHandleHovered=!1;get mode(){return this._mode}get isResizing(){return this._isResizing}get isHandleHovered(){return this._isHandleHovered}_update(J,Z,Q){let Y=this._mode!==J||this._isResizing!==Z||this._isHandleHovered!==Q;if(this._mode=J,this._isResizing=Z,this._isHandleHovered=Q,Y)this.notifyListeners()}}class a01 extends u0{child;minRows;maxRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;controller;constructor({key:J,child:Z,minRows:Q=3,maxRows:Y=12,initialRows:X=null,initialMode:K="auto",dragThresholdRows:V=0,onHandleDoubleClick:G,controller:F}){super(J?{key:J}:{});if(Q>Y)throw Error("minRows must be <= maxRows");if(V<0)throw Error("dragThresholdRows must be >= 0");this.child=Z,this.minRows=Q,this.maxRows=Y,this.initialRows=X,this.initialMode=K,this.dragThresholdRows=V,this.onHandleDoubleClick=G,this.controller=F}createState(){return new oh4}}class oh4 extends f0{_mode="auto";_heightRows=3;_dragSession=null;_isHandleHovered=!1;initState(){super.initState(),this._syncToInitialProps()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.initialMode!==this.widget.initialMode||J.initialRows!==this.widget.initialRows){this._syncToInitialProps();return}this._heightRows=this._clampRows(this._heightRows)}build(J){let Z=this._mode==="manual"?new l0({height:this._heightRows,child:this.widget.child}):new l0({constraints:new E1(0,Number.POSITIVE_INFINITY,this.widget.minRows,this.widget.maxRows),child:this.widget.child});return new d6({children:[Z,this._buildHandleOverlay()]})}get _effectiveMinRows(){return this.widget.minRows}_buildHandleOverlay(){return new r5({top:0,left:0,right:0,height:1,child:new o1({cursor:G3.NS_RESIZE,onClick:this._handleHandlePress,onDrag:this._handleHandleDrag,onRelease:this._handleHandleRelease,onEnter:()=>this._setHandleHovered(!0),onExit:()=>this._setHandleHovered(!1),child:new I0({height:1})})})}_notifyController(){this.widget.controller?._update(this._mode,!!this._dragSession,this._isHandleHovered)}_setHandleHovered(J){if(this._isHandleHovered===J)return;this.setState(()=>{this._isHandleHovered=J,this._notifyController()})}_handleHandlePress=(J)=>{if(J.button!=="left")return;let Z=this._currentRenderedHeightRows(),Q=this._toTerminalRow(J.position.y),Y=J.clickCount===2?this.widget.onHandleDoubleClick?.({mode:this._mode,currentRows:Z,minRows:this._effectiveMinRows,maxRows:this.widget.maxRows}):void 0,X=this._mode==="manual"&&J.clickCount===2&&Y===void 0;this.setState(()=>{this._dragSession={modeAtStart:this._mode,baseHeightRows:Z,startRow:Q,currentRow:Q,resetToAutoOnRelease:X,doubleClickOverride:Y},this._notifyController()})};_handleHandleDrag=(J)=>{if(J.button!=="left"||!this._dragSession)return;let Z=this._toTerminalRow(J.position.y),Q=this._dragSession,Y=Z-Q.startRow,X=Q.modeAtStart==="manual"||Math.abs(Y)>=this.widget.dragThresholdRows;this.setState(()=>{if(Q.currentRow=Z,Y!==0)Q.resetToAutoOnRelease=!1,Q.doubleClickOverride=void 0;if(X)this._mode="manual",this._heightRows=this._clampRows(Q.baseHeightRows-Y);this._notifyController()})};_handleHandleRelease=(J)=>{if(J.button!=="left"||!this._dragSession)return;let Z=this._dragSession,Q=Z.currentRow-Z.startRow,Y=Z.doubleClickOverride==="auto-min"&&Q===0,X=Z.doubleClickOverride==="manual-max"&&Q===0,K=Z.resetToAutoOnRelease&&Q===0,V=Z.modeAtStart==="auto"&&this._mode==="auto"&&this.widget.dragThresholdRows===0&&Q===0;this.setState(()=>{if(Y)this._mode="auto",this._heightRows=this._clampRows(this._effectiveMinRows);else if(X)this._mode="manual",this._heightRows=this._clampRows(this.widget.maxRows);else if(K)this._mode="auto";else if(V)this._mode="manual",this._heightRows=this._clampRows(Z.baseHeightRows);this._dragSession=null,this._notifyController()})};_syncToInitialProps(){this._mode=this.widget.initialMode,this._heightRows=this._resolveInitialRows(),this._dragSession=null,this._notifyController()}_resolveInitialRows(){return this._clampRows(this.widget.initialRows??this._effectiveMinRows)}_clampRows(J){return Math.max(this._effectiveMinRows,Math.min(J,this.widget.maxRows))}_currentRenderedHeightRows(){return this.context.findRenderObject()?.size.height??this._heightRows}_toTerminalRow(J){return Math.floor(J)}}class o01 extends u0{childBuilder;minBodyRows;maxBodyRows;initialRows;initialMode;dragThresholdRows;onHandleDoubleClick;bottomRightLabel;constructor(J){let{key:Z,minBodyRows:Q=3,maxBodyRows:Y=12,initialRows:X=null,initialMode:K="auto",dragThresholdRows:V=0,onHandleDoubleClick:G,bottomRightLabel:F}=J;super(Z?{key:Z}:{});this.childBuilder="childBuilder"in J&&J.childBuilder?J.childBuilder:()=>J.child,this.minBodyRows=Q,this.maxBodyRows=Y,this.initialRows=X,this.initialMode=K,this.dragThresholdRows=V,this.onHandleDoubleClick=G,this.bottomRightLabel=F}createState(){return new rh4}}class rh4 extends f0{_controller=new n01;_onControllerChanged=()=>{this.setState(()=>{})};initState(){super.initState(),this._controller.addListener(this._onControllerChanged)}dispose(){this._controller.removeListener(this._onControllerChanged),this._controller.dispose(),super.dispose()}build(J){let Z=k1.of(J),Q=Z.colorScheme.border,X=this._controller.isResizing||this._controller.isHandleHovered?2:1,K=[];if(this.widget.bottomRightLabel)K.push({child:this.widget.bottomRightLabel,position:"bottom",alignment:"right"});return new a01({controller:this._controller,minRows:this.widget.minBodyRows+2,maxRows:this.widget.maxBodyRows+2,initialRows:this.widget.initialRows,initialMode:this.widget.initialMode,dragThresholdRows:this.widget.dragThresholdRows,onHandleDoubleClick:this.widget.onHandleDoubleClick,child:new H7({decoration:new e4(Z.colorScheme.background,new K4(new Y4(Q,X,"rounded"),new Y4(Q,1,"rounded"),new Y4(Q,1,"rounded"),new Y4(Q,1,"rounded"))),overlays:K,child:this.widget.childBuilder(this._controller.mode)})})}}a0();D4();qB();class r01 extends u0{createState(){return new sh4}}class sh4 extends f0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=y0.of(J).colors;return new $0({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function Cj3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return MG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function s01(J,Z,Q){return new $0({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function _j3(J,Z,Q,Y){return[s01("+",J,Y.success),B5.horizontal(1),s01("~",Z,Y.warning),B5.horizontal(1),s01("-",Q,Y.destructive)]}function Tj3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}var t01=["Alt+W","Ctrl+T"];function e01(J){return J?"all workspaces":"filter by workspace"}class ly extends u0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new th4}}class th4 extends f0{spinner=new A5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=Cj3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=y0.of(J),U=new m0({padding:R0.symmetric(0,1),child:new s1({child:new $0({text:new P("",new g({color:H.colors.foreground,dim:!0}),[new P(t01.join("/"),new g({color:H.colors.primary,dim:!0})),new P(` ${Z.filterByWorkspace?"for":"to"} ${e01(Z.filterByWorkspace===!0)}`,new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=I9(L);return B};return new p3({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!Tj3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,showBorder:Z.showBorder,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError||Z.showInlineWorkspaceFilterHint===!1?void 0:U,renderItem:(L,O,E,M)=>{let A=y0.of(M),{app:j,colors:R}=A,_=O?j.selectionBackground:void 0,C=O?j.selectionForeground:R.foreground,b=R.mutedForeground,d=(t,B0)=>new I0({width:B0,child:q1.end([new $0({text:new P(t,new g({color:b}))})])}),f=Z.threadViewStates[L.id],y=[],x=L.relationshipType==="handoff",m=new jo({connectorColor:R.mutedForeground});if(L.depth>0){let t=[],B0=L.ancestorsAreLast.slice(1);for(let q0 of B0)t.push(new P(m.getAncestorPrefix(q0),new g({color:m.connectorColor,dim:m.connectorDim})));let a=L.isLast?m.elbow:m.tee,J0=m.getConnectorText(a);t.push(new P(J0,new g({color:m.connectorColor,dim:m.connectorDim}))),y.push(new $0({text:new P("",void 0,t)}))}let p=[],h=F===L.id?new P("(current) ",new g({color:R.success})):G.has(L.id)?new P("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)p.push(new $0({text:h}));if(LA(f))p.push(new r01),p.push(new I0({width:1}));let o=L.title;if(L.relationshipType==="fork"){let t=o.match(/^Forked\((\d+)\): /);if(t)o=o.slice(t[0].length);else while(o.startsWith("Forked: "))o=o.slice(8);p.push(new $0({text:new P("[fork] ",new g({color:R.primary}))}))}else if(x)p.push(new $0({text:new P("[handoff] ",new g({color:R.accent}))}));if(p.push(new b1({child:new $0({text:new P(o,new g({color:C})),overflow:"ellipsis",maxLines:1})})),p.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let t=O?{success:b,warning:b,destructive:b}:R;p.push(..._j3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,t)),p.push(new I0({width:2}))}return p.push(d(L.description.timeAgo,W)),new l0({decoration:_?{color:_}:void 0,padding:R0.symmetric(2,0),child:new q1({children:[...y,...p]})})}})}}I1();function $11(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/3600000),X=Math.floor(Y/24),K=Math.floor(X/7),V=Math.floor(X/30);if(Y<1)return"Just now";if(Y<24)return`${Y}h ago`;if(X<7)return`${X}d ago`;if(K<=4)return`${K}w ago`;return`${V}mo ago`}class J11{threadService;constructor(J){this.threadService=J}async fetchThreadSummaries(J="",Z){try{let Q=await new Promise((Y,X)=>{let K=this.threadService.observeThreadList(Z).subscribe({next:(V)=>{K.unsubscribe(),Y(V)},error:X})});return{ok:!0,threads:this.formatThreadSummaries(Q,J,Z)}}catch(Q){return{ok:!1,errorMsg:Q instanceof Error?Q.message:"An unexpected error occurred"}}}observeThreadSummaries(J="",Z={}){return this.threadService.observeThreadList({includeArchived:Z.includeArchived??!1}).pipe(M1((Q)=>this.formatThreadSummaries(Q,J,Z)))}formatThreadSummaries(J,Z,Q={}){return J.filter((X)=>{if(X.mainThreadID)return!1;if(!Q.includeArchived&&X.archived)return!1;if(!Z.trim())return!0;let K=X.title?.toLowerCase()||"untitled",V=X.id.toLowerCase(),G=Z.toLowerCase();return K.includes(G)||V.includes(G)}).map((X)=>{let K=new Date(X.userLastInteractedAt),V=$11(K),G=X.id.slice(-8),F=X.env?.initial.trees?.[0]?.uri;return{id:X.id,title:X.title||"Untitled",updatedAt:new Date(X.userLastInteractedAt).toISOString(),description:{timeAgo:V,title:X.title||"Untitled",shortThreadID:G},diffStats:X.summaryStats?.diffStats,workspaceURI:F,relationships:X.relationships,agentMode:X.agentMode,details:{messageCount:X.summaryStats?.messageCount},archived:X.archived}})}}function Sj3(J){return J.filter((Z)=>!Z.mainThreadID&&!Z.archived).sort((Z,Q)=>new Date(Q.userLastInteractedAt).getTime()-new Date(Z.userLastInteractedAt).getTime()).map((Z)=>{let Q=Z.title||"Untitled",Y=new Date(Z.userLastInteractedAt),X=Z.env?.initial.trees?.[0]?.uri;return{id:Z.id,title:Q,updatedAt:Y.toISOString(),description:{timeAgo:$11(Y),title:Q,shortThreadID:Z.id.slice(-8)},diffStats:Z.summaryStats?.diffStats,workspaceURI:X,relationships:Z.relationships,agentMode:Z.agentMode,details:{messageCount:Z.summaryStats?.messageCount},archived:Z.archived}})}class eh4 extends u0{props;constructor(J){super();this.props=J}createState(){return new $g4}}class $g4 extends f0{threadViewStates={};currentWorkspaceURI=n1(K1.file(process.cwd()));threads=[];isLoading=!0;hasError=!1;filterByWorkspace=!0;handleKeyEvent=(J)=>{if(J.ctrlKey&&J.key.toLowerCase()==="t"||J.altKey&&J.key.toLowerCase()==="w")return this.setState(()=>{this.filterByWorkspace=!this.filterByWorkspace}),"handled";return"ignored"};initState(){super.initState(),this.loadThreadSummaries()}async loadThreadSummaries(){try{let J=await this.widget.props.loadThreads(),Z=Sj3(J);if(!this.mounted)return;this.setState(()=>{this.threads=Z,this.isLoading=!1,this.hasError=!1})}catch(J){if(S.error("Failed to load threads for Neo command palette",{error:J}),!this.mounted)return;this.setState(()=>{this.isLoading=!1,this.hasError=!0})}}build(J){let Z=[{keys:t01,label:e01(this.filterByWorkspace)},{keys:["Esc"],label:"close"}];return new RZ({header:this.widget.props.title,autofocus:!1,chromePadding:R0.symmetric(1,0),footer:Z,onDismiss:this.widget.props.onDismiss,child:new n4({onKey:this.handleKeyEvent,debugLabel:"ThreadSwitchPicker",child:new ly({threads:this.threads,showBorder:!1,showInlineWorkspaceFilterHint:!1,onSelect:this.widget.props.onSelect,onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,hasError:this.hasError,currentWorkspaceURI:this.currentWorkspaceURI,filterByWorkspace:this.filterByWorkspace,threadViewStates:this.threadViewStates,currentThreadID:this.widget.props.activeThreadID??void 0,excludeCurrentThread:this.widget.props.excludeCurrentThread})})})}}function Jg4(J,Z){return new eh4({title:Z.title,activeThreadID:J.activeThreadID,loadThreads:J.loadThreads,excludeCurrentThread:Z.excludeCurrentThread,onSelect:async(Q)=>{try{await J.onSelectThread(Q),J.onThreadSelected()}catch(Y){Z.logFailure(Q,Y)}},onDismiss:J.onDismiss})}function Z11(J){return Jg4(J,{title:"Switch Thread",excludeCurrentThread:!1,logFailure:(Z,Q)=>{S.error("Failed to switch thread",{error:Q,threadID:Z})}})}function Q11(J){return Jg4(J,{title:"Mention Thread",excludeCurrentThread:!0,logFailure:(Z,Q)=>{S.error("Failed to mention thread",{error:Q,threadID:Z})}})}class Y11 extends u0{props;constructor(J){super();this.props=J}createState(){return new Zg4}}var kj3=0;class Zg4 extends f0{imageEntries=[];pendingUploads=new Map;isShowingShortcutsHelp=!1;removeKeyInterceptor=null;imagePreviewOverlay=null;mentionPickerOverlay=null;unregisterCommands=null;initState(){super.initState(),this.isShowingShortcutsHelp=this.widget.props.showShortcutsHelp??!1,this.unregisterCommands=this.registerCommands(),this.removeKeyInterceptor=l4.instance.addKeyInterceptor((J)=>{let Z=this.widget.props.editorController;if(J.key==="?"){if(Z.text===""&&Z.cursorPosition===0)return this.setState(()=>{this.isShowingShortcutsHelp=!this.isShowingShortcutsHelp}),!0}if(this.isShowingShortcutsHelp){if(this.setState(()=>{this.isShowingShortcutsHelp=!1}),J.key==="Escape")return!0;return!1}return!1})}dispose(){this.dismissImagePreview(),this.dismissMentionPicker(),this.unregisterCommands?.(),this.unregisterCommands=null,this.removeKeyInterceptor?.(),this.removeKeyInterceptor=null,super.dispose()}registerCommands(){let J=YV.of(this.context),Z={noun:"thread",verb:"mention",description:"Mention a thread",keywords:["reference","link","attach","cite"],status:{type:"enabled"},run:(Q,Y,X)=>{Q.pushWithDismiss((K)=>Q11({activeThreadID:this.widget.props.activeThreadID,loadThreads:()=>l$.of(this.context).listThreads(),onSelectThread:(V)=>{this.insertThreadMention(V)},onDismiss:K,onThreadSelected:X}))}};return J.register(Z)}handleDoubleAtTrigger=()=>{this.showMentionPicker()};showMentionPicker(){this.dismissMentionPicker();let J=new jL(()=>Q11({activeThreadID:this.widget.props.activeThreadID,loadThreads:()=>l$.of(this.context).listThreads(),onSelectThread:(Z)=>{this.insertThreadMention(Z)},onDismiss:()=>this.dismissMentionPicker(),onThreadSelected:()=>this.dismissMentionPicker()}));this.mentionPickerOverlay=J,pQ.of(this.context).insert(J)}dismissMentionPicker(){if(this.mentionPickerOverlay)this.mentionPickerOverlay.remove(),this.mentionPickerOverlay=null}insertThreadMention(J){let Z=this.widget.props.editorController,Q=Z.text,Y=Z.cursorPosition,K=Q.slice(0,Y).lastIndexOf("@@");if(K!==-1){let V=Q.slice(Y),G=V.length===0,F=`@${J}${G?" ":""}`,z=Q.slice(0,K)+F+V;Z.text=z,Z.cursorPosition=K+F.length;return}Z.insertText(`@${J} `)}handleInsertImage=async(J)=>{if(this.imageEntries.length>=wY)return!1;let Z=await sq(J);if(typeof Z==="string")return!1;let Q=kj3++,Y={id:Q,image:Z,uploading:!1};if(Z.source.type==="base64")Y.uploading=!0,this.setState(()=>{this.imageEntries=[...this.imageEntries,Y]}),this.uploadEntryInBackground(Q,Z.source);else this.setState(()=>{this.imageEntries=[...this.imageEntries,Y]});return!1};async uploadEntryInBackground(J,Z){let Q=(async()=>{try{let{configService:Y}=l$.of(this.context),X=await fh4(Z,Y);if(!this.mounted)return;let K=this.imageEntries.find((G)=>G.id===J);if(!K)return;let V=xh4(X)?K.image:{type:"image",source:{type:"url",url:X},sourcePath:K.image.sourcePath};this.setState(()=>{this.imageEntries=this.imageEntries.map((G)=>G.id===J?{...G,image:V,uploading:!1}:G)})}catch(Y){if(S.error("Failed to upload image attachment",{error:Y}),!this.mounted)return;this.setState(()=>{this.imageEntries=this.imageEntries.map((X)=>X.id===J?{...X,uploading:!1}:X)})}finally{this.pendingUploads.delete(J)}})();this.pendingUploads.set(J,Q)}handlePopImage=()=>{if(this.imageEntries.length===0)return;let J=this.imageEntries[this.imageEntries.length-1];if(J)this.pendingUploads.delete(J.id);this.setState(()=>{this.imageEntries=this.imageEntries.slice(0,-1)})};handleImageClick=(J)=>{let Z=this.imageEntries[J];if(!Z||Z.uploading)return;this.dismissImagePreview();let Q=new jL(()=>new oI({image:Z.image,imageIndex:J,onDismiss:()=>this.dismissImagePreview(),onRemove:()=>{this.dismissImagePreview();let Y=this.imageEntries[J];if(Y)this.pendingUploads.delete(Y.id);this.setState(()=>{this.imageEntries=this.imageEntries.filter((X,K)=>K!==J)})}}));this.imagePreviewOverlay=Q,pQ.of(this.context).insert(Q)};dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}handleSubmitted=(J)=>{if(this.pendingUploads.size>0)this.waitAndSubmit(J);else{let Z=this.imageEntries.map((Q)=>Q.image);this.setState(()=>{this.imageEntries=[]}),this.widget.props.onSubmitted(J,Z)}};async waitAndSubmit(J){if(await Promise.all(this.pendingUploads.values()),!this.mounted)return;let Z=this.imageEntries.map((Q)=>Q.image);this.setState(()=>{this.imageEntries=[]}),this.widget.props.onSubmitted(J,Z)}uploadingIndices(){let J=new Set;for(let Z=0;Z<this.imageEntries.length;Z++)if(this.imageEntries[Z]?.uploading)J.add(Z);return J}build(J){let{editorController:Z,queuedMessages:Q,selectedQueuedMessageIndex:Y,maxBodyRows:X}=this.widget.props,K=Q.length>0,V=k1.of(J),G=[];if(K)G.push(new m0({padding:R0.horizontal(1),child:new dy({queuedMessages:Q,selectedIndex:Y})}));return G.push(new o01({initialRows:3,minBodyRows:3,maxBodyRows:X,bottomRightLabel:this.widget.props.bottomRightLabel,onHandleDoubleClick:({currentRows:F,maxRows:z})=>F>=z?"auto-min":"manual-max",childBuilder:(F)=>new m0({padding:R0.horizontal(1),child:new oU({controller:Z,triggers:[new KV],completionBuilder:gy.of(J),autoOverlayPosition:!0,theme:V.colorScheme,onInsertImage:this.handleInsertImage,imageAttachments:this.imageEntries.map((z)=>z.image),popImage:this.handlePopImage,onImageClick:this.handleImageClick,uploadingImageIndices:this.uploadingIndices(),enabled:this.widget.props.editorEnabled,onDoubleAtTrigger:this.handleDoubleAtTrigger,onSubmitted:this.handleSubmitted,fillAvailableHeight:F==="manual",topWidget:this.isShowingShortcutsHelp?new _o:void 0})})})),new o1({opaque:!1,onClick:!this.widget.props.editorEnabled?()=>D5.maybeInvoke(this.context,new Bo):void 0,child:new uK0({children:G})})}}k8();UB();import vj3 from"node:path";function yj3(J){try{return decodeURIComponent(J)}catch{return J}}function Qg4(J,Z){if(!J?.enabled||!J.authenticated)return null;let Q=J.selections?.[0],Y=!cC(Q)&&Q?Q.range.endLine-Q.range.startLine+1:0,X=[];if(J.openFile)X.push(vj3.basename(yj3(J.openFile)));else if(J.ideName)X.push(J.ideName);if(Q&&Y>0)X.push(`${Y} selected ${j4(Y,"line")}`);if(X.length===0)return null;let K=`✓ ${X.join(" • ")}`;return new $0({text:new P(K,new g({color:Z.app.ideConnected})),textAlign:"right",maxLines:1,overflow:"clip"})}var Yg4=[fy,Ho,Wo];class X11 extends S1{hints;agentLoopState;compactionState;connectionState;pendingSend;statusMessageOverride;ideStatus;constructor(J){super();this.hints=J.hints,this.agentLoopState=J.agentLoopState,this.compactionState=J.compactionState,this.connectionState=J.connectionState,this.pendingSend=J.pendingSend,this.statusMessageOverride=J.statusMessageOverride??null,this.ideStatus=J.ideStatus}build(J){let Z=y0.of(J),Q=[],Y=mj3(this.agentLoopState,this.compactionState,this.connectionState,this.pendingSend),X=xj3(this.hints),K=this.statusMessageOverride;if(X){if(Y||X===fy)Xg4(Z,Q);bj3(Q,hj3(X,J))}else if(K)uj3(Z,K,Q);else if(Y)Xg4(Z,Q),fj3(Z,Y,Q);let V=Qg4(this.ideStatus,Z);if(!V&&Q.length===0)return new I0({width:0,height:0});let G=[...Q];if(V)G.push(B5.flexible()),G.push(V);return new q1({children:G,mainAxisSize:"max",mainAxisAlignment:"start"})}}function xj3(J){for(let Z=Yg4.length-1;Z>=0;Z--){let Q=Yg4[Z];if(J.has(Q))return Q}return}function Xg4(J,Z){Z.push(new Eo({color:J.colors.primary})),Z.push(B5.horizontal(1))}function fj3(J,Z,Q){Q.push(new $0({text:new P(Z,new g({color:J.colors.foreground,dim:!0})),textAlign:"left",maxLines:1,overflow:"clip"}))}function uj3(J,Z,Q){Q.push(new $0({text:new P(Z,new g({color:J.colors.destructive})),textAlign:"left",maxLines:1,overflow:"clip"}))}function bj3(J,Z){J.push(new $0({text:Z,textAlign:"left",maxLines:1,overflow:"clip"}))}function hj3(J,Z){let Q=y0.of(Z),Y=new g({color:Q.app.keybind}),X=new g({color:Q.colors.foreground,dim:!0});switch(J){case Wo:return new P("",void 0,[new P("Ctrl+C",Y),new P(" again to exit",X)]);case Ho:return new P("",void 0,[new P("Esc",Y),new P(" again to cancel",X)]);case fy:return new P("Loading thread…",X)}}function gj3(J){switch(J){case"connected":return null;case"authenticating":return"Authenticating...";default:return"Connecting..."}}function mj3(J,Z,Q,Y){if(Z==="compacting")return"Auto-compacting...";if(Y&&J==="idle")return gj3(Q)??"Sending message...";switch(J){case"working":return"Waiting for response...";case"streaming":return"Streaming response...";case"tool_use":case"running_tools":return"Running tools...";case"awaiting_approval":return"Waiting for approval...";case"error":return"Error";case"idle":return null}}class K11 extends S1{props;constructor(J){super();this.props=J}build(J){if(!l$.of(J).isInternalUser)return new I0;let Q=k1.of(J),Y=this.props.connectionInfo?.state??"disconnected",X=this.props.connectionInfo?.role??null,K=Y==="connected"?X??"connected":Y;return new m0({padding:R0.horizontal(1),child:new $0({text:new P(`(neo: ${K})`,new g({color:Q.colorScheme.mutedForeground,dim:!0})),textAlign:"left"})})}}class To extends S1{props;constructor(J){super();this.props=J}onSubmitted=(J,Z)=>{let Q=J.trim();if(Q.length===0&&Z.length===0)return;let Y=[];if(Q.length>0)Y.push({type:"text",text:Q});Y.push(...Z),this.props.onSubmit(Y),this.props.editorController.clear()};build(J){let{child:Z,editorController:Q,hints:Y,agentState:X,compactionState:K,connectionInfo:V,pendingSend:G,agentMode:F,deepReasoningEffort:z,speedSuffix:q,queuedMessages:W,selectedQueuedMessageIndex:H,editorEnabled:U,statusMessageOverride:D,activeError:B,onErrorResponse:N}=this.props,w=G4.of(J),{width:L,height:O}=w.size,E=Sh4(J,this.props.environment),M=new Map([[t1.key("ArrowUp"),new by],[t1.key("Tab"),new by],[t1.key("ArrowDown"),new uy],[t1.shift("Tab"),new uy],[t1.key("Enter"),new Do],[t1.key("Backspace"),new Uo],[t1.key("PageUp"),new wo],[t1.key("PageDown"),new Lo]]),A=B?new m01({error:B,onResponse:(R)=>N?.(R)}):new Y11({editorController:Q,activeThreadID:this.props.activeThreadID,queuedMessages:W,selectedQueuedMessageIndex:H,editorEnabled:U,maxBodyRows:Math.floor(w.size.height/3),onSubmitted:this.onSubmitted,showShortcutsHelp:this.props.showShortcutsHelp,bottomRightLabel:E}),j=[new p01,new b1({child:Z}),new I0({height:1,child:new q1({mainAxisAlignment:"end",children:[new K11({connectionInfo:V}),B5.flexible(),new m0({padding:R0.horizontal(1),child:new g01({agentMode:F,deepReasoningEffort:z,speedSuffix:q})})]})}),A,new I0({width:L,height:1,child:new X11({hints:Y,agentLoopState:X==="error"?"idle":X,compactionState:K,connectionState:V?.state??"disconnected",pendingSend:G,statusMessageOverride:D,ideStatus:this.props.ideStatus})})];return new w9({shortcuts:M,child:new pQ({child:new l0({constraints:E1.tight(L,O),child:new p0({mainAxisSize:"max",crossAxisAlignment:"stretch",children:j})})})})}}class V11 extends u0{editorController;client;observer;hints;ideStatus;onPromptSubmitted;constructor(J){super({key:new V5(J.observingClient.client.getThreadId())});this.editorController=J.editorController,this.client=J.observingClient.client,this.observer=J.observingClient.observer,this.hints=J.hints,this.ideStatus=J.ideStatus,this.onPromptSubmitted=J.onPromptSubmitted}createState(){return new Kg4}}class Kg4 extends f0{agentState=new EZ(this,"idle");connectionInfo=new EZ(this,null);pendingSend=new EZ(this,!1);compactionState=new EZ(this,"idle");queuedMessages=new EZ(this,[]);activeError=new EZ(this,null);threadSettings=new EZ(this,null);environment=new EZ(this,null);cancelHintTimer=new Oa(this,1000);threadController=null;controllerUnsubscription=null;imagePreviewOverlay=null;initState(){this.recreateThreadController(),this.subscribeToObserver()}didUpdateWidget(J){if(J.client!==this.widget.client||J.observer!==this.widget.observer)this.recreateThreadController(),this.resetThreadClientState(),this.subscribeToObserver()}resetThreadClientState(){this.agentState.dispose(),this.connectionInfo.dispose(),this.pendingSend.dispose(),this.compactionState.dispose(),this.queuedMessages.dispose(),this.activeError.dispose(),this.threadSettings.dispose(),this.environment.dispose()}subscribeToObserver(){this.agentState.subscribe(this.widget.observer.agentState()),this.connectionInfo.subscribe(this.widget.observer.connectionInfo()),this.pendingSend.subscribe(this.widget.observer.pendingSend()),this.compactionState.subscribe(this.widget.observer.compactionState()),this.queuedMessages.subscribe(this.widget.observer.queuedMessages()),this.activeError.subscribe(this.widget.observer.activeError()),this.threadSettings.subscribe(this.widget.observer.threadSettings()),this.environment.subscribe(this.widget.client.environmentChanges())}subscribeToThreadController(){let J=this.threadController;if(!J)return;this.controllerUnsubscription=J.subscribe(()=>{this.setState()})}recreateThreadController(){this.controllerUnsubscription?.(),this.threadController?.dispose(),this.threadController=new I01(this.widget.observer.reader(),this.widget.observer.groupedReader(),this.widget.observer.agentMode),this.subscribeToThreadController()}onEscPressed=()=>{if(this.threadController?.hasSelection)return this.threadController.clearSelection(),"handled";if(!rj(this.agentState.getValue()))return"ignored";if(this.cancelHintTimer.isActive())this.cancelHintTimer.clear(),this.widget.client.cancelAgentLoop();else this.cancelHintTimer.activate();return"handled"};buildHints(){let J=new Set(this.widget.hints);if(this.cancelHintTimer.isActive())J.add(Ho);return J}dispose(){this.dismissImagePreview(),this.controllerUnsubscription?.(),this.threadController?.dispose(),super.dispose()}onShowImagePreview=(J,Z,Q)=>{this.showOverlay(J,()=>new oI({image:Z,imageIndex:Q,onDismiss:()=>this.dismissImagePreview()}))};onShowFileImagePreview=(J)=>{this.showOverlay(this.context,()=>new TI({filePath:J,onDismiss:()=>this.dismissImagePreview()}))};showOverlay(J,Z){this.dismissImagePreview();let Q=new jL(Z);this.imagePreviewOverlay=Q,pQ.of(J).insert(Q)}dismissImagePreview(){if(this.imagePreviewOverlay)this.imagePreviewOverlay.remove(),this.imagePreviewOverlay=null}onErrorResponse=(J)=>{let{client:Z,observer:Q}=this.widget;switch(J){case"retry":Q.dismissActiveError(),Z.retryAgentLoop();break;case"dismiss":Z.dismissActiveError(Q.getActiveErrorSeq()??void 0),Q.dismissActiveError();break;case"add-credits":break}};getSelectedQueuedMessage(){let J=this.threadController?.selectedQueuedMessageIndex;if(J===null||J===void 0)return null;return this.queuedMessages.getValue()[J]??null}build(J){let{editorController:Z,client:Q}=this.widget,Y=this.threadController,X=this.widget.observer.agentMode,K=this.queuedMessages.getValue();Y.setQueuedMessageCount(K.length);let{deepReasoningEffort:V,speedSuffix:G}=EG0(X,this.threadSettings.getValue()),F=new d4(()=>{return this.onEscPressed()}),z=new d4(()=>{let w=this.getSelectedQueuedMessage();if(!w)return"ignored";return Q.interruptQueuedMessage(w.queuedMessage.messageId),"handled"}),q=new d4(()=>{let w=this.getSelectedQueuedMessage();if(!w)return"ignored";return Q.removeQueuedMessage(w.queuedMessage.messageId),Z.text=dy.rowText(w),Y.clearSelection(),"handled"}),W=new d4(()=>{return Y.selectPrevious()?"handled":"ignored"}),H=new d4(()=>{return Y.selectNext()?"handled":"ignored"}),U=new d4(()=>{return Y.onPageUp?.(),"handled"}),D=new d4(()=>{return Y.onPageDown?.(),"handled"}),B=new d4(()=>{return Y.clearSelection(),"handled"});return new D5({actions:new Map([[zG0,F],[Bo,B],[Do,z],[Uo,q],[by,W],[uy,H],[wo,U],[Lo,D]]),child:new w9({shortcuts:new Map([[t1.key("Escape"),new zG0]]),child:new XL({onShowImagePreview:this.onShowFileImagePreview,child:new To({child:new f01({threadController:Y,subagentReaderProvider:(w)=>this.widget.observer.subagentReader(w),onShowImagePreview:this.onShowImagePreview}),editorController:Z,activeThreadID:Q.getThreadId()??null,queuedMessages:K,selectedQueuedMessageIndex:Y.selectedQueuedMessageIndex,editorEnabled:!Y.hasSelection,hints:this.buildHints(),agentState:this.agentState.getValue(),compactionState:this.compactionState.getValue(),connectionInfo:this.connectionInfo.getValue(),pendingSend:this.pendingSend.getValue(),agentMode:X,deepReasoningEffort:V,speedSuffix:G,activeError:this.activeError.getValue(),onErrorResponse:this.onErrorResponse,ideStatus:this.widget.ideStatus,environment:this.environment.getValue(),onSubmit:(w)=>{let L=w.find((E)=>E.type==="text");if(L&&L.type==="text")this.widget.onPromptSubmitted(L.text);this.widget.observer.markMessageSent();let O=xJ0(this.widget.ideStatus);Q.sendUserMessage(w,void 0,{userState:O}),Y.onScrollToBottom?.()}})})})})}}function Vg4(J,Z){return{noun:"thread",verb:"archive and exit",description:"Archive thread and exit",keywords:["close","done","finish","quit"],get status(){return Z()?{type:"enabled"}:{type:"disabled",reason:"Cannot archive an empty thread"}},run:(Q,Y,X)=>{let K=Z()?.client.getThreadId();if(!K)return;(async()=>{let V=await J.archiveThread(K);if(X(),V===null)D5.maybeInvoke(Y,new hy)})()}}}_2();var rU=" .:-=+*#%@",iy=0.5,RL=64,pj3=30,So=0.9,Fg4=1.4,G11=So+Fg4,F11=6,Gg4=0.5,dj3=1.6,cj3=28;class z11 extends u0{originX;originY;agentMode;primaryColor;secondaryColor;fps;onComplete;constructor({originX:J,originY:Z,agentMode:Q,primaryColor:Y,secondaryColor:X,fps:K=pj3,onComplete:V,key:G}){super(G?{key:G}:{});this.originX=J,this.originY=Z,this.agentMode=Q,this.primaryColor=Y,this.secondaryColor=X,this.fps=K,this.onComplete=V}createState(){return new zg4}}class zg4 extends f0{elapsed=0;timer=null;startMs=0;completed=!1;glow=new bQ;initState(){if(super.initState(),this.startMs=performance.now(),this.widget.fps<=0){this.elapsed=G11,this.complete();return}let J=Math.max(16,Math.floor(1000/this.widget.fps));this.timer=setInterval(()=>{if(!this.mounted)return;if(this.elapsed=(performance.now()-this.startMs)/1000,this.elapsed>=G11){this.elapsed=G11,this.setState(()=>{}),this.complete();return}this.setState(()=>{})},J)}dispose(){if(this.timer)clearInterval(this.timer),this.timer=null;super.dispose()}complete(){if(this.completed)return;if(this.completed=!0,this.timer)clearInterval(this.timer),this.timer=null;this.widget.onComplete?.()}build(J){let Z=k1.of(J);return new qg4({originX:this.widget.originX,originY:this.widget.originY,elapsed:this.elapsed,agentMode:this.widget.agentMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Z.colorScheme.background,glow:this.glow})}}class qg4 extends q7{props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new IJ(this)}createRenderObject(){return new Wg4(this.props)}updateRenderObject(J){J.update(this.props)}}function lj3(J){let Z=J>>>0;return()=>{Z=Z+1831565813>>>0;let Q=Z;return Q=Math.imul(Q^Q>>>15,Q|1),Q^=Q+Math.imul(Q^Q>>>7,Q|61),((Q^Q>>>14)>>>0)/4294967296}}class Wg4 extends q4{_props;_palette=[];_paletteSignature="";_fragments=null;_fragmentRadius=0;constructor(J){super();this._props=J,this.rebuildPalette()}update(J){let Z=J.agentMode!==this._props.agentMode||J.primaryColor!==this._props.primaryColor||J.secondaryColor!==this._props.secondaryColor;if(this._props=J,Z)this.rebuildPalette();this.markNeedsPaint()}rebuildPalette(){let J=this._props.primaryColor&&this._props.secondaryColor?{primary:this._props.primaryColor,secondary:this._props.secondaryColor}:void 0;this._palette=Array.from({length:RL},(Z,Q)=>{let Y=Q/(RL-1);return $a(Y,this._props.agentMode,J)}),this._paletteSignature=`${this._props.agentMode??"smart"}|${this._props.primaryColor?`${this._props.primaryColor.r},${this._props.primaryColor.g},${this._props.primaryColor.b}`:""}|${this._props.secondaryColor?`${this._props.secondaryColor.r},${this._props.secondaryColor.g},${this._props.secondaryColor.b}`:""}`}performLayout(){let J=this._lastConstraints,Z=J.constrain(J.biggest.width,J.biggest.height);this.setSize(Z.width,Z.height),super.performLayout()}getMaxRadius(J,Z){let Q=J*Gg4,Y=Z*Gg4*(1/iy);return Math.max(F11+1,Math.min(Q,Y))}buildFragments(J){let Z=lj3(2654435761),Q=[],Y=Math.min(600,Math.max(120,Math.floor(J*J*0.45)));for(let X=0;X<Y;X++){let K=Math.sqrt(Z()),V=Z()*Math.PI*2,G=Math.cos(V)*K*J,F=Math.sin(V)*K*J*iy,z=(0.5+K*0.9)*dj3*J,q=0.7+Z()*0.6,W=Math.cos(V)*z*q,H=Math.sin(V)*z*q*iy-Z()*J*0.6,U=0.4+Z()*0.6,D=Math.min(rU.length-1,Math.floor(U*rU.length));Q.push({x:G,y:F,vx:W,vy:H,glyph:rU[D]||"*",intensity:U})}return Q}paint(J,Z=0,Q=0){let{elapsed:Y,originX:X,originY:K,backgroundColor:V,glow:G}=this._props,F=Z+this.offset.x,z=Q+this.offset.y,q=Math.floor(this.size.width),W=Math.floor(this.size.height),H=J.getSize(),U=H.width,D=H.height,B=this._palette;this._paletteSignature;let N=this.getMaxRadius(q,W),w=X-F,L=K-z;if(Y<So){let j=1-(1-Y/So)**3,R=F11+(N-F11)*j;this.paintOrb(J,F,z,w,L,R,1,Y,G,B,V,U,D);return}if(!this._fragments||this._fragmentRadius!==N)this._fragments=this.buildFragments(N),this._fragmentRadius=N;let O=Math.min(1,(Y-So)/Fg4);if(O<0.2){let A=1-O/0.2;this.paintOrb(J,F,z,w,L,N,A,Y,G,B,V,U,D)}let E=Y-So,M=1-O;for(let A of this._fragments){let j=A.x+A.vx*E,R=A.y+A.vy*E+0.5*cj3*E*E,_=Math.round(F+w+j),C=Math.round(z+L+R);if(_<0||_>=U||C<0||C>=D)continue;let b=Math.max(0.05,A.intensity*M),d=Math.min(rU.length-1,Math.floor(b*rU.length)),f=O>0.7?".":rU[d]||A.glyph,y=Math.min(RL-1,Math.floor(b*RL)),x=B[y]||B[RL-1];if(!x)continue;J.setCell(_,C,{char:f,width:1,style:{fg:x,bg:V,dim:O>0.55,bold:O<0.15}})}}paintOrb(J,Z,Q,Y,X,K,V,G,F,z,q,W,H){let U=Math.max(1,K),D=U*U,B=1/D,N=1/iy,w=Math.max(0,Math.floor(X-U*iy)),L=Math.min(H-Q-1,Math.ceil(X+U*iy));for(let O=w;O<=L;O++){let E=Q+O;if(E<0||E>=H)continue;let M=(O-X)*N,A=M*M;if(A>=D)continue;let j=Math.sqrt(D-A),R=Math.max(0,Math.floor(Y-j)),_=Math.min(W-Z-1,Math.ceil(Y+j));for(let C=R;C<=_;C++){let b=C-Y,d=b*b+A;if(d>=D)continue;let f=1-d*B,x=F.sample(C,O,G,1)*f*V;if(x<=0)continue;let m=Math.min(rU.length-1,Math.floor(x*rU.length)),p=rU[m]||" ",h=Math.min(RL-1,Math.floor(x*RL)),o=z[h]||z[RL-1];if(!o)continue;let l=Z+C;if(l<0||l>=W)continue;J.setCell(l,E,{char:p,width:1,style:{fg:o,bg:q}})}}}}var CG0=5,Hg4=3.8,Ug4=280;var ij3=["*","+",".",":","'"];function Dg4(J,Z,Q=Date.now()){return Math.floor(J)*73856093^Math.floor(Z)*19349663^Q}function Bg4(J,Z,Q={}){let{burstParticleCount:Y=72,burstSpeedMin:X=10,burstSpeedRange:K=16,rainSpeedMin:V=4,rainSpeedRange:G=9,burstDelayMax:F=0.18,rainDelayMax:z=1,burstLifetimeMin:q=1.4,burstLifetimeRange:W=1.2,rainLifetimeMin:H=2.8,rainLifetimeRange:U=1.8,burstDriftMin:D=0.3,burstDriftRange:B=0.9,rainDriftMin:N=0.8,rainDriftRange:w=1.8,rainAngleCenter:L=Math.PI/2,rainAngleSpread:O=1.4,colorIndexCount:E=6,sparkleGlyphs:M=ij3}=Q,A=nj3(J),j=[];for(let R=0;R<Z;R++){let _=R<Y,C=_?A()*Math.PI*2:L+(A()-0.5)*O,b=_?X+A()*K:V+A()*G,d=_?A()*F:A()*z,f=_?q+A()*W:H+A()*U,y=_?D+A()*B:N+A()*w,x=A()*Math.PI*2,m=M[Math.floor(A()*M.length)]??"*";j.push({kind:_?"burst":"rain",angle:C,speed:b,delay:d,lifetime:f,drift:y,phase:x,glyph:m,colorIndex:Math.floor(A()*E)})}return j}function Ng4(J,Z){let{elapsedSeconds:Q,originX:Y,originY:X,unitScale:K=1}=Z,V=Q-J.delay;if(V<0||V>J.lifetime)return null;let G=J.kind==="burst"?9:12,F=J.speed*K,z=Math.cos(J.angle)*F,q=Math.sin(J.angle)*F,W=Math.sin((V+J.phase)*8)*J.drift*K;return{x:Y+z*V+W,y:X+q*V+G*K*V*V,progress:V/J.lifetime}}function nj3(J){let Z=J>>>0;if(Z===0)Z=2654435769;return()=>{return Z=Z*1664525+1013904223>>>0,Z/4294967296}}class _G0 extends q7{text;baseColor;backgroundColor;glow;time;agentMode;orbWidth;orbHeight;glowIntensity;shockwaves;constructor({key:J,text:Z,baseColor:Q,backgroundColor:Y,glow:X,time:K,agentMode:V,orbWidth:G=40,orbHeight:F=40,glowIntensity:z=0.4,shockwaves:q=[]}){super(J?{key:J}:{});this.text=Z,this.baseColor=Q,this.backgroundColor=Y,this.glow=X,this.time=K,this.agentMode=V,this.orbWidth=G,this.orbHeight=F,this.glowIntensity=z,this.shockwaves=q}createElement(){return new IJ(this)}createRenderObject(){return new wg4(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}updateRenderObject(J){J.update(this.text,this.baseColor,this.backgroundColor,this.glow,this.time,this.agentMode,this.orbWidth,this.orbHeight,this.glowIntensity,this.shockwaves)}}var aj3=0.5;class wg4 extends q4{_text;_baseColor;_backgroundColor;_glow;_time;_agentMode;_orbWidth;_orbHeight;_glowIntensity;_shockwaves;constructor(J,Z,Q,Y,X,K,V,G,F,z){super();this._text=J;this._baseColor=Z;this._backgroundColor=Q;this._glow=Y;this._time=X;this._agentMode=K;this._orbWidth=V;this._orbHeight=G;this._glowIntensity=F;this._shockwaves=z}update(J,Z,Q,Y,X,K,V,G,F,z){let q=J!==this._text;if(this._text=J,this._baseColor=Z,this._backgroundColor=Q,this._glow=Y,this._time=X,this._agentMode=K,this._orbWidth=V,this._orbHeight=G,this._glowIntensity=F,this._shockwaves=z,q)this.markNeedsLayout();this.markNeedsPaint()}getMinIntrinsicWidth(J){return Q5(this._text,!1)}getMaxIntrinsicWidth(J){return Q5(this._text,!1)}getMinIntrinsicHeight(J){return 1}getMaxIntrinsicHeight(J){return 1}performLayout(){let J=this._lastConstraints;h4(!!J,"performLayout called without constraints");let Z=Q5(this._text,!1),Q=J.constrain(Z,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=f6(this._text),V=this._agentMode==="rush"?2.5:1,{primary:G,secondary:F}=Nr0(this._agentMode),z=Y;for(let q=0;q<K.length;q++){let W=K[q],H=V3(W,!1),D=(1-q/Math.max(K.length-1,1)*0.7)**1.2,B=this._glow.sample(this._orbWidth-2+q*0.5,this._orbHeight/2,this._time,V),N=0;for(let E of this._shockwaves){let M=this._time-E.startTime;if(M<0||M>$L)continue;let A=this._orbWidth*0.7+q,j=this._orbHeight/2,R=A-E.x,_=(j-E.y)/aj3,C=Math.sqrt(R*R+_*_),b=M*Lr0,d=Math.abs(C-b);if(d<WI){let f=1-M/$L,y=(1-d/WI)*f;N=Math.max(N,y*0.6)}}let w=B**0.7,L=Math.min(1,w*D+N),O=this.blendWithGlow(this._baseColor,L,G,F);J.setCell(z,X,{char:W,width:H,style:{fg:O,bg:this._backgroundColor}}),z+=H}}blendWithGlow(J,Z,Q,Y){let X=YK0(Q,Y,Z),K=Z*this._glowIntensity;if(J.type==="rgb"){let V=J.value,G=Math.round(V.r*(1-K)+X.r*K),F=Math.round(V.g*(1-K)+X.g*K),z=Math.round(V.b*(1-K)+X.b*K);return{type:"rgb",value:{r:G,g:F,b:z}}}if(K>0.15)return{type:"rgb",value:{r:X.r,g:X.g,b:X.b}};return J}}var Lg4=["ctrl+x","y","z"],Og4=1.5,TG0="!@#$%^&*()_+-=[]{}|;:,.<>?/~`0123456789";function oj3(J,Z,Q){let Y=Math.max(J.length,Z.length),X=[];for(let K=0;K<Y;K++){let V=J[K]??" ",G=Z[K]??" ",F=V===" "||V===`
|
|
4939
4939
|
`||V==="\t",z=G===" "||G===`
|
|
4940
4940
|
`||G==="\t";if(F&&z){X.push(Q<0.5?V:G);continue}let q=K/Y*0.4,W=Math.max(0,Math.min(1,(Q-q)/(1-q)));if(W===0)X.push(V);else if(W>=1)X.push(G);else if(F)X.push(W<0.7?" ":G);else if(z)X.push(W<0.3?V:" ");else if(W<0.5){let H=W*2;if(Math.random()<H)X.push(TG0[Math.floor(Math.random()*TG0.length)]);else X.push(V)}else{let H=(W-0.5)*2;if(Math.random()<H)X.push(G);else X.push(TG0[Math.floor(Math.random()*TG0.length)])}}return X.join("").trimEnd()}var Eg4=[{type:"command",text:'amp -x "What package manager do we use here?"'},{type:"command",text:'amp -x "Run the linter and fix the errors"'},{type:"hint",text:"Use Ctrl+O to open the command palette"},{type:"hint",text:"Use Ctrl+G to edit the prompt in your $EDITOR"},{type:"hint",text:"Use the `prompt: queue` command to enqueue messages without interrupting the agent"},{type:"hint",text:"Use the `thread: browser` command to open your thread in the browser"},{type:"hint",text:"Use the `thread: new` command to start a fresh thread"},{type:"hint",text:"Use the `thread: handoff` command to draft a new thread with relevant context"},{type:"hint",text:"Use the `thread: visibility` command to change thread visibility settings"},{type:"hint",text:"Use the `settings: open in editor` command to configure Amp"},{type:"hint",text:"Use the `agents-md: generate` command to create an AGENTS.md"},{type:"hint",text:"Use Tab/Shift+Tab to navigate to previous messages to edit or restore to a previous state"},{type:"prompt",text:'"Use the oracle to review the code we just wrote."'},{type:"prompt",text:'"Use subagents to update these components to use the new attribute we added."'},{type:"prompt",text:'"Do not write any code yet. Plan first."'},{type:"prompt",text:'"Think hard before you start implementing."'},{type:"prompt",text:`"Use 'psql' to change all blog_posts to have comments"`},{type:"prompt",text:'"Run <build command> and fix all the errors"'},{type:"quote",text:`"We are at the 'introduction of photography' period of programming. Painting by hand just doesn't have the same appeal anymore" - Orta Therox`},{type:"quote",text:'"Programming in the normal way feels like walking. You type out each expression, stepping incrementally toward your goal. When programming with AI, each move is bigger than a step. You lift off the ground." - Mary Rose Cook'},{type:"quote",text:'"Tomorrow all this may change, but right now after daily experience writing code with LLMs I strongly believe the maximum quality of work is reached using the human+LLM equation." - antirez'},{type:"quote",text:`"The magic that's coming now is the most powerful yet. And that means that we're beginning a profound period of exploration and creativity, trying to understand how to make that magic work and to derive new advantages from its power." - Tim O'Reilly`},{type:"quote",text:`"They're applying years of hard-won engineering wisdom to shape and constrain the AI's output. The AI is accelerating their implementation, but their expertise is what keeps the code maintainable." - Addy Osmani`},{type:"quote",text:'"I love computers just for the—sheer machine of it. This is the most exciting new thing that computers have been doing, probably in my lifetime." - DHH'},{type:"quote",text:`"We wouldn't even need to bother looking at the AI-generated code any more, just like we don't bother looking at the machine code generated by a compiler." - Martin Kleppmann`},{type:"quote",text:'"Real progress is messy, iterative, and deeply intertwined with the tools we build. Large language models are the latest, most dramatic example of that truth." - Daniel Lemire'},{type:"quote",text:`"'Human in the loop' is evolving from 'human who fixes AI mistakes' to 'human who directs AI work.'" - Ethan Mollick`},{type:"quote",text:`"I'm trying to code like a surgeon. A surgeon isn't a manager, they do the actual work! But their skills and time are highly leveraged." - Geoffrey Litt`},{type:"quote",text:`"It's important to do things fast. You learn more per unit time because you make contact with reality more frequently." - Nat Friedman`},{type:"quote",text:'"Once coding speed jumps, everything around it becomes the constraint. Your throughput gets capped by whatever is slowest." - Paul Dix'},{type:"quote",text:'"Bubble or no bubble, no one knows anything." - Benedict Evans'},{type:"quote",text:`"I actually don't think documentation is too important: LLMs can read the code a lot faster than you to figure out how to use it." - Simon Willison`},{type:"quote",text:`"The vast majority of AI tokens in the future will be used on things we don't even do today as workers." - Aaron Levie`},{type:"quote",text:`"Once you're airborne, you're suddenly immune to the length of the runway. You have days, not months. Time to break some things." - Kent Beck`},{type:"quote",text:'"Absolutely every fundamental assumption about how I work has to be questioned. There are days when it feels like I would be better off if I did not know anything about programming and started from scratch." - David Crawshaw'},{type:"quote",text:'"Code was the easiest part." - Andrej Karpathy'},{type:"quote",text:`"It's amazing for learning a codebase you're not familiar with, so it's great for discovery. Getting us out of writing boilerplate, getting us out of memorizing APIs, getting us out of looking up that thing from Stack Overflow." - Jeremy Howard`},{type:"quote",text:`"Don't anthropomorphize them!" - Steven Sinofsky`}],SG0=40,kG0=40,rj3={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}};function sj3(J){if(J==="internal")return{colorMode:"vertical",colors:rj3};return{colorMode:"intensity"}}class ny extends u0{agentMode;mysteriousMessage;mysterySequenceProgress;onShowMysteryModal;onOrbExplode;constructor(J={}){super(J.key?{key:J.key}:{});this.agentMode=J.agentMode,this.mysteriousMessage=J.mysteriousMessage,this.mysterySequenceProgress=J.mysterySequenceProgress,this.onShowMysteryModal=J.onShowMysteryModal,this.onOrbExplode=J.onOrbExplode}createState(){return new Mg4}}class Mg4 extends f0{_glow;_t=0;_timer=null;_fps=0;_shockwaves=[];_orbClickCount=0;_suggestion;_morphStartTime=null;_previousHasMystery=!1;initState(){super.initState(),this._glow=new bQ;let J=process.env.NO_SPLASH_QUOTE==="1"?Eg4.filter((Z)=>Z.type!=="quote"):Eg4;this._suggestion=J[Math.floor(Math.random()*J.length)],this._previousHasMystery=!!this.widget.mysteriousMessage}getMorphProgress(J){if(this._morphStartTime===null)return null;let Z=J-this._morphStartTime;if(Z>=Og4)return null;return Z/Og4}get orbExploded(){return this._orbClickCount>=CG0}handleShockwave=(J)=>{if(this.orbExploded)return;this._shockwaves.push(J),this.setState(()=>{})};handleOrbClick=(J)=>{if(this.orbExploded)return;if(this._orbClickCount+=1,this._orbClickCount>=CG0)this._orbClickCount=CG0,this._shockwaves=[],this.widget.onOrbExplode?.({x:J.x,y:J.y});this.setState(()=>{})};dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}startAnimation(J){if(this._timer)clearInterval(this._timer),this._timer=null;if(this._fps=J,J>0)this._timer=setInterval(()=>{this._t+=1/J,this._shockwaves=this._shockwaves.filter((Z)=>this._t-Z.startTime<$L),this.setState(()=>{})},1000/J)}build(J){let Q=k1.of(J).colorScheme,X=y0.of(J).app,V=G4.of(J).capabilities.animationSupport,G=V==="fast"?30:V==="slow"?15:0;if(G!==this._fps)this.startAnimation(G);let F=!!this.widget.mysteriousMessage,z=this._suggestion,q=V==="disabled"?3:this._t;if(F&&!this._previousHasMystery&&V!=="disabled")this._morphStartTime=q;this._previousHasMystery=F;let W=this.getMorphProgress(q),H=W!==null,U=this.orbExploded,D=sj3(this.widget.agentMode),B=D.colors,N=z.type==="quote"||z.type==="news"?new g({color:Q.foreground,dim:!0}):z.type==="hint"?new g({color:Q.secondary}):new g({color:z.type==="prompt"||z.type==="note"?Q.primary:Q.warning}),w=new g({color:X.keybind}),L=new g({color:X.command}),O=new g({color:Q.foreground,dim:!0}),E=[];if(z.type==="hint"){let y=z.text.split(/(`[^`]+`)/g);for(let x of y)if(x.startsWith("`")&&x.endsWith("`")){let m=x.slice(1,-1);E.push(new P(m,L))}else E.push(new P(x,N))}else E.push(new P(z.text,N));let M=V==="fast",j=M&&!U?new _G0({text:"Welcome to Amp",baseColor:Q.foreground,backgroundColor:Q.background,glow:this._glow,time:q,agentMode:this.widget.agentMode,orbWidth:SG0,orbHeight:kG0,glowIntensity:1,shockwaves:this._shockwaves}):new $0({text:new P("Welcome to Amp",new g({color:Q.foreground}))}),R=null;if(F){let x=0.3+(Math.sin(q*0.5)*0.5+0.5)*0.4,m=new g({color:Q.primary,italic:!0,dim:x<0.5}),h=this.widget.mysterySequenceProgress?.matched.length??0,o=h>0?"Keep going...":"A message awaits...",l=[];for(let t=0;t<Lg4.length;t++){let B0=Lg4[t],a=B0==="ctrl+x"?"Ctrl-X":B0.toUpperCase(),q0=t<h?new g({color:Q.primary,bold:!0}):w;if(t>0)l.push(new P(", ",O));l.push(new P(a,q0))}R=new p0({crossAxisAlignment:"start",mainAxisSize:"min",children:[M?new _G0({text:o,baseColor:Q.primary,glow:this._glow,time:q,agentMode:this.widget.agentMode,orbWidth:SG0,orbHeight:kG0,glowIntensity:0.6,shockwaves:this._shockwaves}):new $0({text:new P(o,m)}),new $0({text:new P("",void 0,[...l,new P(" to unlock",O)])})]})}let _,C=`A message awaits...
|
|
4941
4941
|
Ctrl-X, Y, Z to unlock`;if(H){let x=z.text.replace(/`([^`]+)`/g,"$1")+`
|
|
@@ -5695,7 +5695,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
|
|
|
5695
5695
|
`),K=[];for(let V=0;V<X.length;V++){let z=X[V].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 q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new P(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new P(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new P(`
|
|
5696
5696
|
`))}return new l0({decoration:{color:Q.colorScheme.background,border:K4.all(new Y4(Y.app.keybind,1,"rounded"))},child:new m0({padding:R0.symmetric(0,1),child:new $0({text:new P(void 0,void 0,K)})})})}}class S41 extends q7{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=Yz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new _41({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function wc4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?E9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),W=Math.floor(z/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?E9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),W=Math.round(z/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function Pk3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?E9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=Math.max(1,Math.floor(q/X)),U=z+Z*H+Math.floor(H/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:U,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?E9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),U=G>0?V/G:0,D=Math.round((1-U)*(W-1));return{x:H,y:D}}default:return null}}function Ck3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function _k3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function Tk3(J,Z,Q,Y,X,K,V){let G;try{let D=k1.of(J),B=y0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new g({color:G.foreground,bold:!0}),z=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],H=new g({color:G.foreground,underline:!0}),U=(D,B)=>new P(B,H,void 0,rX0(D),()=>{N3(J,D)});if(Y.length<=1){if(W.push(new P(`${Z.label}: `,F)),Z.link)W.push(U(Z.link,K(Z.value)));else W.push(new P(K(Z.value),z));if(Z.meta)W.push(new P(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new P(`${Z.label}
|
|
5697
5697
|
`,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new P("● ",new g({color:O}))),W.push(new P(`${w.name}: `,q)),L.link)W.push(U(L.link,K(L.value)));else W.push(new P(K(L.value),z));if(N<Y.length-1||D)W.push(new P(`
|
|
5698
|
-
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),z))}return new l0({decoration:{color:G.background,border:K4.all(new Y4(G.border,1,"rounded"))},child:new $0({text:new P(void 0,void 0,W)})})}a0();k8();yE();_2();t3();C2();wc();iX();A$();rJ();tJ();tA();s4();fm();BC();I1();a0();A$();class k41{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1776946513-g63e052"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await C60(Z,this.configService)}catch(Z){S.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class cL extends u0{props;constructor(J){super();this.props=J}createState(){return new Lc4}}class Lc4 extends f0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}tJ();class Oc4 extends f0{controller=new c7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.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(J)=>{if(this.imageAttachments.length>=wY)return!1;let Z=await sq(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!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(J){let Z=y0.of(J),{colors:Q,app:Y}=Z,K=G4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new oU({controller:this.controller,triggers:[new KV],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:l4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new n4({focusNode:this.focusNode,child:G}),z=new l0({constraints:new E1({maxHeight:V}),padding:R0.symmetric(1,0),child:F}),q=new l0({padding:R0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new l0({padding:R0.symmetric(1,0),child:new $0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new b1({child:z}),new I0({height:1}),W];return new l0({decoration:{border:K4.all(new Y4(Q.foreground,1,"solid")),color:Q.background},padding:R0.all(1),child:new p0({children:H})})}}class v41 extends u0{props;constructor(J){super();this.props=J}createState(){return new Oc4}}function Ec4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class y41 extends S1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Ec4(X.pubDate).length));return new p3({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=y0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new P(B,new g({color:U}))})])});return new l0({decoration:W?{color:W}:void 0,padding:R0.symmetric(2,0),child:new q1({children:[new b1({child:new $0({text:new P(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Ec4(X.pubDate),Q)]})})}})}}class xJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!xJ._instance)xJ._instance=new xJ;return xJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}a0();class Mc4 extends f0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){S.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){S.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=y0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new p3({title:"Add Label",items:F,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(z,q,W,H)=>{let U=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new l0({decoration:U?{color:U}:void 0,padding:R0.symmetric(2,0),child:new $0({text:new P("",void 0,[new P("Create new label: ",new g({color:D})),new P(N,new g({color:D,bold:!0}))])})})}return new l0({decoration:U?{color:U}:void 0,padding:R0.symmetric(2,0),child:new $0({text:new P(z.name,new g({color:D}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let H=q.trim().toLowerCase();return H.length===0||z.name.includes(H)},sortItems:(z,q,W)=>{let H="__isCreateMarker"in z.item&&z.item.__isCreateMarker,U="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(H&&!U)return-1;if(!H&&U)return 1;return q.score-z.score}})}}class x41 extends u0{props;constructor(J){super();this.props=J}createState(){return new Mc4}}k8();class Ac4 extends u0{props;constructor(J){super();this.props=J}createState(){return new jc4}}class jc4 extends f0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=L9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=y0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new P("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new P(`${K}/${X} ${j4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new P(` (${V} ${j4(V,"command")}, ${G} ${j4(G,"tool")})`,new g({dim:!0})));Y.push(new P(`
|
|
5698
|
+
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),z))}return new l0({decoration:{color:G.background,border:K4.all(new Y4(G.border,1,"rounded"))},child:new $0({text:new P(void 0,void 0,W)})})}a0();k8();yE();_2();t3();C2();wc();iX();A$();rJ();tJ();tA();s4();fm();BC();I1();a0();A$();class k41{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1776949187-g6c0bed"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await C60(Z,this.configService)}catch(Z){S.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class cL extends u0{props;constructor(J){super();this.props=J}createState(){return new Lc4}}class Lc4 extends f0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}tJ();class Oc4 extends f0{controller=new c7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.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(J)=>{if(this.imageAttachments.length>=wY)return!1;let Z=await sq(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!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(J){let Z=y0.of(J),{colors:Q,app:Y}=Z,K=G4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new oU({controller:this.controller,triggers:[new KV],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:l4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new n4({focusNode:this.focusNode,child:G}),z=new l0({constraints:new E1({maxHeight:V}),padding:R0.symmetric(1,0),child:F}),q=new l0({padding:R0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new l0({padding:R0.symmetric(1,0),child:new $0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new b1({child:z}),new I0({height:1}),W];return new l0({decoration:{border:K4.all(new Y4(Q.foreground,1,"solid")),color:Q.background},padding:R0.all(1),child:new p0({children:H})})}}class v41 extends u0{props;constructor(J){super();this.props=J}createState(){return new Oc4}}function Ec4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class y41 extends S1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>Ec4(X.pubDate).length));return new p3({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=y0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:q1.end([new $0({text:new P(B,new g({color:U}))})])});return new l0({decoration:W?{color:W}:void 0,padding:R0.symmetric(2,0),child:new q1({children:[new b1({child:new $0({text:new P(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Ec4(X.pubDate),Q)]})})}})}}class xJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!xJ._instance)xJ._instance=new xJ;return xJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}a0();class Mc4 extends f0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){S.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){S.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=y0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new p3({title:"Add Label",items:F,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(z,q,W,H)=>{let U=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new l0({decoration:U?{color:U}:void 0,padding:R0.symmetric(2,0),child:new $0({text:new P("",void 0,[new P("Create new label: ",new g({color:D})),new P(N,new g({color:D,bold:!0}))])})})}return new l0({decoration:U?{color:U}:void 0,padding:R0.symmetric(2,0),child:new $0({text:new P(z.name,new g({color:D}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let H=q.trim().toLowerCase();return H.length===0||z.name.includes(H)},sortItems:(z,q,W)=>{let H="__isCreateMarker"in z.item&&z.item.__isCreateMarker,U="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(H&&!U)return-1;if(!H&&U)return 1;return q.score-z.score}})}}class x41 extends u0{props;constructor(J){super();this.props=J}createState(){return new Mc4}}k8();class Ac4 extends u0{props;constructor(J){super();this.props=J}createState(){return new jc4}}class jc4 extends f0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=L9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=y0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new $0({text:new P("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new P(`${K}/${X} ${j4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new P(` (${V} ${j4(V,"command")}, ${G} ${j4(G,"tool")})`,new g({dim:!0})));Y.push(new P(`
|
|
5699
5699
|
|
|
5700
5700
|
`));for(let F of this.plugins){let{icon:z,color:q}=this.statusIcon(F.status),W=this.getRelativePath(F.uri.toString());if(Y.push(new P(`${z} `,new g({color:q}))),Y.push(new P(W,new g({bold:!0}))),Y.push(new P(` ${F.status}`,new g({dim:!0}))),Y.push(new P(`
|
|
5701
5701
|
`)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new P(" Events: ",new g({dim:!0}))),Y.push(new P(F.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new P(`
|
|
@@ -5878,7 +5878,7 @@ ${r.content||""}`:r.content||"",_0=[],x0=r.baseDir.startsWith("file://")?uz0(r.b
|
|
|
5878
5878
|
`),process.exit(1)}process.stdout.write(await Qu3(F.result.displayText)+`
|
|
5879
5879
|
`),process.exit(0)})}mN();import{stdout as Yu3}from"node:process";function Xu3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${bz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function En4(J){Yu3.write(`${Xu3(J)}
|
|
5880
5880
|
`)}function Mn4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{En4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{En4(Z),process.exit(0)})}var Rm3=dr.join(cX,"logs","headless.log"),m31=dr.join(rv,"device-id.json"),Pm3=`cli-tui-${rr4(16).toString("hex")}`;async function Cm3(){for(let J of uE)try{if((await J.listConfigs()).length>0)return J}catch(Z){S.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => U4(lx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){xZ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
5881
|
-
`)}function _m3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function M2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")B$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")B$("experimental.agentMode",Z.mode);if(J.getOptionValueSourceWithGlobals("model")==="cli"&&Z.model)B$("internal.model",Tm3(Z.model))}function dr4(J){let Z=J.indexOf(":");if(Z===-1)throw new B4(`Invalid model format "${J}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let Q=J.slice(0,Z).trim(),Y=J.slice(Z+1).trim();if(!Q||!Y)throw new B4(`Invalid model format "${J}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Tm3(J){if(!J.includes("="))return dr4(J),J;let Z={};for(let Q of J.split(",")){let Y=Q.trim();if(!Y)continue;let X=Y.indexOf("=");if(X===-1)throw new B4(`Invalid mode-specific model entry "${Y}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K)throw new B4(`Missing mode name in "${Y}". Expected "mode=provider:model".`,1);if(!V)throw new B4(`Missing model value for mode "${K}". Expected "${K}=provider:model".`,1);dr4(V),Z[K]=V}if(Object.keys(Z).length===0)throw new B4("No valid model overrides found in --model flag value.",1);return Z}function Sm3(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function km3(J){try{return await sr4(J,"utf-8")}catch{return J}}async function cr4(J,Z,Q){let Y=Sm3(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!ix(X,j7.HARNESS_SYSTEM_PROMPT)&&!(K&&P2(K)))throw new B4("You are not allowed to do this.",1);B$("systemPrompt",await km3(Y))}function ix(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function vm3(J){return J!=="pending"}function ax(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function ym3(J){let Z=ax(J);if(Z)return Z.id;if(KH(J))throw Error(J.error.message);throw Error("unreachable")}function xm3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function fm3(J){let Y=xm3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new B4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}function d31(J,Z){let Q=ba0(Error(J.error.message));if(Q.message===e2.networkOffline||Q.message===e2.networkTimeout)return fm3(Z);if(Q.message!==e2.internalBug)return new B4(Q.message,1,Q.suggestion);return new B4(J.error.message.replace(/^Error: /,""),1)}var lr4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"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:(J)=>`${J?"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??oK,description:`Custom settings file path (overrides the default location ${oK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Fn})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","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:p7(),description:(J)=>J?"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:(J)=>J?"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:(J)=>J?"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:vE.SMART.key,description:`Set the agent mode (${oZ({}).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:oZ().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",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}],ir4=(J)=>("deprecated"in J)&&J.deprecated===!0,um3=(J)=>("hidden"in J)&&J.hidden===!0,bm3=(J)=>("default"in J),hm3=(J)=>("default"in J)?J.default:void 0,tr4=[{name:"toggle-skills-count",entryPoint:N11}];function gm3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new B4(e2.unknownCommand(Q),1,V)}}async function Cq0(J){return{...J,getThreadEnvironment:qU,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new _M(J.fileSystem),generateThreadTitle:v14,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YQ(J.configService),pluginService:J.pluginService}}function er4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qU,filesystem:J.fileSystem,threadService:J.threadService}}var $s4="code-tour";function p31(J){return J.filter((Z)=>Z.name!==$s4)}function mm3(J){return{...J,skills:J.skills.pipe(M1(p31)),getSkills:async()=>p31(await J.getSkills()),getSkill:async(Z)=>Z===$s4?void 0:J.getSkill(Z),getSkillsList:async()=>{let Z=p31(await J.getSkills());return DT(Z)}}}var Rq0=K1.file(Im3.homedir()),c31=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):F1.joinPath(Rq0,".config");function pm3(J){return $H4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(DC4())BC4();else if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())eW4();else fp0(Z);let Q=vK0(),Y=ir0();if((!Q||Y||KT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(vU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(vU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(vK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function L7(J,Z,Q){let Y=Q?.deferAuth??!1,X=Q?.skipToolProviders??!1;Qb1("0.0.
|
|
5881
|
+
`)}function _m3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function M2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")B$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")B$("experimental.agentMode",Z.mode);if(J.getOptionValueSourceWithGlobals("model")==="cli"&&Z.model)B$("internal.model",Tm3(Z.model))}function dr4(J){let Z=J.indexOf(":");if(Z===-1)throw new B4(`Invalid model format "${J}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let Q=J.slice(0,Z).trim(),Y=J.slice(Z+1).trim();if(!Q||!Y)throw new B4(`Invalid model format "${J}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function Tm3(J){if(!J.includes("="))return dr4(J),J;let Z={};for(let Q of J.split(",")){let Y=Q.trim();if(!Y)continue;let X=Y.indexOf("=");if(X===-1)throw new B4(`Invalid mode-specific model entry "${Y}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let K=Y.slice(0,X).trim(),V=Y.slice(X+1).trim();if(!K)throw new B4(`Missing mode name in "${Y}". Expected "mode=provider:model".`,1);if(!V)throw new B4(`Missing model value for mode "${K}". Expected "${K}=provider:model".`,1);dr4(V),Z[K]=V}if(Object.keys(Z).length===0)throw new B4("No valid model overrides found in --model flag value.",1);return Z}function Sm3(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function km3(J){try{return await sr4(J,"utf-8")}catch{return J}}async function cr4(J,Z,Q){let Y=Sm3(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!ix(X,j7.HARNESS_SYSTEM_PROMPT)&&!(K&&P2(K)))throw new B4("You are not allowed to do this.",1);B$("systemPrompt",await km3(Y))}function ix(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function vm3(J){return J!=="pending"}function ax(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function ym3(J){let Z=ax(J);if(Z)return Z.id;if(KH(J))throw Error(J.error.message);throw Error("unreachable")}function xm3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function fm3(J){let Y=xm3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new B4(`Couldn't connect to the Amp server at ${J}.`,1,Y)}function d31(J,Z){let Q=ba0(Error(J.error.message));if(Q.message===e2.networkOffline||Q.message===e2.networkTimeout)return fm3(Z);if(Q.message!==e2.internalBug)return new B4(Q.message,1,Q.suggestion);return new B4(J.error.message.replace(/^Error: /,""),1)}var lr4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"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:(J)=>`${J?"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??oK,description:`Custom settings file path (overrides the default location ${oK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(S).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Fn})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","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:p7(),description:(J)=>J?"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:(J)=>J?"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:(J)=>J?"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:vE.SMART.key,description:`Set the agent mode (${oZ({}).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:oZ().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neo",long:"neo",type:"switch",description:"Use the Neo TUI",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}],ir4=(J)=>("deprecated"in J)&&J.deprecated===!0,um3=(J)=>("hidden"in J)&&J.hidden===!0,bm3=(J)=>("default"in J),hm3=(J)=>("default"in J)?J.default:void 0,tr4=[{name:"toggle-skills-count",entryPoint:N11}];function gm3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new B4(e2.unknownCommand(Q),1,V)}}async function Cq0(J){return{...J,getThreadEnvironment:qU,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new _M(J.fileSystem),generateThreadTitle:v14,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YQ(J.configService),pluginService:J.pluginService}}function er4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:qU,filesystem:J.fileSystem,threadService:J.threadService}}var $s4="code-tour";function p31(J){return J.filter((Z)=>Z.name!==$s4)}function mm3(J){return{...J,skills:J.skills.pipe(M1(p31)),getSkills:async()=>p31(await J.getSkills()),getSkill:async(Z)=>Z===$s4?void 0:J.getSkill(Z),getSkillsList:async()=>{let Z=p31(await J.getSkills());return DT(Z)}}}var Rq0=K1.file(Im3.homedir()),c31=process.env.XDG_CONFIG_HOME?K1.file(process.env.XDG_CONFIG_HOME):F1.joinPath(Rq0,".config");function pm3(J){return $H4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(DC4())BC4();else if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())eW4();else fp0(Z);let Q=vK0(),Y=ir0();if((!Q||Y||KT4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(vU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(vU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(vK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function L7(J,Z,Q){let Y=Q?.deferAuth??!1,X=Q?.skipToolProviders??!1;Qb1("0.0.1776949187-g6c0bed");let K=fC({storage:J.settings,secretStorage:J.secrets,workspaceRoot:h0.of(K1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Rq0,userConfigDir:c31});Vm4(K);let V=await K.getLatest();S.debug("Global configuration initialized",{settingsKeys:Object.keys(V.settings)});let G=!1;{let m=await J.secrets.get("apiKey",J.ampURL);if(G=Boolean(m),S.info("API key lookup before login",{found:Boolean(m),ampURL:J.ampURL,deferAuth:Y}),!m)if(Y)S.info("No API key found, continuing startup with deferred auth");else{d5.write(`No API key found. Starting login flow...
|
|
5882
5882
|
`);let p=await dm3(J),h=await J.secrets.get("apiKey",J.ampURL);if(S.info("Login flow completed",{success:p,storedKeyPresent:Boolean(h),ampURL:J.ampURL}),!p)await Cq(),process.exit(1);G=!0}}{let m=await K.getLatest(),p=m.settings.url,h=m.secrets.isSet?.[p];S.info("Config secrets state after login",{configURL:p,apiKeySet:h?.apiKey??!1})}let F=v1(YQ(K).pipe(Q3(vm3))),z=Y?"pending":await F;if(!Y)S.info("Server status resolved",{status:"ready",isAuthenticated:_6(z),isError:KH(z),errorMessage:KH(z)?z.error.message:void 0});let q=F.then((m)=>ym3(m));q.catch(()=>{return});let{toolService:W,dispose:H}=wZ0({configService:K}),U=new Map,D=()=>U.clear(),B=new oT0(K,J.settings.getWorkspaceRootPath()),N=r80({configService:K,filesystem:q8}),w=do1({configService:K,trustStore:B,skillMCPServers:N.skillMCPServers,createOAuthProvider:async(m,p,h)=>{let o=`${m}:${p}`,l=U.get(o);if(l)return S.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:p}),l;S.debug("Creating OAuth provider for server",{serverName:m,serverUrl:p});let t=(async()=>{let B0=new dE(J.secrets),a=await B0.getClientInfo(m,p),J0=h?.scopes??a?.scopes,q0=OC4();S.info("OAuth headless mode check",{useHeadless:q0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:d5.isTTY});let N0;if(q0)N0=J.executeMode?LC4():wC4(m);let Q0=new TR0({storage:B0,serverName:m,serverUrl:p,clientId:h?.clientId??a?.clientId,clientSecret:h?.clientSecret??a?.clientSecret,authUrl:h?.authUrl??a?.authUrl,tokenUrl:h?.tokenUrl??a?.tokenUrl,scopes:J0,headlessAuthHandler:N0});return S.debug("OAuth provider created",{serverName:m,serverUrl:p,hasManualClientId:!!(h?.clientId??a?.clientId),willUseDCR:!(h?.clientId??a?.clientId),scopes:J0,headlessMode:q0,executeMode:J.executeMode}),Q0})();return U.set(o,t),t}}),L=im0({configService:K,filesystem:q8,spawn:gJ0}),O;if(X)O=new Map;else if(J.executeMode){let m=await wz4({toolService:W,providers:[w,L],initialTimeout:15000});O=m.registrations;for(let[p,h]of m.initErrors)S.warn(`${p} provider initialization slow or failed:`,h)}else O=nm0({toolService:W,providers:[w,L]});if(Z.jetbrains)xE("JetBrains");else if(Z.ide&&Q_4())xE("VS Code");else if(Z.ide&&Y_4())xE("Neovim");else if(Z.ide){let m=await Cm3();if(m){let p=c40(m.ideName);if(p)xE(p)}}if(J.executeMode)Yb1(!0);let E,M=n8.status.pipe(M1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&vb1(m.ideName))),c4()).subscribe((m)=>{if(m){if(!E)E=W.registerTool(Nz4)}else E?.dispose(),E=void 0}),A;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];A=new av(process.cwd(),{alwaysIncludePaths:m},!0)}else A=new class extends av{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let j=new ek0(vM(K),{maxThreads:200});S.info("Starting Amp background services");let R=new A11,_=process.env.PLUGINS??"off",C=Z.headless?lg4():void 0,b=C??new xG0({configService:K}),d=b instanceof xG0?b:void 0;if(d)d.pluginExecutorKind="local";let f=WS0({configService:K,fileSystem:q8,platform:b,internalPlugins:tr4,pluginFilter:_}),y=ur1({pluginService:f,toolService:W}),x={configService:K,toolService:W,mcpService:w,skillService:N,toolboxService:L,trustStore:B,threadService:j,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:A,fileSystem:q8,terminal:R,pluginService:f,pluginPlatform:d,headlessPluginPlatform:C,serverStatus:z,serverStatusPromise:F,viewerUserIDPromise:q,hasAPIKeyAtStartup:G};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())S.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of O.values())m.dispose();await x.mcpService.dispose(),D(),await x.threadService.asyncDispose(),x.configService.unsubscribe(),H(),x.fuzzyServer.dispose(),x.settingsStorage[Symbol.dispose](),M.unsubscribe(),E?.dispose(),y.dispose(),await x.pluginService.dispose()}}}async function dm3(J){if(!J.executeMode){if(!await wK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return d5.write(`Login cancelled. Run the command again to retry.
|
|
5883
5883
|
`),!1}return await Js4(J)}async function Js4(J){let Z=rr4(32).toString("hex"),Q=await Yy(J.ampURL,Z),Y=new AbortController;try{await bV(Q,Y.signal)}catch(K){S.error("Error opening browser",{error:K})}let X=await Yy(J.ampURL,Z,!1);d5.write(`If your browser does not open automatically, visit:
|
|
5884
5884
|
|
|
@@ -5886,7 +5886,7 @@ ${n0.blue.bold(X)}
|
|
|
5886
5886
|
|
|
5887
5887
|
`);try{return await wS4(J.ampURL,Z,J.secrets,Y),d5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return S.error("Login failed",{error:K}),xZ.write(`
|
|
5888
5888
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
5889
|
-
`),!1}}function cm3(J){let Z=new qw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)aj(),process.exit(0);let B=D.originalError??D;HR4(B)}),Mn4(Z,{version:"0.0.
|
|
5889
|
+
`),!1}}function cm3(J){let Z=new qw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)aj(),process.exit(0);let B=D.originalError??D;HR4(B)}),Mn4(Z,{version:"0.0.1776949187-g6c0bed",buildTimestamp:"2026-04-23T13:03:36.797Z",buildType:"'release'"}),Z.addHelpText("after",$_4()),Z.configureHelp({formatHelp:J_4}),Z.command("logout").description("Log out by removing stored API key").action(async(D,B)=>{let N=B.optsWithGlobals(),w=await l3(N);await sm3(w)}),Z.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(D,B)=>{let N=B.optsWithGlobals(),w=await l3(N);await rm3(w,await Pn(N,w.settings))}),Z.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(D,B,N)=>{let w=N.optsWithGlobals(),L=await l3(w);await GC4(D??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.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(D,B)=>{let N=B.optsWithGlobals(),w=await l3(N);await FC4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),Z.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(D)=>{await OT4({raw:D.raw===!0}),process.exit(process.exitCode??0)}),Z.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(`
|
|
5890
5890
|
`)).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(D,B,N)=>{if(D&&B.apply)throw new B4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let w=B.apply??D;if(!w||w.trim().length===0)d5.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.
|
|
5891
5891
|
|
|
5892
5892
|
`),N.outputHelp(),process.exit(0);let L=I9(w)??JX(w),O=N.optsWithGlobals(),E=await l3(O);M2(N,O);let M=await L7(E,O),A=!1;try{if(B.checkout&&B.skipCheckout)throw new B4("Choose either --checkout or --skip-checkout, not both.",1);if(KH(M.serverStatus))throw d31(M.serverStatus,E.ampURL);let j=_6(M.serverStatus)?M.serverStatus.features:void 0;if(!ix(j,j7.V2))throw new B4("live-sync is not enabled for your user",1);await VS4({ampURL:E.ampURL,threadId:L,configService:M.configService,threadService:M.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof B.apply==="string",checkoutMode:B.checkout?"always":B.skipCheckout?"never":"prompt",promptForYesNo:wK0}),A=!0}finally{if(await M.asyncDispose(),A)process.exit(0)}});let Q=async(D,B,N)=>{fC({storage:B.settings,secretStorage:B.secrets,workspaceRoot:h0.of(K1.file(process.cwd())),defaultAmpURL:B.ampURL,homeDir:Rq0,userConfigDir:c31});let w={...B,executeMode:!1};await Pq0(w,{...D,openThreadSwitcher:!0},N,J)},Y=Z.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(D,B)=>{let N=B.optsWithGlobals(),w=await l3(N);await or4(N,w,B)});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(D,B)=>{let N=B.optsWithGlobals(),w=await l3(N);await Gp3(N,w,B)}),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(D,B,N)=>{let w=N.optsWithGlobals(),L=await l3(w);if(B.pick)xZ.write(`${n0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
@@ -5920,8 +5920,8 @@ ${E}
|
|
|
5920
5920
|
|
|
5921
5921
|
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 lm3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await bG0()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await bG0()).trimEnd(),stdinInput:null}}function im3(J,Z,Q){if(J.streamJson&&!Z)throw new B4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new B4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new B4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new B4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new B4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new B4("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(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new B4("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"
|
|
5922
5922
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function Pq0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(c,n)=>{let r=Number(process.hrtime.bigint()-n)/1e6,e=aE4();S.info("Startup phase",{phase:c,phaseMs:Math.round(r),sinceMainMs:e===null?void 0:Math.round(e)})},{userInput:V,stdinInput:G}=await lm3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;im3({...Z,streamJson:F},J.executeMode,V),M2(Q,Z);let z=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&q;S.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let H=await L7(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",z);let{serverStatus:U}=H;if(!W&&KH(U))throw d31(U,J.ampURL);let D=_6(U)?U:null,B=D?.user.email,N=!!(B&&P2(B));if(!W)await cr4(Q,Z,U);let w=ax(U),L=w?.features??[],O=w?.team??null,E=BG0(Z,w);if(E instanceof Error)P3(E.message);if(D&&!Zh(Z.mode,B))throw new B4(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(Z.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!B||!P2(B)))throw new B4("Headless executor mode is only available for Amp employees",1);let n=await H.secretStorage.get("apiKey",J.ampURL);if(!n)throw new B4("API key required for headless mode. Please run `amp login` first.",1);let r=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(r&&!sZ(r))throw new B4(`Invalid thread ID: ${r}`,1);let e=r?void 0:await Kp3({dependencies:H,apiKey:n,visibility:E??void 0}),K0=r??e?.threadId;if(!K0)throw new B4("Failed to resolve headless thread ID",1);let Y0=await jC4(K0);if(Y0.status==="already-running")await H.asyncDispose(),await Cq(),process.exit(0);try{await HC4({ampURL:J.ampURL,apiKey:n,workspaceRoot:process.cwd(),threadId:K0,ownerUserId:e?.ownerUserId,threadVersion:e?.threadVersion,agentMode:e?.agentMode,initialToolDiscovery:Promise.all([H.mcpService.initialized,H.toolboxService.initialized]).then(()=>{return}),configService:H.configService,mcpService:H.mcpService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,pluginService:H.pluginService,pluginPlatform:H.headlessPluginPlatform})}finally{await Y0.release(),await H.asyncDispose()}await Cq(),process.exit(0)}let M=Z.threadId&&sZ(Z.threadId)?Z.threadId:void 0,A=W?await H.serverStatusPromise:U,j=_6(A)&&ix(A.features,j7.NEO_TUI);if((j||Z.neo||!1)&&!J.executeMode&&!Z.takeMeBack){if(Z.neo&&!j&&(!_6(A)||!P2(A.user.email)))throw new B4("--neo is only available for Amp employees",1);let c=await H.secretStorage.get("apiKey",J.ampURL);if(!c)throw new B4("API key required. Please run `amp login` first.",1);let n=vM(H.configService),r=new eI(H.fuzzyServer),e=process.cwd();await B11({ampURL:J.ampURL,apiKey:c,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??lK(J.ampURL),configService:H.configService,toolService:H.toolService,skillService:H.skillService,mcpService:H.mcpService,readFileSystemDirectory:({uri:K0})=>cw({fileSystem:H.fileSystem,workspaceRoot:e},K0),completionBuilder:r,listThreads:()=>n.listThreads(),getThreadFromServer:(K0)=>n.getThread(K0),isInternalUser:_6(A)&&P2(A.user.email)},{initialThreadID:M,openThreadPickerOnStart:Z.openThreadSwitcher});return}let _=_6(A)&&ix(A.features,j7.THREAD_ACTORS_TUI);if(J.executeMode&&!Z.takeMeBack&&_&&!F){let c=await H.secretStorage.get("apiKey",J.ampURL);if(!c)throw new B4("API key required. Please run `amp login` first.",1);Tr0(H.mcpService,J.settings);try{let n=await SP4({apiKey:c,ampURL:J.ampURL,workspaceRoot:process.cwd(),dependencies:H,userInput:V,stdinInput:G,stats:!!Z.stats,agentMode:Z.mode,labels:Z.label,initialThreadID:M});if(await nx(n,"execute"),Z.archive)await H.threadService.archive(n,!0)}finally{await H.asyncDispose()}await Cq(),process.exit(0)}if(!J.executeMode&&!Z.headless)H.skillService=mm3(H.skillService);z=process.hrtime.bigint();let b=await Cq0(H);K("runMainThread:createWorkerDeps",z);let d=J.executeMode?void 0:async(c)=>nx(c,"interactive"),f={threadService:H.threadService,workerDeps:b,createThread:async(c)=>{let n=W?await H.serverStatusPromise:U,r=await VX0(J.settings,process.cwd(),ax(n),E);if(r instanceof Error)P3(r.message);return U51(b,{threadMeta:r?VF(r):void 0,agentMode:c??Z.mode,onFirstAssistantMessage:d})},validateThreadOwnership:async(c,n)=>{if(n?.nonBlockingOwnershipCheck){nr4(c,H.configService,H.viewerUserIDPromise).catch((r)=>{if(r instanceof B4){if(n.onOwnershipError){n.onOwnershipError(r,c);return}PU(r,c);return}S.warn("Failed to validate thread ownership in CLI, allowing to open",{error:r})});return}try{await nr4(c,H.configService,H.viewerUserIDPromise)}catch(r){if(r instanceof B4)throw r;S.warn("Failed to validate thread ownership in CLI, allowing to open",{error:r})}},switchThreadVisibility:E,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:d,handleError:PU},y=async()=>{try{return Bn4(f,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(c){if(c instanceof B4)throw c;throw await PU(c,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")xZ.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
5923
|
-
`),await Cq(),process.exit(1);let x=(async()=>{if(W){S.info("Skipping initial free tier status fetch until auth is complete");return}try{let c=await H.configService.getLatest(),n=ib(c),r=await X5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(n)});if(r.ok)return S.info("User free tier status:",r),r.result;return}catch(c){S.error("Failed to fetch free tier status:",c);return}})(),p=!J.executeMode?new v11:null,h,o=null;if(p)h=p,o=(async()=>{let c=W?await H.serverStatusPromise:H.serverStatus;if(KH(c))throw d31(c,J.ampURL);await cr4(Q,Z,c);let n=process.hrtime.bigint(),r=await y();if(K("runMainThread:createThreadPool",n),p.attach(r),V){let e=await v1(r.threadHandles$);if(!e)throw new B4("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}})(),o.catch(async(c)=>{let n=c instanceof Error?c:Error(String(c));p.setInitError(n),await PU(c,Z.threadId)});else z=process.hrtime.bigint(),h=await y(),K("runMainThread:createThreadPool",z);let l=Z.notifications!==void 0?Z.notifications:!J.executeMode,t=D!==null&&ix(D.features,j7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((c)=>{t=_6(c)&&ix(c.features,j7.TUI_VOICE_NOTIF)}).catch((c)=>{S.debug("Failed to resolve TUI voice notification feature flag",{error:c})});z=process.hrtime.bigint();let B0=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),pm3({configService:H.configService,threadService:H.threadService,config:B0,useNotificationsForService:l,isTUIVoiceNotifEnabled:()=>t,threadViewStates$:()=>h.threadHandles$.pipe(p4((c)=>{if(!c)return h0.of({});return j5(c.thread$,c.threadViewState$).pipe(M1(([n,r])=>({[n.id]:r})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){Tr0(H.mcpService,J.settings);let c={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isInternalUser:N,agentMode:Z.mode,labels:Z.label},n=await PR4({threadPool:h,...c});if(await nx(n,"execute"),Z.archive)await H.threadService.archive(n,!0);await H.asyncDispose(),process.exit(0)}let a=!1,J0=!1;if(Z.jetbrains||Z.ide){await l40();let c=await aW({jetbrainsOnly:Z.jetbrains});if(c.length===0){if(Z.jetbrains)a=!await H.configService.get("jetbrains.skipInstall")}else if(c.length===1){let n=c[0];if(n)n8.selectConfig(n)}else J0=!0}z=process.hrtime.bigint();let q0=ro0("0.0.
|
|
5924
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await ao1({get:async(G)=>{if(G!==ag)return;try{let F=await sr4(m31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==ag)return;await Am3(dr.dirname(m31),{recursive:!0}),await jm3(m31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:S30()});Xb1(Y);let X=await fX0({...J,workspaceTrust:{current:!0,changes:XI0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await CS4(J.mcpConfig);X=_S4(X,G)}let K=dr.dirname(X.getSettingsFilePath());tW4(rv,K),X=bf1(X);let V=await X.get("url","admin")??await X.get("url","global");if(!V)V=o7;if(S.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KB(V))S.info("Targeting custom Amp server",{ampURL:V});return{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AK0(await Pn(J,X))}}function nm3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function am3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=dr.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Rm3:Fn));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function om3(){nE4();let J=nm3(process.argv),Z=am3(process.argv,J),Q=QR4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)n0.level=0;if(_m3(S),S.info("Starting Amp CLI.",{version:"0.0.
|
|
5923
|
+
`),await Cq(),process.exit(1);let x=(async()=>{if(W){S.info("Skipping initial free tier status fetch until auth is complete");return}try{let c=await H.configService.getLatest(),n=ib(c),r=await X5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(n)});if(r.ok)return S.info("User free tier status:",r),r.result;return}catch(c){S.error("Failed to fetch free tier status:",c);return}})(),p=!J.executeMode?new v11:null,h,o=null;if(p)h=p,o=(async()=>{let c=W?await H.serverStatusPromise:H.serverStatus;if(KH(c))throw d31(c,J.ampURL);await cr4(Q,Z,c);let n=process.hrtime.bigint(),r=await y();if(K("runMainThread:createThreadPool",n),p.attach(r),V){let e=await v1(r.threadHandles$);if(!e)throw new B4("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}})(),o.catch(async(c)=>{let n=c instanceof Error?c:Error(String(c));p.setInitError(n),await PU(c,Z.threadId)});else z=process.hrtime.bigint(),h=await y(),K("runMainThread:createThreadPool",z);let l=Z.notifications!==void 0?Z.notifications:!J.executeMode,t=D!==null&&ix(D.features,j7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((c)=>{t=_6(c)&&ix(c.features,j7.TUI_VOICE_NOTIF)}).catch((c)=>{S.debug("Failed to resolve TUI voice notification feature flag",{error:c})});z=process.hrtime.bigint();let B0=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),pm3({configService:H.configService,threadService:H.threadService,config:B0,useNotificationsForService:l,isTUIVoiceNotifEnabled:()=>t,threadViewStates$:()=>h.threadHandles$.pipe(p4((c)=>{if(!c)return h0.of({});return j5(c.thread$,c.threadViewState$).pipe(M1(([n,r])=>({[n.id]:r})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){Tr0(H.mcpService,J.settings);let c={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isInternalUser:N,agentMode:Z.mode,labels:Z.label},n=await PR4({threadPool:h,...c});if(await nx(n,"execute"),Z.archive)await H.threadService.archive(n,!0);await H.asyncDispose(),process.exit(0)}let a=!1,J0=!1;if(Z.jetbrains||Z.ide){await l40();let c=await aW({jetbrainsOnly:Z.jetbrains});if(c.length===0){if(Z.jetbrains)a=!await H.configService.get("jetbrains.skipInstall")}else if(c.length===1){let n=c[0];if(n)n8.selectConfig(n)}else J0=!0}z=process.hrtime.bigint();let q0=ro0("0.0.1776949187-g6c0bed",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let N0=new Sr0(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let c=await v1(h.threadHandles$);if(!c)throw new B4("No active thread is available yet.",1);await c.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let Q0=await Xy();K("runMainThread:loadSessionState",z),S.info("Loaded session state:",Q0);let V0={...Q0,launchCount:Q0.launchCount+1};sK((c)=>({...c,launchCount:c.launchCount+1}));try{if(z=process.hrtime.bigint(),await Up4({history:new wn,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:X5,threadPool:h,createSystemPromptDeps:async()=>er4(H),ideClient:n8,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:N0,updateService:q0,pluginPlatform:H.pluginPlatform,pluginService:H.pluginService},{initialServerStatus:H.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:H.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:M,showJetBrainsInstaller:a,showIdePickerHint:J0,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Pm3,logFile:{path:Y},sessionState:V0,freeTierStatusPromise:x,workspace:O??null,features:L,isInternalUser:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-23T13:03:36.797Z"},(c)=>new g11({...c,threadPool:c.threadPool},(n)=>new W51({...n,threadState:n.threadState}))),K("runMainThread:mountApp-returned",z),o)await o}finally{await h.dispose().catch((c)=>{S.error("Failed to dispose thread pool during shutdown",c)})}await H.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function l3(J){if(S.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)}),J.interactive)xZ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
5924
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;S.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await ao1({get:async(G)=>{if(G!==ag)return;try{let F=await sr4(m31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==ag)return;await Am3(dr.dirname(m31),{recursive:!0}),await jm3(m31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:S30()});Xb1(Y);let X=await fX0({...J,workspaceTrust:{current:!0,changes:XI0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await CS4(J.mcpConfig);X=_S4(X,G)}let K=dr.dirname(X.getSettingsFilePath());tW4(rv,K),X=bf1(X);let V=await X.get("url","admin")??await X.get("url","global");if(!V)V=o7;if(S.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!KB(V))S.info("Targeting custom Amp server",{ampURL:V});return{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:AK0(await Pn(J,X))}}function nm3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function am3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=dr.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Rm3:Fn));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function om3(){nE4();let J=nm3(process.argv),Z=am3(process.argv,J),Q=QR4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)n0.level=0;if(_m3(S),S.info("Starting Amp CLI.",{version:"0.0.1776949187-g6c0bed",buildTimestamp:"2026-04-23T13:03:36.797Z"}),process.platform==="win32"&&QI())M_4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new B4(e2.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await cm3(Q).parseAsync(process.argv)}rW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await om3().catch(PU)});async function rm3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),d5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
5925
5925
|
`);else if(!KB(J.ampURL))d5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
5926
5926
|
`);let Y=process.env.AMP_API_KEY;if(Y)d5.write(`API key found in environment variable, storing...
|
|
5927
5927
|
`),await Z.set("apiKey",Y,J.ampURL),d5.write(`API key successfully stored.
|