@sourcegraph/amp 0.0.1774590201-g775913 → 0.0.1774599058-g7bb23d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +10 -10
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4665,7 +4665,7 @@ ${F9($v5)}
4665
4665
  `))}await q.asyncDispose(),process.exit(0)}catch(W){await q.asyncDispose();let U=`Failed to analyze thread context: ${W instanceof Error?W.message:String(W)}`;F(U)}}var $H4=process.hrtime.bigint(),Zd0=null;function JH4(){Zd0=process.hrtime.bigint()}function ZH4(){if(Zd0===null)return null;return Number(process.hrtime.bigint()-Zd0)/1e6}SX();m0();var Ww4=G4(O4(),1),cY=G4(Fw4(),1),Uw4=G4(oA(),1);import uZ0 from"node:fs";import bZ0 from"node:path";var qw4=Object.keys(P),yp5=bZ0.join(eZ,"logs"),eA=bZ0.join(yp5,"cli.log"),vp5=10485760;function xp5(J){try{if(uZ0.statSync(J).size>vp5)uZ0.truncateSync(J,0)}catch{}}var Pl,pc0=!1,Il=null;function fp5(J){return J instanceof Error&&J.message.includes("write after end")}function Rl(J,Z,Q,Y){if(pc0)return;try{J[Z](Q,...Y)}catch(X){if(!fp5(X))throw X}}function Hw4(J){pc0=!1,Il=null;let Z=bZ0.resolve(J?.logFile||eA),Q=J?.logLevel||"info";if(!qw4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{uZ0.mkdirSync(bZ0.dirname(Z),{recursive:!0})}catch(G){console.error(`Failed to create log directory: ${G}`)}xp5(Z);let Y=cY.default.format((G)=>{for(let z of Object.keys(G)){let F=G[z];if(F instanceof Error)G[z]={name:F.name,message:F.message,stack:F.stack}}return G}),X=cY.default.format((G)=>{return G.pid=process.pid,G}),K=[new cY.default.transports.File({filename:Z}),new Dw4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new cY.default.transports.Console({level:"debug",format:cY.default.format.combine(cY.default.format.colorize(),cY.default.format.simple())}));Pl=cY.default.createLogger({level:qw4.includes(Q)?Q:"info",format:cY.default.format.combine(cY.default.format.timestamp(),X(),Y(),cY.default.format.json(),cY.default.format.errors({stack:!0})),transports:K});let V=Pl;Ax1({error:(G,...z)=>{Rl(V,"error",G,z)},warn:(G,...z)=>{Rl(V,"warn",G,z)},info:(G,...z)=>{Rl(V,"info",G,z)},debug:(G,...z)=>{Rl(V,"debug",G,z)},audit:(G,...z)=>{let F=typeof z[0]==="object"&&z[0]!==null?{audit:!0,...z[0]}:{audit:!0};Rl(V,"info",G,[F])}})}class Dw4 extends Uw4.default{log({message:J,...Z},Q){Ww4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function JH(){if(Il)return Il;let J=Pl;if(!J)return Promise.resolve();return pc0=!0,Il=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,Pl===J)Pl=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),Il}m0();import{execFile as up5}from"node:child_process";import{promisify as bp5}from"node:util";var hp5=bp5(up5),gp5=["private","public","workspace"];function dc0(J){return J.endsWith("/")?J.slice(0,-1):J}function mp5(J){let Z=KZ0(J);try{let X=new URL(Z);return dc0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return dc0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return dc0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function ww4(J){try{let{stdout:Z}=await hp5("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return mp5(Q)}catch{return null}}function pp5(J){let Z=[...gp5];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function Bw4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function dp5(J){if(J?.team?.groups!==void 0)return Error(["Group visibility is not available. ",`You are not a member of any group in this workspace.
4666
4666
  `].join(""));return Error(`Group visibility is not available.
4667
4667
  `)}function Nw4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
4668
- `].join("");return Error(Y)}function cp5(J,Z){return Z.includes(J)}function lp5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function Lw4(J,Z,Q){if(J===void 0||J===null)return;let Y=pp5(Z);if(typeof J!=="string")return Nw4(Q,Y);if(J==="group"&&!Y.includes("group"))return dp5(Z);if(cp5(J,Y))return J;return Nw4(Q,Y)}async function ip5(J,Z,Q){let Y=await ww4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return Lw4(K,Q,Y)}async function hZ0(J,Z,Q,Y){if(Y)return Y;if(!lp5(Q))return Bw4(Q);let X=await ip5(J,Z,Q);if(X instanceof Error)return X;return X??Bw4(Q)}function Ow4(J,Z){return Lw4(J,Z)}async function Ew4(J,Z,Q){let Y=await ww4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}$J();function gZ0(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")}f3();H4();rj0();$J();var z8=y.string().min(1),lc0=y.string().regex(/^[0-9A-Za-z]{22}$/),np5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),Cl=y.templateLiteral(["T-",np5]),ap5=y.enum(["fork","handoff","mention"]),op5=y.enum(["parent","child"]),Mw4=y.object({threadID:Cl,type:ap5,role:op5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),r6=y.templateLiteral(["M-",lc0]);function aF(){return`M-${gZ0(GE())}`}var r8=y.templateLiteral(["TU-",lc0]);function Aw4(){return`TU-${gZ0(GE())}`}var _l=y.templateLiteral(["E-",lc0]);function ic0(){return`E-${gZ0(GE())}`}var rp5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),sp5=y.union([y.literal("builtin"),y.object({toolbox:z8}).strict(),y.object({mcp:z8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:z8}).strict(),y.object({remote:z8}).strict()]),tp5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(z8).optional()}),jw4=y.looseObject({name:z8,description:y.string(),inputSchema:rp5,source:sp5,meta:tp5.optional()}),I09=y.object({id:z8,category:z8,title:z8,description:y.string().optional(),pluginName:z8}),nc0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.openai.websocket.enabled":y.boolean().optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),Rw4=y.object({settings:nc0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),Iw4=y.enum(["sandbox","local-client"]),Tl=y.any().and(y.object({status:y.string()})),Pw4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),oF=z8,Cw4=30000,jk=Sz,ep5=y.enum(["file","directory"]),$d5=y.object({mtimeMs:y.number().nonnegative().optional()}),Sl=y.tuple([y.string(),ep5,$d5.optional()]),Jd5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Zw=y.object({code:Jd5,message:y.string()}),Zd5=y.object({ok:y.literal(!0),entries:y.array(Sl)}),Qd5=y.object({ok:y.literal(!1),error:Zw}),P09=y.discriminatedUnion("ok",[Zd5,Qd5]),Yd5=y.object({ok:y.literal(!0),contentBase64:y.string()}),Xd5=y.object({ok:y.literal(!1),error:Zw}),C09=y.discriminatedUnion("ok",[Yd5,Xd5]),Kd5=z8,ac0=y.object({key:z8,dataType:Kd5,contentBase64:y.string()}),oc0=ac0.extend({toolCallId:r8.optional(),updatedAt:y.string()}),Rk=y.looseObject({uri:Sz,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),_w4=y.object({name:z8,description:y.string(),baseDir:Sz,frontmatter:y.object({name:z8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),rc0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),Tw4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),Ik=y.array(y.discriminatedUnion("type",[rc0,Tw4])),Ak=y.record(y.string(),y.unknown()),Sw4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Vd5=Sw4.extend({complete:y.literal(!0),input:Ak,normalizedInput:Ak.optional()}),Gd5=Sw4.extend({complete:y.literal(!1),input:Ak,inputIncomplete:Ak,inputPartialJSON:y.object({json:y.string()}),normalizedInput:Ak.optional()}),zd5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Fd5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:Tl,userInput:zd5.optional()}),qd5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),Wd5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),Ud5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:Ak}),Hd5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:Tl,hidden:y.boolean().optional()}),Dd5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:Cl.optional()}),Bd5=y.object({uri:Sz,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),Nd5=y.union([rc0,Tw4,Fd5]),wd5=y.union([rc0,qd5,Wd5,Vd5,Gd5,Ud5]),sc0=y.array(Nd5),tc0=y.array(wd5),Ld5=y.array(Hd5),cc0=y.looseObject({line:y.number().int(),column:y.number().int()}),Od5=y.looseObject({start:cc0,end:cc0}),Ed5=y.looseObject({name:y.string(),repositoryURL:y.string()}),Md5=y.looseObject({currentURL:y.string(),availableProjects:y.array(Ed5).optional()}),Ad5=y.object({treeOID:y.string(),repoRoot:y.string()}),ec0=y.looseObject({currentlyVisibleFiles:y.array(Sz),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:cc0.optional(),cursorLocationLine:y.string().optional(),selectionRange:Od5.optional(),snapshotOIDs:y.array(Ad5).optional(),aggmanContext:Md5.optional()}),$l0=y.custom((J)=>typeof J==="string"&&L$(J)!==void 0),jd5=y.object({threadId:Cl,role:y.literal("user"),content:sc0,agentMode:$l0.optional(),discoveredGuidanceFiles:y.array(Bd5).optional(),meta:Dd5.optional(),userState:ec0.optional(),readAt:y.string().nullable().optional(),messageId:r6,createdAt:y.string().optional()}),Jl0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),Rd5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),Id5=y.object({threadId:Cl,role:y.literal("assistant"),content:tc0,state:Rd5.optional(),usage:Jl0.optional(),readAt:y.string().nullable().optional(),messageId:r6,createdAt:y.string().optional()}),Pd5=y.object({threadId:Cl,role:y.literal("info"),content:Ld5,messageId:r6,createdAt:y.string().optional()}),kw4=y.discriminatedUnion("role",[jd5,Id5,Pd5]),kl=y.object({workspaceRoot:Sz.optional(),workingDirectory:Sz.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),Cd5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),_d5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),oldContent:y.string().optional(),newContent:y.string().optional(),diffStat:Cd5}),Td5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),yw4=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(Td5).optional(),files:y.array(_d5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),mZ0=y.object({id:y.string(),toolCallId:r8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:r8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),Sd5=y.object({type:y.literal("request"),id:z8,method:z8,params:y.unknown()}),kd5=y.object({type:y.literal("response"),id:z8,result:y.unknown().optional(),error:y.string().optional()}),yd5=y.object({type:y.literal("event"),event:z8,data:y.unknown(),span:y.string().optional()}),pZ0=y.discriminatedUnion("type",[Sd5,kd5,yd5]);var vd5=y.object({type:y.literal("executor_connect"),clientId:z8,capabilities:Rw4,executorType:Iw4.optional()}),xd5=y.object({type:y.literal("executor_settings_update"),settings:nc0}),fd5=y.object({type:y.literal("executor_tools_register"),tools:y.array(jw4)}),ud5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(z8)}),bd5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),hd5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:r8}),Zl0=y.object({type:y.literal("tool_progress"),toolCallId:r8,progress:y.union([Pw4,y.unknown()]).optional(),parentToolCallId:r8.optional()}),gd5=y.object({type:y.literal("executor_tool_result"),toolCallId:r8,run:Tl}),md5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:z8,files:y.array(Rk),isLast:y.boolean(),userConfigDir:y.any().optional()}),pd5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:r8,files:y.array(Rk),isLast:y.boolean()}),dd5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:z8,skills:y.array(_w4),isLast:y.boolean()}),cd5=y.object({type:y.literal("executor_rollback_ack"),editId:_l,ok:y.boolean(),error:y.string().optional()}),ld5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:r8}),id5=y.object({type:y.literal("executor_environment_snapshot"),environment:kl}),nd5=y.object({type:y.literal("executor_environment_update"),environment:kl}),ad5=y.object({type:y.literal("executor_artifact_upsert"),artifact:ac0,toolCallId:r8.optional()}),od5=y.object({type:y.literal("executor_artifact_delete"),key:z8}),rd5=y.object({type:y.literal("executor_tool_approval_request"),approval:mZ0}),sd5=y.object({type:y.literal("executor_plugin_message"),message:pZ0}),td5=y.object({type:y.literal("client_append_user_msg"),content:Ik,userState:ec0.optional(),discoveredGuidanceFiles:y.array(Rk).optional(),agentMode:y.string().optional(),messageId:r6}),ed5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:r6}),$c5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:r6}),Jc5=y.object({type:y.literal("client_edit_message"),messageId:r6,editId:_l,content:Ik,agentMode:y.string().optional()}),Zc5=y.object({type:y.literal("client_mark_message_read"),messageId:r6}),Qc5=y.object({type:y.literal("client_mark_message_unread"),messageId:r6}),Yc5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Xc5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Kc5=y.object({endpoint:y.string().url(),keys:Xc5}),Vc5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Kc5,threadURL:y.string().min(1)}),Gc5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:oF,uri:jk}),zc5=y.object({type:y.literal("client_filesystem_read_file"),requestId:oF,uri:jk}),Fc5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:oF,ok:y.boolean(),entries:y.array(Sl).optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),qc5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:oF,ok:y.boolean(),contentBase64:y.string().optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Wc5=y.object({type:y.literal("client_resume"),version:y.number()}),Uc5=y.object({type:y.literal("client_retry")}),Hc5=y.object({type:y.literal("client_cancel")}),Dc5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:Tl,hidden:y.boolean().optional()}),Bc5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:r8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),Nc5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),k09=y.enum(["agg-man"]),vw4=y.discriminatedUnion("type",[vd5,xd5,fd5,ud5,bd5,hd5,Zl0,gd5,md5,pd5,dd5,cd5,ld5,id5,nd5,ad5,od5,rd5,sd5,td5,ed5,$c5,Jc5,Zc5,Qc5,Yc5,Vc5,Gc5,zc5,Fc5,qc5,Wc5,Uc5,Hc5,Dc5,Bc5,Nc5]);$J();$J();var wc5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),Lc5=y.enum(["start","generating","tool_use","complete","error"]),Oc5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),Ec5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),Mc5=y.enum(["starting","running","failed"]),Ac5=y.object({cutMessageId:r6,createdAt:y.string()}),xw4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:r6,content:Ik,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Rk).optional(),createdAt:y.string().optional()})}),jc5=y.object({type:y.literal("agent_state"),state:wc5,messageId:r6.optional()}),Rc5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),Ic5=y.object({type:y.literal("error_set"),seq:y.number(),error:Oc5}),Pc5=y.object({type:y.literal("error_cleared"),seq:y.number()}),Cc5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:r6.optional()}),_c5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),Tc5=y.object({type:y.literal("retry_started")}),Sc5=y.object({type:y.literal("retry_cancelled")}),kc5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),yc5=y.object({type:y.literal("tool_lease"),toolCallId:r8,toolName:y.string(),args:y.unknown(),messageId:r6,parentToolCallId:r8.optional()}),vc5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:oF,uri:jk}),xc5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:oF,uri:jk}),fc5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:oF,ok:y.boolean(),entries:y.array(Sl).optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),uc5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:oF,ok:y.boolean(),contentBase64:y.string().optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),bc5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(mZ0)}),hc5=y.object({type:y.literal("executor_rollback_request"),editId:_l,messageId:r6,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(r8)}),gc5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),mc5=y.object({type:y.literal("plugin_message"),message:pZ0}),pc5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:r8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),dc5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),cc5=y.object({type:y.literal("delta"),messageId:r6,role:y.literal("assistant"),blocks:tc0.optional(),state:Lc5,usage:Jl0.optional(),parentToolCallId:r8.optional()}),lc5=y.object({type:y.literal("delta"),messageId:r6,role:y.literal("user"),blocks:sc0.optional(),state:y.literal("complete"),parentToolCallId:r8.optional()}),ic5=y.discriminatedUnion("role",[cc5,lc5]),nc5=y.object({type:y.literal("queued_messages"),messages:y.array(xw4)}),ac5=y.object({type:y.literal("queued_message_added"),message:xw4,seq:y.number()}),oc5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:r6,seq:y.number()}),rc5=y.object({type:y.literal("message_added"),message:kw4,seq:y.number(),parentToolUseId:z8.optional()}),sc5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),tc5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:r6,content:Ik,truncateToMessageId:r6,reason:y.literal("message_edit"),agentMode:$l0.optional()}),ec5=y.looseObject({type:y.literal("cf_agent_state")}),$l5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),Jl5=y.looseObject({type:y.literal("cf_agent_identity")}),Zl5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(Ec5),hasExecutor:y.boolean().optional()}),Ql5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:Mc5,message:y.string().optional(),executorId:y.string().optional()}),Yl5=y.object({type:y.literal("environment_update"),environment:kl}),Xl5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(oc0)}),Kl5=y.object({type:y.literal("artifact_upserted"),artifact:oc0}),Vl5=y.object({type:y.literal("artifact_deleted"),key:z8}),Gl5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),zl5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),Fl5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(Mw4)}),ql5=y.object({type:y.literal("compaction_started")}),Wl5=y.object({type:y.literal("compaction_complete"),cutMessageId:r6}),Ul5=y.object({type:y.literal("compaction_records"),records:y.array(Ac5)}),dZ0=y.discriminatedUnion("type",[jc5,Rc5,Ic5,Pc5,Cc5,_c5,Tc5,Sc5,kc5,yc5,vc5,xc5,fc5,uc5,bc5,hc5,gc5,mc5,pc5,Zl0,dc5,ic5,nc5,ac5,oc5,rc5,sc5,tc5,ec5,$l5,Jl5,Zl5,Ql5,Yl5,Xl5,Kl5,Vl5,Gl5,zl5,Fl5,ql5,Wl5,Ul5]);var Ql0=(J)=>y.codec(y.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}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),fw4=Ql0(vw4),Hl5=y.union([dZ0,y.array(dZ0)]),uw4=Ql0(dZ0),bw4=Ql0(Hl5);H4();function hw4(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=l1(Y1.parse(V.uri))}catch{if(Y)return null;continue}let z={uri:G};if(typeof V.content==="string")z.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))z.lineCount=V.lineCount;if(typeof V.hash==="string")z.hash=V.hash;X.push(z)}return X}var gw4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Yl0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function Dl5(J){return J.replace(/\s+/g," ").trim()}function Bl5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function Nl5(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 Yl0(JSON.stringify(J),120)}catch{return Yl0(String(J),120)}}function mw4(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 wl5(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=mw4(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 pw4(J){for(let Z of J){let Q=wl5(Z);if(Q)return Q}return null}function Ll5(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"||mw4(Q.path)==="type")})}function Ol5(J,Z){let Q=pw4(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 dw4(J,Z,Q){let Y=Bl5(Z),X=(()=>{let F=Dl5(J);if(F.length===0)return null;return Yl0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=pw4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"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,z=Nl5(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${z??"unknown value"}`,messageType:null,typePreview:z,payloadPreview:X,issues:Y};if(Ll5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:z,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:Ol5(G,Y),messageType:G,typePreview:z,payloadPreview:X,issues:Y}}function yl(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"}}function cw4(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}}$J();var lw4="[dtw-parse-error]",Kl0="dtw-parse-error",El5=y.object({kind:y.literal(Kl0),failureType:y.enum(gw4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),Ml5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function Xl0(J){return{kind:Kl0,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 iw4(J){let Z=Xl0(J);return JSON.stringify(Z)}function nw4(J,Z){let Q=dw4(J,Z);return iw4({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})}function Vl0(J){let Z=J.startsWith(lw4)?J.slice(lw4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=El5.safeParse(Q);if(Y.success)return Xl0(Y.data);let X=Ml5.safeParse(Q);if(X.success)return Xl0(X.data);return null}w1();class Gl0 extends Error{constructor(J){super(J);this.name="DTWError"}}class T9 extends Gl0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}w1();var Al5=1000,jl5=30000,Rl5=5,Il5=30000,Pl5=200,Cl5=30000,aw4=["online","focus","pageshow","keydown","pointerdown"],ow4=["visibilitychange"];function Fl0(){return globalThis}function sw4(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 rw4(){return sw4(Fl0().window)}function zl0(){let J=Fl0().document;if(!sw4(J))return null;return J}function _l5(){let J=Fl0().navigator;if(!J||typeof J!=="object")return null;return J}function Tl5(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(" ")}function cZ0(J){return!!(J.apiKey&&J.WebSocketClass)}function ql0(J){if(cZ0(J))return"one-step";return"two-step"}class Wl0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId: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 Y4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new Y4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??Al5,maxReconnectDelayMs:J.maxReconnectDelayMs??jl5,maxReconnectAttempts:J.maxReconnectAttempts??Rl5,pingIntervalMs:J.pingIntervalMs??Il5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${ql0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}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=Pl5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new T9("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 Z=this.config.WebSocketClass??WebSocket,Q;if(this.config.webSocketProvider)Q=await this.config.webSocketProvider();else if(cZ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new T9("1-step flow requires apiKey");let K=this.currentThreadID??this.config.threadId;if(!K)K=(await this.fetchWsToken()).threadId;let V=`${Y}/threads`;if(K)V=`${V}?threadId=${encodeURIComponent(K)}`;Q=new Z(V,{headers:{Authorization:`Bearer ${X}`}})}else{let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),{threadId:X,wsToken:K}=await this.ensureWsToken();this.currentThreadID=X,this.currentWsToken=K;let V=`${Y}/threads`;Q=new Z(V,["amp",K])}try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(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)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}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 T9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${Tl5(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let G=await K.text().catch(()=>"");throw new T9(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new T9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let G="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new T9(`WebSocket connection failed: ${G}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new T9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K)})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(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}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else 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();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=rw4(),Z=zl0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=_l5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=zl0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=rw4(),Z=zl0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of aw4)J?.addEventListener(Y,Q);for(let Y of ow4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of aw4)J?.removeEventListener(Y,Q);for(let Y of ow4)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},Cl5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}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}}function Sl5(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}class rF extends Wl0{deltaSubject=new $4;errorSubject=new $4;errorEventSubject=new $4;cancelledSubject=new $4;agentStateSubject=new $4;messageAddedSubject=new $4;editRejectedSubject=new $4;messageEditedSubject=new $4;queuedMessagesSubject=new $4;retrySubject=new $4;toolLeaseSubject=new $4;toolLeaseRevokedSubject=new $4;toolApprovalQueueSubject=new $4;executorToolApprovalResponseSubject=new $4;toolProgressSubject=new $4;executorErrorSubject=new $4;executorConnectedSubject=new $4;executorRollbackRequestSubject=new $4;observersSubject=new $4;executorStatusSubject=new $4;environmentUpdateSubject=new $4;artifactsSubject=new $4;threadTitleSubject=new $4;threadStatusSubject=new $4;threadRelationshipsSubject=new $4;compactionSubject=new $4;compactionRecordsSubject=new $4;pluginMessageSubject=new $4;fileSystemReadDirectoryRequestSubject=new $4;fileSystemReadFileRequestSubject=new $4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??aF();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),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})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;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}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new T9("Transport is disposed");if(!this.hasOpenSocket())throw new T9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,G=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;z.unsubscribe(),F.unsubscribe(),q()},z=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),G(()=>Y(q))},error:(q)=>{G(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{G(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{G(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=yl(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})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId: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})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}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})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}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})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}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 T9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new T9(`Filesystem request timed out: ${Z}`))},Cw4);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(Sl5(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 T9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=bw4.safeDecode(J);if(!Z.success){let Y=uw4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:nw4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(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":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(fw4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new T9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function kl5(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function yl5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function vl5(J){if(kl5(J))return J.queuedMessage.messageId;if(yl5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function Ul0(J,Z,Q={}){let Y=Q.getQueuedMessageId??vl5;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var xl5=15000;function fl5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let z of K)z.unsubscribe()};return{promise:new Promise((z,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),z(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function Hl0(J){let Z=J.workerUrl??p7(J.ampURL),Q=new rF({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??xl5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=fl5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as ul5}from"node:fs";import{mkdir as bl5,readdir as hl5,readFile as gl5}from"node:fs/promises";import{createServer as ml5}from"node:http";import Dl0 from"node:path";function tw4(J){return J instanceof Error?J.message:String(J)}function $j(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function pl5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function ew4(J,Z){let Q=Dl0.basename(Z),Y=Q.endsWith(".json")?Dl0.join(J,Q):Dl0.join(J,`${Q}.json`),X=await gl5(Y,"utf-8");return JSON.parse(X)}async function dl5(J){let Z=await hl5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await ew4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function cl5(){return`<!doctype html>
4668
+ `].join("");return Error(Y)}function cp5(J,Z){return Z.includes(J)}function lp5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function Lw4(J,Z,Q){if(J===void 0||J===null)return;let Y=pp5(Z);if(typeof J!=="string")return Nw4(Q,Y);if(J==="group"&&!Y.includes("group"))return dp5(Z);if(cp5(J,Y))return J;return Nw4(Q,Y)}async function ip5(J,Z,Q){let Y=await ww4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return Lw4(K,Q,Y)}async function hZ0(J,Z,Q,Y){if(Y)return Y;if(!lp5(Q))return Bw4(Q);let X=await ip5(J,Z,Q);if(X instanceof Error)return X;return X??Bw4(Q)}function Ow4(J,Z){return Lw4(J,Z)}async function Ew4(J,Z,Q){let Y=await ww4(Z);if(!Y)return Error("No git origin remote found for this repository.");let K={...await J.get("defaultVisibility","global")??{},[Y]:Q};return await J.set("defaultVisibility",K,"global"),{repoKey:Y}}$J();function gZ0(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")}f3();H4();rj0();$J();var z8=y.string().min(1),lc0=y.string().regex(/^[0-9A-Za-z]{22}$/),np5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),Cl=y.templateLiteral(["T-",np5]),ap5=y.enum(["fork","handoff","mention"]),op5=y.enum(["parent","child"]),Mw4=y.object({threadID:Cl,type:ap5,role:op5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),r6=y.templateLiteral(["M-",lc0]);function aF(){return`M-${gZ0(GE())}`}var r8=y.templateLiteral(["TU-",lc0]);function Aw4(){return`TU-${gZ0(GE())}`}var _l=y.templateLiteral(["E-",lc0]);function ic0(){return`E-${gZ0(GE())}`}var rp5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),sp5=y.union([y.literal("builtin"),y.object({toolbox:z8}).strict(),y.object({mcp:z8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:z8}).strict(),y.object({remote:z8}).strict()]),tp5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(z8).optional()}),jw4=y.looseObject({name:z8,description:y.string(),inputSchema:rp5,source:sp5,meta:tp5.optional()}),I09=y.object({id:z8,category:z8,title:z8,description:y.string().optional(),pluginName:z8}),nc0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.openai.websocket.enabled":y.boolean().optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),Rw4=y.object({settings:nc0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),Iw4=y.enum(["sandbox","local-client"]),Tl=y.any().and(y.object({status:y.string()})),Pw4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),oF=z8,Cw4=30000,jk=Sz,ep5=y.enum(["file","directory"]),$d5=y.object({mtimeMs:y.number().nonnegative().optional()}),Sl=y.tuple([y.string(),ep5,$d5.optional()]),Jd5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Zw=y.object({code:Jd5,message:y.string()}),Zd5=y.object({ok:y.literal(!0),entries:y.array(Sl)}),Qd5=y.object({ok:y.literal(!1),error:Zw}),P09=y.discriminatedUnion("ok",[Zd5,Qd5]),Yd5=y.object({ok:y.literal(!0),contentBase64:y.string()}),Xd5=y.object({ok:y.literal(!1),error:Zw}),C09=y.discriminatedUnion("ok",[Yd5,Xd5]),Kd5=z8,ac0=y.object({key:z8,dataType:Kd5,contentBase64:y.string()}),oc0=ac0.extend({toolCallId:r8.optional(),updatedAt:y.string()}),Rk=y.looseObject({uri:Sz,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),_w4=y.object({name:z8,description:y.string(),baseDir:Sz,frontmatter:y.object({name:z8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),rc0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),Tw4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),Ik=y.array(y.discriminatedUnion("type",[rc0,Tw4])),Ak=y.record(y.string(),y.unknown()),Sw4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Vd5=Sw4.extend({complete:y.literal(!0),input:Ak,normalizedInput:Ak.optional()}),Gd5=Sw4.extend({complete:y.literal(!1),input:Ak,inputIncomplete:Ak,inputPartialJSON:y.object({json:y.string()}),normalizedInput:Ak.optional()}),zd5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Fd5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:Tl,userInput:zd5.optional()}),qd5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),Wd5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),Ud5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:Ak}),Hd5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:Tl,hidden:y.boolean().optional()}),Dd5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:Cl.optional()}),Bd5=y.object({uri:Sz,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),Nd5=y.union([rc0,Tw4,Fd5]),wd5=y.union([rc0,qd5,Wd5,Vd5,Gd5,Ud5]),sc0=y.array(Nd5),tc0=y.array(wd5),Ld5=y.array(Hd5),cc0=y.looseObject({line:y.number().int(),column:y.number().int()}),Od5=y.looseObject({start:cc0,end:cc0}),Ed5=y.looseObject({name:y.string(),repositoryURL:y.string()}),Md5=y.looseObject({currentURL:y.string(),availableProjects:y.array(Ed5).optional()}),Ad5=y.object({treeOID:y.string(),repoRoot:y.string()}),ec0=y.looseObject({currentlyVisibleFiles:y.array(Sz),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:cc0.optional(),cursorLocationLine:y.string().optional(),selectionRange:Od5.optional(),snapshotOIDs:y.array(Ad5).optional(),aggmanContext:Md5.optional()}),$l0=y.custom((J)=>typeof J==="string"&&L$(J)!==void 0),jd5=y.object({threadId:Cl,role:y.literal("user"),content:sc0,agentMode:$l0.optional(),discoveredGuidanceFiles:y.array(Bd5).optional(),meta:Dd5.optional(),userState:ec0.optional(),readAt:y.string().nullable().optional(),messageId:r6,createdAt:y.string().optional()}),Jl0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),Rd5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),Id5=y.object({threadId:Cl,role:y.literal("assistant"),content:tc0,state:Rd5.optional(),usage:Jl0.optional(),readAt:y.string().nullable().optional(),messageId:r6,createdAt:y.string().optional()}),Pd5=y.object({threadId:Cl,role:y.literal("info"),content:Ld5,messageId:r6,createdAt:y.string().optional()}),kw4=y.discriminatedUnion("role",[jd5,Id5,Pd5]),kl=y.object({workspaceRoot:Sz.optional(),workingDirectory:Sz.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),Cd5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),_d5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),oldContent:y.string().optional(),newContent:y.string().optional(),diffStat:Cd5}),Td5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),yw4=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(Td5).optional(),files:y.array(_d5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),mZ0=y.object({id:y.string(),toolCallId:r8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:r8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),Sd5=y.object({type:y.literal("request"),id:z8,method:z8,params:y.unknown()}),kd5=y.object({type:y.literal("response"),id:z8,result:y.unknown().optional(),error:y.string().optional()}),yd5=y.object({type:y.literal("event"),event:z8,data:y.unknown(),span:y.string().optional()}),pZ0=y.discriminatedUnion("type",[Sd5,kd5,yd5]);var vd5=y.object({type:y.literal("executor_connect"),clientId:z8,capabilities:Rw4,executorType:Iw4.optional()}),xd5=y.object({type:y.literal("executor_settings_update"),settings:nc0}),fd5=y.object({type:y.literal("executor_tools_register"),tools:y.array(jw4)}),ud5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(z8)}),bd5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),hd5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:r8}),Zl0=y.object({type:y.literal("tool_progress"),toolCallId:r8,progress:y.union([Pw4,y.unknown()]).optional(),parentToolCallId:r8.optional()}),gd5=y.object({type:y.literal("executor_tool_result"),toolCallId:r8,run:Tl}),md5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:z8,files:y.array(Rk),isLast:y.boolean(),userConfigDir:y.any().optional()}),pd5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:r8,files:y.array(Rk),isLast:y.boolean()}),dd5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:z8,skills:y.array(_w4),isLast:y.boolean()}),cd5=y.object({type:y.literal("executor_rollback_ack"),editId:_l,ok:y.boolean(),error:y.string().optional()}),ld5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:r8}),id5=y.object({type:y.literal("executor_environment_snapshot"),environment:kl}),nd5=y.object({type:y.literal("executor_environment_update"),environment:kl}),ad5=y.object({type:y.literal("executor_artifact_upsert"),artifact:ac0,toolCallId:r8.optional()}),od5=y.object({type:y.literal("executor_artifact_delete"),key:z8}),rd5=y.object({type:y.literal("executor_tool_approval_request"),approval:mZ0}),sd5=y.object({type:y.literal("executor_plugin_message"),message:pZ0}),td5=y.object({type:y.literal("client_append_user_msg"),content:Ik,userState:ec0.optional(),discoveredGuidanceFiles:y.array(Rk).optional(),agentMode:y.string().optional(),messageId:r6}),ed5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:r6}),$c5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:r6}),Jc5=y.object({type:y.literal("client_edit_message"),messageId:r6,editId:_l,content:Ik,agentMode:y.string().optional()}),Zc5=y.object({type:y.literal("client_mark_message_read"),messageId:r6}),Qc5=y.object({type:y.literal("client_mark_message_unread"),messageId:r6}),Yc5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Xc5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Kc5=y.object({endpoint:y.string().url(),keys:Xc5}),Vc5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Kc5,threadURL:y.string().min(1)}),Gc5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:oF,uri:jk}),zc5=y.object({type:y.literal("client_filesystem_read_file"),requestId:oF,uri:jk}),Fc5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:oF,ok:y.boolean(),entries:y.array(Sl).optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),qc5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:oF,ok:y.boolean(),contentBase64:y.string().optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Wc5=y.object({type:y.literal("client_resume"),version:y.number()}),Uc5=y.object({type:y.literal("client_retry")}),Hc5=y.object({type:y.literal("client_cancel")}),Dc5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:Tl,hidden:y.boolean().optional()}),Bc5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:r8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),Nc5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),k09=y.enum(["agg-man"]),vw4=y.discriminatedUnion("type",[vd5,xd5,fd5,ud5,bd5,hd5,Zl0,gd5,md5,pd5,dd5,cd5,ld5,id5,nd5,ad5,od5,rd5,sd5,td5,ed5,$c5,Jc5,Zc5,Qc5,Yc5,Vc5,Gc5,zc5,Fc5,qc5,Wc5,Uc5,Hc5,Dc5,Bc5,Nc5]);$J();$J();var wc5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),Lc5=y.enum(["start","generating","tool_use","complete","error"]),Oc5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),Ec5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),Mc5=y.enum(["starting","running","failed"]),Ac5=y.object({cutMessageId:r6,createdAt:y.string()}),xw4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:r6,content:Ik,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Rk).optional(),createdAt:y.string().optional()})}),jc5=y.object({type:y.literal("agent_state"),state:wc5,messageId:r6.optional()}),Rc5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),Ic5=y.object({type:y.literal("error_set"),seq:y.number(),error:Oc5}),Pc5=y.object({type:y.literal("error_cleared"),seq:y.number()}),Cc5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:r6.optional()}),_c5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),Tc5=y.object({type:y.literal("retry_started")}),Sc5=y.object({type:y.literal("retry_cancelled")}),kc5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),yc5=y.object({type:y.literal("tool_lease"),toolCallId:r8,toolName:y.string(),args:y.unknown(),messageId:r6,parentToolCallId:r8.optional()}),vc5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:oF,uri:jk}),xc5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:oF,uri:jk}),fc5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:oF,ok:y.boolean(),entries:y.array(Sl).optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),uc5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:oF,ok:y.boolean(),contentBase64:y.string().optional(),error:Zw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),bc5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(mZ0)}),hc5=y.object({type:y.literal("executor_rollback_request"),editId:_l,messageId:r6,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(r8)}),gc5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),mc5=y.object({type:y.literal("plugin_message"),message:pZ0}),pc5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:r8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),dc5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),cc5=y.object({type:y.literal("delta"),messageId:r6,role:y.literal("assistant"),blocks:tc0.optional(),state:Lc5,usage:Jl0.optional(),parentToolCallId:r8.optional()}),lc5=y.object({type:y.literal("delta"),messageId:r6,role:y.literal("user"),blocks:sc0.optional(),state:y.literal("complete"),parentToolCallId:r8.optional()}),ic5=y.discriminatedUnion("role",[cc5,lc5]),nc5=y.object({type:y.literal("queued_messages"),messages:y.array(xw4)}),ac5=y.object({type:y.literal("queued_message_added"),message:xw4,seq:y.number()}),oc5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:r6,seq:y.number()}),rc5=y.object({type:y.literal("message_added"),message:kw4,seq:y.number(),parentToolUseId:z8.optional()}),sc5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),tc5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:r6,content:Ik,truncateToMessageId:r6,reason:y.literal("message_edit"),agentMode:$l0.optional()}),ec5=y.looseObject({type:y.literal("cf_agent_state")}),$l5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),Jl5=y.looseObject({type:y.literal("cf_agent_identity")}),Zl5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(Ec5),hasExecutor:y.boolean().optional()}),Ql5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:Mc5,message:y.string().optional(),executorId:y.string().optional()}),Yl5=y.object({type:y.literal("environment_update"),environment:kl}),Xl5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(oc0)}),Kl5=y.object({type:y.literal("artifact_upserted"),artifact:oc0}),Vl5=y.object({type:y.literal("artifact_deleted"),key:z8}),Gl5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),zl5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),Fl5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(Mw4)}),ql5=y.object({type:y.literal("compaction_started")}),Wl5=y.object({type:y.literal("compaction_complete"),cutMessageId:r6}),Ul5=y.object({type:y.literal("compaction_records"),records:y.array(Ac5)}),dZ0=y.discriminatedUnion("type",[jc5,Rc5,Ic5,Pc5,Cc5,_c5,Tc5,Sc5,kc5,yc5,vc5,xc5,fc5,uc5,bc5,hc5,gc5,mc5,pc5,Zl0,dc5,ic5,nc5,ac5,oc5,rc5,sc5,tc5,ec5,$l5,Jl5,Zl5,Ql5,Yl5,Xl5,Kl5,Vl5,Gl5,zl5,Fl5,ql5,Wl5,Ul5]);var Ql0=(J)=>y.codec(y.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}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),fw4=Ql0(vw4),Hl5=y.union([dZ0,y.array(dZ0)]),uw4=Ql0(dZ0),bw4=Ql0(Hl5);H4();function hw4(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=l1(Y1.parse(V.uri))}catch{if(Y)return null;continue}let z={uri:G};if(typeof V.content==="string")z.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))z.lineCount=V.lineCount;if(typeof V.hash==="string")z.hash=V.hash;X.push(z)}return X}var gw4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Yl0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function Dl5(J){return J.replace(/\s+/g," ").trim()}function Bl5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function Nl5(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 Yl0(JSON.stringify(J),120)}catch{return Yl0(String(J),120)}}function mw4(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 wl5(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=mw4(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 pw4(J){for(let Z of J){let Q=wl5(Z);if(Q)return Q}return null}function Ll5(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"||mw4(Q.path)==="type")})}function Ol5(J,Z){let Q=pw4(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 dw4(J,Z,Q){let Y=Bl5(Z),X=(()=>{let F=Dl5(J);if(F.length===0)return null;return Yl0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=pw4(Y);return{failureType:"invalid_json",summary:F?`malformed JSON: ${F}`:"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,z=Nl5(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${z??"unknown value"}`,messageType:null,typePreview:z,payloadPreview:X,issues:Y};if(Ll5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:z,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:Ol5(G,Y),messageType:G,typePreview:z,payloadPreview:X,issues:Y}}function yl(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"}}function cw4(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}}$J();var lw4="[dtw-parse-error]",Kl0="dtw-parse-error",El5=y.object({kind:y.literal(Kl0),failureType:y.enum(gw4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),Ml5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function Xl0(J){return{kind:Kl0,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 iw4(J){let Z=Xl0(J);return JSON.stringify(Z)}function nw4(J,Z){let Q=dw4(J,Z);return iw4({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})}function Vl0(J){let Z=J.startsWith(lw4)?J.slice(lw4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=El5.safeParse(Q);if(Y.success)return Xl0(Y.data);let X=Ml5.safeParse(Q);if(X.success)return Xl0(X.data);return null}w1();class Gl0 extends Error{constructor(J){super(J);this.name="DTWError"}}class T9 extends Gl0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}w1();var Al5=1000,jl5=30000,Rl5=5,Il5=30000,Pl5=200,Cl5=30000,aw4=["online","focus","pageshow","keydown","pointerdown"],ow4=["visibilitychange"];function Fl0(){return globalThis}function sw4(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 rw4(){return sw4(Fl0().window)}function zl0(){let J=Fl0().document;if(!sw4(J))return null;return J}function _l5(){let J=Fl0().navigator;if(!J||typeof J!=="object")return null;return J}function Tl5(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(" ")}function cZ0(J){return!!(J.apiKey&&J.WebSocketClass)}function ql0(J){if(cZ0(J))return"one-step";return"two-step"}class Wl0{ws=null;connectionInfo={state:"disconnected",role:null,clientId:null,threadId: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 Y4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new Y4([]);config;currentThreadID=null;currentWsToken=null;constructor(J){this.config={baseURL:J.baseURL,threadId:J.threadId,apiKey:J.apiKey,wsToken:J.wsToken,wsTokenProvider:J.wsTokenProvider,webSocketProvider:J.webSocketProvider,reconnectDelayMs:J.reconnectDelayMs??Al5,maxReconnectDelayMs:J.maxReconnectDelayMs??jl5,maxReconnectAttempts:J.maxReconnectAttempts??Rl5,pingIntervalMs:J.pingIntervalMs??Il5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${ql0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}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=Pl5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new T9("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 Z=this.config.WebSocketClass??WebSocket,Q;if(this.config.webSocketProvider)Q=await this.config.webSocketProvider();else if(cZ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new T9("1-step flow requires apiKey");let K=this.currentThreadID??this.config.threadId;if(!K)K=(await this.fetchWsToken()).threadId;let V=`${Y}/threads`;if(K)V=`${V}?threadId=${encodeURIComponent(K)}`;Q=new Z(V,{headers:{Authorization:`Bearer ${X}`}})}else{let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),{threadId:X,wsToken:K}=await this.ensureWsToken();this.currentThreadID=X,this.currentWsToken=K;let V=`${Y}/threads`;Q=new Z(V,["amp",K])}try{Q.binaryType="arraybuffer"}catch{}await this.waitForOpen(Q),this.ws=Q,this.lastPongAt=Date.now(),this.setupWebSocketHandlers(Q),this.stopWaitingForReconnectActivity(),this.scheduleReconnectAttemptsReset(),this.reconnectCause=null,this.updateConnectionState("connected"),this.recordLifecycleEvent("connect_succeeded",`threadId=${this.currentThreadID??"none"} attempt=${this.reconnectAttempts}`)}catch(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)this.ws=null,this.intentionallyClosedSockets.add(J),J.close(1000,"Client disconnect");this.updateConnectionState("disconnected")}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 T9("WebSocket is not connected");this.ws?.send(J)}hasOpenSocket(){return!!this.ws&&this.ws.readyState===WebSocket.OPEN}updateConnectionState(J){if(J==="disconnected"||J==="reconnecting"){let Z={state:J,role:null,clientId:null,threadId:null};if(this.reconnectCause)Z.reconnectCause=this.reconnectCause;this.connectionInfo=Z}else if(this.connectionInfo.state=J,J==="connected")this.connectionInfo.threadId=this.currentThreadID,this.reconnectCause=null,delete this.connectionInfo.reconnectCause;else if(this.reconnectCause)this.connectionInfo.reconnectCause=this.reconnectCause;this.connectionSubject.next({...this.connectionInfo}),this.recordLifecycleEvent("state_changed",`state=${J} cause=${Tl5(this.reconnectCause)}`)}async handleAuthExpired(){this.recordLifecycleEvent("auth_refresh_started");try{if(this.currentWsToken=null,this.config.wsTokenProvider){let J=await this.config.wsTokenProvider({forceRefresh:!0});this.currentThreadID=J.threadId,this.currentWsToken=J.wsToken}this.recordLifecycleEvent("auth_refresh_succeeded",`threadId=${this.currentThreadID??"none"}`)}catch{this.recordLifecycleEvent("auth_refresh_failed")}}onRawMessage(J){}onMaxReconnectExceeded(J){}async ensureWsToken(){let J=this.reconnectAttempts>0;if(!J&&this.currentWsToken&&this.currentThreadID)return{threadId:this.currentThreadID,wsToken:this.currentWsToken};if(this.config.wsTokenProvider){let Z=await this.config.wsTokenProvider(J?{forceRefresh:!0}:void 0);return this.currentThreadID=Z.threadId,this.currentWsToken=Z.wsToken,Z}if(!J&&this.config.wsToken&&this.config.threadId)return{threadId:this.config.threadId,wsToken:this.config.wsToken};return this.fetchWsToken()}async fetchWsToken(){let Z=`${this.config.baseURL.replace(/^ws:/,"http:").replace(/^wss:/,"https:")}/threads`,Q={"Content-Type":"application/json"};if(this.config.apiKey)Q.Authorization=`Bearer ${this.config.apiKey}`;let Y=this.currentThreadID??this.config.threadId,X={};if(Y)X.threadId=Y;let K=await fetch(Z,{method:"POST",headers:Q,body:JSON.stringify(X)});if(!K.ok){let G=await K.text().catch(()=>"");throw new T9(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new T9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let G="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new T9(`WebSocket connection failed: ${G}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new T9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};if(J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K),J.readyState===WebSocket.OPEN)return Y();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return K({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();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(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}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else 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();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=rw4(),Z=zl0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=_l5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=zl0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=rw4(),Z=zl0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of aw4)J?.addEventListener(Y,Q);for(let Y of ow4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of aw4)J?.removeEventListener(Y,Q);for(let Y of ow4)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},Cl5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}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}}function Sl5(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}class rF extends Wl0{deltaSubject=new $4;errorSubject=new $4;errorEventSubject=new $4;cancelledSubject=new $4;agentStateSubject=new $4;messageAddedSubject=new $4;editRejectedSubject=new $4;messageEditedSubject=new $4;queuedMessagesSubject=new $4;retrySubject=new $4;toolLeaseSubject=new $4;toolLeaseRevokedSubject=new $4;toolApprovalQueueSubject=new $4;executorToolApprovalResponseSubject=new $4;toolProgressSubject=new $4;executorErrorSubject=new $4;executorConnectedSubject=new $4;executorRollbackRequestSubject=new $4;observersSubject=new $4;executorStatusSubject=new $4;environmentUpdateSubject=new $4;artifactsSubject=new $4;threadTitleSubject=new $4;threadStatusSubject=new $4;threadRelationshipsSubject=new $4;compactionSubject=new $4;compactionRecordsSubject=new $4;pluginMessageSubject=new $4;fileSystemReadDirectoryRequestSubject=new $4;fileSystemReadFileRequestSubject=new $4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}threadTitles(){return this.threadTitleSubject}threadStatuses(){return this.threadStatusSubject}threadRelationships(){return this.threadRelationshipsSubject}compactionEvents(){return this.compactionSubject}compactionRecords(){return this.compactionRecordsSubject}pluginMessages(){return this.pluginMessageSubject}fileSystemReadDirectoryRequests(){return this.fileSystemReadDirectoryRequestSubject}fileSystemReadFileRequests(){return this.fileSystemReadFileRequestSubject}dispose(){if(this.disposed)return;super.dispose(),this.rejectPendingFileSystemRequests("Transport disposed"),this.deltaSubject.complete(),this.errorSubject.complete(),this.errorEventSubject.complete(),this.cancelledSubject.complete(),this.agentStateSubject.complete(),this.messageAddedSubject.complete(),this.editRejectedSubject.complete(),this.messageEditedSubject.complete(),this.queuedMessagesSubject.complete(),this.retrySubject.complete(),this.toolLeaseSubject.complete(),this.toolLeaseRevokedSubject.complete(),this.toolApprovalQueueSubject.complete(),this.executorToolApprovalResponseSubject.complete(),this.toolProgressSubject.complete(),this.executorErrorSubject.complete(),this.executorConnectedSubject.complete(),this.executorRollbackRequestSubject.complete(),this.observersSubject.complete(),this.executorStatusSubject.complete(),this.environmentUpdateSubject.complete(),this.artifactsSubject.complete(),this.threadTitleSubject.complete(),this.threadStatusSubject.complete(),this.threadRelationshipsSubject.complete(),this.compactionSubject.complete(),this.compactionRecordsSubject.complete(),this.pluginMessageSubject.complete(),this.fileSystemReadDirectoryRequestSubject.complete(),this.fileSystemReadFileRequestSubject.complete()}sendUserMessage(J,Z,Q){let Y=Q?.messageId??aF();return this.send({type:"client_append_user_msg",content:J,agentMode:Z,messageId:Y,userState:Q?.userState,discoveredGuidanceFiles:Q?.discoveredGuidanceFiles}),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})}retryAgentLoop(){this.send({type:"client_retry"})}cancelAgentLoop(){if(!this.hasOpenSocket())return;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}})}async executorHandshake(J,Z,Q){if(this.disposed)throw new T9("Transport is disposed");if(!this.hasOpenSocket())throw new T9("WebSocket is not connected. Call connect() first.");return new Promise((Y,X)=>{let K=!1,V=null,G=(q)=>{if(K)return;if(K=!0,V)clearTimeout(V),V=null;z.unsubscribe(),F.unsubscribe(),q()},z=this.executorConnectedSubject.subscribe({next:(q)=>{this.connectionInfo.clientId=q.executorId,this.connectionInfo.role="executor",this.updateConnectionState("connected"),G(()=>Y(q))},error:(q)=>{G(()=>X(q))}}),F=this.executorErrorSubject.subscribe({next:(q)=>{G(()=>X(Error(q.message)))}});this.send({type:"executor_connect",clientId:J,capabilities:Z,executorType:Q?.executorType}),V=setTimeout(()=>{G(()=>X(Error("Executor connect timeout")))},1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=yl(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})}sendRevocationAck(J){this.send({type:"executor_revocation_ack",toolCallId: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})}sendExecutorSettingsUpdate(J){this.send({type:"executor_settings_update",settings:J})}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})}sendEnvironmentUpdate(J){this.send({type:"executor_environment_update",environment:J})}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})}updateConnectionState(J){if(super.updateConnectionState(J),J==="reconnecting"||J==="disconnected")this.rejectPendingFileSystemRequests("Connection closed before filesystem request completed")}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 T9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new T9(`Filesystem request timed out: ${Z}`))},Cw4);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(Sl5(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 T9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new T9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=bw4.safeDecode(J);if(!Z.success){let Y=uw4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:nw4(J,X),code:"PARSE_ERROR"});return}let Q=Array.isArray(Z.data)?Z.data:[Z.data];for(let Y of Q)this.handleServerMessage(Y)}handleServerMessage(J){switch(J.type){case"agent_state":this.agentStateSubject.next(J);break;case"error":this.errorSubject.next(J);break;case"error_set":case"error_cleared":this.errorEventSubject.next(J);break;case"cancelled":this.cancelledSubject.next(J);break;case"retry_scheduled":case"retry_started":case"retry_cancelled":this.retrySubject.next(J);break;case"delta":this.deltaSubject.next(J);break;case"message_added":this.messageAddedSubject.next(J);break;case"edit_rejected":this.editRejectedSubject.next(J);break;case"message_edited":this.messageEditedSubject.next(J);break;case"queued_messages":case"queued_message_added":case"queued_message_removed":this.queuedMessagesSubject.next(J);break;case"executor_connected":this.connectionInfo.role="executor",this.connectionInfo.clientId=J.executorId,this.connectionSubject.next({...this.connectionInfo}),this.executorConnectedSubject.next(J);break;case"tool_lease":this.toolLeaseSubject.next(J);break;case"executor_filesystem_read_directory":this.fileSystemReadDirectoryRequestSubject.next(J);break;case"executor_filesystem_read_file":this.fileSystemReadFileRequestSubject.next(J);break;case"executor_rollback_request":this.executorRollbackRequestSubject.next(J);break;case"executor_tool_lease_revoked":this.toolLeaseRevokedSubject.next(J);break;case"tool_approval_queue":this.toolApprovalQueueSubject.next(J);break;case"plugin_message":this.pluginMessageSubject.next(J);break;case"executor_tool_approval_response":this.executorToolApprovalResponseSubject.next(J);break;case"tool_progress":this.toolProgressSubject.next(J);break;case"executor_error":this.executorErrorSubject.next(J);break;case"cf_agent_state":case"cf_agent_mcp_servers":case"cf_agent_identity":break;case"observers":this.observersSubject.next(J);break;case"executor_status":this.executorStatusSubject.next(J);break;case"environment_update":this.environmentUpdateSubject.next(J);break;case"artifacts_snapshot":case"artifact_upserted":case"artifact_deleted":this.artifactsSubject.next(J);break;case"thread_title":this.threadTitleSubject.next(J);break;case"thread_status":this.threadStatusSubject.next(J);break;case"thread_relationships":this.threadRelationshipsSubject.next(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":this.compactionSubject.next(J);break;case"compaction_records":this.compactionRecordsSubject.next(J);break}}onMaxReconnectExceeded(J){this.errorSubject.next({type:"error",message:`Failed to reconnect after ${J} attempts`,code:"MAX_RECONNECT_EXCEEDED"})}send(J){try{this.sendRaw(fw4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new T9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function kl5(J){if(!J||typeof J!=="object")return!1;let Z=J.queuedMessage;if(!Z||typeof Z!=="object")return!1;return typeof Z.messageId==="string"}function yl5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function vl5(J){if(kl5(J))return J.queuedMessage.messageId;if(yl5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function Ul0(J,Z,Q={}){let Y=Q.getQueuedMessageId??vl5;if(Z.type==="queued_messages")return[...Z.messages];if(Z.type==="queued_message_added"){if(Q.dedupeAdded&&J.some((X)=>Y(X)===Y(Z.message)))return[...J];return[...J,Z.message]}if(!J.some((X)=>Y(X)===Z.queuedMessageId))return[...J];return J.filter((X)=>Y(X)!==Z.queuedMessageId)}var xl5=15000;function fl5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let z of K)z.unsubscribe()};return{promise:new Promise((z,F)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),z(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),F(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),F(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),F(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function Hl0(J){let Z=J.workerUrl??p7(J.ampURL),Q=new rF({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??xl5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=fl5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as ul5}from"node:fs";import{mkdir as bl5,readdir as hl5,readFile as gl5}from"node:fs/promises";import{createServer as ml5}from"node:http";import Dl0 from"node:path";function tw4(J){return J instanceof Error?J.message:String(J)}function $j(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function pl5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function ew4(J,Z){let Q=Dl0.basename(Z),Y=Q.endsWith(".json")?Dl0.join(J,Q):Dl0.join(J,`${Q}.json`),X=await gl5(Y,"utf-8");return JSON.parse(X)}async function dl5(J){let Z=await hl5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await ew4(J,Y.name);Q.push({sessionID:X.sessionID,createdAt:X.createdAt,runtimeMode:X.runtimeMode,traceName:X.traceName,threadId:X.threadId,protocolEvents:X.protocolEvents.length,providerStates:X.providerStateEvents.length,adapterStates:X.adapterStateEvents.length,commands:X.commandEvents.length})}catch{}}return Q.sort((Y,X)=>X.createdAt-Y.createdAt)}function cl5(){return`<!doctype html>
4669
4669
  <html lang="en">
4670
4670
  <head>
4671
4671
  <meta charset="utf-8" />
@@ -6221,11 +6221,11 @@ ${H}`))}},error:(U)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${U.message}`))}
6221
6221
  ${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))D+=`
6222
6222
 
6223
6223
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6224
- npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();ZA();async function TX0(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 z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=J_4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var FY3="https://static.ampcode.com/cli/cli-version.txt";async function SX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${FY3}?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=J_4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var qY3=604800000;function $_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>qY3)return{ageMs:Q};return null}function J_4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},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,z=X.parts[V]||0;if(G<z)return-1;if(G>z)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 lo0(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?PF(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function io0(J,Z,Q={}){let Y=new $4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new kz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await XF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await XF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await _X0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await SX0(J):await TX0(J,hj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ho0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Fn(U.latestVersion,q);let D=await Cw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await XF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}ZA();import{stderr as Oq}from"node:process";function Z_4(J){let Z=new oN().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 vo0(Y.force||!1,Y.verbose||!1,"0.0.1774590201-g775913"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new oN("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 WY3(Y.targetVersion)});J.addCommand(Q)}async function WY3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Oq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6224
+ npm install -g @sourcegraph/amp`;G(Error(D))}},error:(U)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${U.message}`))},complete:()=>{if(!q)q=!0,V()}})})}m0();m0();ZA();async function TX0(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 z=await G.json(),F=z.version??z["dist-tags"]?.latest;if(!F)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=J_4(J,F),W=q<0,U,H;if(z.time){let D=z.time[J],B=z.time[F],N=Date.now();if(D)U=Math.floor((N-new Date(D).getTime())/3600000);if(B)H=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:U,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:U,latestVersionAge:H,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var FY3="https://static.ampcode.com/cli/cli-version.txt";async function SX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${FY3}?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=J_4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var qY3=604800000;function $_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>qY3)return{ageMs:Q};return null}function J_4(J,Z){let Q=(V)=>{let[G,z]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},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,z=X.parts[V]||0;if(G<z)return-1;if(G>z)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 lo0(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?PF(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function io0(J,Z,Q={}){let Y=new $4,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new kz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await XF(V);let G=X.subscribe({next:(z)=>{K.debug("emit new state",z)}});try{let z=process.env.AMP_TEST_UPDATE_STATUS;if(z){K.debug("using fake update status for testing",{status:z}),await XF(500),Y.next(z);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let F=await Z.get("updates.mode");if(F==="disabled"){K.debug("checking disabled");return}let q=await _X0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let U=W?await SX0(J):await TX0(J,hj());if(!(U.latestVersion&&U.hasUpdate)){K.debug("no update available");return}let H=()=>{if(U.currentVersionAge!==void 0&&U.latestVersionAge!==void 0){let D=U.currentVersionAge-U.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:U.currentVersionAge,latestVersionAge:U.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!F)F=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:F});if(q==="brew"){if(!H())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==ho0()){if(K.debug("non-standard binary path, showing warning"),!H())Y.next("update-available-unrecognized-path");return}if(F==="warn"){if(!H())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Fn(U.latestVersion,q);let D=await Cw(U.latestVersion),B={from:U.currentVersion,to:U.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await XF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}ZA();import{stderr as Oq}from"node:process";function Z_4(J){let Z=new oN().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 vo0(Y.force||!1,Y.verbose||!1,"0.0.1774599058-g7bb23d"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new oN("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 WY3(Y.targetVersion)});J.addCommand(Q)}async function WY3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Oq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6225
6225
 
6226
6226
  `));try{if(!J){Oq.write(c0.blue(`Checking for updates...
6227
- `));let{hasUpdate:Y,latestVersion:X}=fo0()?await SX0("0.0.1774590201-g775913"):await TX0("0.0.1774590201-g775913",hj());if(!Y){let K=lo0("0.0.1774590201-g775913"),V=K?.age?`released ${K.age} ago`:`built ${PF(new Date("2026-03-27T05:47:14.565Z"))} ago`;Oq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774590201-g775913"} (${V})
6228
- `));let G=await Cw("0.0.1774590201-g775913");if(G.warning)Oq.write(`
6227
+ `));let{hasUpdate:Y,latestVersion:X}=fo0()?await SX0("0.0.1774599058-g7bb23d"):await TX0("0.0.1774599058-g7bb23d",hj());if(!Y){let K=lo0("0.0.1774599058-g7bb23d"),V=K?.age?`released ${K.age} ago`:`built ${PF(new Date("2026-03-27T08:14:47.138Z"))} ago`;Oq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774599058-g7bb23d"} (${V})
6228
+ `));let G=await Cw("0.0.1774599058-g7bb23d");if(G.warning)Oq.write(`
6229
6229
  `+c0.yellow(G.warning)+`
6230
6230
  `);process.exit(0)}if(!X)Oq.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Oq.write(c0.blue(`Updating to version ${J}...
6231
6231
  `)),await Fn(J,void 0,(Y)=>{Oq.write(c0.dim(`Running: ${Y}
@@ -6233,7 +6233,7 @@ Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm in
6233
6233
  `));let Q=await Cw(J);if(Q.warning)Oq.write(`
6234
6234
  `+c0.yellow(Q.warning)+`
6235
6235
  `);process.exit(0)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);Oq.write(c0.red.bold("Error: ")+Q+`
6236
- `),process.exit(1)}}import{execFile as GK3}from"node:child_process";import{lstat as zT4,mkdir as zK3,readFile as FK3,rm as Or0,writeFile as qK3}from"node:fs/promises";import eY from"node:path";import h$ from"node:process";import{createInterface as WK3}from"node:readline";import{promisify as UK3}from"node:util";class G3{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((K,V)=>{let G=this.neighborMap[V].filter((z)=>this.state[z]).length;if(K)return G===2||G===3;return G===3||G===6}),Z=J.every((K,V)=>K===this.state[V]),Q=this.previousState.length>0&&J.every((K,V)=>K===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((K)=>!K),X=J.filter((K)=>K).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let K;do K=Array.from({length:8},()=>Math.random()>0.6);while(K.filter((V)=>V).length<3);this.state=K,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}m0();_2();H4();m0();XJ();w1();function yX0(J){return typeof J==="object"&&J!==null}function no0(J){if(!Array.isArray(J))return;return J}function Q_4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return no0(Q)}catch{return}}function kX0(J){if(typeof J==="string")return J;if(!yX0(J))return;if("output"in J&&typeof J.output==="string")return J.output;if("displayMessage"in J&&typeof J.displayMessage==="string")return J.displayMessage;if("message"in J&&typeof J.message==="string")return J.message;if("reason"in J&&typeof J.reason==="string")return J.reason;if("result"in J){let Z=kX0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=kX0(J.error);if(Z!==void 0)return Z}if("value"in J)return kX0(J.value);return}function UY3(J){return J.type==="text"}function Y_4(J){if(J===void 0)return;let Z;try{Z=yl(J,"snapshot")}catch{return}if(Z.type==="snapshot")return kX0(Z.value);let Q=(Z.blocks??[]).filter(UY3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var HY3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function DY3(J){return typeof J==="string"&&HY3.includes(J)}function X_4(J){if(J===void 0)return;let Z;try{Z=yl(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!yX0(Q))return;if(!("status"in Q)||!DY3(Q.status))return;return Q.status}function K_4(J){let Z=no0(J);if(Z!==void 0)return Z;if(!yX0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=no0(Y);if(X!==void 0)return X;if(typeof Y==="string")return Q_4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!yX0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return Q_4(Q)}var BY3=3000,NY3=30000,wY3=5;function F_4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:aF(),role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({messageId:aF(),role:"assistant",content:[...X.content],meta:X.meta,usage:X.usage,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let K=X.content.filter((V)=>V.type==="manual_bash_invocation");if(K.length>0)Z.push({messageId:aF(),role:"info",content:K,parentToolUseId:X.parentToolUseId});for(let V of X.content){if(V.type!=="summary"||V.summary.type!=="message")continue;Q+=1,Z.push({messageId:aF(),role:"assistant",content:[{type:"text",text:V.summary.summary}],parentToolUseId:X.parentToolUseId})}}let Y=J.meta?.status!==void 0||J.meta?.executorType!==void 0?{...J.meta?.status!==void 0?{status:J.meta.status}:{},...J.meta?.executorType!==void 0?{executorType:J.meta.executorType}:{}}:void 0;return{id:J.id,v:J.v,...J.title?{title:J.title}:{},...J.agentMode?{agentMode:J.agentMode}:{},...Y?{meta:Y}:{},messages:Z,convertedSummaryMessages:Q}}function LY3(J,Z){let Q=Z.messages.map((Y,X)=>{if(Y.role==="user")return{role:"user",content:[...Y.content],meta:Y.meta,userState:Y.userState,readAt:Y.readAt,messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId};if(Y.role==="assistant"){let K=Y.content.some((V)=>V.type==="tool_use");return{role:"assistant",content:[...Y.content],meta:Y.meta,usage:Y.usage,readAt:Y.readAt,state:Y.cancelled?{type:"cancelled"}:{type:"complete",stopReason:K?"tool_use":"end_turn"},messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}}return{role:"info",content:[...Y.content],messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}});return{...J,messages:Q}}async function OH(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 K8("/api/durable-thread-workers",oo0({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,executorType:V.executorType??null,ownerUserId:V.ownerUserId,threadVersion:V.threadVersion,...V.agentMode?{agentMode:V.agentMode}:{}}}async function OY3(J,Z,Q,Y){let X=await Z.getLatest(),K=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!K)throw Error("API key required. Please run `amp login` first.");let V=Y.payload??F_4(J),G=Y.workerURL??p7(Y.ampURL),z=await fetch(`${G}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(z.status===409)return"already-imported";if(!z.ok)throw Error(`Failed to import thread into DTW: ${z.status} ${await z.text()}`);if((await z.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function EY3(J,Z,Q){let Y=await K8(`/api/durable-thread-workers/${J}`,oo0({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({executorType:"local-client"})},Q),Z);if(!Y.ok)throw Error(`Failed to mark thread as DTW-backed: ${Y.status} ${await Y.text()}`);let X=await Y.json();if(X.ok!==!0||X.usesDtw!==!0||X.executorType!=="local-client")throw Error("Failed to mark thread as DTW-backed: server returned an invalid response")}async function Hn(J,Z,Q){let Y=await K8(`/api/threads/${J}`,oo0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function oo0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function Un(J){let Z=r6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=r6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function MY3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=Un(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function AY3(J){let Z=new Set;for(let Q of J){let Y=Un(Q);if(Y)Z.add(Y)}return Z}function qn(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((K)=>K.type==="tool_use"&&K.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function jY3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function RY3(J,Z){let Q=J.parentToolCallId,Y=J.role==="assistant"?J:null,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});if(Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0,J.blocks&&J.blocks.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:J.blocks??[],parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:J.blocks??[],usage:Y?.usage,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){if(J.role==="user"){let V=J.blocks;X.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q})}else{let V=J.blocks;X.push({messageId:J.messageId,role:"assistant",blocks:V,usage:Y?.usage,parentToolCallId:Q})}return}let K=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")K=qn(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&K.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:K,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=qn([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=qn(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=qn([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=qn(Z.streamingBlocks,J.blocks)}}function IY3(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let K of Z){if(Q.has(K.messageId))continue;Q.add(K.messageId);let V=X++;if(K.role==="assistant")Y.push({role:"assistant",content:K.blocks,state:{type:"complete",stopReason:"end_turn"},usage:K.usage,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId});else Y.push({role:"user",content:K.blocks,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function PY3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function ao0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:PY3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function CY3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>Un(G)===Y);if(K<0)return Z;let V=Z[K];if(!V)return Z;if(J.message.role!==V.role)return Z;if(V.role==="user"&&J.message.role==="user"){let G={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ao0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}if(V.role==="assistant"&&J.message.role==="assistant"){let G={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}if(V.role==="info"&&J.message.role==="info"){let G={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}return Z}Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},usage:J.message.usage,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ao0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function _Y3(J,Z){let Q=Z.findIndex((G)=>Un(G)===J.messageId),Y=Z.findIndex((G)=>Un(G)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let K={role:"user",content:J.content,agentMode:J.agentMode,messageId:X.messageId,dtwMessageID:J.messageId},V=Z.slice(0,Y+1);return V[Q]=K,V}function V_4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function Wn(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q})),discoveredGuidanceFiles:Z.queuedMessage.discoveredGuidanceFiles?.map((Q)=>({...Q}))}}))}function G_4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:Z.messageId,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,discoveredGuidanceFiles:ao0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function TY3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>G_4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:G_4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function SY3(J,Z){let Q=TY3(Z);return Ul0(Wn(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function kY3(J,Z){if(J.useThreadActors){let Q=VZ0(J.ampURL),Y=Li({endpoint:`${Q}/api/rivet`});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL});return await Y.threadActor.getOrCreate([X.threadId],{params:{wsToken:X.wsToken},createWithInput:{threadId:X.threadId,threadVersion:X.threadVersion,ownerUserId:X.ownerUserId,agentMode:X.agentMode}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}return{baseURL:J.workerUrl??p7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function z_4(J){if(!J)return{};let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCauseCode=J.code;if(J.reason)Z.reconnectCauseReason=J.reason;if(J.error)Z.reconnectCauseError=J.error;return Z}class vX0{threadSubject;agentLoopStateSubject=new Y4("idle");editErrorSubject=new $4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new Y4(new Map);toolProgressSubject=new $4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new Y4("idle");compactionState="idle";transportSubscribed=!1;connectPromise=null;lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Wn(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=cw4(Y),this.threadSubject=new Y4(J)}static async create(J){let Z=await OH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await Hn(Z.threadId,J.configService,J.apiKey);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let z=F_4(Q),F=await OY3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:z});if(await EY3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=LY3(Q,z)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=MY3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Wn(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new rF(await kY3(J,Z)),G=new vX0(K,V,X,Q.v);try{if(J.connectOnCreate??!0)await G.connect();return G}catch(z){throw G.dispose(),z}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setRelationships(J){if(this.relationships.length>0)return;this.relationships=J,this.emitThread()}setAgentMode(J,Z){if(!J)return;let Q=this.threadSubject.getValue();if(!Z?.overwrite&&Q.agentMode)return;if(Q.agentMode===J)return;let Y={...Q,agentMode:J};this.threadSubject.next(Y)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=jY3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((z,F)=>Math.max(z,F.messageId),-1)+1,G={...Z,id:this.threadId,...Q?{agentMode:Q}:{},v:this.threadResumeCursor.getVersion(),title:this.threadTitle,messages:K,queuedMessages:this.queuedMessages.length>0?Wn(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}advanceThreadVersionFromSeq(J){this.threadResumeCursor.advanceFromSeq(J)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.threadResumeCursor.reset(),this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Vl0(J.message):null;if(P.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(J.state)})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(RY3(J,this.deltaState),J.role==="user"&&J.state==="complete"&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=IY3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=Y_4(J.progress),Y=X_4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?K_4(J.progress):X?.subagentProgressTurns,V=J.progress!==void 0;if(Q===void 0&&Y===void 0&&!V){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}let G={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===G.status&&X?.content===G.content&&X?.subagentProgressTurns===G.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,G),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{let Z=V_4(J);if(this.messages=CY3(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{let Z=V_4(J);this.messages=_Y3(J,this.messages),this.processedIds=AY3(this.messages),this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.threadRelationships().subscribe({next:(J)=>{this.runTransportHandler("threadRelationships",()=>{if(J.relationships.length>0||this.relationships.length===0)this.relationships=J.relationships;this.advanceThreadVersionFromSeq(J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=SY3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,role:Z.role,clientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadResumeCursor.getVersion(),...z_4(Z.reconnectCause)};if(Z.state==="connected"){if(J==="reconnecting"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){P.info("[dtw] Transport role changed",{threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,fromClientId:J.clientId,toClientId:Z.clientId,transportThreadId:Z.threadId,threadVersion:this.threadResumeCursor.getVersion()})}ensureTransportSubscriptions(){if(this.transportSubscribed)return;this.transportSubscribed=!0,this.subscribeToTransport()}async connect(){if(this.connectPromise)return this.connectPromise;this.ensureTransportSubscriptions();let J=this.transport.getConnectionInfo();if(J.state==="connected"||J.state==="connecting"||J.state==="authenticating"||J.state==="reconnecting")return;this.connectPromise=(async()=>{try{await this.transport.connect()}catch(Z){let Q=this.transport.getConnectionInfo();if(Q.state!=="reconnecting")throw Z;P.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:this.threadId,connectionState:Q.state,...z_4(Q.reconnectCause),error:Z})}this.emitThread()})();try{await this.connectPromise}finally{this.connectPromise=null}}async ensureConnected(){let J=BY3,Z=NY3,Q=wY3;for(let K=0;K<Q;K++){await this.connect();let V=Math.min(J*2**K,Z);if(await this.waitForTransportConnected(V))return;P.info("[dtw] Connection attempt timed out, retrying",{attempt:K+1,maxAttempts:Q,nextDelayMs:K+1<Q?Math.min(J*2**(K+1),Z):null,threadId:this.threadId})}let X=this.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";throw Error(X)}waitForTransportConnected(J){if(this.transport.getConnectionInfo().state==="connected")return Promise.resolve(!0);return new Promise((Z)=>{let Q=!1,Y=null,X=(V)=>{if(Q)return;Q=!0,clearTimeout(K),Z(V),Y?.unsubscribe(),Y=null},K=setTimeout(()=>{X(!1)},J);if(Y=this.transport.connectionChanges().subscribe({next:(V)=>{if(V.state==="connected")X(!0)},error:()=>{X(!1)}}),Q)Y.unsubscribe(),Y=null})}sendUserMessage(J,Z,Q,Y,X){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Wn(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>r6.safeParse(Q.id)).filter((Q)=>Q.success).map((Q)=>Q.data);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as yY3,readFile as vY3,rm as ro0,writeFile as xY3}from"node:fs/promises";import fY3 from"node:path";var uY3=5000,bY3=100;function hY3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function to0(J,Z){return J.code===Z}function gY3(J){return J instanceof Error?J.message:String(J)}function so0(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function mY3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function q_4(J,Z){return so0(Reflect.get(J,Z))}function pY3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=mY3(Z,"pid"),Y=q_4(Z,"threadId"),X=q_4(Z,"threadTitle");if(Q===void 0||Y===null)return;return{pid:Q,threadId:Y,threadTitle:X}}function dY3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
6236
+ `),process.exit(1)}}import{execFile as GK3}from"node:child_process";import{lstat as zT4,mkdir as zK3,readFile as FK3,rm as Or0,writeFile as qK3}from"node:fs/promises";import eY from"node:path";import h$ from"node:process";import{createInterface as WK3}from"node:readline";import{promisify as UK3}from"node:util";class G3{state=[!0,!1,!0,!1,!0,!1,!0,!1];previousState=[];generation=0;maxGenerations=15;neighborMap=[[1,3,4,5,7],[0,2,4,5,6],[1,3,5,6,7],[0,2,4,6,7],[0,1,3,5,7],[0,1,2,4,6],[1,2,3,5,7],[0,2,3,4,6]];step(){let J=this.state.map((K,V)=>{let G=this.neighborMap[V].filter((z)=>this.state[z]).length;if(K)return G===2||G===3;return G===3||G===6}),Z=J.every((K,V)=>K===this.state[V]),Q=this.previousState.length>0&&J.every((K,V)=>K===this.previousState[V]);this.previousState=[...this.state],this.state=J,this.generation++;let Y=J.every((K)=>!K),X=J.filter((K)=>K).length;if(Z||Q||this.generation>=this.maxGenerations||Y||X<2){let K;do K=Array.from({length:8},()=>Math.random()>0.6);while(K.filter((V)=>V).length<3);this.state=K,this.previousState=[],this.generation=0}}toBraille(){let J=[0,1,2,6,3,4,5,7],Z=10240;for(let Q=0;Q<8;Q++)if(this.state[Q])Z|=1<<J[Q];return String.fromCharCode(Z)}}m0();_2();H4();m0();XJ();w1();function yX0(J){return typeof J==="object"&&J!==null}function no0(J){if(!Array.isArray(J))return;return J}function Q_4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return no0(Q)}catch{return}}function kX0(J){if(typeof J==="string")return J;if(!yX0(J))return;if("output"in J&&typeof J.output==="string")return J.output;if("displayMessage"in J&&typeof J.displayMessage==="string")return J.displayMessage;if("message"in J&&typeof J.message==="string")return J.message;if("reason"in J&&typeof J.reason==="string")return J.reason;if("result"in J){let Z=kX0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=kX0(J.error);if(Z!==void 0)return Z}if("value"in J)return kX0(J.value);return}function UY3(J){return J.type==="text"}function Y_4(J){if(J===void 0)return;let Z;try{Z=yl(J,"snapshot")}catch{return}if(Z.type==="snapshot")return kX0(Z.value);let Q=(Z.blocks??[]).filter(UY3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var HY3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function DY3(J){return typeof J==="string"&&HY3.includes(J)}function X_4(J){if(J===void 0)return;let Z;try{Z=yl(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!yX0(Q))return;if(!("status"in Q)||!DY3(Q.status))return;return Q.status}function K_4(J){let Z=no0(J);if(Z!==void 0)return Z;if(!yX0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=no0(Y);if(X!==void 0)return X;if(typeof Y==="string")return Q_4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!yX0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return Q_4(Q)}var BY3=3000,NY3=30000,wY3=5;function F_4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:aF(),role:"user",content:[...X.content],meta:X.meta,userState:X.userState,readAt:X.readAt,parentToolUseId:X.parentToolUseId});continue}if(X.role==="assistant"){Z.push({messageId:aF(),role:"assistant",content:[...X.content],meta:X.meta,usage:X.usage,readAt:X.readAt,cancelled:X.state.type==="cancelled",parentToolUseId:X.parentToolUseId});continue}let K=X.content.filter((V)=>V.type==="manual_bash_invocation");if(K.length>0)Z.push({messageId:aF(),role:"info",content:K,parentToolUseId:X.parentToolUseId});for(let V of X.content){if(V.type!=="summary"||V.summary.type!=="message")continue;Q+=1,Z.push({messageId:aF(),role:"assistant",content:[{type:"text",text:V.summary.summary}],parentToolUseId:X.parentToolUseId})}}let Y=J.meta?.status!==void 0||J.meta?.executorType!==void 0?{...J.meta?.status!==void 0?{status:J.meta.status}:{},...J.meta?.executorType!==void 0?{executorType:J.meta.executorType}:{}}:void 0;return{id:J.id,v:J.v,...J.title?{title:J.title}:{},...J.agentMode?{agentMode:J.agentMode}:{},...Y?{meta:Y}:{},messages:Z,convertedSummaryMessages:Q}}function LY3(J,Z){let Q=Z.messages.map((Y,X)=>{if(Y.role==="user")return{role:"user",content:[...Y.content],meta:Y.meta,userState:Y.userState,readAt:Y.readAt,messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId};if(Y.role==="assistant"){let K=Y.content.some((V)=>V.type==="tool_use");return{role:"assistant",content:[...Y.content],meta:Y.meta,usage:Y.usage,readAt:Y.readAt,state:Y.cancelled?{type:"cancelled"}:{type:"complete",stopReason:K?"tool_use":"end_turn"},messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}}return{role:"info",content:[...Y.content],messageId:X,dtwMessageID:Y.messageId,parentToolUseId:Y.parentToolUseId}});return{...J,messages:Q}}async function OH(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 K8("/api/durable-thread-workers",oo0({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,executorType:V.executorType??null,ownerUserId:V.ownerUserId,threadVersion:V.threadVersion,...V.agentMode?{agentMode:V.agentMode}:{}}}async function OY3(J,Z,Q,Y){let X=await Z.getLatest(),K=Q??await X.secrets.getToken("apiKey",X.settings.url);if(!K)throw Error("API key required. Please run `amp login` first.");let V=Y.payload??F_4(J),G=Y.workerURL??p7(Y.ampURL),z=await fetch(`${G}/threads/${J.id}/import`,{method:"POST",headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json"},body:JSON.stringify({thread:V})});if(z.status===409)return"already-imported";if(!z.ok)throw Error(`Failed to import thread into DTW: ${z.status} ${await z.text()}`);if((await z.json()).ok!==!0)throw Error("Failed to import thread into DTW: import endpoint returned an invalid response");return"imported"}async function EY3(J,Z,Q){let Y=await K8(`/api/durable-thread-workers/${J}`,oo0({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({executorType:"local-client"})},Q),Z);if(!Y.ok)throw Error(`Failed to mark thread as DTW-backed: ${Y.status} ${await Y.text()}`);let X=await Y.json();if(X.ok!==!0||X.usesDtw!==!0||X.executorType!=="local-client")throw Error("Failed to mark thread as DTW-backed: server returned an invalid response")}async function Hn(J,Z,Q){let Y=await K8(`/api/threads/${J}`,oo0(void 0,Q),Z);if(!Y.ok)throw Error(`Failed to fetch thread snapshot: ${Y.status} ${await Y.text()}`);return await Y.json()}function oo0(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function Un(J){let Z=r6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=r6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function MY3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=Un(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function AY3(J){let Z=new Set;for(let Q of J){let Y=Un(Q);if(Y)Z.add(Y)}return Z}function qn(J,Z){let Q=[...J];for(let Y of Z)if(Y.type==="text"){let X=Q[Q.length-1];if(X?.type==="text")Q[Q.length-1]={...X,text:X.text+Y.text};else Q.push(Y)}else if(Y.type==="tool_use"){let X=Q.findIndex((K)=>K.type==="tool_use"&&K.id===Y.id);if(X>=0)Q[X]=Y;else Q.push(Y)}else if(Y.type==="thinking"){let X=Q[Q.length-1];if(X?.type==="thinking")Q[Q.length-1]={...X,thinking:X.thinking+Y.thinking};else Q.push(Y)}else Q.push(Y);return Q}function jY3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function RY3(J,Z){let Q=J.parentToolCallId,Y=J.role==="assistant"?J:null,{completedMessages:X}=Z;if(J.state==="complete"||J.state==="error"){if(Z.streamingMessageId!==null&&J.messageId!==Z.streamingMessageId){if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:Z.streamingBlocks,parentToolCallId:Z.streamingParentToolCallId});if(Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0,J.blocks&&J.blocks.length>0)if(J.role==="user")X.push({messageId:J.messageId,role:"user",blocks:J.blocks??[],parentToolCallId:Q});else X.push({messageId:J.messageId,role:"assistant",blocks:J.blocks??[],usage:Y?.usage,parentToolCallId:Q});return}if(Z.streamingMessageId===null&&J.blocks&&J.blocks.length>0){if(J.role==="user"){let V=J.blocks;X.push({messageId:J.messageId,role:"user",blocks:V,parentToolCallId:Q})}else{let V=J.blocks;X.push({messageId:J.messageId,role:"assistant",blocks:V,usage:Y?.usage,parentToolCallId:Q})}return}let K=Z.streamingBlocks;if(J.messageId===Z.streamingMessageId&&J.blocks&&J.role==="assistant")K=qn(Z.streamingBlocks,J.blocks);if(Z.streamingMessageId&&K.length>0)X.push({messageId:Z.streamingMessageId,role:"assistant",blocks:K,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="tool_use"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=qn([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=qn(Z.streamingBlocks,J.blocks);if(Z.streamingBlocks.length>0)X.push({messageId:Z.streamingMessageId??J.messageId,role:"assistant",blocks:Z.streamingBlocks,usage:Y?.usage,parentToolCallId:Z.streamingParentToolCallId});Z.streamingMessageId=null,Z.streamingBlocks=[],Z.streamingParentToolCallId=void 0;return}if(J.state==="start"||J.state==="generating"){if(J.role!=="assistant")return;if(Z.streamingMessageId===null||Z.streamingMessageId!==J.messageId)Z.streamingMessageId=J.messageId,Z.streamingBlocks=qn([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=qn(Z.streamingBlocks,J.blocks)}}function IY3(J,Z,Q){if(Z.length===0)return J;let Y=[],X=J.length;for(let K of Z){if(Q.has(K.messageId))continue;Q.add(K.messageId);let V=X++;if(K.role==="assistant")Y.push({role:"assistant",content:K.blocks,state:{type:"complete",stopReason:"end_turn"},usage:K.usage,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId});else Y.push({role:"user",content:K.blocks,messageId:V,dtwMessageID:K.messageId,parentToolUseId:K.parentToolCallId})}if(Y.length===0)return J;return[...J,...Y]}function PY3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function ao0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:PY3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function CY3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>Un(G)===Y);if(K<0)return Z;let V=Z[K];if(!V)return Z;if(J.message.role!==V.role)return Z;if(V.role==="user"&&J.message.role==="user"){let G={...V,content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ao0(J.message.discoveredGuidanceFiles),parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}if(V.role==="assistant"&&J.message.role==="assistant"){let G={...V,content:J.message.content,usage:J.message.usage,state:{type:"complete",stopReason:"end_turn"},parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}if(V.role==="info"&&J.message.role==="info"){let G={...V,content:J.message.content,parentToolUseId:J.parentToolUseId},z=[...Z];return z[K]=G,z}return Z}Q.add(Y);let X=Z.length;if(J.message.role==="assistant")return[...Z,{role:"assistant",content:J.message.content,state:{type:"complete",stopReason:"end_turn"},usage:J.message.usage,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];if(J.message.role==="info")return[...Z,{role:"info",content:J.message.content,messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}];return[...Z,{role:"user",content:J.message.content,agentMode:J.message.agentMode,userState:J.message.userState,discoveredGuidanceFiles:ao0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function _Y3(J,Z){let Q=Z.findIndex((G)=>Un(G)===J.messageId),Y=Z.findIndex((G)=>Un(G)===J.truncateToMessageId);if(Q<0||Y<0)throw Error("Unable to apply edit: message mapping not found");let X=Z[Q];if(!X||X.role!=="user")throw Error("Unable to apply edit: target message is not editable");let K={role:"user",content:J.content,agentMode:J.agentMode,messageId:X.messageId,dtwMessageID:J.messageId},V=Z.slice(0,Y+1);return V[Q]=K,V}function V_4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function Wn(J){if(!J||J.length===0)return;return J.map((Z)=>({...Z,queuedMessage:{...Z.queuedMessage,content:Z.queuedMessage.content.map((Q)=>({...Q})),discoveredGuidanceFiles:Z.queuedMessage.discoveredGuidanceFiles?.map((Q)=>({...Q}))}}))}function G_4(J){let Z=J.queuedMessage,Q=Z.content.map((Y)=>({...Y}));return{id:Z.messageId,interrupt:J.interrupt,queuedMessage:{role:"user",content:Q,userState:Z.userState,discoveredGuidanceFiles:ao0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function TY3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>G_4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:G_4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function SY3(J,Z){let Q=TY3(Z);return Ul0(Wn(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function kY3(J,Z){if(J.useThreadActors){let Q=VZ0(J.ampURL),Y=Li({endpoint:`${Q}/api/rivet`});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL});return await Y.threadActor.getOrCreate([X.threadId],{params:{wsToken:X.wsToken},createWithInput:{threadId:X.threadId,threadVersion:X.threadVersion,ownerUserId:X.ownerUserId,agentMode:X.agentMode}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}return{baseURL:J.workerUrl??p7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>OH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function z_4(J){if(!J)return{};let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCauseCode=J.code;if(J.reason)Z.reconnectCauseReason=J.reason;if(J.error)Z.reconnectCauseError=J.error;return Z}class vX0{threadSubject;agentLoopStateSubject=new Y4("idle");editErrorSubject=new $4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new Y4(new Map);toolProgressSubject=new $4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new Y4("idle");compactionState="idle";transportSubscribed=!1;connectPromise=null;lastConnectionState="disconnected";lastConnectionInfo=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Wn(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=cw4(Y),this.threadSubject=new Y4(J)}static async create(J){let Z=await OH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await Hn(Z.threadId,J.configService,J.apiKey);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let z=F_4(Q),F=await OY3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:z});if(await EY3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=LY3(Q,z)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=MY3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Wn(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new rF(await kY3(J,Z)),G=new vX0(K,V,X,Q.v);try{if(J.connectOnCreate??!0)await G.connect();return G}catch(z){throw G.dispose(),z}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionInfo(){return this.lastConnectionInfo?{...this.lastConnectionInfo}:null}getCompactionState(){return this.compactionState}compactionStateChanges(){return this.compactionStateSubject}willQueueNextUserMessage(){return this.agentLoopState!=="idle"||this.deltaState.streamingMessageId!==null}setEnvironment(J){let Z=this.threadSubject.getValue();if(Z.env?.initial)return;let Q={...Z,...{env:J}};this.threadSubject.next(Q)}setRelationships(J){if(this.relationships.length>0)return;this.relationships=J,this.emitThread()}setAgentMode(J,Z){if(!J)return;let Q=this.threadSubject.getValue();if(!Z?.overwrite&&Q.agentMode)return;if(Q.agentMode===J)return;let Y={...Q,agentMode:J};this.threadSubject.next(Y)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=jY3(this.deltaState.streamingMessageId,this.deltaState.streamingBlocks,this.messages.length,this.deltaState.streamingParentToolCallId),K=Y?[...this.messages,Y]:[...this.messages],V=K.reduce((z,F)=>Math.max(z,F.messageId),-1)+1,G={...Z,id:this.threadId,...Q?{agentMode:Q}:{},v:this.threadResumeCursor.getVersion(),title:this.threadTitle,messages:K,queuedMessages:this.queuedMessages.length>0?Wn(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G)}emitToolProgress(){this.toolProgressByToolUseIDSubject.next(new Map(this.toolProgressByToolUseID))}clearToolProgress(J){if(this.toolProgressByToolUseID.delete(J))this.emitToolProgress()}clearToolProgressFromBlocks(J){for(let Z of J)if(Z.type==="tool_result")this.clearToolProgress(Z.toolUseID)}setCompactionState(J){if(this.compactionState===J)return;this.compactionState=J,this.compactionStateSubject.next(J)}advanceThreadVersionFromSeq(J){this.threadResumeCursor.advanceFromSeq(J)}runTransportHandler(J,Z){try{Z()}catch(Q){let Y=Q instanceof Error?Q.message:String(Q);P.error("[dtw] Transport handler failed",{threadId:this.threadId,handler:J,connectionState:this.lastConnectionState,error:Q}),this.editErrorSubject.next(`[dtw] ${J}: ${Y}`)}}subscribeToTransport(){this.subscriptions.push(this.transport.connectionChanges().subscribe({next:(J)=>{this.runTransportHandler("connectionChanges",()=>{let Z=this.lastConnectionInfo,Q=J.state!==this.lastConnectionState,Y=Z!==null&&(J.role!==Z.role||J.clientId!==Z.clientId);if(!Q&&!Y)return;if(Q)this.logConnectionStateTransition(this.lastConnectionState,J);else if(Y&&Z)this.logConnectionRoleTransition(Z,J);let X=J.state;if(X==="connected"&&this.lastConnectionState!=="connected")this.threadResumeCursor.reset(),this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());this.lastConnectionState=X,this.lastConnectionInfo={...J}})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Vl0(J.message):null;if(P.warn("[dtw] Transport error",{threadId:this.threadId,connectionState:this.lastConnectionState,code:J.code,message:Z!==null?"Received invalid DTW payload (see parse details)":J.message,parseErrorSource:Z?.source,parseErrorDirection:Z?.direction,parseErrorStage:Z?.stage,parseErrorSummary:Z?.summary,parseErrorMessageType:Z?.messageType,parseErrorIssues:Z?.issues,parseErrorPayloadPreview:Z?.payloadPreview}),J.code==="PARSE_ERROR"){let Q=Z?.messageType?` (type="${Z.messageType}")`:"";this.editErrorSubject.next(`Received an invalid DTW message${Q}. The connection will continue running. Check logs for details.`)}})}}),this.transport.agentStates().subscribe({next:(J)=>{this.runTransportHandler("agentStates",()=>{this.agentLoopState=J.state,this.agentLoopStateSubject.next(J.state)})}}),this.transport.deltas().subscribe({next:(J)=>{this.runTransportHandler("deltas",()=>{if(RY3(J,this.deltaState),J.role==="user"&&J.state==="complete"&&J.blocks)this.clearToolProgressFromBlocks(J.blocks);if(this.deltaState.completedMessages.length>0){for(let Z of this.deltaState.completedMessages)if(Z.role==="user")this.clearToolProgressFromBlocks(Z.blocks);this.messages=IY3(this.messages,this.deltaState.completedMessages,this.processedIds),this.deltaState.completedMessages=[]}this.emitThread()})}}),this.transport.toolProgress().subscribe({next:(J)=>{this.runTransportHandler("toolProgress",()=>{this.toolProgressSubject.next(J);let Z=J.toolCallId,Q=Y_4(J.progress),Y=X_4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?K_4(J.progress):X?.subagentProgressTurns,V=J.progress!==void 0;if(Q===void 0&&Y===void 0&&!V){if(this.toolProgressByToolUseID.delete(Z))this.emitToolProgress();return}let G={status:Y??X?.status??"in-progress",content:Q??X?.content??"",...K!==void 0?{subagentProgressTurns:K}:{}};if(X?.status===G.status&&X?.content===G.content&&X?.subagentProgressTurns===G.subagentProgressTurns)return;this.toolProgressByToolUseID.set(Z,G),this.emitToolProgress()})}}),this.transport.compactionEvents().subscribe({next:(J)=>{this.runTransportHandler("compactionEvents",()=>{if(J.type==="compaction_started"){this.setCompactionState("compacting");return}this.setCompactionState("idle")})}}),this.transport.messageEvents().subscribe({next:(J)=>{this.runTransportHandler("messageEvents",()=>{let Z=V_4(J);if(this.messages=CY3(J,this.messages,this.processedIds),J.message.role==="user")this.clearToolProgressFromBlocks(J.message.content);if(this.deltaState.streamingMessageId===J.message.messageId)this.deltaState.streamingMessageId=null,this.deltaState.streamingBlocks=[],this.deltaState.streamingParentToolCallId=void 0;this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.messageEdited().subscribe({next:(J)=>{this.runTransportHandler("messageEdited",()=>{let Z=V_4(J);this.messages=_Y3(J,this.messages),this.processedIds=AY3(this.messages),this.advanceThreadVersionFromSeq(J.seq),this.emitThread({agentMode:Z})})}}),this.transport.threadTitles().subscribe({next:(J)=>{this.runTransportHandler("threadTitles",()=>{this.threadTitle=J.title??void 0,this.emitThread()})}}),this.transport.threadRelationships().subscribe({next:(J)=>{this.runTransportHandler("threadRelationships",()=>{if(J.relationships.length>0||this.relationships.length===0)this.relationships=J.relationships;this.advanceThreadVersionFromSeq(J.seq),this.emitThread()})}}),this.transport.queuedMessages().subscribe({next:(J)=>{this.runTransportHandler("queuedMessages",()=>{this.queuedMessages=SY3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...z_4(Z.reconnectCause)};if(Z.role)Q.role=Z.role;if(Z.clientId)Q.clientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;if(Z.state==="connected"){if(J==="reconnecting"){P.info("[dtw] Transport reconnected",Q);return}P.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){P.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){P.warn("[dtw] Transport disconnected",Q);return}P.info("[dtw] Transport state changed",Q)}logConnectionRoleTransition(J,Z){let Q={threadId:this.threadId,state:Z.state,fromRole:J.role,toRole:Z.role,threadVersion:this.threadResumeCursor.getVersion()};if(J.clientId||Z.clientId)Q.fromClientId=J.clientId,Q.toClientId=Z.clientId;if(Z.threadId&&Z.threadId!==this.threadId)Q.transportThreadId=Z.threadId;P.info("[dtw] Transport role changed",Q)}ensureTransportSubscriptions(){if(this.transportSubscribed)return;this.transportSubscribed=!0,this.subscribeToTransport()}async connect(){if(this.connectPromise)return this.connectPromise;this.ensureTransportSubscriptions();let J=this.transport.getConnectionInfo();if(J.state==="connected"||J.state==="connecting"||J.state==="authenticating"||J.state==="reconnecting")return;this.connectPromise=(async()=>{try{await this.transport.connect()}catch(Z){let Q=this.transport.getConnectionInfo();if(Q.state!=="reconnecting")throw Z;P.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:this.threadId,connectionState:Q.state,...z_4(Q.reconnectCause),error:Z})}this.emitThread()})();try{await this.connectPromise}finally{this.connectPromise=null}}async ensureConnected(){let J=BY3,Z=NY3,Q=wY3;for(let K=0;K<Q;K++){await this.connect();let V=Math.min(J*2**K,Z);if(await this.waitForTransportConnected(V))return;P.info("[dtw] Connection attempt timed out, retrying",{attempt:K+1,maxAttempts:Q,nextDelayMs:K+1<Q?Math.min(J*2**(K+1),Z):null,threadId:this.threadId})}let X=this.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";throw Error(X)}waitForTransportConnected(J){if(this.transport.getConnectionInfo().state==="connected")return Promise.resolve(!0);return new Promise((Z)=>{let Q=!1,Y=null,X=(V)=>{if(Q)return;Q=!0,clearTimeout(K),Z(V),Y?.unsubscribe(),Y=null},K=setTimeout(()=>{X(!1)},J);if(Y=this.transport.connectionChanges().subscribe({next:(V)=>{if(V.state==="connected")X(!0)},error:()=>{X(!1)}}),Q)Y.unsubscribe(),Y=null})}sendUserMessage(J,Z,Q,Y,X){return this.setAgentMode(Z),this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X})}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Wn(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>r6.safeParse(Q.id)).filter((Q)=>Q.success).map((Q)=>Q.data);this.queuedMessages=[],this.emitThread();try{for(let Q of Z)this.transport.removeQueuedMessage(Q)}catch(Q){throw this.queuedMessages=J??[],this.emitThread(),Q}}resumeFromVersion(J){this.transport.resumeFromVersion(J)}dispose(){for(let J of this.subscriptions)J.unsubscribe();this.subscriptions.length=0,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as yY3,readFile as vY3,rm as ro0,writeFile as xY3}from"node:fs/promises";import fY3 from"node:path";var uY3=5000,bY3=100;function hY3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function to0(J,Z){return J.code===Z}function gY3(J){return J instanceof Error?J.message:String(J)}function so0(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function mY3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function q_4(J,Z){return so0(Reflect.get(J,Z))}function pY3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=mY3(Z,"pid"),Y=q_4(Z,"threadId"),X=q_4(Z,"threadTitle");if(Q===void 0||Y===null)return;return{pid:Q,threadId:Y,threadTitle:X}}function dY3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
6237
6237
  `}function cY3(J){let Z=so0(J.currentThreadId);if(Z===null)throw new P1("Live-sync PID file requires a thread ID.",1);return{pid:J.currentPID??process.pid,threadId:Z,threadTitle:so0(J.currentThreadTitle)}}async function U_4(J){try{let Z=await vY3(J,"utf-8"),Q=pY3(Z);if(Q===void 0)return{kind:"invalid",value:Z.trim()};return{kind:"valid",contents:Q}}catch(Z){if(to0(Z,"ENOENT"))return{kind:"missing"};throw Z}}async function H_4(J,Z){let Q=await U_4(J);if(Q.kind!=="valid"||Q.contents.pid!==Z)return;await ro0(J,{force:!0})}async function lY3(J){try{process.kill(J,"SIGTERM")}catch(Z){if(to0(Z,"ESRCH"))return;throw Z}}async function iY3(J,Z){let Q=Date.now()+uY3;while(Date.now()<Q){if(!Z(J))return!0;await aY3(bY3)}return!Z(J)}function nY3(J){return["Another amp live-sync is already running for this checkout.","",...[J.running.threadTitle,J.running.threadId,`PID ${J.running.pid}`].filter((Q)=>Boolean(Q)),"","Kill the running live-sync process and continue? [y/N]: "].join(`
6238
6238
  `)}function W_4(J,Z){return{status:"claimed",pidFilePath:J,release:async()=>H_4(J,Z)}}function aY3(J){return new Promise((Z)=>{setTimeout(Z,J)})}async function D_4(J){let Z=J.currentPID??process.pid,Q=cY3(J),Y=J.isProcessRunning??hY3,X=J.killProcess??lY3,K=J.waitForProcessExit??((V)=>iY3(V,Y));await yY3(fY3.dirname(J.pidFilePath),{recursive:!0});while(!0){let V=await U_4(J.pidFilePath);if(V.kind==="valid"){if(V.contents.pid===Z)return W_4(J.pidFilePath,Z);if(Y(V.contents.pid)){if(!J.promptForYesNo)return{status:"already-running",pidFilePath:J.pidFilePath,runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle};let G=J.formatRunningPrompt?.({runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle})??nY3({running:V.contents});if(!await J.promptForYesNo(G))return{status:"already-running",pidFilePath:J.pidFilePath,runningPID:V.contents.pid,runningThreadId:V.contents.threadId,runningThreadTitle:V.contents.threadTitle};try{await X(V.contents.pid)}catch(F){throw new P1(`Couldn't stop live-sync PID ${V.contents.pid}: ${gY3(F)}`,1)}if(!await K(V.contents.pid))throw new P1(`Timed out waiting for live-sync PID ${V.contents.pid} to stop.`,1);await H_4(J.pidFilePath,V.contents.pid);continue}await ro0(J.pidFilePath,{force:!0});continue}if(V.kind==="invalid"){await ro0(J.pidFilePath,{force:!0});continue}try{return await xY3(J.pidFilePath,dY3(Q),{encoding:"utf-8",flag:"wx",mode:384}),W_4(J.pidFilePath,Z)}catch(G){if(to0(G,"EEXIST"))continue;throw G}}}m0();class sY{static instance=null;logs=[];maxLogs=1000;listeners=new Set;constructor(){}static getInstance(){if(!sY.instance)sY.instance=new sY;return sY.instance}addLog(J,Z,...Q){let Y={timestamp:new Date,level:J,message:Z,args:Q};if(this.logs.push(Y),this.logs.length>this.maxLogs)this.logs.shift();this.notifyListeners()}notifyListeners(){let J=this.getLogs();for(let Z of this.listeners)try{Z(J)}catch(Q){let Y=this.originalConsole?.error;if(Y)Y("Error in log change listener:",Q)}}getLogs(){return[...this.logs]}clear(){this.logs=[],this.notifyListeners()}addListener(J){this.listeners.add(J)}removeListener(J){this.listeners.delete(J)}interceptConsole(){let J={error:console.error.bind(console),warn:console.warn.bind(console),info:console.info.bind(console),log:console.log.bind(console),debug:console.debug.bind(console)};console.error=(Z,...Q)=>{this.addLog("error",Z,...Q)},console.warn=(Z,...Q)=>{this.addLog("warn",Z,...Q)},console.info=(Z,...Q)=>{this.addLog("info",Z,...Q)},console.log=(Z,...Q)=>{this.addLog("info",Z,...Q)},console.debug=(Z,...Q)=>{this.addLog("debug",Z,...Q)},this.originalConsole=J}restoreConsole(){let J=this.originalConsole;if(J)console.error=J.error,console.warn=J.warn,console.info=J.info,console.log=J.log,console.debug=J.debug}}function B_4(){try{if(sY.getInstance().restoreConsole(),process.stdout.write("\x1B[?1002l"),process.stdout.write("\x1B[?1003l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1006l"),process.stdout.write("\x1B[?1016l"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?2031l"),process.stdout.write("\x1B[?2048l"),process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[0 q"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[999;1H"),process.stdout.write("\x1B[0m"),!process.env.TERM_PROGRAM?.startsWith("iTerm"))process.stdout.write("\x1B]9;4;0\x1B\\")}catch(J){}}function J6(J,...Z){if(!J){let Q=Z.join(" "),Y=Error(Q);P.error("TUI Assert failed",{assertion:Q,stackTrace:Y.stack,meta:Z});let X=process.env.AMP_DEBUG,K=process.env.VITEST;if(X||K){if(K)throw Y;B_4(),console.error("FATAL TUI ERROR:",Q),console.error("Stack trace:",Y.stack),console.error("Context:",{meta:Z}),process.exit(1)}}}var eo0=null,$r0=null;function N_4(J,Z){eo0=J,$r0=Z}function w_4(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function L_4(){if(!eo0){if(w_4())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return eo0}function xX0(){if(!$r0){if(w_4())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return $r0}class gj{_parent;_children=[];_needsLayout=!1;_needsPaint=!1;_cachedDepth;_attached=!1;_debugData={};allowHitTestOutsideBounds=!1;parentData;setupParentData(J){}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}get parent(){return this._parent}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Z=this._parent;while(Z)J++,Z=Z._parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get needsLayout(){return this._needsLayout}get needsPaint(){return this._needsPaint}get attached(){return this._attached}adoptChild(J){if(J._parent=this,J._invalidateDepth(),this._children.push(J),this.setupParentData(J),this._attached)J.attach();this.markNeedsLayout()}dropChild(J){let Z=this._children.indexOf(J);if(Z!==-1){if(J._attached)J.detach();this._children.splice(Z,1),J._parent=void 0,J._invalidateDepth(),this.markNeedsLayout()}}removeAllChildren(){for(let J of this._children){if(J._attached)J.detach();J._parent=void 0,J._invalidateDepth()}this._children.length=0,this.markNeedsLayout()}replaceChildren(J){for(let Z of J)Z._parent=this,Z._invalidateDepth(),this.setupParentData(Z);this._children=J,this.markNeedsLayout()}attach(){if(this._attached)return;this._attached=!0;for(let J of this._children)J.attach()}detach(){if(!this._attached)return;this._attached=!1;for(let J of this._children)J.detach()}markNeedsLayout(){if(this._needsLayout)return;if(!this._attached)return;if(this._needsLayout=!0,this.parent)this.parent.markNeedsLayout();else xX0().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,xX0().requestPaint(this)}performLayout(){}paint(J,Z=0,Q=0){this._needsPaint=!1;for(let Y of this.children)if("offset"in Y){let X=Y,K=Z+X.offset.x,V=Q+X.offset.y;Y.paint(J,K,V)}else Y.paint(J,Z,Q)}visitChildren(J){for(let Z of this._children)J(Z)}dispose(){xX0().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}class v4 extends gj{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Z){J6(Number.isFinite(J)&&Number.isFinite(Z),`RenderBox.setSize received non-finite dimension: ${J}x${Z}`),this._size.width=J,this._size.height=Z}_offset={x:0,y:0};get offset(){return{...this._offset}}setOffset(J,Z){let Q=Number.isFinite(J)?Math.round(J):0,Y=Number.isFinite(Z)?Math.round(Z):0;this._offset.x=Q,this._offset.y=Y}localToGlobal(J){let{x:Z,y:Q}=J,Y=this;while(Y)if(Z+=Y._offset.x,Q+=Y._offset.y,Y=Y.parent,Y&&!("_offset"in Y))break;return{x:Z,y:Q}}globalToLocal(J){let Z=this.localToGlobal({x:0,y:0});return{x:J.x-Z.x,y:J.y-Z.y}}_lastConstraints;layout(J){let Z=!this._lastConstraints||!J.equals(this._lastConstraints);if(!this._needsLayout&&!Z)return;this._lastConstraints=J,this._needsLayout=!1,this.performLayout()}getMinIntrinsicWidth(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMinIntrinsicWidth(J));return Q}getMaxIntrinsicWidth(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMaxIntrinsicWidth(J));return Q}getMinIntrinsicHeight(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMinIntrinsicHeight(J));return Q}getMaxIntrinsicHeight(J){let Z=this.children;if(Z.length===0)return 0;let Q=0;for(let Y of Z)Q=Math.max(Q,Y.getMaxIntrinsicHeight(J));return Q}paint(J,Z=0,Q=0){let Y=J.getSize(),X=Y.width,K=Y.height;for(let V of this.children)if(V instanceof v4){let G=Z+this.offset.x+V.offset.x,z=Q+this.offset.y+V.offset.y,F=G+V.size.width,q=z+V.size.height;if(!(G>=X||z>=K||F<=0||q<=0))V.paint(J,Z+this.offset.x,Q+this.offset.y)}}hitTest(J,Z,Q=0,Y=0){let X=Q+this.offset.x,K=Y+this.offset.y,V=Z.x>=X&&Z.x<X+this.size.width,G=Z.y>=K&&Z.y<K+this.size.height;if(V&&G){J.addWithPaintOffset(this,{x:X,y:K},Z);let z=!0;for(let F=this.children.length-1;F>=0;F--)if(this.children[F].hitTest(J,Z,X,K))z=!0;return z}if(this.allowHitTestOutsideBounds){let z=!1;for(let F=this.children.length-1;F>=0;F--)if(this.children[F].hitTest(J,Z,X,K))z=!0;return z}return!1}}function Dn(J,Z=0){return Number.isFinite(J)?J:Z}class R1{minWidth;maxWidth;minHeight;maxHeight;constructor(J,Z,Q,Y){if(typeof J==="object")this.minWidth=J.minWidth??0,this.maxWidth=J.maxWidth??1/0,this.minHeight=J.minHeight??0,this.maxHeight=J.maxHeight??1/0;else this.minWidth=J??0,this.maxWidth=Z??1/0,this.minHeight=Q??0,this.maxHeight=Y??1/0}static tight(J,Z){return new R1(J,J,Z,Z)}static loose(J,Z){return new R1(0,J,0,Z)}get hasBoundedWidth(){return this.maxWidth!==1/0}get hasBoundedHeight(){return this.maxHeight!==1/0}get hasTightWidth(){return this.minWidth>=this.maxWidth}get hasTightHeight(){return this.minHeight>=this.maxHeight}constrain(J,Z){return J6(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),J6(isFinite(Z),`BoxConstraints.constrain received infinite height: ${Z}. This indicates a layout bug where a widget is not properly calculating its desired size.`),{width:Math.max(this.minWidth,Math.min(this.maxWidth,J)),height:Math.max(this.minHeight,Math.min(this.maxHeight,Z))}}enforce(J){let Z=(Q,Y,X)=>Math.max(Y,Math.min(X,Q));return new R1(Z(J.minWidth,this.minWidth,this.maxWidth),Z(J.maxWidth,this.minWidth,this.maxWidth),Z(J.minHeight,this.minHeight,this.maxHeight),Z(J.maxHeight,this.minHeight,this.maxHeight))}get biggest(){return{width:this.maxWidth,height:this.maxHeight}}get smallest(){return{width:this.minWidth,height:this.minHeight}}loosen(){return new R1(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Z}={}){return new R1(J===void 0?this.minWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),J===void 0?this.maxWidth:Math.max(this.minWidth,Math.min(this.maxWidth,J)),Z===void 0?this.minHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Z)),Z===void 0?this.maxHeight:Math.max(this.minHeight,Math.min(this.maxHeight,Z)))}static tightFor({width:J,height:Z}={}){return new R1(J??0,J??1/0,Z??0,Z??1/0)}equals(J){return this.minWidth===J.minWidth&&this.maxWidth===J.maxWidth&&this.minHeight===J.minHeight&&this.maxHeight===J.maxHeight}}var Eq=G4(O_4(),1),rY3=globalThis;rY3.Prism=Eq.default;(function(J){var Z="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",Q={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},Y={bash:Q,environment:{pattern:RegExp("\\$"+Z),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+Z),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};J.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+Z),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:Y},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:Q}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:Y},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:Y.entity}}],environment:{pattern:RegExp("\\$?"+Z),alias:"constant"},variable:Y.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},Q.inside=J.languages.bash;var X=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],K=Y.variable[1].inside;for(var V=0;V<X.length;V++)K[X[V]]=J.languages.bash[X[V]];J.languages.sh=J.languages.bash,J.languages.shell=J.languages.bash})(Prism);Prism.languages.c=Prism.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/});Prism.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}});Prism.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},Prism.languages.c.string],char:Prism.languages.c.char,comment:Prism.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:Prism.languages.c}}}});Prism.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/});delete Prism.languages.c.boolean;Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/};(function(J){var Z=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,Q=/\b(?!<keyword>)\w+(?:\s*\.\s*\w+)*\b/.source.replace(/<keyword>/g,function(){return Z.source});J.languages.cpp=J.languages.extend("c",{"class-name":[{pattern:RegExp(/(\b(?:class|concept|enum|struct|typename)\s+)(?!<keyword>)\w+/.source.replace(/<keyword>/g,function(){return Z.source})),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:Z,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),J.languages.insertBefore("cpp","string",{module:{pattern:RegExp(/(\b(?:import|module)\s+)/.source+"(?:"+/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|<[^<>\r\n]*>/.source+"|"+/<mod-name>(?:\s*:\s*<mod-name>)?|:\s*<mod-name>/.source.replace(/<mod-name>/g,function(){return Q})+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),J.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:J.languages.cpp}}}}),J.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),J.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:J.languages.extend("cpp",{})}}),J.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},J.languages.cpp["base-clause"])})(Prism);(function(J){function Z(n,c){return n.replace(/<<(\d+)>>/g,function(s,F0){return"(?:"+c[+F0]+")"})}function Q(n,c,s){return RegExp(Z(n,c),s||"")}function Y(n,c){for(var s=0;s<c;s++)n=n.replace(/<<self>>/g,function(){return"(?:"+n+")"});return n.replace(/<<self>>/g,"[^\\s\\S]")}var X={type:"bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void",typeDeclaration:"class enum interface record struct",contextual:"add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)",other:"abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield"};function K(n){return"\\b(?:"+n.trim().replace(/ /g,"|")+")\\b"}var V=K(X.typeDeclaration),G=RegExp(K(X.type+" "+X.typeDeclaration+" "+X.contextual+" "+X.other)),z=K(X.typeDeclaration+" "+X.contextual+" "+X.other),F=K(X.type+" "+X.typeDeclaration+" "+X.other),q=Y(/<(?:[^<>;=+\-*/%&|^]|<<self>>)*>/.source,2),W=Y(/\((?:[^()]|<<self>>)*\)/.source,2),U=/@?\b[A-Za-z_]\w*\b/.source,H=Z(/<<0>>(?:\s*<<1>>)?/.source,[U,q]),D=Z(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[z,H]),B=/\[\s*(?:,\s*)*\]/.source,N=Z(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[D,B]),w=Z(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[q,W,B]),L=Z(/\(<<0>>+(?:,<<0>>+)+\)/.source,[w]),O=Z(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[L,D,B]),E={keyword:G,punctuation:/[<>()?,.:[\]]/},M=/'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source,A=/"(?:\\.|[^\\"\r\n])*"/.source,j=/@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;J.languages.csharp=J.languages.extend("clike",{string:[{pattern:Q(/(^|[^$\\])<<0>>/.source,[j]),lookbehind:!0,greedy:!0},{pattern:Q(/(^|[^@$\\])<<0>>/.source,[A]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:Q(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source,[D]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[U,O]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+)<<0>>(?=\s*=)/.source,[U]),lookbehind:!0},{pattern:Q(/(\b<<0>>\s+)<<1>>/.source,[V,H]),lookbehind:!0,inside:E},{pattern:Q(/(\bcatch\s*\(\s*)<<0>>/.source,[D]),lookbehind:!0,inside:E},{pattern:Q(/(\bwhere\s+)<<0>>/.source,[U]),lookbehind:!0},{pattern:Q(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[N]),lookbehind:!0,inside:E},{pattern:Q(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[O,F,U]),inside:E}],keyword:G,number:/(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,operator:/>>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),J.languages.insertBefore("csharp","number",{range:{pattern:/\.\./,alias:"operator"}}),J.languages.insertBefore("csharp","punctuation",{"named-parameter":{pattern:Q(/([(,]\s*)<<0>>(?=\s*:)/.source,[U]),lookbehind:!0,alias:"punctuation"}}),J.languages.insertBefore("csharp","class-name",{namespace:{pattern:Q(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[U]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:Q(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source,[W]),lookbehind:!0,alias:"class-name",inside:E},"return-type":{pattern:Q(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source,[O,D]),inside:E,alias:"class-name"},"constructor-invocation":{pattern:Q(/(\bnew\s+)<<0>>(?=\s*[[({])/.source,[O]),lookbehind:!0,inside:E,alias:"class-name"},"generic-method":{pattern:Q(/<<0>>\s*<<1>>(?=\s*\()/.source,[U,q]),inside:{function:Q(/^<<0>>/.source,[U]),generic:{pattern:RegExp(q),alias:"class-name",inside:E}}},"type-list":{pattern:Q(/\b((?:<<0>>\s+<<1>>|record\s+<<1>>\s*<<5>>|where\s+<<2>>)\s*:\s*)(?:<<3>>|<<4>>|<<1>>\s*<<5>>|<<6>>)(?:\s*,\s*(?:<<3>>|<<4>>|<<6>>))*(?=\s*(?:where|[{;]|=>|$))/.source,[V,H,U,O,G.source,W,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:Q(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[H,W]),lookbehind:!0,greedy:!0,inside:J.languages.csharp},keyword:G,"class-name":{pattern:RegExp(O),greedy:!0,inside:E},punctuation:/[,()]/}},preprocessor:{pattern:/(^[\t ]*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}});var R=A+"|"+M,T=Z(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[R]),S=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[T]),2),u=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,m=Z(/<<0>>(?:\s*\(<<1>>*\))?/.source,[D,S]);J.languages.insertBefore("csharp","class-name",{attribute:{pattern:Q(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[u,m]),lookbehind:!0,greedy:!0,inside:{target:{pattern:Q(/^<<0>>(?=\s*:)/.source,[u]),alias:"keyword"},"attribute-arguments":{pattern:Q(/\(<<0>>*\)/.source,[S]),inside:J.languages.csharp},"class-name":{pattern:RegExp(D),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var x=/:[^}\r\n]+/.source,_=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[T]),2),f=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[_,x]),p=Y(Z(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[R]),2),d=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[p,x]);function h(n,c){return{interpolation:{pattern:Q(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[n]),lookbehind:!0,inside:{"format-string":{pattern:Q(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[c,x]),lookbehind:!0,inside:{punctuation:/^:/}},punctuation:/^\{|\}$/,expression:{pattern:/[\s\S]+/,alias:"language-csharp",inside:J.languages.csharp}}},string:/[\s\S]+/}}J.languages.insertBefore("csharp","string",{"interpolation-string":[{pattern:Q(/(^|[^\\])(?:\$@|@\$)"(?:""|\\[\s\S]|\{\{|<<0>>|[^\\{"])*"/.source,[f]),lookbehind:!0,greedy:!0,inside:h(f,_)},{pattern:Q(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[d]),lookbehind:!0,greedy:!0,inside:h(d,p)}],char:{pattern:RegExp(M),greedy:!0}}),J.languages.dotnet=J.languages.cs=J.languages.csharp})(Prism);(function(J){var Z=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;J.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+Z.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+Z.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+Z.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+Z.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:Z,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},J.languages.css.atrule.inside.rest=J.languages.css;var Q=J.languages.markup;if(Q)Q.tag.addInlined("style","css"),Q.tag.addAttribute("style","css")})(Prism);(function(J){var Z=[/\b(?:async|sync|yield)\*/,/\b(?:abstract|assert|async|await|break|case|catch|class|const|continue|covariant|default|deferred|do|dynamic|else|enum|export|extends|extension|external|factory|final|finally|for|get|hide|if|implements|import|in|interface|library|mixin|new|null|on|operator|part|rethrow|return|set|show|static|super|switch|sync|this|throw|try|typedef|var|void|while|with|yield)\b/],Q=/(^|[^\w.])(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source,Y={pattern:RegExp(Q+/[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}}}};J.languages.dart=J.languages.extend("clike",{"class-name":[Y,{pattern:RegExp(Q+/[A-Z]\w*(?=\s+\w+\s*[;,=()])/.source),lookbehind:!0,inside:Y.inside}],keyword:Z,operator:/\bis!|\b(?:as|is)\b|\+\+|--|&&|\|\||<<=?|>>=?|~(?:\/=?)?|[+\-*\/%&^|=!<>]=?|\?/}),J.languages.insertBefore("dart","string",{"string-literal":{pattern:/r?(?:("""|''')[\s\S]*?\1|(["'])(?:\\.|(?!\2)[^\\\r\n])*\2(?!\2))/,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:\w+|\{(?:[^{}]|\{[^{}]*\})*\})/,lookbehind:!0,inside:{punctuation:/^\$\{?|\}$/,expression:{pattern:/[\s\S]+/,inside:J.languages.dart}}},string:/[\s\S]+/}},string:void 0}),J.languages.insertBefore("dart","class-name",{metadata:{pattern:/@\w+/,alias:"function"}}),J.languages.insertBefore("dart","class-name",{generics:{pattern:/<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,inside:{"class-name":Y,keyword:Z,punctuation:/[<>(),.:]/,operator:/[?&|]/}}})})(Prism);(function(J){var Z=/\\[\r\n](?:\s|\\[\r\n]|#.*(?!.))*(?![\s#]|\\[\r\n])/.source,Q=/(?:[ \t]+(?![ \t])(?:<SP_BS>)?|<SP_BS>)/.source.replace(/<SP_BS>/g,function(){return Z}),Y=/"(?:[^"\\\r\n]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\r\n]|\\(?:\r\n|[\s\S]))*'/.source,X=/--[\w-]+=(?:<STR>|(?!["'])(?:[^\s\\]|\\.)+)/.source.replace(/<STR>/g,function(){return Y}),K={pattern:RegExp(Y),greedy:!0},V={pattern:/(^[ \t]*)#.*/m,lookbehind:!0,greedy:!0};function G(z,F){return z=z.replace(/<OPT>/g,function(){return X}).replace(/<SP>/g,function(){return Q}),RegExp(z,F)}J.languages.docker={instruction:{pattern:/(^[ \t]*)(?:ADD|ARG|CMD|COPY|ENTRYPOINT|ENV|EXPOSE|FROM|HEALTHCHECK|LABEL|MAINTAINER|ONBUILD|RUN|SHELL|STOPSIGNAL|USER|VOLUME|WORKDIR)(?=\s)(?:\\.|[^\r\n\\])*(?:\\$(?:\s|#.*$)*(?![\s#])(?:\\.|[^\r\n\\])*)*/im,lookbehind:!0,greedy:!0,inside:{options:{pattern:G(/(^(?:ONBUILD<SP>)?\w+<SP>)<OPT>(?:<SP><OPT>)*/.source,"i"),lookbehind:!0,greedy:!0,inside:{property:{pattern:/(^|\s)--[\w-]+/,lookbehind:!0},string:[K,{pattern:/(=)(?!["'])(?:[^\s\\]|\\.)+/,lookbehind:!0}],operator:/\\$/m,punctuation:/=/}},keyword:[{pattern:G(/(^(?:ONBUILD<SP>)?HEALTHCHECK<SP>(?:<OPT><SP>)*)(?:CMD|NONE)\b/.source,"i"),lookbehind:!0,greedy:!0},{pattern:G(/(^(?:ONBUILD<SP>)?FROM<SP>(?:<OPT><SP>)*(?!--)[^ \t\\]+<SP>)AS/.source,"i"),lookbehind:!0,greedy:!0},{pattern:G(/(^ONBUILD<SP>)\w+/.source,"i"),lookbehind:!0,greedy:!0},{pattern:/^\w+/,greedy:!0}],comment:V,string:K,variable:/\$(?:\w+|\{[^{}"'\\]*\})/,operator:/\\$/m}},comment:V},J.languages.dockerfile=J.languages.docker})(Prism);Prism.languages.go=Prism.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/});Prism.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}});delete Prism.languages.go["class-name"];Prism.languages.graphql={comment:/#.*/,description:{pattern:/(?:"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*")(?=\s*[a-z_])/i,greedy:!0,alias:"string",inside:{"language-markdown":{pattern:/(^"(?:"")?)(?!\1)[\s\S]+(?=\1$)/,lookbehind:!0,inside:Prism.languages.markdown}}},string:{pattern:/"""(?:[^"]|(?!""")")*"""|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},number:/(?:\B-|\b)\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,boolean:/\b(?:false|true)\b/,variable:/\$[a-z_]\w*/i,directive:{pattern:/@[a-z_]\w*/i,alias:"function"},"attr-name":{pattern:/\b[a-z_]\w*(?=\s*(?:\((?:[^()"]|"(?:\\.|[^\\"\r\n])*")*\))?:)/i,greedy:!0},"atom-input":{pattern:/\b[A-Z]\w*Input\b/,alias:"class-name"},scalar:/\b(?:Boolean|Float|ID|Int|String)\b/,constant:/\b[A-Z][A-Z_\d]*\b/,"class-name":{pattern:/(\b(?:enum|implements|interface|on|scalar|type|union)\s+|&\s*|:\s*|\[)[A-Z_]\w*/,lookbehind:!0},fragment:{pattern:/(\bfragment\s+|\.{3}\s*(?!on\b))[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-mutation":{pattern:/(\bmutation\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},"definition-query":{pattern:/(\bquery\s+)[a-zA-Z_]\w*/,lookbehind:!0,alias:"function"},keyword:/\b(?:directive|enum|extend|fragment|implements|input|interface|mutation|on|query|repeatable|scalar|schema|subscription|type|union)\b/,operator:/[!=|&]|\.{3}/,"property-query":/\w+(?=\s*\()/,object:/\w+(?=\s*\{)/,punctuation:/[!(){}\[\]:=,]/,property:/\w+/};Prism.hooks.add("after-tokenize",function(Z){if(Z.language!=="graphql")return;var Q=Z.tokens.filter(function(B){return typeof B!=="string"&&B.type!=="comment"&&B.type!=="scalar"}),Y=0;function X(B){return Q[Y+B]}function K(B,N){N=N||0;for(var w=0;w<B.length;w++){var L=X(w+N);if(!L||L.type!==B[w])return!1}return!0}function V(B,N){var w=1;for(var L=Y;L<Q.length;L++){var O=Q[L],E=O.content;if(O.type==="punctuation"&&typeof E==="string"){if(B.test(E))w++;else if(N.test(E)){if(w--,w===0)return L}}}return-1}function G(B,N){var w=B.alias;if(!w)B.alias=w=[];else if(!Array.isArray(w))B.alias=w=[w];w.push(N)}for(;Y<Q.length;){var z=Q[Y++];if(z.type==="keyword"&&z.content==="mutation"){var F=[];if(K(["definition-mutation","punctuation"])&&X(1).content==="("){Y+=2;var q=V(/^\($/,/^\)$/);if(q===-1)continue;for(;Y<q;Y++){var W=X(0);if(W.type==="variable")G(W,"variable-input"),F.push(W.content)}Y=q+1}if(K(["punctuation","property-query"])&&X(0).content==="{"){if(Y++,G(X(0),"property-mutation"),F.length>0){var U=V(/^\{$/,/^\}$/);if(U===-1)continue;for(var H=Y;H<U;H++){var D=Q[H];if(D.type==="variable"&&F.indexOf(D.content)>=0)G(D,"variable-input")}}}}}});(function(J){var Z=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,Q=/(?:[a-z]\w*\s*\.\s*)*(?:[A-Z]\w*\s*\.\s*)*/.source,Y={pattern:RegExp(/(^|[^\w.])/.source+Q+/[A-Z](?:[\d_A-Z]*[a-z]\w*)?\b/.source),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}},punctuation:/\./}};J.languages.java=J.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,lookbehind:!0,greedy:!0},"class-name":[Y,{pattern:RegExp(/(^|[^\w.])/.source+Q+/[A-Z]\w*(?=\s+\w+\s*[;,=()]|\s*(?:\[[\s,]*\]\s*)?::\s*new\b)/.source),lookbehind:!0,inside:Y.inside},{pattern:RegExp(/(\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\s+)/.source+Q+/[A-Z]\w*\b/.source),lookbehind:!0,inside:Y.inside}],keyword:Z,function:[J.languages.clike.function,{pattern:/(::\s*)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0},constant:/\b[A-Z][A-Z_\d]+\b/}),J.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"},char:{pattern:/'(?:\\.|[^'\\\r\n]){1,6}'/,greedy:!0}}),J.languages.insertBefore("java","class-name",{annotation:{pattern:/(^|[^.])@\w+(?:\s*\.\s*\w+)*/,lookbehind:!0,alias:"punctuation"},generics:{pattern:/<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,inside:{"class-name":Y,keyword:Z,punctuation:/[<>(),.:]/,operator:/[?&|]/}},import:[{pattern:RegExp(/(\bimport\s+)/.source+Q+/(?:[A-Z]\w*|\*)(?=\s*;)/.source),lookbehind:!0,inside:{namespace:Y.inside.namespace,punctuation:/\./,operator:/\*/,"class-name":/\w+/}},{pattern:RegExp(/(\bimport\s+static\s+)/.source+Q+/(?:\w+|\*)(?=\s*;)/.source),lookbehind:!0,alias:"static",inside:{namespace:Y.inside.namespace,static:/\b\w+$/,punctuation:/\./,operator:/\*/,"class-name":/\w+/}}],namespace:{pattern:RegExp(/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)(?!<keyword>)[a-z]\w*(?:\.[a-z]\w*)*\.?/.source.replace(/<keyword>/g,function(){return Z.source})),lookbehind:!0,inside:{punctuation:/\./}}})})(Prism);Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/});Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/});Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}});Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}});if(Prism.languages.markup)Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript");Prism.languages.js=Prism.languages.javascript;Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}};Prism.languages.webmanifest=Prism.languages.json;(function(J){var Z=J.util.clone(J.languages.javascript),Q=/(?:\s|\/\/.*(?!.)|\/\*(?:[^*]|\*(?!\/))\*\/)/.source,Y=/(?:\{(?:\{(?:\{[^{}]*\}|[^{}])*\}|[^{}])*\})/.source,X=/(?:\{<S>*\.{3}(?:[^{}]|<BRACES>)*\})/.source;function K(z,F){return z=z.replace(/<S>/g,function(){return Q}).replace(/<BRACES>/g,function(){return Y}).replace(/<SPREAD>/g,function(){return X}),RegExp(z,F)}X=K(X).source,J.languages.jsx=J.languages.extend("markup",Z),J.languages.jsx.tag.pattern=K(/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/.source),J.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,J.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,J.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,J.languages.jsx.tag.inside.comment=Z.comment,J.languages.insertBefore("inside","attr-name",{spread:{pattern:K(/<SPREAD>/.source),inside:J.languages.jsx}},J.languages.jsx.tag),J.languages.insertBefore("inside","special-attr",{script:{pattern:K(/=<BRACES>/.source),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:J.languages.jsx}}},J.languages.jsx.tag);var V=function(z){if(!z)return"";if(typeof z==="string")return z;if(typeof z.content==="string")return z.content;return z.content.map(V).join("")},G=function(z){var F=[];for(var q=0;q<z.length;q++){var W=z[q],U=!1;if(typeof W!=="string")if(W.type==="tag"&&W.content[0]&&W.content[0].type==="tag")if(W.content[0].content[0].content==="</"){if(F.length>0&&F[F.length-1].tagName===V(W.content[0].content[1]))F.pop()}else if(W.content[W.content.length-1].content==="/>");else F.push({tagName:V(W.content[0].content[1]),openedBraces:0});else if(F.length>0&&W.type==="punctuation"&&W.content==="{")F[F.length-1].openedBraces++;else if(F.length>0&&F[F.length-1].openedBraces>0&&W.type==="punctuation"&&W.content==="}")F[F.length-1].openedBraces--;else U=!0;if(U||typeof W==="string"){if(F.length>0&&F[F.length-1].openedBraces===0){var H=V(W);if(q<z.length-1&&(typeof z[q+1]==="string"||z[q+1].type==="plain-text"))H+=V(z[q+1]),z.splice(q+1,1);if(q>0&&(typeof z[q-1]==="string"||z[q-1].type==="plain-text"))H=V(z[q-1])+H,z.splice(q-1,1),q--;z[q]=new J.Token("plain-text",H,null,H)}}if(W.content&&typeof W.content!=="string")G(W.content)}};J.hooks.add("after-tokenize",function(z){if(z.language!=="jsx"&&z.language!=="tsx")return;G(z.tokens)})})(Prism);(function(J){J.languages.kotlin=J.languages.extend("clike",{keyword:{pattern:/(^|[^.])\b(?:abstract|actual|annotation|as|break|by|catch|class|companion|const|constructor|continue|crossinline|data|do|dynamic|else|enum|expect|external|final|finally|for|fun|get|if|import|in|infix|init|inline|inner|interface|internal|is|lateinit|noinline|null|object|open|operator|out|override|package|private|protected|public|reified|return|sealed|set|super|suspend|tailrec|this|throw|to|try|typealias|val|var|vararg|when|where|while)\b/,lookbehind:!0},function:[{pattern:/(?:`[^\r\n`]+`|\b\w+)(?=\s*\()/,greedy:!0},{pattern:/(\.)(?:`[^\r\n`]+`|\w+)(?=\s*\{)/,lookbehind:!0,greedy:!0}],number:/\b(?:0[xX][\da-fA-F]+(?:_[\da-fA-F]+)*|0[bB][01]+(?:_[01]+)*|\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?[fFL]?)\b/,operator:/\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/}),delete J.languages.kotlin["class-name"];var Z={"interpolation-punctuation":{pattern:/^\$\{?|\}$/,alias:"punctuation"},expression:{pattern:/[\s\S]+/,inside:J.languages.kotlin}};J.languages.insertBefore("kotlin","string",{"string-literal":[{pattern:/"""(?:[^$]|\$(?:(?!\{)|\{[^{}]*\}))*?"""/,alias:"multiline",inside:{interpolation:{pattern:/\$(?:[a-z_]\w*|\{[^{}]*\})/i,inside:Z},string:/[\s\S]+/}},{pattern:/"(?:[^"\\\r\n$]|\\.|\$(?:(?!\{)|\{[^{}]*\}))*"/,alias:"singleline",inside:{interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$(?:[a-z_]\w*|\{[^{}]*\})/i,lookbehind:!0,inside:Z},string:/[\s\S]+/}}],char:{pattern:/'(?:[^'\\\r\n]|\\(?:.|u[a-fA-F0-9]{0,4}))'/,greedy:!0}}),delete J.languages.kotlin.string,J.languages.insertBefore("kotlin","keyword",{annotation:{pattern:/\B@(?:\w+:)?(?:[A-Z]\w*|\[[^\]]+\])/,alias:"builtin"}}),J.languages.insertBefore("kotlin","function",{label:{pattern:/\b\w+@|@\w+\b/,alias:"symbol"}}),J.languages.kt=J.languages.kotlin,J.languages.kts=J.languages.kotlin})(Prism);Prism.languages.lua={comment:/^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,string:{pattern:/(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[^z]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,greedy:!0},number:/\b0x[a-f\d]+(?:\.[a-f\d]*)?(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|(?:\.\d*)?(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,keyword:/\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,function:/(?!\d)\w+(?=\s*(?:[({]))/,operator:[/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,{pattern:/(^|[^.])\.\.(?!\.)/,lookbehind:!0}],punctuation:/[\[\](){},;]|\.+|:+/};(function(J){var Z=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?![\r\n]))/.source;function Q(q){return q=q.replace(/<inner>/g,function(){return Z}),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+q+")")}var Y=/(?:\\.|``(?:[^`\r\n]|`(?!`))+``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,X=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|(?![\s\S]))/.source.replace(/__/g,function(){return Y}),K=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;J.languages.markdown=J.languages.extend("markup",{}),J.languages.insertBefore("markdown","prolog",{"front-matter-block":{pattern:/(^(?:\s*[\r\n])?)---(?!.)[\s\S]*?[\r\n]---(?!.)/,lookbehind:!0,greedy:!0,inside:{punctuation:/^---|---$/,"front-matter":{pattern:/\S+(?:\s+\S+)*/,alias:["yaml","language-yaml"],inside:J.languages.yaml}}},blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+X+K+"(?:"+X+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+X+K+")(?:"+X+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(Y),inside:J.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+X+")"+K+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+X+"$"),inside:{"table-header":{pattern:RegExp(Y),alias:"important",inside:J.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:Q(/\b__(?:(?!_)<inner>|_(?:(?!_)<inner>)+_)+__\b|\*\*(?:(?!\*)<inner>|\*(?:(?!\*)<inner>)+\*)+\*\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:Q(/\b_(?:(?!_)<inner>|__(?:(?!_)<inner>)+__)+_\b|\*(?:(?!\*)<inner>|\*\*(?:(?!\*)<inner>)+\*\*)+\*/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:Q(/(~~?)(?:(?!~)<inner>)+\2/.source),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},"code-snippet":{pattern:/(^|[^\\`])(?:``[^`\r\n]+(?:`[^`\r\n]+)*``(?!`)|`[^`\r\n]+`(?!`))/,lookbehind:!0,greedy:!0,alias:["code","keyword"]},url:{pattern:Q(/!?\[(?:(?!\])<inner>)+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)|[ \t]?\[(?:(?!\])<inner>)+\])/.source),lookbehind:!0,greedy:!0,inside:{operator:/^!/,content:{pattern:/(^\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},variable:{pattern:/(^\][ \t]?\[)[^\]]+(?=\]$)/,lookbehind:!0},url:{pattern:/(^\]\()[^\s)]+/,lookbehind:!0},string:{pattern:/(^[ \t]+)"(?:\\.|[^"\\])*"(?=\)$)/,lookbehind:!0}}}}),["url","bold","italic","strike"].forEach(function(q){["url","bold","italic","strike","code-snippet"].forEach(function(W){if(q!==W)J.languages.markdown[q].inside.content.inside[W]=J.languages.markdown[W]})}),J.hooks.add("after-tokenize",function(q){if(q.language!=="markdown"&&q.language!=="md")return;function W(U){if(!U||typeof U==="string")return;for(var H=0,D=U.length;H<D;H++){var B=U[H];if(B.type!=="code"){W(B.content);continue}var N=B.content[1],w=B.content[3];if(N&&w&&N.type==="code-language"&&w.type==="code-block"&&typeof N.content==="string"){var L=N.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");L=(/[a-z][\w-]*/i.exec(L)||[""])[0].toLowerCase();var O="language-"+L;if(!w.alias)w.alias=[O];else if(typeof w.alias==="string")w.alias=[w.alias,O];else w.alias.push(O)}}}W(q.tokens)}),J.hooks.add("wrap",function(q){if(q.type!=="code-block")return;var W="";for(var U=0,H=q.classes.length;U<H;U++){var D=q.classes[U],B=/language-(.+)/.exec(D);if(B){W=B[1];break}}var N=J.languages[W];if(!N){if(W&&W!=="none"&&J.plugins.autoloader){var w="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*10000000000000000);q.attributes.id=w,J.plugins.autoloader.loadLanguages(W,function(){var L=document.getElementById(w);if(L)L.innerHTML=J.highlight(L.textContent,J.languages[W],W)})}}else q.content=J.highlight(F(q.content),N,W)});var V=RegExp(J.languages.markup.tag.pattern.source,"gi"),G={amp:"&",lt:"<",gt:">",quot:'"'},z=String.fromCodePoint||String.fromCharCode;function F(q){var W=q.replace(V,"");return W=W.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(U,H){if(H=H.toLowerCase(),H[0]==="#"){var D;if(H[1]==="x")D=parseInt(H.slice(2),16);else D=Number(H.slice(1));return z(D)}else{var B=G[H];if(B)return B;return U}}),W}J.languages.md=J.languages.markdown})(Prism);Prism.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]};Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity;Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup;Prism.hooks.add("wrap",function(J){if(J.type==="entity")J.attributes.title=J.content.replace(/&amp;/,"&")});Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(Z,Q){var Y={};Y["language-"+Q]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:Prism.languages[Q]},Y.cdata=/^<!\[CDATA\[|\]\]>$/i;var X={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:Y}};X["language-"+Q]={pattern:/[\s\S]+/,inside:Prism.languages[Q]};var K={};K[Z]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return Z}),"i"),lookbehind:!0,greedy:!0,inside:X},Prism.languages.insertBefore("markup","cdata",K)}});Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(J,Z){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+J+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[Z,"language-"+Z],inside:Prism.languages[Z]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}});Prism.languages.html=Prism.languages.markup;Prism.languages.mathml=Prism.languages.markup;Prism.languages.svg=Prism.languages.markup;Prism.languages.xml=Prism.languages.extend("markup",{});Prism.languages.ssml=Prism.languages.xml;Prism.languages.atom=Prism.languages.xml;Prism.languages.rss=Prism.languages.xml;(function(J){var Z=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,Q=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],Y=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,X=/<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,K=/[{}\[\](),:;]/;J.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:Z,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:Q,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:Y,operator:X,punctuation:K};var V={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:J.languages.php},G=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:V}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:V}}];J.languages.insertBefore("php","variable",{string:G,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:Z,string:G,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:Q,number:Y,operator:X,punctuation:K}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),J.hooks.add("before-tokenize",function(z){if(!/<\?/.test(z.code))return;var F=/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g;J.languages["markup-templating"].buildPlaceholders(z,"php",F)}),J.hooks.add("after-tokenize",function(z){J.languages["markup-templating"].tokenizePlaceholders(z,"php")})})(Prism);(function(J){var Z=J.languages.powershell={comment:[{pattern:/(^|[^`])<#[\s\S]*?#>/,lookbehind:!0},{pattern:/(^|[^`])#.*/,lookbehind:!0}],string:[{pattern:/"(?:`[\s\S]|[^`"])*"/,greedy:!0,inside:null},{pattern:/'(?:[^']|'')*'/,greedy:!0}],namespace:/\[[a-z](?:\[(?:\[[^\]]*\]|[^\[\]])*\]|[^\[\]])*\]/i,boolean:/\$(?:false|true)\b/i,variable:/\$\w+\b/,function:[/\b(?:Add|Approve|Assert|Backup|Block|Checkpoint|Clear|Close|Compare|Complete|Compress|Confirm|Connect|Convert|ConvertFrom|ConvertTo|Copy|Debug|Deny|Disable|Disconnect|Dismount|Edit|Enable|Enter|Exit|Expand|Export|Find|ForEach|Format|Get|Grant|Group|Hide|Import|Initialize|Install|Invoke|Join|Limit|Lock|Measure|Merge|Move|New|Open|Optimize|Out|Ping|Pop|Protect|Publish|Push|Read|Receive|Redo|Register|Remove|Rename|Repair|Request|Reset|Resize|Resolve|Restart|Restore|Resume|Revoke|Save|Search|Select|Send|Set|Show|Skip|Sort|Split|Start|Step|Stop|Submit|Suspend|Switch|Sync|Tee|Test|Trace|Unblock|Undo|Uninstall|Unlock|Unprotect|Unpublish|Unregister|Update|Use|Wait|Watch|Where|Write)-[a-z]+\b/i,/\b(?:ac|cat|chdir|clc|cli|clp|clv|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|ebp|echo|epal|epcsv|epsn|erase|fc|fl|ft|fw|gal|gbp|gc|gci|gcs|gdr|gi|gl|gm|gp|gps|group|gsv|gu|gv|gwmi|iex|ii|ipal|ipcsv|ipsn|irm|iwmi|iwr|kill|lp|ls|measure|mi|mount|move|mp|mv|nal|ndr|ni|nv|ogv|popd|ps|pushd|pwd|rbp|rd|rdr|ren|ri|rm|rmdir|rni|rnp|rp|rv|rvpa|rwmi|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls|sort|sp|spps|spsv|start|sv|swmi|tee|trcm|type|write)\b/i],keyword:/\b(?:Begin|Break|Catch|Class|Continue|Data|Define|Do|DynamicParam|Else|ElseIf|End|Exit|Filter|Finally|For|ForEach|From|Function|If|InlineScript|Parallel|Param|Process|Return|Sequence|Switch|Throw|Trap|Try|Until|Using|Var|While|Workflow)\b/i,operator:{pattern:/(^|\W)(?:!|-(?:b?(?:and|x?or)|as|(?:Not)?(?:Contains|In|Like|Match)|eq|ge|gt|is(?:Not)?|Join|le|lt|ne|not|Replace|sh[lr])\b|-[-=]?|\+[+=]?|[*\/%]=?)/i,lookbehind:!0},punctuation:/[|{}[\];(),.]/};Z.string[0].inside={function:{pattern:/(^|[^`])\$\((?:\$\([^\r\n()]*\)|(?!\$\()[^\r\n)])*\)/,lookbehind:!0,inside:Z},boolean:Z.boolean,variable:Z.variable}})(Prism);Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/};Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python;Prism.languages.py=Prism.languages.python;Prism.languages.r={comment:/#.*/,string:{pattern:/(['"])(?:\\.|(?!\1)[^\\\r\n])*\1/,greedy:!0},"percent-operator":{pattern:/%[^%\s]*%/,alias:"operator"},boolean:/\b(?:FALSE|TRUE)\b/,ellipsis:/\.\.(?:\.|\d+)/,number:[/\b(?:Inf|NaN)\b/,/(?:\b0x[\dA-Fa-f]+(?:\.\d*)?|\b\d+(?:\.\d*)?|\B\.\d+)(?:[EePp][+-]?\d+)?[iL]?/],keyword:/\b(?:NA|NA_character_|NA_complex_|NA_integer_|NA_real_|NULL|break|else|for|function|if|in|next|repeat|while)\b/,operator:/->?>?|<(?:=|<?-)?|[>=!]=?|::?|&&?|\|\|?|[+*\/^$@~]/,punctuation:/[(){}\[\],;]/};(function(J){J.languages.ruby=J.languages.extend("clike",{comment:{pattern:/#.*|^=begin\s[\s\S]*?^=end/m,greedy:!0},"class-name":{pattern:/(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,operator:/\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,punctuation:/[(){}[\].,;]/}),J.languages.insertBefore("ruby","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}});var Z={pattern:/((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,lookbehind:!0,inside:{content:{pattern:/^(#\{)[\s\S]+(?=\}$)/,lookbehind:!0,inside:J.languages.ruby},delimiter:{pattern:/^#\{|\}$/,alias:"punctuation"}}};delete J.languages.ruby.function;var Q="(?:"+[/([^a-zA-Z0-9\s{(\[<=])(?:(?!\1)[^\\]|\\[\s\S])*\1/.source,/\((?:[^()\\]|\\[\s\S]|\((?:[^()\\]|\\[\s\S])*\))*\)/.source,/\{(?:[^{}\\]|\\[\s\S]|\{(?:[^{}\\]|\\[\s\S])*\})*\}/.source,/\[(?:[^\[\]\\]|\\[\s\S]|\[(?:[^\[\]\\]|\\[\s\S])*\])*\]/.source,/<(?:[^<>\\]|\\[\s\S]|<(?:[^<>\\]|\\[\s\S])*>)*>/.source].join("|")+")",Y=/(?:"(?:\\.|[^"\\\r\n])*"|(?:\b[a-zA-Z_]\w*|[^\s\0-\x7F]+)[?!]?|\$.)/.source;J.languages.insertBefore("ruby","keyword",{"regex-literal":[{pattern:RegExp(/%r/.source+Q+/[egimnosux]{0,6}/.source),greedy:!0,inside:{interpolation:Z,regex:/[\s\S]+/}},{pattern:/(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,lookbehind:!0,greedy:!0,inside:{interpolation:Z,regex:/[\s\S]+/}}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:[{pattern:RegExp(/(^|[^:]):/.source+Y),lookbehind:!0,greedy:!0},{pattern:RegExp(/([\r\n{(,][ \t]*)/.source+Y+/(?=:(?!:))/.source),lookbehind:!0,greedy:!0}],"method-definition":{pattern:/(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,lookbehind:!0,inside:{function:/\b\w+$/,keyword:/^self\b/,"class-name":/^\w+/,punctuation:/\./}}}),J.languages.insertBefore("ruby","string",{"string-literal":[{pattern:RegExp(/%[qQiIwWs]?/.source+Q),greedy:!0,inside:{interpolation:Z,string:/[\s\S]+/}},{pattern:/("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,greedy:!0,inside:{interpolation:Z,string:/[\s\S]+/}},{pattern:/<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?/}},interpolation:Z,string:/[\s\S]+/}},{pattern:/<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?'|'$/}},string:/[\s\S]+/}}],"command-literal":[{pattern:RegExp(/%x/.source+Q),greedy:!0,inside:{interpolation:Z,command:{pattern:/[\s\S]+/,alias:"string"}}},{pattern:/`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,greedy:!0,inside:{interpolation:Z,command:{pattern:/[\s\S]+/,alias:"string"}}}]}),delete J.languages.ruby.string,J.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,constant:/\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/}),J.languages.rb=J.languages.ruby})(Prism);(function(J){var Z=/\/\*(?:[^*/]|\*(?!\/)|\/(?!\*)|<self>)*\*\//.source;for(var Q=0;Q<2;Q++)Z=Z.replace(/<self>/g,function(){return Z});Z=Z.replace(/<self>/g,function(){return/[^\s\S]/.source}),J.languages.rust={comment:[{pattern:RegExp(/(^|[^\\])/.source+Z),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},J.languages.rust["closure-params"].inside.rest=J.languages.rust,J.languages.rust.attribute.inside.string=J.languages.rust.string})(Prism);Prism.languages.scss=Prism.languages.extend("css",{comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,lookbehind:!0},atrule:{pattern:/@[\w-](?:\([^()]+\)|[^()\s]|\s+(?!\s))*?(?=\s+[{;])/,inside:{rule:/@[\w-]+/}},url:/(?:[-a-z]+-)?url(?=\()/i,selector:{pattern:/(?=\S)[^@;{}()]?(?:[^@;{}()\s]|\s+(?!\s)|#\{\$[-\w]+\})+(?=\s*\{(?:\}|\s|[^}][^:{}]*[:{][^}]))/,inside:{parent:{pattern:/&/,alias:"important"},placeholder:/%[-\w]+/,variable:/\$[-\w]+|#\{\$[-\w]+\}/}},property:{pattern:/(?:[-\w]|\$[-\w]|#\{\$[-\w]+\})+(?=\s*:)/,inside:{variable:/\$[-\w]+|#\{\$[-\w]+\}/}}});Prism.languages.insertBefore("scss","atrule",{keyword:[/@(?:content|debug|each|else(?: if)?|extend|for|forward|function|if|import|include|mixin|return|use|warn|while)\b/i,{pattern:/( )(?:from|through)(?= )/,lookbehind:!0}]});Prism.languages.insertBefore("scss","important",{variable:/\$[-\w]+|#\{\$[-\w]+\}/});Prism.languages.insertBefore("scss","function",{"module-modifier":{pattern:/\b(?:as|hide|show|with)\b/i,alias:"keyword"},placeholder:{pattern:/%[-\w]+/,alias:"selector"},statement:{pattern:/\B!(?:default|optional)\b/i,alias:"keyword"},boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"},operator:{pattern:/(\s)(?:[-+*\/%]|[=!]=|<=?|>=?|and|not|or)(?=\s)/,lookbehind:!0}});Prism.languages.scss.atrule.inside.rest=Prism.languages.scss;(function(J){var Z=[/"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/.source,/'[^']*'/.source,/\$'(?:[^'\\]|\\[\s\S])*'/.source,/<<-?\s*(["']?)(\w+)\1\s[\s\S]*?[\r\n]\2/.source].join("|");J.languages["shell-session"]={command:{pattern:RegExp(/^/.source+"(?:"+(/[^\s@:$#%*!/\\]+@[^\r\n@:$#%*!/\\]+(?::[^\0-\x1F$#%*?"<>:;|]+)?/.source+"|"+/[/~.][^\0-\x1F$#%*?"<>@:;|]*/.source)+")?"+/[$#%](?=\s)/.source+/(?:[^\\\r\n \t'"<$]|[ \t](?:(?!#)|#.*$)|\\(?:[^\r]|\r\n?)|\$(?!')|<(?!<)|<<str>>)+/.source.replace(/<<str>>/g,function(){return Z}),"m"),greedy:!0,inside:{info:{pattern:/^[^#$%]+/,alias:"punctuation",inside:{user:/^[^\s@:$#%*!/\\]+@[^\r\n@:$#%*!/\\]+/,punctuation:/:/,path:/[\s\S]+/}},bash:{pattern:/(^[$#%]\s*)\S[\s\S]*/,lookbehind:!0,alias:"language-bash",inside:J.languages.bash},"shell-symbol":{pattern:/^[$#%]/,alias:"important"}}},output:/.(?:.*(?:[\r\n]|.$))*/},J.languages["sh-session"]=J.languages.shellsession=J.languages["shell-session"]})(Prism);Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/};Prism.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp(/(^|[^"#])/.source+"(?:"+/"(?:\\(?:\((?:[^()]|\([^()]*\))*\)|\r\n|[^(])|[^\\\r\n"])*"/.source+"|"+/"""(?:\\(?:\((?:[^()]|\([^()]*\))*\)|[^(])|[^\\"]|"(?!""))*"""/.source+")"+/(?!["#])/.source),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp(/(^|[^"#])(#+)/.source+"(?:"+/"(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|\r\n|[^#])|[^\\\r\n])*?"/.source+"|"+/"""(?:\\(?:#+\((?:[^()]|\([^()]*\))*\)|[^#])|[^\\])*?"""/.source+")\\2"),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp(/#/.source+"(?:"+(/(?:elseif|if)\b/.source+"(?:[ \t]*"+/(?:![ \t]*)?(?:\b\w+\b(?:[ \t]*\((?:[^()]|\([^()]*\))*\))?|\((?:[^()]|\([^()]*\))*\))(?:[ \t]*(?:&&|\|\|))?/.source+")+")+"|"+/(?:else|endif)\b/.source+")"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/};Prism.languages.swift["string-literal"].forEach(function(J){J.inside.interpolation.inside=Prism.languages.swift});(function(J){var Z=/(?:[\w-]+|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*")/.source;function Q(Y){return Y.replace(/__/g,function(){return Z})}J.languages.toml={comment:{pattern:/#.*/,greedy:!0},table:{pattern:RegExp(Q(/(^[\t ]*\[\s*(?:\[\s*)?)__(?:\s*\.\s*__)*(?=\s*\])/.source),"m"),lookbehind:!0,greedy:!0,alias:"class-name"},key:{pattern:RegExp(Q(/(^[\t ]*|[{,]\s*)__(?:\s*\.\s*__)*(?=\s*=)/.source),"m"),lookbehind:!0,greedy:!0,alias:"property"},string:{pattern:/"""(?:\\[\s\S]|[^\\])*?"""|'''[\s\S]*?'''|'[^'\n\r]*'|"(?:\\.|[^\\"\r\n])*"/,greedy:!0},date:[{pattern:/\b\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?\b/i,alias:"number"},{pattern:/\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/,alias:"number"}],number:/(?:\b0(?:x[\da-zA-Z]+(?:_[\da-zA-Z]+)*|o[0-7]+(?:_[0-7]+)*|b[10]+(?:_[10]+)*))\b|[-+]?\b\d+(?:_\d+)*(?:\.\d+(?:_\d+)*)?(?:[eE][+-]?\d+(?:_\d+)*)?\b|[-+]?\b(?:inf|nan)\b/,boolean:/\b(?:false|true)\b/,punctuation:/[.,=[\]{}]/}})(Prism);(function(J){var Z=J.util.clone(J.languages.typescript);J.languages.tsx=J.languages.extend("jsx",Z),delete J.languages.tsx.parameter,delete J.languages.tsx["literal-property"];var Q=J.languages.tsx.tag;Q.pattern=RegExp(/(^|[^\w$]|(?=<\/))/.source+"(?:"+Q.pattern.source+")",Q.pattern.flags),Q.lookbehind=!0})(Prism);(function(J){J.languages.typescript=J.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),J.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete J.languages.typescript.parameter,delete J.languages.typescript["literal-property"];var Z=J.languages.extend("typescript",{});delete Z["class-name"],J.languages.typescript["class-name"].inside=Z,J.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:Z}}}}),J.languages.ts=J.languages.typescript})(Prism);(function(J){function Z(K,V){if(J.languages[K])J.languages.insertBefore(K,"comment",{"doc-comment":V})}var Q=J.languages.markup.tag,Y={pattern:/\/\/\/.*/,greedy:!0,alias:"comment",inside:{tag:Q}},X={pattern:/'''.*/,greedy:!0,alias:"comment",inside:{tag:Q}};Z("csharp",Y),Z("fsharp",Y),Z("vbnet",X)})(Prism);(function(J){var Z=/[*&][^\s[\]{},]+/,Q=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,Y="(?:"+Q.source+"(?:[ \t]+"+Z.source+")?|"+Z.source+"(?:[ \t]+"+Q.source+")?)",X=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),K=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function V(G,z){z=(z||"").replace(/m/g,"")+"m";var F=/([:\-,[{]\s*(?:\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\]|\}|(?:[\r\n]\s*)?#))/.source.replace(/<<prop>>/g,function(){return Y}).replace(/<<value>>/g,function(){return G});return RegExp(F,z)}J.languages.yaml={scalar:{pattern:RegExp(/([\-:]\s*(?:\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\S[^\r\n]*(?:\2[^\r\n]+)*)/.source.replace(/<<prop>>/g,function(){return Y})),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp(/((?:^|[:\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\s*:\s)/.source.replace(/<<prop>>/g,function(){return Y}).replace(/<<key>>/g,function(){return"(?:"+X+"|"+K+")"})),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:V(/\d{4}-\d\d?-\d\d?(?:[tT]|[ \t]+)\d\d?:\d{2}:\d{2}(?:\.\d*)?(?:[ \t]*(?:Z|[-+]\d\d?(?::\d{2})?))?|\d{4}-\d{2}-\d{2}|\d\d?:\d{2}(?::\d{2}(?:\.\d*)?)?/.source),lookbehind:!0,alias:"number"},boolean:{pattern:V(/false|true/.source,"i"),lookbehind:!0,alias:"important"},null:{pattern:V(/null|~/.source,"i"),lookbehind:!0,alias:"important"},string:{pattern:V(K),lookbehind:!0,greedy:!0},number:{pattern:V(/[+-]?(?:0x[\da-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/.source,"i"),lookbehind:!0},tag:Q,important:Z,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},J.languages.yml=J.languages.yaml})(Prism);(function(J){function Z(z){return function(){return z}}var Q=/\b(?:align|allowzero|and|anyframe|anytype|asm|async|await|break|cancel|catch|comptime|const|continue|defer|else|enum|errdefer|error|export|extern|fn|for|if|inline|linksection|nakedcc|noalias|nosuspend|null|or|orelse|packed|promise|pub|resume|return|stdcallcc|struct|suspend|switch|test|threadlocal|try|undefined|union|unreachable|usingnamespace|var|volatile|while)\b/,Y="\\b(?!"+Q.source+")(?!\\d)\\w+\\b",X=/align\s*\((?:[^()]|\([^()]*\))*\)/.source,K=/(?:\?|\bpromise->|(?:\[[^[\]]*\]|\*(?!\*)|\*\*)(?:\s*<ALIGN>|\s*const\b|\s*volatile\b|\s*allowzero\b)*)/.source.replace(/<ALIGN>/g,Z(X)),V=/(?:\bpromise\b|(?:\berror\.)?<ID>(?:\.<ID>)*(?!\s+<ID>))/.source.replace(/<ID>/g,Z(Y)),G="(?!\\s)(?:!?\\s*(?:"+K+"\\s*)*"+V+")+";J.languages.zig={comment:[{pattern:/\/\/[/!].*/,alias:"doc-comment"},/\/{2}.*/],string:[{pattern:/(^|[^\\@])c?"(?:[^"\\\r\n]|\\.)*"/,lookbehind:!0,greedy:!0},{pattern:/([\r\n])([ \t]+c?\\{2}).*(?:(?:\r\n?|\n)\2.*)*/,lookbehind:!0,greedy:!0}],char:{pattern:/(^|[^\\])'(?:[^'\\\r\n]|[\uD800-\uDFFF]{2}|\\(?:.|x[a-fA-F\d]{2}|u\{[a-fA-F\d]{1,6}\}))'/,lookbehind:!0,greedy:!0},builtin:/\B@(?!\d)\w+(?=\s*\()/,label:{pattern:/(\b(?:break|continue)\s*:\s*)\w+\b|\b(?!\d)\w+\b(?=\s*:\s*(?:\{|while\b))/,lookbehind:!0},"class-name":[/\b(?!\d)\w+(?=\s*=\s*(?:(?:extern|packed)\s+)?(?:enum|struct|union)\s*[({])/,{pattern:RegExp(/(:\s*)<TYPE>(?=\s*(?:<ALIGN>\s*)?[=;,)])|<TYPE>(?=\s*(?:<ALIGN>\s*)?\{)/.source.replace(/<TYPE>/g,Z(G)).replace(/<ALIGN>/g,Z(X))),lookbehind:!0,inside:null},{pattern:RegExp(/(\)\s*)<TYPE>(?=\s*(?:<ALIGN>\s*)?;)/.source.replace(/<TYPE>/g,Z(G)).replace(/<ALIGN>/g,Z(X))),lookbehind:!0,inside:null}],"builtin-type":{pattern:/\b(?:anyerror|bool|c_u?(?:int|long|longlong|short)|c_longdouble|c_void|comptime_(?:float|int)|f(?:16|32|64|128)|[iu](?:8|16|32|64|128|size)|noreturn|type|void)\b/,alias:"keyword"},keyword:Q,function:/\b(?!\d)\w+(?=\s*\()/,number:/\b(?:0b[01]+|0o[0-7]+|0x[a-fA-F\d]+(?:\.[a-fA-F\d]*)?(?:[pP][+-]?[a-fA-F\d]+)?|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)\b/,boolean:/\b(?:false|true)\b/,operator:/\.[*?]|\.{2,3}|[-=]>|\*\*|\+\+|\|\||(?:<<|>>|[-+*]%|[-+*/%^&|<>!=])=?|[?~]/,punctuation:/[.:,;(){}[\]]/},J.languages.zig["class-name"].forEach(function(z){if(z.inside===null)z.inside=J.languages.zig})})(Prism);function sY3(J){let Z=J.split(".").pop()?.toLowerCase()||"";return{js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",javascript:"javascript",ts:"typescript",tsx:"typescript",typescript:"typescript",py:"python",pyw:"python",python:"python",java:"java",c:"c",h:"c",cc:"cpp",cpp:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hh:"cpp",hxx:"cpp",cs:"csharp",csharp:"csharp",go:"go",golang:"go",rs:"rust",rust:"rust",rb:"ruby",ruby:"ruby",php:"php",swift:"swift",kt:"kotlin",kts:"kotlin",kotlin:"kotlin",dart:"dart",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",sql:"sql",json:"json",yaml:"yaml",yml:"yaml",md:"markdown",markdown:"markdown",zig:"zig",pas:"pascal",pascal:"pascal",html:"markup",htm:"markup",xml:"markup",svg:"markup",markup:"markup",css:"css"}[Z]||"plain"}function tY3(J,Z){switch(J.split(" ")[0]){case"keyword":case"important":case"atrule":return Z.keyword;case"string":case"char":case"regex":case"url":case"selector":case"attr-value":case"inserted":return Z.string;case"number":case"constant":case"boolean":case"symbol":return Z.number;case"comment":case"prolog":case"doctype":case"cdata":return Z.comment;case"function":case"class":return Z.function;case"variable":case"property":case"attr-name":case"class-name":return Z.variable;case"type":case"tag":return Z.type;case"operator":case"punctuation":case"delimiter":case"entity":case"builtin":case"deleted":return Z.operator;default:return Z.operator}}var uX0="unknown",E_4;function bX0(J,Z){uX0=J,E_4=Z}function Tw(){return uX0}function M_4(){return E_4}function A_4(J,Z,Q){if(uX0==="unknown")return null;if(J.type!=="rgb"||Z.type!=="rgb")return null;let Y=uX0==="light"?0.15:0.12,X=(K)=>{if(K.type==="rgb")return{...K,alpha:Y};if(K.type==="index")return{...K,alpha:Y};return{type:"default",alpha:Y}};return{added:X(J),removed:X(Z)}}function eY3(J,Z,Q){let Y=[];function X(K,V){if(typeof K==="string")Y.push({content:K,color:V});else{let G=V??tY3(K.type,Z);if(typeof K.content==="string")Y.push({content:K.content,color:G});else if(Array.isArray(K.content))K.content.forEach((z)=>X(z,G));else X(K.content,G)}}return J.forEach((K)=>X(K,Q)),Y}function Sw(J,Z,Q){try{let Y=Q?sY3(Q):"plain";if(Y==="plain"||!Eq.default.languages[Y])return[{content:J}];let X=Eq.default.tokenize(J,Eq.default.languages[Y]);return eY3(X,Z)}catch(Y){return[{content:J}]}}var gX0=4,M0={default(J){return J!==void 0?{type:"default",alpha:J}:{type:"default"}},index(J,Z){return Z!==void 0?{type:"index",value:J,alpha:Z}:{type:"index",value:J}},rgb(J,Z,Q,Y){return Y!==void 0?{type:"rgb",value:{r:J,g:Z,b:Q},alpha:Y}:{type:"rgb",value:{r:J,g:Z,b:Q}}},none(){return{type:"none"}},black:{type:"index",value:0},red:{type:"index",value:1},green:{type:"index",value:2},yellow:{type:"index",value:3},blue:{type:"index",value:4},magenta:{type:"index",value:5},cyan:{type:"index",value:6},white:{type:"index",value:7},brightWhite:{type:"index",value:15}};function F6(J=" ",Z={},Q=1,Y){return{char:J,style:{...Z},width:Q,hyperlink:Y}}var kw=F6(" ",{});function $X3(J,Z){return J.char===Z.char&&J.width===Z.width&&JX3(J.style,Z.style)&&mX0(J.hyperlink,Z.hyperlink)}function JX3(J,Z){return j_4(J.fg,Z.fg)&&j_4(J.bg,Z.bg)&&J.bold===Z.bold&&J.italic===Z.italic&&J.underline===Z.underline&&J.strikethrough===Z.strikethrough&&J.reverse===Z.reverse&&J.dim===Z.dim}function mX0(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;return J.uri===Z.uri&&J.id===Z.id}function Bn(J){if(J.type==="none")return;return J.alpha}function j_4(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;if(J.type!==Z.type)return!1;if(Bn(J)!==Bn(Z))return!1;switch(J.type){case"none":return!0;case"default":return!0;case"index":return Z.value===J.value;case"rgb":{let Q=Z.value;return Q.r===J.value.r&&Q.g===J.value.g&&Q.b===J.value.b}default:return!1}}function Jr0(J,Z){switch(J.type){case"rgb":return J.value;case"index":return Z?.[J.value]??null;case"default":return null;default:return null}}function hX0(J,Z,Q){if(J.type==="none")return Z;if(Z.type==="none"){let F=J.alpha??1;if(F>=1)return J;let q=M_4(),W=Tw(),U=q??(W==="light"?{r:255,g:255,b:255}:{r:0,g:0,b:0}),H=Jr0(J,Q);if(!H)return J;let D=Math.round(H.r*F+U.r*(1-F)),B=Math.round(H.g*F+U.g*(1-F)),N=Math.round(H.b*F+U.b*(1-F));return{type:"rgb",value:{r:Math.max(0,Math.min(255,D)),g:Math.max(0,Math.min(255,B)),b:Math.max(0,Math.min(255,N))}}}let Y=J.alpha??1;if(Y>=1)return J;if(Y<=0)return Z;let X=Jr0(J,Q),K=Jr0(Z,Q);if(!X||!K)return Y>0.5?J:Z;let V=Math.round(X.r*Y+K.r*(1-Y)),G=Math.round(X.g*Y+K.g*(1-Y)),z=Math.round(X.b*Y+K.b*(1-Y));return{type:"rgb",value:{r:Math.max(0,Math.min(255,V)),g:Math.max(0,Math.min(255,G)),b:Math.max(0,Math.min(255,z))}}}function ZX3(J,Z,Q,Y,X){let K={...Z};if(J.fg)if(Z.fg)K.fg=hX0(J.fg,Z.fg,X);else K.fg=hX0(J.fg,Y,X);if(J.bg){let V=Bn(J.bg);if(J.bg.type==="none"||V===0){if(Z.bg)K.bg=Z.bg}else if(Z.bg)K.bg=hX0(J.bg,Z.bg,X);else K.bg=hX0(J.bg,Q,X)}if(J.bold!==void 0)K.bold=J.bold;if(J.italic!==void 0)K.italic=J.italic;if(J.underline!==void 0)K.underline=J.underline;if(J.strikethrough!==void 0)K.strikethrough=J.strikethrough;if(J.reverse!==void 0)K.reverse=J.reverse;if(J.dim!==void 0)K.dim=J.dim;return K}class Zr0{cells;width;height;indexToRgb=[];defaultBg=M0.default();defaultFg=M0.default();constructor(J,Z){this.width=J,this.height=Z,this.cells=[],this.resize(J,Z)}setDefaultColors(J,Z){this.defaultBg=J,this.defaultFg=Z}setIndexRgbMapping(J){this.indexToRgb=J}getSize(){return{width:this.width,height:this.height}}resize(J,Z){this.width=J,this.height=Z,this.cells=Array(Z).fill(null).map(()=>Array(J).fill(null).map(()=>kw))}getCell(J,Z){if(J<0||J>=this.width||Z<0||Z>=this.height)return null;return this.cells[Z]?.[J]||null}setCell(J,Z,Q){if(J<0||J>=this.width||Z<0||Z>=this.height)return;let Y=Q.style.fg?Bn(Q.style.fg):void 0,X=Q.style.bg?Bn(Q.style.bg):void 0;if(Y!==void 0&&Y<1||X!==void 0&&X<1){let V=this.cells[Z]?.[J]||kw,G=ZX3(Q.style,V.style,this.defaultBg,this.defaultFg,this.indexToRgb);if(this.cells[Z])this.cells[Z][J]={char:Q.char,style:G,width:Q.width}}else if(this.cells[Z])this.cells[Z][J]={...Q,style:{...Q.style}};if(Q.width>1){for(let V=1;V<Q.width;V++)if(J+V<this.width&&this.cells[Z])this.cells[Z][J+V]=F6(" ",Q.style,1)}}setChar(J,Z,Q,Y,X){this.setCell(J,Z,F6(Q,Y,X))}clear(){for(let J=0;J<this.height;J++)for(let Z=0;Z<this.width;Z++){let Q=this.cells[J];if(Q)Q[Z]=kw}}fill(J,Z,Q,Y,X=" ",K={}){let V=F6(X,K);for(let G=0;G<Y;G++)for(let z=0;z<Q;z++)this.setCell(J+z,Z+G,V)}copyTo(J){let{width:Z,height:Q}=J.getSize();for(let Y=0;Y<Math.min(this.height,Q);Y++)for(let X=0;X<Math.min(this.width,Z);X++){let K=this.getCell(X,Y);if(K)J.setCell(X,Y,K)}}getCells(){return this.cells.map((J)=>J.map((Z)=>({...Z,style:{...Z.style}})))}getCellRows(){return this.cells}setCursor(J,Z){}clearCursor(){}setCursorShape(J){}markForRefresh(){}}class EH{frontBuffer;backBuffer;width;height;needsFullRefresh=!1;cursorPosition=null;cursorVisible=!1;cursorShape=0;constructor(J=80,Z=24){this.width=J,this.height=Z,this.frontBuffer=new Zr0(J,Z),this.backBuffer=new Zr0(J,Z)}getSize(){return{width:this.width,height:this.height}}resize(J,Z){this.width=J,this.height=Z,this.frontBuffer.resize(J,Z),this.backBuffer.resize(J,Z)}getBuffer(){return this.backBuffer}setDefaultColors(J,Z){this.frontBuffer.setDefaultColors(J,Z),this.backBuffer.setDefaultColors(J,Z)}setIndexRgbMapping(J){this.frontBuffer.setIndexRgbMapping(J),this.backBuffer.setIndexRgbMapping(J)}getCell(J,Z){return this.backBuffer.getCell(J,Z)}setCell(J,Z,Q){this.backBuffer.setCell(J,Z,Q)}setChar(J,Z,Q,Y,X){this.backBuffer.setChar(J,Z,Q,Y,X)}clear(){this.backBuffer.clear()}fill(J,Z,Q,Y,X=" ",K={}){this.backBuffer.fill(J,Z,Q,Y,X,K)}present(){let J=this.frontBuffer;this.frontBuffer=this.backBuffer,this.backBuffer=J}getDiff(){let J=[],Z=this.frontBuffer.getCellRows(),Q=this.backBuffer.getCellRows();if(this.needsFullRefresh){for(let Y=0;Y<this.height;Y++){let X=Q[Y];if(!X)continue;for(let K=0;K<this.width;K++){let V=X[K]??kw;if(J.push({x:K,y:Y,cell:V}),V.width>1)K+=V.width-1}}return this.needsFullRefresh=!1,J}for(let Y=0;Y<this.height;Y++){let X=Z[Y],K=Q[Y];if(!X||!K)continue;for(let V=0;V<this.width;V++){let G=X[V]??kw,z=K[V]??kw;if(G===kw&&z===kw)continue;if(!$X3(G,z)){if(J.push({x:V,y:Y,cell:z}),z.width>1)V+=z.width-1}else if(z.width>1)V+=z.width-1}}return J}getFrontBuffer(){return this.frontBuffer}getBackBuffer(){return this.backBuffer}markForRefresh(){this.needsFullRefresh=!0}get requiresFullRefresh(){return this.needsFullRefresh}setCursor(J,Z){this.cursorPosition={x:J,y:Z},this.cursorVisible=!0}setCursorPositionHint(J,Z){this.cursorPosition={x:J,y:Z}}clearCursor(){this.cursorPosition=null,this.cursorVisible=!1}getCursor(){return this.cursorPosition}isCursorVisible(){return this.cursorVisible}setCursorShape(J){this.cursorShape=J}getCursorShape(){return this.cursorShape}}var QX3=0;function YX3(){return`amp-${++QX3}`}function pX0(J,Z){return{uri:J,id:Z??YX3()}}function R_4(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function dX0(){return"\x1B]8;;\x1B\\"}class Nn{parts=[];append(...J){this.parts.push(...J)}toString(){return this.parts.join("")}reset(){this.parts.length=0}get length(){return this.parts.length}get isEmpty(){return this.parts.length===0}}var MH="\x1B",M6="\x1B[",I_4=M6+"0m",XX3=M6+"m",P_4=(J,Z)=>M6+`${J+1};${Z+1}H`,KX3=M6+"H",VX3=M6+"?25l",GX3=M6+"?25h",zX3=M6+"2J",FX3=M6+"?2026h",qX3=M6+"?2026l",WX3=M6+"?2004h",UX3=M6+"?2004l",C_4=[...Array.from({length:216},(J,Z)=>{let Q=Math.floor(Z/36),Y=Math.floor(Z%36/6),X=Z%6,K=(V)=>V===0?0:55+V*40;return[K(Q),K(Y),K(X)]}),...Array.from({length:24},(J,Z)=>{let Q=8+Z*10;return[Q,Q,Q]})],__4=new Map;function wn(J,Z,Q){let Y=`${J},${Z},${Q}`,X=__4.get(Y);if(X!==void 0)return X;let K=16,V=1/0;for(let G=0;G<C_4.length;G++){let[z,F,q]=C_4[G],W=(J-z)**2+(Z-F)**2+(Q-q)**2;if(W<V)V=W,K=G+16}return __4.set(Y,K),K}var HX3=M6+"?1049h",DX3=M6+"?1049l",BX3=M6+"?1002h"+M6+"?1003h"+M6+"?1004h"+M6+"?1006h",NX3=M6+"?1002l"+M6+"?1003l"+M6+"?1004l"+M6+"?1006l",wX3=M6+"?1016h",LX3=M6+"?1016l",OX3=M6+"?2027h",EX3=M6+"?2027l",MX3=M6+"?2048h",AX3=M6+"?2048l",jX3=M6+">5u",RX3=M6+"<u",IX3=M6+">4;1m",PX3=M6+">4;0m",CX3=(J)=>MH+`]22;${J}`+MH+"\\",_X3=(J)=>MH+`]0;${J}\x07`;function TX3(J){if(J==="\t")return!1;let Z=J.codePointAt(0);if(Z===void 0)return!1;if(Z>=0&&Z<=8||Z>=10&&Z<=31||Z===127)return!0;if(Z>=128&&Z<=159)return!0;if(Z===8232||Z===8233)return!0;if(Z===65279)return!0;return!1}function SX3(J){let Z=J.codePointAt(0);if(Z===void 0)return"�";if(Z>=0&&Z<=31)return String.fromCodePoint(9216+Z);if(Z===127)return"␡";return"�"}var kX3=MH+"]9;4;3"+MH+"\\",S_4=MH+"]9;4;0"+MH+"\\",yX3=MH+"]9;4;4"+MH+"\\",vX3=(J)=>M6+`${J} q`;function xX3(J){return BX3+(J?wX3:"")}function fX3(){return NX3+LX3}function lX0(J){return _X3(J)}function k_4(){return S_4}function T_4(J,Z,Q){if(!J)return"";switch(J.type){case"none":return"";case"default":return M6+(Z?"39":"49")+"m";case"index":return M6+`${Z?"38":"48"};5;${J.value}m`;case"rgb":{if(Q&&!Q.canRgb){let{r:G,g:z,b:F}=J.value,q=wn(G,z,F);return M6+`${Z?"38":"48"};5;${q}m`}let Y=Z?"38":"48",{r:X,g:K,b:V}=J.value;return M6+`${Y};2;${X};${K};${V}m`}default:return""}}function uX3(J,Z,Q){let Y="";if(!cX0(J.fg,Z.fg)){if(J.fg===void 0&&Z.fg!==void 0)Y+=M6+"39m";else Y+=T_4(J.fg,!0,Q);Z.fg=J.fg}if(!cX0(J.bg,Z.bg)){let X=J.bg?.type==="none",K=Z.bg?.type==="none";if((J.bg===void 0||X)&&Z.bg!==void 0&&!K)Y+=M6+"49m";else if(!X)Y+=T_4(J.bg,!1,Q);Z.bg=J.bg}if(J.bold!==Z.bold){if(Y+=J.bold?M6+"1m":M6+"22m",Z.bold=J.bold,!J.bold&&J.dim)Y+=M6+"2m"}if(J.italic!==Z.italic)Y+=J.italic?M6+"3m":M6+"23m",Z.italic=J.italic;if(J.underline!==Z.underline){if(Q?.underlineSupport!=="none")Y+=J.underline?M6+"4m":M6+"24m";Z.underline=J.underline}if(J.strikethrough!==Z.strikethrough)Y+=J.strikethrough?M6+"9m":M6+"29m",Z.strikethrough=J.strikethrough;if(J.reverse!==Z.reverse)Y+=J.reverse?M6+"7m":M6+"27m",Z.reverse=J.reverse;if(J.dim!==Z.dim){if(Y+=J.dim?M6+"2m":M6+"22m",Z.dim=J.dim,!J.dim&&J.bold)Y+=M6+"1m"}return Y}function bX3(J,Z){let Q="";if(!mX0(J,Z.hyperlink)){if(Z.hyperlink)Q+=dX0();if(J)Q+=R_4(J);Z.hyperlink=J}return Q}function cX0(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;if(J.type!==Z.type)return!1;switch(J.type){case"none":return!0;case"default":return!0;case"index":return Z.value===J.value;case"rgb":{let Q=Z.value;return Q.r===J.value.r&&Q.g===J.value.g&&Q.b===J.value.b}default:return!1}}function hX3(J,Z){return cX0(J.fg,Z.fg)&&cX0(J.bg,Z.bg)&&J.bold===Z.bold&&J.italic===Z.italic&&J.underline===Z.underline&&J.strikethrough===Z.strikethrough&&J.reverse===Z.reverse&&J.dim===Z.dim}var gX3=" ".repeat(gX0);function mX3(J,Z){if(J.char==="\t")return gX3;if(Z?.kittyExplicitWidth&&J.width>1)return`\x1B]66;w=${J.width};${J.char}\x1B\\`;return J.char}class Qr0{capabilities;currentStyle={};currentX=0;currentY=0;constructor(J){this.capabilities=J}updateCapabilities(J){this.capabilities=J}render(J){if(J.length===0)return"";let Z=new Nn,Q=null,Y,X=-1,K=-1,V=-1,G=-1;for(let z of J){let F=z.cell.char,q=TX3(F),W=q?SX3(F):F;if(J6(!q,`Cell contains disallowed control at (${z.x}, ${z.y}):`,`U+${F.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")}`),z.y!==V)V=z.y,G=-1;if(G!==-1&&z.x<G)continue;if(G=-1,!(Q!==null&&z.y===K&&z.x===X&&hX3(Q,z.cell.style)&&mX0(Y,z.cell.hyperlink))){if(this.currentX!==z.x||this.currentY!==z.y)Z.append(P_4(z.y,z.x)),this.currentX=z.x,this.currentY=z.y;Z.append(uX3(z.cell.style,this.currentStyle,this.capabilities)),Z.append(bX3(z.cell.hyperlink,this.currentStyle)),Q=z.cell.style,Y=z.cell.hyperlink}let H=q?{...z.cell,char:W}:z.cell;if(Z.append(mX3(H,this.capabilities)),this.currentX+=z.cell.width,X=z.x+z.cell.width,K=z.y,z.cell.width>1)G=z.x+z.cell.width}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},I_4+dX0()+zX3+KX3}hideCursor(){return VX3}showCursor(){return GX3}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return vX3(J)}reset(){return this.currentStyle={},I_4+dX0()}moveTo(J,Z){return this.currentX=J,this.currentY=Z,P_4(Z,J)}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return FX3}endSync(){return qX3}enterAltScreen(){return HX3+this.clearScreen()}exitAltScreen(){return DX3}resetCursor(){return XX3}enableMouse(J=!1){return xX3(J)}disableMouse(){return fX3()}enableEmojiWidth(){return OX3}disableEmojiWidth(){return EX3}enableInBandResize(){return MX3}disableInBandResize(){return AX3}enableBracketedPaste(){return WX3}disableBracketedPaste(){return UX3}enableKittyKeyboard(){return jX3}disableKittyKeyboard(){return RX3}enableModifyOtherKeys(){return IX3}disableModifyOtherKeys(){return PX3}setMouseShape(J){return CX3(J)}setProgressBarIndeterminate(){return kX3}setProgressBarOff(){return S_4}setProgressBarPaused(){return yX3}}class iX0{constructor(){}}class A3 extends iX0{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof A3))return!1;return this.value===J.value}get hashCode(){if(this.value===null||this.value===void 0)return 0;if(typeof this.value==="string")return this.stringHash(this.value);if(typeof this.value==="number")return this.value;if(typeof this.value==="boolean")return this.value?1:0;return this.stringHash(String(this.value))}stringHash(J){let Z=0;for(let Q=0;Q<J.length;Q++){let Y=J.charCodeAt(Q);Z=(Z<<5)-Z+Y,Z=Z&Z}return Z}toString(){return`ValueKey(${this.value})`}}class e7 extends iX0{static _registry=new Map;static _counter=0;_id;_currentElement;constructor(J){super();if(J)this._id=`${J}_${e7._counter++}`;else this._id=`GlobalKey_${e7._counter++}`;e7._registry.set(this._id,this)}equals(J){if(!(J instanceof e7))return!1;return this._id===J._id}get hashCode(){return this.stringHash(this._id)}stringHash(J){let Z=0;for(let Q=0;Q<J.length;Q++){let Y=J.charCodeAt(Q);Z=(Z<<5)-Z+Y,Z=Z&Z}return Z}get currentElement(){return this._currentElement}get currentWidget(){return this._currentElement?.widget}_setElement(J){J6(this._currentElement===void 0,`GlobalKey ${this._id} is already associated with an element. Each GlobalKey can only be used once in the widget tree.`),this._currentElement=J}_clearElement(){this._currentElement=void 0,e7._registry.delete(this._id)}toString(){return`GlobalKey(${this._id})`}static _clearRegistry(){e7._registry.clear(),e7._counter=0}}class RJ{key;_debugData={};constructor({key:J}={}){if(this.constructor===RJ)throw Error("Widget is abstract and cannot be instantiated directly");this.key=J}sendDebugData(J){this._debugData={...this._debugData,...J}}get debugData(){return this._debugData}canUpdate(J){if(this.constructor!==J.constructor)return!1;if(this.key===void 0&&J.key===void 0)return!0;if(this.key===void 0||J.key===void 0)return!1;return this.key.equals(J.key)}}class tY{widget;parent;_children=[];_inheritedDependencies=new Set;_dirty=!1;_cachedDepth;_mounted=!1;constructor(J){this.widget=J}get children(){return this._children}get depth(){if(this._cachedDepth!==void 0)return this._cachedDepth;let J=0,Z=this.parent;while(Z)J++,Z=Z.parent;return this._cachedDepth=J,J}_invalidateDepth(){this._cachedDepth=void 0;for(let J of this._children)J._invalidateDepth()}get dirty(){return this._dirty}get mounted(){return this._mounted}get renderObject(){return}update(J){this.widget=J}addChild(J){J.parent=this,J._invalidateDepth(),this._children.push(J)}removeChild(J){let Z=this._children.indexOf(J);if(Z!==-1)this._children.splice(Z,1),J.parent=void 0,J._invalidateDepth()}removeAllChildren(){for(let J of this._children)J.parent=void 0,J._invalidateDepth();this._children.length=0}markMounted(){if(this._mounted=!0,this.widget.key instanceof e7)this.widget.key._setElement(this)}unmount(){if(this.widget.key instanceof e7)this.widget.key._clearElement();this._mounted=!1,this._dirty=!1,this._cachedDepth=void 0;for(let J of this._inheritedDependencies)if("removeDependent"in J)J.removeDependent(this);this._inheritedDependencies.clear()}markNeedsRebuild(){if(!this._mounted)return;this._dirty=!0,L_4().scheduleBuildFor(this)}dependOnInheritedWidgetOfExactType(J){let Z=this.parent;while(Z){if(Z.widget.constructor===J){if("addDependent"in Z&&"removeDependent"in Z){let Q=Z;Q.addDependent(this),this._inheritedDependencies.add(Q)}return Z}Z=Z.parent}return null}findAncestorElementOfType(J){let Z=this.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){let Z=this.parent;while(Z){if(Z.widget instanceof J)return Z.widget;Z=Z.parent}return null}}class Ly extends RJ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new Ln(this)}updateRenderObject(J){}}class o3 extends Ly{child;constructor({key:J,child:Z}={}){super(J?{key:J}:{});this.child=Z}createElement(){return new Mq(this)}}class jZ extends Ly{children;constructor({key:J,children:Z=[]}={}){super(J?{key:J}:{});this.children=[...Z]}createElement(){return new nX0(this)}}class u$ extends Ly{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new bK(this)}}class Ln extends tY{_renderObject;constructor(J){super(J)}get renderObjectWidget(){return this.widget}get renderObject(){return this._renderObject}mount(){this._renderObject=this.renderObjectWidget.createRenderObject(),this._renderObject.attach(),this.markMounted()}unmount(){if(this._renderObject)this._renderObject.detach(),this._renderObject.dispose(),this._renderObject=void 0;super.unmount()}update(J){super.update(J);let Z=this.renderObjectWidget;if(this._renderObject)Z.updateRenderObject(this._renderObject)}performRebuild(){}}class Mq extends Ln{_child;constructor(J){super(J)}get singleChildWidget(){return this.widget}get child(){return this._child}mount(){if(super.mount(),this.singleChildWidget.child){if(this._child=this.singleChildWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this._child.renderObject&&this.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;super.unmount()}update(J){super.update(J);let Z=this.singleChildWidget;if(Z.child&&this._child){if(this._child.widget.canUpdate(Z.child))this._child.update(Z.child);else if(this._child.unmount(),this.removeChild(this._child),this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject){if(this.renderObject.removeAllChildren(),this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}}else if(Z.child&&!this._child){if(this._child=Z.child.createElement(),this.addChild(this._child),this._child.mount(),this.renderObject&&this._child.renderObject)this.renderObject.adoptChild(this._child.renderObject)}else if(!Z.child&&this._child){if(this._child.unmount(),this.removeChild(this._child),this._child=void 0,this.renderObject)this.renderObject.removeAllChildren()}}performRebuild(){}}class nX0 extends Ln{_childElements=[];constructor(J){super(J)}get multiChildWidget(){return this.widget}get children(){return this._childElements}mount(){super.mount();for(let J of this.multiChildWidget.children){let Z=J.createElement();if(this._childElements.push(Z),this.addChild(Z),Z.mount(),Z.renderObject&&this.renderObject)this.renderObject.adoptChild(Z.renderObject)}}unmount(){for(let J of this._childElements)J.unmount(),this.removeChild(J);this._childElements.length=0,super.unmount()}update(J){super.update(J);let Z=this.multiChildWidget;this.updateChildren(this._childElements,[...Z.children])}updateChildren(J,Z){let Q=[],Y=0,X=0,K=J.length-1,V=Z.length-1;while(Y<=K&&X<=V){let z=J[Y],F=Z[X];if(!z||!F||!z.widget.canUpdate(F))break;if(z.widget!==F)z.update(F);Q.push(z),Y++,X++}let G=[];while(Y<=K&&X<=V){let z=J[K],F=Z[V];if(!z||!F||!z.widget.canUpdate(F))break;if(z.widget!==F)z.update(F);G.unshift(z),K--,V--}if(Y>K)for(let z=X;z<=V;z++){let F=Z[z];if(F){let q=this.createChildElement(F);Q.push(q)}}else if(X>V)for(let z=Y;z<=K;z++){let F=J[z];if(F)this.deactivateChild(F)}else{let z=new Map,F=new Map;for(let q=Y;q<=K;q++){let W=J[q];if(W.widget.key){let U=W.widget.key.toString();z.set(U,W),F.set(U,q)}}for(let q=X;q<=V;q++){let W=Z[q];if(!W)continue;let U;if(W.key){let H=W.key.toString();if(U=z.get(H),U){z.delete(H);let D=F.get(H);if(D!==void 0)J[D]=null;if(U.widget===W);else if(U.widget.canUpdate(W))U.update(W);else this.deactivateChild(U),U=this.createChildElement(W)}else U=this.createChildElement(W)}else{let H=!1;for(let D=Y;D<=K;D++){let B=J[D];if(B&&!B.widget.key){if(B.widget===W){U=B,J[D]=null,H=!0;break}else if(B.widget.canUpdate(W)){U=B,J[D]=null,U.update(W),H=!0;break}}}if(!H)U=this.createChildElement(W)}if(U)Q.push(U)}for(let q=Y;q<=K;q++){let W=J[q];if(W)this.deactivateChild(W)}for(let q of z.values())this.deactivateChild(q)}if(Q.push(...G),this._childElements=Q,this.renderObject){let z=[];for(let W of Q)if(W.renderObject)z.push(W.renderObject);let F=this.renderObject.children;if(F.length!==z.length||F.some((W,U)=>W!==z[U]))this.renderObject.replaceChildren(z)}}createChildElement(J){let Z=J.createElement();return this.addChild(Z),Z.mount(),Z}deactivateChild(J){J.unmount(),this.removeChild(J)}performRebuild(){}}class bK extends Ln{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}class d0{widget;context;_mounted=!1;get mounted(){return this._mounted}initState(){}didUpdateWidget(J){}dispose(){}setState(J){if(!this._mounted)throw Error("setState() called after dispose()");if(J)J();this._markNeedsBuild()}_mount(J,Z){this.widget=J,this.context=Z,this._mounted=!0,this.initState()}_update(J){let Z=this.widget;this.widget=J,this.didUpdateWidget(Z)}_unmount(){this._mounted=!1,this.dispose()}_markNeedsBuild(){let J=this.context.element;if("markNeedsBuild"in J&&typeof J.markNeedsBuild==="function")J.markNeedsBuild()}}class xG{element;widget;mediaQuery;parent;constructor(J,Z,Q=void 0,Y=null){this.element=J;this.widget=Z;this.mediaQuery=Q;this.parent=Y}findAncestorElementOfType(J){let Z=this.element.parent;while(Z){if(Z instanceof J)return Z;Z=Z.parent}return null}findAncestorWidgetOfType(J){return this.element.findAncestorWidgetOfType(J)}dependOnInheritedWidgetOfExactType(J){return this.element.dependOnInheritedWidgetOfExactType(J)}findAncestorStateOfType(J){let Z=this.element.parent;while(Z){if("state"in Z&&Z.state instanceof J)return Z.state;Z=Z.parent}return null}findRenderObject(){if("renderObject"in this.element){let J=this.element.renderObject;return J instanceof gj?J:void 0}return}}class l0 extends RJ{createElement(){return new Yr0(this)}}class Yr0 extends tY{_state;_child;_context;constructor(J){super(J)}get statefulWidget(){return this.widget}get state(){return this._state}get child(){return this._child}mount(){this._context=new xG(this,this.widget),this._state=this.statefulWidget.createState(),this._state._mount(this.statefulWidget,this._context),this.rebuild(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;if(this._state)this._state._unmount(),this._state=void 0;this._context=void 0,super.unmount()}update(J){if(this.widget===J)return;if(super.update(J),this._state)this._state._update(this.statefulWidget);if(this._context)this._context.widget=J;this.rebuild()}performRebuild(){this.rebuild()}rebuild(){if(!this._context||!this._state)throw Error("Cannot rebuild unmounted element");let J=this._state.build(this._context);if(this._child)if(this._child.widget.canUpdate(J))this._child.update(J);else{let Z=this._child,Q=this.findNearestRenderObjectAncestor();if(Q&&Z.renderObject)Q.dropChild(Z.renderObject);else if(!Q&&Z.renderObject)Z.renderObject.detach();if(this._child.unmount(),this.removeChild(this._child),this._child=J.createElement(),this.addChild(this._child),this._child.mount(),Q&&this._child.renderObject)Q.adoptChild(this._child.renderObject),this._child.renderObject.markNeedsLayout();else if(!Q&&this._child.renderObject)this._child.renderObject.attach(),this._child.renderObject.markNeedsLayout();if(this._child.renderObject)this._child.renderObject.markNeedsLayout()}else this._child=J.createElement(),this.addChild(this._child),this._child.mount()}markNeedsBuild(){this.markNeedsRebuild()}findNearestRenderObjectAncestor(){let J=this.parent;while(J){if(J.renderObject){if(this._child?.renderObject&&J.renderObject===this._child.renderObject){J=J.parent;continue}return J.renderObject}J=J.parent}return}get renderObject(){return this._child?.renderObject}}var p5={DEFAULT:"default",POINTER:"pointer",TEXT:"text",WAIT:"wait",CROSSHAIR:"crosshair",HELP:"help",MOVE:"move",NOT_ALLOWED:"not-allowed",PROGRESS:"progress",CELL:"cell",CONTEXT_MENU:"context-menu",COPY:"copy",ALIAS:"alias",ZOOM_IN:"zoom-in",ZOOM_OUT:"zoom-out",GRAB:"grab",GRABBING:"grabbing",N_RESIZE:"n-resize",S_RESIZE:"s-resize",E_RESIZE:"e-resize",W_RESIZE:"w-resize",NE_RESIZE:"ne-resize",NW_RESIZE:"nw-resize",SE_RESIZE:"se-resize",SW_RESIZE:"sw-resize",NS_RESIZE:"ns-resize",EW_RESIZE:"ew-resize",COL_RESIZE:"col-resize",ROW_RESIZE:"row-resize"};class Xr0{static hitTest(J,Z){let Q=new y_4;return J.hitTest(Q,Z),Q}}class y_4{_hits=[];get hits(){return this._hits}add(J){this._hits.push(J)}addWithPaintOffset(J,Z,Q){let Y={x:Q.x-Z.x,y:Q.y-Z.y};this.add({target:J,localPosition:Y})}addMouseTarget(J,Z){}}function pX3(){let J=gj.prototype;if(!J.hitTest)J.hitTest=function(Z,Q,Y=0,X=0){if("size"in this&&"offset"in this){let V=this,G=V.size,z=V.offset;if(G&&z){let F=Y+z.x,q=X+z.y,W=Q.x>=F&&Q.x<F+G.width,U=Q.y>=q&&Q.y<q+G.height;if(W&&U){let H={x:Q.x-F,y:Q.y-q};Z.add({target:this,localPosition:H});let D=this.children,B=!0;for(let N=D.length-1;N>=0;N--)if(D[N].hitTest(Z,Q,F,q))B=!0;return B}if(this.allowHitTestOutsideBounds){let H=!1,D=this.children;for(let B=D.length-1;B>=0;B--)if(D[B].hitTest(Z,Q,F,q))H=!0;return H}return!1}}let K=!1;for(let V of this.children)if(V.hitTest(Z,Q,Y,X))K=!0;return K}}pX3();function AH(J,Z,Q){return{position:Z,localPosition:Q,modifiers:{shift:J.modifiers.shift,ctrl:J.modifiers.ctrl,alt:J.modifiers.alt,meta:J.modifiers.meta},timestamp:Date.now()}}function v_4(J,Z,Q,Y=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:Y,...AH(J,Z,Q)}}function aX0(J,Z,Q){let Y;switch(J.button){case"wheel_up":Y="up";break;case"wheel_down":Y="down";break;case"wheel_left":Y="left";break;case"wheel_right":Y="right";break;default:Y="down"}return{type:"scroll",direction:Y,...AH(J,Z,Q)}}class j8{static _instance=null;static SCROLL_SESSION_TIMEOUT=200;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=p5.DEFAULT;_lastMousePosition=null;_dragTargets=[];_lastDragPosition=null;_globalReleaseCallbacks=new Set;_globalClickCallbacks=new Set;_scrollSessionTarget=null;_scrollSessionLastEvent=0;_lastClickTime=new Map;_lastClickPosition=new Map;_currentClickCount=new Map;static DOUBLE_CLICK_TIME=500;static DOUBLE_CLICK_DISTANCE=2;static DOUBLE_CLICK_DISTANCE_SQUARED=j8.DOUBLE_CLICK_DISTANCE*j8.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!j8._instance)j8._instance=new j8;return j8._instance}setRootRenderObject(J){this._rootRenderObject=J}setTui(J){this._vaxis=J}handleMouseEvent(J){if(!this._rootRenderObject)return;let Z={x:J.x,y:J.y},Q=Xr0.hitTest(this._rootRenderObject,Z),Y=this._findMouseTargets(Q.hits);switch(J.action){case"press":if(J.button==="left"||J.button==="middle"||J.button==="right"){if(this._handleClick(J,Z,Y),J.button==="left"){this._dragTargets=[];for(let{target:X,localPosition:K}of Y){let V={x:Z.x-K.x,y:Z.y-K.y};if(this._dragTargets.push({target:X,localPosition:K,globalOffset:V}),X instanceof xQ&&X.opaque)break}}}break;case"release":this._handleRelease(J,Z,Y),this._dragTargets=[],this._lastDragPosition=null;break;case"scroll":if(J.button==="wheel_up"||J.button==="wheel_down"||J.button==="wheel_left"||J.button==="wheel_right")this._handleScroll(J,Z,Y);break;case"move":if(this._handleMove(J,Z,Y),J.drag)this._handleDrag(J,Z,Y);break}this._lastMousePosition=Z}addGlobalReleaseCallback(J){this._globalReleaseCallbacks.add(J)}removeGlobalReleaseCallback(J){this._globalReleaseCallbacks.delete(J)}addGlobalClickCallback(J){this._globalClickCallbacks.add(J)}removeGlobalClickCallback(J){this._globalClickCallbacks.delete(J)}requestCursorChange(J){if(this._vaxis&&J!==this._currentCursor)this._currentCursor=J,this._vaxis.setMouseCursor(J)}_handleRelease(J,Z,Q){for(let X of this._globalReleaseCallbacks)X();let Y=J.button==="left"||J.button==="middle"||J.button==="right"?J.button:"left";if(this._dragTargets.length>0)for(let{target:X,globalOffset:K}of this._dragTargets){let V={x:Z.x-K.x,y:Z.y-K.y},G={type:"release",button:Y,...AH(J,Z,V)};X.handleMouseEvent(G)}else for(let{target:X,localPosition:K}of Q){let V={type:"release",button:Y,...AH(J,Z,K)};if(X.handleMouseEvent(V),X instanceof xQ&&X.opaque)break}}_handleDrag(J,Z,Q){let Y=J.button==="left"||J.button==="middle"||J.button==="right"?J.button:"left",X=this._lastDragPosition?Z.x-this._lastDragPosition.x:0,K=this._lastDragPosition?Z.y-this._lastDragPosition.y:0;for(let{target:V,globalOffset:G}of this._dragTargets){let z={x:Z.x-G.x,y:Z.y-G.y},F={type:"drag",button:Y,deltaX:X,deltaY:K,...AH(J,Z,z)};V.handleMouseEvent(F)}this._lastDragPosition=Z}_handleClick(J,Z,Q){let Y=this._calculateClickCount(Z,J.button);for(let X of this._globalClickCallbacks)X({event:J,globalPosition:Z,mouseTargets:Q,clickCount:Y});for(let{target:X,localPosition:K}of Q){let V=v_4(J,Z,K,Y);if(X.handleMouseEvent(V),X instanceof xQ&&X.opaque)break}}_handleScroll(J,Z,Q){let Y=Date.now();if(this._scrollSessionTarget&&this._scrollSessionTarget.attached&&Y-this._scrollSessionLastEvent<=j8.SCROLL_SESSION_TIMEOUT&&this._scrollSessionTarget){let V=Q.find((G)=>G.target===this._scrollSessionTarget);if(V){let G=aX0(J,Z,V.localPosition);this._scrollSessionTarget.onScroll?.(G)}else{let G=this._scrollSessionTarget.globalToLocal(Z),z=aX0(J,Z,{x:G.x,y:G.y});this._scrollSessionTarget.onScroll?.(z)}this._scrollSessionLastEvent=Y;return}let K=this._findScrollTargets(Q);if(K.length===0){this._scrollSessionTarget=null,this._scrollSessionLastEvent=0;return}for(let V=K.length-1;V>=0;V--){let G=K[V];if(!G)continue;let z=aX0(J,Z,G.localPosition);if(G.target.onScroll?.(z)??!1){this._scrollSessionTarget=G.target,this._scrollSessionLastEvent=Y;return}}this._scrollSessionTarget=null,this._scrollSessionLastEvent=0}_handleMove(J,Z,Q){let Y=Q.filter((G)=>G.target instanceof xQ),X=this._scratchCurrentRegions,K=this._scratchExitedRegions,V=this._scratchEnteredRegions;X.clear();for(let{target:G}of Y)X.add(G);K.clear();for(let G of this._hoveredRegions)if(!X.has(G))K.add(G);V.clear();for(let G of X)if(!this._hoveredRegions.has(G))V.add(G);for(let G of K)if(G.onExit){let z={type:"exit",...AH(J,Z,Z)};G.handleMouseEvent(z)}for(let{target:G,localPosition:z}of Y)if(V.has(G)&&G.onEnter){let F={type:"enter",...AH(J,Z,z)};G.handleMouseEvent(F)}for(let{target:G,localPosition:z}of Y)if(G.onHover&&this._hoveredRegions.has(G)){let F={type:"hover",...AH(J,Z,z)};G.handleMouseEvent(F)}this._hoveredRegions.clear();for(let G of X)this._hoveredRegions.add(G);this._updateCursor(Y)}_updateCursor(J){if(!this._vaxis)return;let Z=p5.DEFAULT,Q=-1;for(let{target:Y}of J){let X=Y.depth;if(X<=Q)break;if(Y.cursor!==null)Z=Y.cursor;Q=X}if(Z!==this._currentCursor)this._currentCursor=Z,this._vaxis.setMouseCursor(Z)}_findMouseTargets(J){let Z=[];for(let Q of J)if(this._canHandleMouseEvents(Q.target))Z.push({target:Q.target,localPosition:Q.localPosition});return Z}_findScrollTargets(J){let Z=[],Q=-1;for(let Y of J){let K=Y.target.depth;if(K<=Q)break;if(Y.target instanceof xQ&&Y.target.onScroll)Z.push({target:Y.target,localPosition:Y.localPosition});Q=K}return Z}_canHandleMouseEvents(J){if(J instanceof xQ)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==p5.DEFAULT)this._currentCursor=p5.DEFAULT,this._vaxis.setMouseCursor(p5.DEFAULT)}removeRegion(J){this._hoveredRegions.delete(J)}reestablishHoverState(){if(!this._lastMousePosition||!this._rootRenderObject)return;let J={type:"mouse",action:"move",x:this._lastMousePosition.x,y:this._lastMousePosition.y,button:"unknown",drag:!1,modifiers:{shift:!1,ctrl:!1,alt:!1,meta:!1}};this.handleMouseEvent(J)}_calculateClickCount(J,Z="left"){let Q=Date.now(),Y=this._lastClickTime.get(Z)??0,X=Q-Y,K=1,V=this._lastClickPosition.get(Z);if(V&&X<=j8.DOUBLE_CLICK_TIME&&this._isWithinDoubleClickDistance(J,V))K=(this._currentClickCount.get(Z)??0)+1;else K=1;return this._lastClickTime.set(Z,Q),this._lastClickPosition.set(Z,J),this._currentClickCount.set(Z,K),K}_isWithinDoubleClickDistance(J,Z){let Q=J.x-Z.x,Y=J.y-Z.y;return Q*Q+Y*Y<=j8.DOUBLE_CLICK_DISTANCE_SQUARED}dispose(){this.clearHoverState(),this._lastMousePosition=null,this._rootRenderObject=null,this._lastClickTime.clear(),this._lastClickPosition.clear(),this._currentClickCount.clear(),this._globalReleaseCallbacks.clear(),this._globalClickCallbacks.clear(),j8._instance=null}}class J4 extends o3{child;onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;constructor({key:J,child:Z,onClick:Q,onEnter:Y,onExit:X,onHover:K,onScroll:V,onRelease:G,onDrag:z,cursor:F,opaque:q=!0}){super({key:J});this.child=Z,this.onClick=Q??null,this.onEnter=Y??null,this.onExit=X??null,this.onHover=K??null,this.onScroll=V??null,this.onRelease=G??null,this.onDrag=z??null,this.cursor=F??null,this.opaque=q}createElement(){return new x_4(this)}createRenderObject(){return new xQ({onClick:this.onClick,onEnter:this.onEnter,onExit:this.onExit,onHover:this.onHover,onScroll:this.onScroll,onRelease:this.onRelease,onDrag:this.onDrag,cursor:this.cursor,opaque:this.opaque})}updateRenderObject(J){J.onClick=this.onClick,J.onEnter=this.onEnter,J.onExit=this.onExit,J.onHover=this.onHover,J.onScroll=this.onScroll,J.onRelease=this.onRelease,J.onDrag=this.onDrag,J.cursor=this.cursor,J.opaque=this.opaque}}class x_4 extends Mq{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}}class xQ extends v4{onClick;onEnter;onExit;onHover;onScroll;onRelease;onDrag;cursor;opaque;_isHovered=!1;constructor({onClick:J,onEnter:Z,onExit:Q,onHover:Y,onScroll:X,onRelease:K,onDrag:V,cursor:G,opaque:z}){super();this.onClick=J,this.onEnter=Z,this.onExit=Q,this.onHover=Y,this.onScroll=X,this.onRelease=K,this.onDrag=V,this.cursor=G,this.opaque=z}get hasMouseListeners(){return!!(this.onClick||this.onEnter||this.onExit||this.onHover||this.onScroll||this.onRelease||this.onDrag)}get isHovered(){return this._isHovered}handleMouseEvent(J){switch(J.type){case"click":this.onClick?.(J);break;case"enter":this._isHovered=!0,this.onEnter?.(J);break;case"exit":this._isHovered=!1,this.onExit?.(J);break;case"hover":this.onHover?.(J);break;case"scroll":this.onScroll?.(J);break;case"drag":this.onDrag?.(J);break;case"release":this.onRelease?.(J);break}}performLayout(){let J=this._lastConstraints;if(J6(!!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),Z.setOffset(0,0)}else this.setSize(0,0);super.performLayout()}getMinIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMinIntrinsicHeight(J);return 0}getMaxIntrinsicHeight(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicHeight(J);return 0}getMinIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMinIntrinsicWidth(J);return 0}getMaxIntrinsicWidth(J){if(this.children.length>0)return this.children[0].getMaxIntrinsicWidth(J);return 0}paint(J,Z=0,Q=0){if(this.children.length>0)this.children[0].paint(J,Z+this.offset.x,Q+this.offset.y)}hitTest(J,Z,Q=0,Y=0){let X=super.hitTest(J,Z,Q,Y);if(X&&this.hasMouseListeners)J.addMouseTarget(this,Z);return X}getDebugProperties(){return{hasMouseListeners:this.hasMouseListeners,isHovered:this.isHovered,cursor:this.cursor,opaque:this.opaque}}dispose(){j8.instance.removeRegion(this),this.onClick=null,this.onEnter=null,this.onExit=null,this.onHover=null,this.onScroll=null,this.onRelease=null,this.onDrag=null,this.cursor=null,super.dispose()}}class t5 extends RJ{child;constructor({key:J,child:Z}){super(J!==void 0?{key:J}:{});this.child=Z}createElement(){return new f_4(this)}}class f_4 extends tY{_child;_dependents=new Set;constructor(J){super(J)}get inheritedWidget(){return this.widget}get child(){return this._child}get renderObject(){return this._child?.renderObject}mount(){this._child=this.inheritedWidget.child.createElement(),this.addChild(this._child),this._child.mount(),this.markMounted()}unmount(){if(this._child)this._child.unmount(),this.removeChild(this._child),this._child=void 0;this._dependents.clear(),super.unmount()}update(J){let Z=this.inheritedWidget;super.update(J);let Q=this.inheritedWidget;if(Q.updateShouldNotify(Z))this.notifyDependents();if(this._child&&this._child.widget.canUpdate(Q.child))this._child.update(Q.child);else{if(this._child)this._child.unmount(),this.removeChild(this._child);this._child=Q.child.createElement(),this.addChild(this._child),this._child.mount()}}addDependent(J){this._dependents.add(J)}removeDependent(J){this._dependents.delete(J)}notifyDependents(){for(let J of this._dependents)J.markNeedsRebuild()}performRebuild(){}}class yw{foreground;mutedForeground;background;cursor;primary;secondary;accent;border;success;warning;info;destructive;selection;copyHighlight;tableBorder;constructor({foreground:J,mutedForeground:Z,background:Q,cursor:Y,primary:X,secondary:K,accent:V,border:G,success:z,warning:F,info:q,destructive:W,selection:U,copyHighlight:H,tableBorder:D}){this.foreground=J,this.mutedForeground=Z,this.background=Q,this.cursor=Y,this.primary=X,this.secondary=K,this.accent=V,this.border=G,this.success=z,this.warning=F,this.info=q,this.destructive=W,this.selection=U,this.copyHighlight=H,this.tableBorder=D}static default(){return new yw({foreground:M0.default(),mutedForeground:M0.default(),background:M0.none(),cursor:M0.default(),primary:M0.blue,secondary:M0.cyan,accent:M0.magenta,border:M0.default(),success:M0.green,warning:M0.yellow,info:M0.index(12),destructive:M0.red,selection:M0.index(8),copyHighlight:M0.yellow,tableBorder:M0.default()})}static fromRgb(J){return new yw({foreground:M0.rgb(J.fg.r,J.fg.g,J.fg.b),mutedForeground:M0.rgb(J.indices[7].r,J.indices[7].g,J.indices[7].b),background:M0.none(),cursor:M0.rgb(J.cursor.r,J.cursor.g,J.cursor.b),primary:M0.rgb(J.indices[4].r,J.indices[4].g,J.indices[4].b),secondary:M0.rgb(J.indices[6].r,J.indices[6].g,J.indices[6].b),accent:M0.rgb(J.indices[5].r,J.indices[5].g,J.indices[5].b),border:M0.rgb(J.fg.r,J.fg.g,J.fg.b),success:M0.rgb(J.indices[2].r,J.indices[2].g,J.indices[2].b),warning:M0.rgb(J.indices[3].r,J.indices[3].g,J.indices[3].b),info:M0.rgb(J.indices[6].r,J.indices[6].g,J.indices[6].b),destructive:M0.rgb(J.indices[1].r,J.indices[1].g,J.indices[1].b),selection:M0.index(8),copyHighlight:M0.rgb(J.indices[3].r,J.indices[3].g,J.indices[3].b),tableBorder:M0.rgb(J.fg.r,J.fg.g,J.fg.b)})}}class o9{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new o9({colorScheme:yw.default()})}static withRgb(J){return new o9({colorScheme:yw.fromRgb(J)})}}class T1 extends t5{data;constructor({key:J,data:Z,child:Q}){super({key:J,child:Q});this.data=Z}static of(J){let Z=J.dependOnInheritedWidgetOfExactType(T1);if(Z)return Z.widget.data;return o9.default()}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(T1);if(Z)return Z.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}function Kr0(J,Z,Q){return J+(Z-J)*Q}function oX0(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(Kr0(J.r,Z.r,Y)),g:Math.round(Kr0(J.g,Z.g,Y)),b:Math.round(Kr0(J.b,Z.b,Y))}}O$();var s_4=G4(o_4(),1),r_4=20;function Ur0(J){let Z=L$(J??"smart")??L$("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:Nu1,secondary:wu1}}function Hr0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:K}=Q??Ur0(Z),V=oX0(X,K,Y);return{type:"rgb",value:{r:V.r,g:V.g,b:V.b}}}class jq{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=s_4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/r_4,Z/r_4+Q*Y)+1)*0.5}sampleEdge(J,Z,Q,Y,X=1){let K=J-1,V=Z/2+Q*(Z/2);return this.sample(K,V,Y,X)}getColor(J,Z,Q){return Hr0(J,Z,Q)}}var Dr0=" .:-=+*#%@",VK3=" ",mj=64,t_4=0.5,vw=1,Br0=30,pj=3;class Nr0 extends l0{width;height;minWidth;minHeight;maxWidth;maxHeight;agentMode;colorMode;primaryColor;secondaryColor;backgroundColor;t;onFrame;fps;seed;glow;shockwaves;onShockwave;onClick;constructor({key:J,width:Z=40,height:Q=40,minWidth:Y,minHeight:X,maxWidth:K,maxHeight:V,agentMode:G,colorMode:z="intensity",primaryColor:F,secondaryColor:q,backgroundColor:W,t:U,onFrame:H,fps:D=30,seed:B,glow:N,shockwaves:w,onShockwave:L,onClick:O}){super(J?{key:J}:{});this.width=Z,this.height=Q,this.minWidth=Y??8,this.minHeight=X??8,this.maxWidth=K??40,this.maxHeight=V??40,this.agentMode=G,this.colorMode=z,this.primaryColor=F,this.secondaryColor=q,this.backgroundColor=W,this.t=U,this.onFrame=H,this.fps=D,this.seed=B,this.glow=N,this.shockwaves=w,this.onShockwave=L,this.onClick=O}createState(){return new e_4}}class e_4 extends d0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new jq(this.widget.seed),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this.widget.onFrame){let J=this._t;setImmediate(()=>this.widget.onFrame?.(J))}this._internalShockwaves=this._internalShockwaves.filter((J)=>this._t-J.startTime<vw),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new jq(this.widget.seed);if(this.widget.t!==void 0&&this.widget.t!==J.t)this._t=this.widget.t,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}handleClick=(J)=>{this.widget.onClick?.({x:J.position.x,y:J.position.y,localX:J.localPosition.x,localY:J.localPosition.y,time:this._t});let Z={x:J.localPosition.x,y:J.localPosition.y,startTime:this._t};if(this.widget.onShockwave)this.widget.onShockwave(Z);else this._internalShockwaves.push(Z);this.setState(()=>{})};build(J){let Z=T1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new $T4({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,agentMode:this.widget.agentMode,colorMode:this.widget.colorMode,primaryColor:this.widget.primaryColor,secondaryColor:this.widget.secondaryColor,backgroundColor:Q,glow:this._glow,shockwaves:this.widget.shockwaves??this._internalShockwaves});return new J4({onClick:this.handleClick,child:Y})}}class $T4 extends u${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new bK(this)}createRenderObject(){return new Oy(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}updateRenderObject(J){J.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.agentMode,this.props.colorMode,this.props.primaryColor,this.props.secondaryColor,this.props.backgroundColor,this.props.glow,this.props.shockwaves)}}class Oy extends v4{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_agentMode;_colorMode;_primaryColor;_secondaryColor;_backgroundColor;_glow;_shockwaves;_palette=[];_paletteSignature="";constructor(J,Z,Q,Y,X,K,V,G,z,F,q,W,U,H=[]){super();this._width=J;this._height=Z;this._minWidth=Q;this._minHeight=Y;this._maxWidth=X;this._maxHeight=K;this._time=V;this._agentMode=G;this._colorMode=z;this._primaryColor=F;this._secondaryColor=q;this._backgroundColor=W;this._glow=U;this._shockwaves=H;this.rebuildPalette(this._agentMode,this._primaryColor,this._secondaryColor)}getPaletteSignature(J,Z,Q){if(Z&&Q)return`${Z.r},${Z.g},${Z.b}|${Q.r},${Q.g},${Q.b}`;return`mode:${J??"smart"}`}rebuildPalette(J,Z,Q){let Y=Z&&Q?{primary:Z,secondary:Q}:void 0;this._palette=Array.from({length:mj},(X,K)=>{let V=K/(mj-1);return Hr0(V,J,Y)}),this._paletteSignature=this.getPaletteSignature(J,Z,Q)}getMinIntrinsicWidth(J){return this._minWidth}getMaxIntrinsicWidth(J){return this._maxWidth}getMinIntrinsicHeight(J){return this._minHeight}getMaxIntrinsicHeight(J){return this._maxHeight}update(J,Z,Q,Y,X,K,V,G,z,F,q,W,U,H=[]){let D=!1;if(J!==this._width||Z!==this._height||Q!==this._minWidth||Y!==this._minHeight||X!==this._maxWidth||K!==this._maxHeight)this._width=J,this._height=Z,this._minWidth=Q,this._minHeight=Y,this._maxWidth=X,this._maxHeight=K,D=!0;if(this._time=V,this._agentMode=G,this._colorMode=z,this._primaryColor=F,this._secondaryColor=q,this._backgroundColor=W,this._glow=U,this._shockwaves=H,this.getPaletteSignature(G,F,q)!==this._paletteSignature)this.rebuildPalette(G,F,q);if(D)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=J.constrain(this._width,this._height);this.setSize(Z.width,Z.height),super.performLayout()}getPaletteIndex(J,Z,Q){if(this._colorMode==="vertical"){let Y=Math.max(0,Math.min(1,0.5-Z/(2*Q)));return Math.min(mj-1,Math.floor(Y*mj))}return Math.min(mj-1,Math.floor(J*mj))}paint(J,Z=0,Q=0){let Y=Z+this.offset.x,X=Q+this.offset.y,K=Math.floor(this.size.width),V=Math.floor(this.size.height),G=J.getSize(),z=G.width,F=G.height,q=this._backgroundColor,W=this._palette,U=K/2,H=V/2,D=Math.max(1,K/2-1),B=Math.max(1,V/(2*t_4)-1),N=Math.min(D,B),w=N*N,L=1/w,O=1/t_4,E=this._agentMode==="rush"?2.5:1,M=this._shockwaves.length>0;for(let A=0;A<V;A++){let j=X+A;if(j<0||j>=F)continue;let R=(A-H)*O,T=R*R;if(T>=w)continue;let S=Math.sqrt(w-T),u=Math.max(0,Math.floor(U-S)),m=Math.min(K-1,Math.ceil(U+S));for(let x=u;x<=m;x++){let _=x-U,f=_*_+T;if(f>=w)continue;let p=1-f*L,h=this._glow.sample(x,A,this._time,E)*p;if(h<=0)continue;if(M){let q0=f*L;if(q0<0.9025)for(let L0 of this._shockwaves){let G0=this._time-L0.startTime;if(G0<0||G0>vw)continue;let $0=x-L0.x,W0=(A-L0.y)*O,i=$0*$0+W0*W0,a=G0*Br0,t=Math.max(0,a-pj),e=a+pj;if(i<t*t||i>e*e)continue;let z0=Math.sqrt(i),K0=Math.abs(z0-a);if(K0>=pj)continue;let Z0=1-G0/vw,Y0=(1-K0/pj)*Z0,w0=Math.sqrt(q0),X0=1-q0*w0;h=Math.min(1,h+Y0*0.8*X0)}}let n=Math.min(Dr0.length-1,Math.floor(h*Dr0.length)),c=Dr0[n]||VK3,s=this.getPaletteIndex(h,R,N),F0=W[s]||W[mj-1],o=Y+x;if(o<0||o>=z)continue;J.setCell(o,j,{char:c,width:1,style:{fg:F0,bg:q}})}}}}var HK3=UK3(GK3),DK3=Number.MAX_SAFE_INTEGER,BK3=30000,NK3=60000,wK3=14400000,LK3=10,OK3=1000,EK3=5,MK3=80,AK3=3,JT4=3,FT4="Watching this thread for changes. Press Ctrl-C to stop.",jK3="Live sync paused after 4 hours to save the connection. Press Enter to resume.",dj=14,xw=7,RK3=42,Er0="[y/N]: ",qT4=eY.posix.join(".amp","live-sync.pid"),Ey=Symbol("live-sync-archived-transition"),An=Symbol("live-sync-session-paused"),My=Symbol("live-sync-stop-requested"),IK3="\x1B[0m",PK3=/^Filesystem error \(([^)]+)\):/;function CK3(J,Z){let Q=new Map;for(let V of J?.available?J.files:[])Q.set(V.path,QT4(V));let Y=new Set(Z.files.map((V)=>V.path)),X=Z.files.filter((V)=>Q.get(V.path)!==QT4(V)),K=UT4([...J?.available?J.files.filter((V)=>!Y.has(V.path)).map((V)=>V.path):[],...Z.files.flatMap((V)=>V.changeType==="renamed"&&V.previousPath&&!Y.has(V.previousPath)?[V.previousPath]:[])]);return{syncFiles:X,restorePaths:K}}function wr0(J){let Z=J.filter((X)=>X.changeType==="untracked").length,Q=J.length-Z,Y=[];if(Q>0)Y.push(`${Q} changed ${d4(Q,"file")}`);if(Z>0)Y.push(`${Z} untracked ${d4(Z,"file")}`);return Y.length>0?Y.join(" and "):"0 files"}function _K3(J){let Z=J.changeType.replaceAll("_"," ");if((J.changeType==="renamed"||J.changeType==="copied")&&J.previousPath)return`${Z}: ${J.previousPath} -> ${J.path}`;return`${Z}: ${J.path}`}function TK3(J,Z=LK3){let Q=J.slice(0,Z).map((X)=>` ${_K3(X)}`),Y=J.length-Q.length;if(Y>0)Q.push(` ...and ${Y} more ${d4(Y,"file")}`);return Q.join(`
6239
6239
  `)}async function YK0(J){let Z=await uw(J,["status","--porcelain=v1","-z","--untracked-files=all"]);return Do0(Z.stdout).filter((Q)=>Q.path!==qT4).map((Q)=>({path:Q.path,changeType:Q.changeType,previousPath:Q.previousPath}))}async function SK3(J){await uw(J,["reset","--hard","HEAD"]),await uw(J,["clean","-fd","-e",qT4])}async function kK3(J){let Z=await YK0(J.repoRoot);if(Z.length===0)return;if(!await J.promptForYesNo([`Local checkout has ${wr0(Z)}:`,TK3(Z),"Clean them up before live sync starts?","This will discard tracked changes and delete untracked files.",Er0].join(`
@@ -7396,7 +7396,7 @@ Ctrl-X, Y, Z to unlock`;if(U){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7396
7396
  `),K=[];for(let V=0;V<X.length;V++){let F=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 F)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
7397
7397
  `))}return new i0({decoration:{color:Q.colorScheme.background,border:c1.all(new g1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class q11 extends u${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=Oz0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new z11({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 Jm4(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?v9:0,z=Y-G;if(z<=0)return null;let F=Z-G;if(F<0||F>=z)return null;let q=Math.max(1,Math.floor(z/K)),W=Math.floor(F/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?v9:0,z=Y-G;if(z<=0)return null;let F=Math.max(0,Math.min(z-1,Z-G));if(K===1)return 0;let q=z/(K-1),W=Math.round(F/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function QP3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let z=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=Math.max(1,Math.floor(q/X)),H=F+Z*U+Math.floor(U/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?v9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let U=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,D=Math.round((1-H)*(W-1));return{x:U,y:D}}default:return null}}function YP3(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 XP3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),z=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+z.length}let K=J.label.length,V=0;for(let G of Q){let z=G.points[Z];if(!z)continue;V+=z.value;let F=2+G.name.length+2+Y(z.value).length;K=Math.max(K,F)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function KP3(J,Z,Q,Y,X,K,V){let G;try{let D=T1.of(J),B=f0.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 z=new g({color:G.foreground,bold:!0}),F=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],U=new g({color:G.foreground,underline:!0}),H=(D,B)=>new C(B,U,void 0,pX0(D),()=>{t3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new C(K(Z.value),F));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
7398
7398
  `,z));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 C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new C(K(L.value),F));if(N<Y.length-1||D)W.push(new C(`
7399
- `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}UE();m0();_2();import{execSync as vP3}from"node:child_process";LE();O$();f3();T7();rd();ZA();RV();XJ();$Z();HY();vA();f4();Vm();Kb();w1();var Jp4=G4(QU(),1);import{writeFile as rm4}from"fs/promises";import sm4 from"path";m0();XJ();class W11{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.1774590201-g775913"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await s40(Z,this.configService)}catch(Z){P.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 BL extends l0{props;constructor(J){super();this.props=J}createState(){return new Zm4}}class Zm4 extends d0{_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)}}class Qm4 extends d0{controller=new Y$;focusNode=new W6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new SZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class Jo extends l0{props;constructor(J){super();this.props=J}createState(){return new Qm4}}import{isDeepStrictEqual as U11}from"node:util";var VP3=/[\\/_ +.#"@[({&]/,GP3=/[\\/_ +.#"@[({&]/g,zP3=/[\s-]/,Ym4=/[\s-]/g;function Az0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=Az0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(zP3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(Ym4),D&&X>0)W*=0.999**D.length}else if(VP3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(GP3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Az0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function Mz0(J){return J.toLowerCase().replace(Ym4," ")}function Xm4(J,Z){let Q=Az0(J,Z,Mz0(J),Mz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=Az0(J,G,Mz0(J),Mz0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Tv{}class Sv{}class jz0{}class Rz0{}class Km4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Vm4}}class Vm4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function FP3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Xm4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Gm4}}class Gm4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Y$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>U11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!U11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>U11(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Tv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Sv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof jz0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Rz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...FP3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;jv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new SZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Tv],[new U4("ArrowUp"),new Sv],[new U4("Tab"),new Tv],[new U4("Tab",{shift:!0}),new Sv],[new U4("n",{ctrl:!0}),new Tv],[new U4("p",{ctrl:!0}),new Sv],[new U4("Enter"),new jz0],[new U4("Escape"),new Rz0]]),focusNode:this.focusNode,child:G}),F=new O2({actions:new Map([[Tv,new U6(this.invoke)],[Sv,new U6(this.invoke)],[jz0,new U6(this.invoke)],[Rz0,new U6(this.invoke)]]),child:z}),q=new W1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Km4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else H.push(new k1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function zm4(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 H11 extends e1{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)=>zm4(X.pubDate).length));return new r2({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 z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new I0({width:N,child:W1.end([new J0({text:new C(B,new g({color:H}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new k1({child:new J0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(zm4(X.pubDate),Q)]})})}})}}class D11 extends l0{createState(){return new Fm4}}class Fm4 extends d0{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=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function qP3(J){return RY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function WP3(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((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return tV0.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 B11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function UP3(J,Z,Q,Y){return[B11("+",J,Y.success),b3.horizontal(1),B11("~",Z,Y.warning),b3.horizontal(1),B11("-",Q,Y.destructive)]}function HP3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class Iz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new qm4}}class qm4 extends d0{spinner=new G3;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===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),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)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=WP3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=qP3(L);return B};return new r2({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(!HP3(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,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,T=O?j.selectionBackground:void 0,S=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:W1.end([new J0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[L.id],_=[],f=L.relationshipType==="handoff",p=new Ca({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],F0=L.ancestorsAreLast.slice(1);for(let L0 of F0)s.push(new C(p.getAncestorPrefix(L0),new g({color:p.connectorColor,dim:p.connectorDim})));let o=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(PN(x))d.push(new D11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:u,warning:u,destructive:u}:R;d.push(...UP3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,W)),new i0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[..._,...d]})})}})}}function Wm4(J){return 1-(1-J)**3}function Um4(J,Z,Q){return J+(Z-J)*Q}function Zo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=Wm4(Y),V=Wm4(X);return{x:Um4(J.startOffset.x,J.targetOffset.x,K),y:Um4(J.startOffset.y,J.targetOffset.y,V)}}var DP3={nodeWidth:3,horizontalSpacing:3};class kv{options;constructor(J={}){this.options={...DP3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var BP3={nodeWidth:3,nodeHeight:2};class yv{options;constructor(J={}){this.options={...BP3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var NP3={nodeWidth:3,nodeHeight:2},wP3={x:0,y:0};class Cz0{options;constructor(J={}){this.options={...NP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=wP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let T=[],S=0;for(let u of R){if(u.position.x>S)T.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;T.push(this.renderNode(m,x,_,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:T})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,T=L+A.position.x+this.options.nodeWidth+1,S=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:T,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:z,bold:F}))}),new J0({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new J0({text:new C(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new J0({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new J0({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new J0({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new J0({text:new C(W.join(""),new g({color:z}))})),V}}var LP3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},OP3={x:0,y:0};class N11{options;constructor(J={}){this.options={...LP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=OP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let T=[],S=0;for(let u of R){if(u.position.x>S)T.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1;T.push(this.renderNode(m,x,_,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:T})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,T=L+A.position.x+this.options.nodeWidth+1,S=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:T,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((N)=>N.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new J0({text:new C(F.join(""),new g({color:z}))})),V}}class Qo extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Hm4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Hm4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class xR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Nm4}}var Dm4=400,Bm4=300,EP3=16;class Nm4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new kv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new yv;renderer=new N11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Dm4,durationY:Bm4};let Z=Math.max(Dm4,Bm4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Zo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},EP3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Qo({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Lm4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Om4}}class Om4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var wm4=30,MP3=30;class vv{}class xv{}class _z0{}class Tz0{}class w11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Em4}}class Em4 extends d0{highlightedIndex=0;controller=new Y$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;jv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof vv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof _z0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof Tz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=MP3+wm4,z=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new SZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new d$({shortcuts:new Map([[new U4("ArrowDown"),new vv],[new U4("ArrowUp"),new xv],[new U4("Tab"),new vv],[new U4("Tab",{shift:!0}),new xv],[new U4("n",{ctrl:!0}),new vv],[new U4("p",{ctrl:!0}),new xv],[new U4("Enter"),new _z0],[new U4("Escape"),new Tz0]]),focusNode:this.focusNode,child:W}),H=new O2({actions:new Map([[vv,new U6(this.invoke)],[xv,new U6(this.invoke)],[_z0,new U6(this.invoke)],[Tz0,new U6(this.invoke)]]),child:U}),D=new W1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,T=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:S})),new C(` (${M.threads.length})`,new g({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Lm4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new i0({padding:C0.all(1),child:new xR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:wm4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new I0({height:1}),new k1({child:E})]})})}}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()}}m0();class Mm4 extends d0{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){P.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){P.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=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),z=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:z,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let H=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:D})),new C(N,new g({color:D,bold:!0}))])})})}return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(F.name,new g({color:D}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,H="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!H)return-1;if(!U&&H)return 1;return q.score-F.score}})}}class L11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class aG extends l0{props;constructor(J){super();this.props=J}createState(){return new Am4}}class Am4 extends d0{_spinner=new G3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new g1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),z=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)z.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:z})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var Yo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},Sz0=["workspace","global","flag","default","external","skill","other"];function AP3(J){return Array.from(new Set(J))}function jm4(J){return AP3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function fv(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return jm4(J).length>0?"skill":"other"}function O11(J){return fv(J)==="skill"}function Rm4(J){let Z=jm4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=fv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Yo[Y].description}: ${Q}`}function Im4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var Pm4=process.platform==="win32"?" ":"█",Cm4=process.platform==="win32"?"░":"█";class L9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Pm4,thumbChar:K=Cm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createState(){return new _m4}}class _m4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),z=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-G,q=Math.max(0,F*z),W=q+G;return J>=q&&J<=W}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),z=Math.max(1,K*G),F=K-z;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,H=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(H)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),z=Math.max(1,V*G),F=Q-Y,q=V-z,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),H=U+z;if(Z>=U&&Z<=H)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?p5.POINTER:p5.DEFAULT,child:new Tm4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class Tm4 extends Ly{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Pm4,thumbChar:K=Cm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createRenderObject(){return new Sm4(this)}updateRenderObject(J){J.updateWidget(this)}}class Sm4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,z=process.platform==="win32",F=Y,q=Y+X;if(!z){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let H="█",D=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);H=W[N]||"█",D=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);H=W[N]||"█"}else if(U>F&&U<q)D=!1;J.setChar(Z,Q+U,H,{fg:G,bg:V,reverse:D},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,H=U>=F&&U<q,D=H?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,D,{fg:H?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class fR extends l0{props;constructor(J){super();this.props=J}createState(){return new km4}}class km4 extends d0{scrollController=new j5;scrollAreaKey=new e7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof o2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=Xz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new g1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),z=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new W1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new L9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),H=q+U;return{totalContentHeight:Math.max(H,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new g({color:Z.app.keybind}),U=new g({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),z,F]})})})}}_2();class ym4 extends l0{props;constructor(J){super();this.props=J}createState(){return new vm4}}class vm4 extends d0{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=k9.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=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((z)=>z.status==="active").length,V=this.plugins.reduce((z,F)=>z+F.registeredCommands.length,0),G=this.plugins.reduce((z,F)=>z+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
7399
+ `))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),F))}return new i0({decoration:{color:G.background,border:c1.all(new g1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}UE();m0();_2();import{execSync as vP3}from"node:child_process";LE();O$();f3();T7();rd();ZA();RV();XJ();$Z();HY();vA();f4();Vm();Kb();w1();var Jp4=G4(QU(),1);import{writeFile as rm4}from"fs/promises";import sm4 from"path";m0();XJ();class W11{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.1774599058-g7bb23d"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await s40(Z,this.configService)}catch(Z){P.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 BL extends l0{props;constructor(J){super();this.props=J}createState(){return new Zm4}}class Zm4 extends d0{_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)}}class Qm4 extends d0{controller=new Y$;focusNode=new W6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=c1.all(new g1(Q.foreground,1,"solid")),z=new SZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let D=H.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new W1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let U=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),F,new b3,U]})})}}class Jo extends l0{props;constructor(J){super();this.props=J}createState(){return new Qm4}}import{isDeepStrictEqual as U11}from"node:util";var VP3=/[\\/_ +.#"@[({&]/,GP3=/[\\/_ +.#"@[({&]/g,zP3=/[\s-]/,Ym4=/[\s-]/g;function Az0(J,Z,Q,Y,X,K,V){if(K===Z.length){if(X===J.length)return 1;return 0.99}let G=`${X},${K}`;if(V[G]!==void 0)return V[G];let z=Y.charAt(K),F=Q.indexOf(z,X),q=0,W,U,H,D;while(F>=0){if(W=Az0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(zP3.test(J.charAt(F-1))){if(W*=0.9,D=J.slice(X,F-1).match(Ym4),D&&X>0)W*=0.999**D.length}else if(VP3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(GP3),H&&X>0)W*=0.999**H.length}else if(W*=0.3,X>0)W*=0.999**(F-X);if(J.charAt(F)!==Z.charAt(K))W*=0.9999}if(W<0.1&&(Q.charAt(F-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(F-1)!==Y.charAt(K))){if(U=Az0(J,Z,Q,Y,F+1,K+2,V),U*0.1>W)W=U*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function Mz0(J){return J.toLowerCase().replace(Ym4," ")}function Xm4(J,Z){let Q=Az0(J,Z,Mz0(J),Mz0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=Az0(J,G,Mz0(J),Mz0(G),0,0,{});if(z===0)return Q;X+=z,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class Tv{}class Sv{}class jz0{}class Rz0{}class Km4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Vm4}}class Vm4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function FP3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Xm4(Z,J);return{matches:Q>0.15,score:Q}}class r2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Gm4}}class Gm4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new Y$(this.widget.props.controller?.query??""),this.focusNode=new W6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>U11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!U11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>U11(Q,this.widget.props.controller?.selectedItem));if(Z>=0)this.selectedIndex=Z}this.clampSelectedIndex(),this.ensureSelectedItemVisible(),this.syncSelection()}}dispose(){this.widget.props.onSelectionChange?.(null),this.textController.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof Tv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Sv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof jz0){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length){let Q=Z[this.selectedIndex];if(Q){if(!(this.widget.props.isItemDisabled?.(Q)??!1))this.widget.props.onAccept(Q,{hasUserInteracted:this.hasUserInteracted})}}return"handled"}if(J instanceof Rz0)return this.widget.props.onDismiss?.(),"handled";return"ignored"};syncSelection(){let Z=this.cachedFiltered[this.selectedIndex]??null;if(this.widget.props.controller)this.widget.props.controller.selectedItem=Z;this.widget.props.onSelectionChange?.(Z)}clampSelectedIndex(){let J=this.cachedFiltered.length-1;if(J<0){this.selectedIndex=0;return}this.selectedIndex=Math.max(0,Math.min(this.selectedIndex,J))}recomputeFilteredItems(){let J=this.textController.text,Z=this.widget.props.items,Q=this.widget.props.normalizeQuery?.(J)??J,Y=Z.filter((X)=>!this.widget.props.filterItem||this.widget.props.filterItem(X,J)).map((X)=>({item:X,...FP3(Q,this.widget.props.getLabel(X))})).filter((X)=>X.matches).sort(this.widget.props.sortItems?(X,K)=>this.widget.props.sortItems(X,K,J):(X,K)=>K.score-X.score).map((X)=>X.item);this.cachedQuery=J,this.cachedItemsRef=Z,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.textController.text,Z=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Z)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;jv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=c1.all(new g1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new SZ({controller:this.textController,focusNode:this.focusNode,autofocus:!0,enabled:V,style:{backgroundColor:Q.background,textColor:Q.foreground,cursorColor:Q.cursor,placeholderColor:Q.mutedForeground,border:null},maxLines:1}),z=new d$({shortcuts:new Map([[new U4("ArrowDown"),new Tv],[new U4("ArrowUp"),new Sv],[new U4("Tab"),new Tv],[new U4("Tab",{shift:!0}),new Sv],[new U4("n",{ctrl:!0}),new Tv],[new U4("p",{ctrl:!0}),new Sv],[new U4("Enter"),new jz0],[new U4("Escape"),new Rz0]]),focusNode:this.focusNode,child:G}),F=new O2({actions:new Map([[Tv,new U6(this.invoke)],[Sv,new U6(this.invoke)],[jz0,new U6(this.invoke)],[Rz0,new U6(this.invoke)]]),child:z}),q=new W1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Km4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new x0({children:N,crossAxisAlignment:"start"})}let U=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(N)}if(!K)H.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);H.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:U}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else H.push(new k1({child:U}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:H})})}}function zm4(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 H11 extends e1{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)=>zm4(X.pubDate).length));return new r2({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 z=f0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,U=K?q.selectionForeground:F.foreground,H=F.mutedForeground,D=(B,N)=>new I0({width:N,child:W1.end([new J0({text:new C(B,new g({color:H}))})])});return new i0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[new k1({child:new J0({text:new C(X.title,new g({color:U})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(zm4(X.pubDate),Q)]})})}})}}class D11 extends l0{createState(){return new Fm4}}class Fm4 extends d0{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=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function qP3(J){return RY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function WP3(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((z)=>z.role==="child"&&Z.has(z.threadID)&&(z.type==="fork"||z.type==="handoff"));if(G){Y.set(V.id,G.type);let z=G.threadID,F=Q.get(z)||[];F.push(V),Q.set(z,F)}else X.push(V)}return tV0.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 B11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function UP3(J,Z,Q,Y){return[B11("+",J,Y.success),b3.horizontal(1),B11("~",Z,Y.warning),b3.horizontal(1),B11("-",Q,Y.destructive)]}function HP3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class Iz0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new qm4}}class qm4 extends d0{spinner=new G3;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===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),z=Z.currentThreadID,F=[...K].sort((L,O)=>{if(z){if(L.id===z)return-1;if(O.id===z)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=WP3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),U=f0.of(J),H=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:U.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:U.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:U.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=qP3(L);return B};return new r2({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(!HP3(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,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:H,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,T=O?j.selectionBackground:void 0,S=O?j.selectionForeground:R.foreground,u=R.mutedForeground,m=(s,F0)=>new I0({width:F0,child:W1.end([new J0({text:new C(s,new g({color:u}))})])}),x=Z.threadViewStates[L.id],_=[],f=L.relationshipType==="handoff",p=new Ca({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],F0=L.ancestorsAreLast.slice(1);for(let L0 of F0)s.push(new C(p.getAncestorPrefix(L0),new g({color:p.connectorColor,dim:p.connectorDim})));let o=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(o);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=z===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(PN(x))d.push(new D11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(f)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:S})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:u,warning:u,destructive:u}:R;d.push(...UP3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,W)),new i0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new W1({children:[..._,...d]})})}})}}function Wm4(J){return 1-(1-J)**3}function Um4(J,Z,Q){return J+(Z-J)*Q}function Zo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=Wm4(Y),V=Wm4(X);return{x:Um4(J.startOffset.x,J.targetOffset.x,K),y:Um4(J.startOffset.y,J.targetOffset.y,V)}}var DP3={nodeWidth:3,horizontalSpacing:3};class kv{options;constructor(J={}){this.options={...DP3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,z)=>{let F=Z.get(G.id)??[];if(this.options.comparator)F.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(F.length===0){Y.push({node:q,position:{x:K,y:z}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let W=[];for(let B of F)W.push(V(B,z+1));let U=Math.min(...W),H=Math.max(...W),D=Math.floor((U+H)/2);return Y.push({node:q,position:{x:D,y:z}}),D};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var BP3={nodeWidth:3,nodeHeight:2};class yv{options;constructor(J={}){this.options={...BP3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let z=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:z}),Y}}var NP3={nodeWidth:3,nodeHeight:2},wP3={x:0,y:0};class Cz0{options;constructor(J={}){this.options={...NP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=wP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let T=[],S=0;for(let u of R){if(u.position.x>S)T.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1,f=u.node.id===K?.copyFlashNodeId;T.push(this.renderNode(m,x,_,f,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:T})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,T=L+A.position.x+this.options.nodeWidth+1,S=O+R*B+1,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:T,top:S,child:this.renderInfoBox(j,u,F,q)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",z=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,F=!1;if(Y)z=X?.threadGraphNodeSelected??K?.primary??z,V="┏━┓",G="┗━┛",F=!0;else if(Z&&Q)z=X?.toolSuccess??K?.primary??z,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:z,bold:F}))}),new J0({text:new C(G,new g({color:z,bold:F}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((U)=>U.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",z="└"+"─".repeat(V)+"┘",F=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,W=[new J0({text:new C(G,new g({color:F}))})];for(let U of X){let H=" ".repeat(K-U.length);W.push(new J0({text:new C("│ ",new g({color:F}),[new C(U+H,new g({color:q??F})),new C(" │",new g({color:F}))])}))}return W.push(new J0({text:new C(z,new g({color:F}))})),new x0({crossAxisAlignment:"start",children:W})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let U of Z){let H=U.position.x+G;if(H>=0&&H<Y)F[H]="▲"}V.push(new J0({text:new C(F.join(""),new g({color:z}))}));let q=Array(Y).fill(" ");for(let U of J){let H=Z.filter((L)=>L.node.parentID===U.node.id);if(H.length===0)continue;let D=U.position.x+G,B=H.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===D)if(H.length===1&&B[0]===D)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:z}))}));let W=Array(Y).fill(" ");for(let U of J){if(Z.filter((B)=>B.node.parentID===U.node.id).length===0)continue;let D=U.position.x+G;if(D>=0&&D<Y)W[D]="│"}return V.push(new J0({text:new C(W.join(""),new g({color:z}))})),V}}var LP3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},OP3={x:0,y:0};class N11{options;constructor(J={}){this.options={...LP3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=OP3,X,K,V,G){let z=G?f0.of(G):null,F=z?.colors,q=z?.app,W=F?.mutedForeground??F?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:W}))});let U=Math.max(...J.map((j)=>j.position.y)),D=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=U;j>=0;j--){let R=J.filter((u)=>u.position.y===j);R.sort((u,m)=>u.position.x-m.position.x);let T=[],S=0;for(let u of R){if(u.position.x>S)T.push(new I0({width:u.position.x-S}));let m=u.node.id===Q,x=V?.(u.node.data)??!1,_=K?.activeFlashOn??!1;T.push(this.renderNode(m,x,_,q,F)),S=u.position.x+this.options.nodeWidth}if(N.push(new W1({crossAxisAlignment:"start",children:T})),j>0){let u=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(u,m,Z,D,F,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(U+1)*B,M=[new I0({width:D,height:E}),new $5({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=U-A.position.y,T=L+A.position.x+this.options.nodeWidth+1,S=O+R*B,u=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)u=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new $5({left:T,top:S,child:this.renderInfoBox(j,u,F)}))}return new i0({padding:C0.horizontal(2),child:new gG(new z5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),z=K?.threadGraphConnector??X?.primary??X?.foreground,F=Array(Y).fill(" ");for(let q of J){let W=Z.filter((N)=>N.node.parentID===q.node.id);if(W.length===0)continue;let U=q.position.x+G,H=W.map((N)=>N.position.x+G),D=Math.min(...H),B=Math.max(...H);for(let N=D;N<=B;N++)if(N>=0&&N<Y){let w=N===U,L=H.includes(N);if(w&&L)if(W.length===1)F[N]="│";else if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┼";else if(w)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┬";else if(L)if(N===D)F[N]="└";else if(N===B)F[N]="┘";else F[N]="┴";else if(F[N]===" ")F[N]="─"}}return V.push(new J0({text:new C(F.join(""),new g({color:z}))})),V}}class Qo extends o3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Hm4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Hm4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class xR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Nm4}}var Dm4=400,Bm4=300,EP3=16;class Nm4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new kv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new yv;renderer=new N11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((z)=>z.id)),Q=new Set(this.widget.props.threads.map((z)=>z.id));if(Z.size!==Q.size||[...Z].some((z)=>!Q.has(z)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let F=this.widget.props.threads.find((q)=>q.id===K);if(F)this.selectedNodeId=F.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((z)=>z.isActive),G=this.widget.props.threads.some((z)=>z.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:Dm4,durationY:Bm4};let Z=Math.max(Dm4,Bm4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Zo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},EP3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,z=Math.floor(this.viewportHeight/2),q=Math.floor(z/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((W)=>W.node.id===this.selectedNodeId):null)??this.positionedNodes.find((W)=>!W.node.parentID);if(q){let W=Math.max(...this.positionedNodes.map((U)=>U.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,W)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(F)=>F.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(F)=>F.isActive??!1,J),z=new Qo({onWidth:(F)=>{if(this.viewportWidth!==F)this.viewportWidth=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(F)=>{if(this.viewportHeight!==F)this.viewportHeight=F,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:z})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class Lm4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new Om4}}class Om4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var wm4=30,MP3=30;class vv{}class xv{}class _z0{}class Tz0{}class w11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Em4}}class Em4 extends d0{highlightedIndex=0;controller=new Y$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new W6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;jv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof vv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof xv){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof _z0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof Tz0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=MP3+wm4,z=c1.all(new g1(Y.foreground,1,"solid")),F=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),W=new SZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),U=new d$({shortcuts:new Map([[new U4("ArrowDown"),new vv],[new U4("ArrowUp"),new xv],[new U4("Tab"),new vv],[new U4("Tab",{shift:!0}),new xv],[new U4("n",{ctrl:!0}),new vv],[new U4("p",{ctrl:!0}),new xv],[new U4("Enter"),new _z0],[new U4("Escape"),new Tz0]]),focusNode:this.focusNode,child:W}),H=new O2({actions:new Map([[vv,new U6(this.invoke)],[xv,new U6(this.invoke)],[_z0,new U6(this.invoke)],[Tz0,new U6(this.invoke)]]),child:U}),D=new W1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:H})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,T=j?X.selectionBackground:void 0,S=j?X.selectionForeground:Y.foreground,u=[new C(M.label,new g({color:S})),new C(` (${M.threads.length})`,new g({color:S,dim:!0}))];if(R)u.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new Lm4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,u)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=F?F.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=F?new i0({padding:C0.all(1),child:new xR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:wm4});E=new W1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:z,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,D,new I0({height:1}),new k1({child:E})]})})}}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()}}m0();class Mm4 extends d0{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){P.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){P.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=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),z=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new r2({title:"Add Label",items:z,getLabel:(F)=>{if("__isCreateMarker"in F)return this.currentQuery.trim().toLowerCase();return F.name},onAccept:(F)=>{if("__isCreateMarker"in F)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(F.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(F,q,W,U)=>{let H=q?Q.selectionBackground:void 0,D=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in F&&F.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:D})),new C(N,new g({color:D,bold:!0}))])})})}return new i0({decoration:H?{color:H}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(F.name,new g({color:D}))})})},filterItem:(F,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in F&&F.__isCreateMarker)return this.shouldShowCreateMarker(q);let U=q.trim().toLowerCase();return U.length===0||F.name.includes(U)},sortItems:(F,q,W)=>{let U="__isCreateMarker"in F.item&&F.item.__isCreateMarker,H="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(U&&!H)return-1;if(!U&&H)return 1;return q.score-F.score}})}}class L11 extends l0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class aG extends l0{props;constructor(J){super();this.props=J}createState(){return new Am4}}class Am4 extends d0{_spinner=new G3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=c1.all(new g1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),z=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)z.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let F=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:z})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:F});return F}}var Yo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},Sz0=["workspace","global","flag","default","external","skill","other"];function AP3(J){return Array.from(new Set(J))}function jm4(J){return AP3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function fv(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return jm4(J).length>0?"skill":"other"}function O11(J){return fv(J)==="skill"}function Rm4(J){let Z=jm4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=fv(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${Yo[Y].description}: ${Q}`}function Im4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var Pm4=process.platform==="win32"?" ":"█",Cm4=process.platform==="win32"?"░":"█";class L9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Pm4,thumbChar:K=Cm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createState(){return new _m4}}class _m4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),z=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),F=X-G,q=Math.max(0,F*z),W=q+G;return J>=q&&J<=W}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),z=Math.max(1,K*G),F=K-z;if(F<=0)return;let q=Z-Q,W=F/q,U=V/W,H=Math.max(0,Math.min(q,this._dragStartOffset+U));this.widget.controller.jumpTo(H)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),z=Math.max(1,V*G),F=Q-Y,q=V-z,W=Math.max(0,Math.min(1,X/(Q-Y))),U=Math.max(0,q*W),H=U+z;if(Z>=U&&Z<=H)return;if(Z<U)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(F,X+Y))};build(J){return new J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?p5.POINTER:p5.DEFAULT,child:new Tm4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class Tm4 extends Ly{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=Pm4,thumbChar:K=Cm4,showTrack:V=!0,thumbColor:G,trackColor:z}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=z}createRenderObject(){return new Sm4(this)}updateRenderObject(J){J.updateWidget(this)}}class Sm4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,z=process.platform==="win32",F=Y,q=Y+X;if(!z){let W=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let H="█",D=!0;if(U===Math.floor(F)){let B=1-(F-U),N=Math.floor(B*8);H=W[N]||"█",D=!1}else if(U===Math.floor(q)){let B=1-(q-U),N=Math.floor(B*8);H=W[N]||"█"}else if(U>F&&U<q)D=!1;J.setChar(Z,Q+U,H,{fg:G,bg:V,reverse:D},1)}return}for(let W=0;W<this.size.height;W++){let U=W+0.5,H=U>=F&&U<q,D=H?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+W,D,{fg:H?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class fR extends l0{props;constructor(J){super();this.props=J}createState(){return new km4}}class km4 extends d0{scrollController=new j5;scrollAreaKey=new e7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof o2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=Xz0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=c1.all(new g1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),z=new k1({child:new c$({child:new i0({padding:C0.symmetric(1,0),child:new W1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new L9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,W=this.scrollController.offset,U=this.getViewportHeight(),H=q+U;return{totalContentHeight:Math.max(H,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(W,0)}}})]})})})}),F=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let W=new g({color:Z.app.keybind}),U=new g({color:Z.colors.foreground,dim:!0});return new C("",U,[new C("Press ",U),new C("Escape",W),new C(" to close • Use ",U),new C("↑↓",W),new C(" or ",U),new C("j/k",W),new C(" to scroll",U)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),z,F]})})})}}_2();class ym4 extends l0{props;constructor(J){super();this.props=J}createState(){return new vm4}}class vm4 extends d0{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=k9.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=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((z)=>z.status==="active").length,V=this.plugins.reduce((z,F)=>z+F.registeredCommands.length,0),G=this.plugins.reduce((z,F)=>z+F.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${d4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${d4(V,"command")}, ${G} ${d4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
7400
7400
 
7401
7401
  `));for(let z of this.plugins){let{icon:F,color:q}=this.statusIcon(z.status),W=this.getRelativePath(z.uri.toString());if(Y.push(new C(`${F} `,new g({color:q}))),Y.push(new C(W,new g({bold:!0}))),Y.push(new C(` ${z.status}`,new g({dim:!0}))),Y.push(new C(`
7402
7402
  `)),z.status==="active"&&z.registeredEvents.length>0)Y.push(new C(" Events: ",new g({dim:!0}))),Y.push(new C(z.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new C(`
@@ -7625,7 +7625,7 @@ ${t.content||""}`:t.content||"",_0=[],e0=t.baseDir.startsWith("file://")?NF0(t.b
7625
7625
  `),process.exit(1)}process.stdout.write(await Nk3(z.result.displayText)+`
7626
7626
  `),process.exit(0)})}ZA();import{stdout as wk3}from"node:process";function Lk3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${PF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Ol4(J){wk3.write(`${Lk3(J)}
7627
7627
  `)}function El4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Ol4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Ol4(Z),process.exit(0)})}var gf3=fL.join(eZ,"logs","headless.log"),r51=fL.join(wy,"device-id.json");async function mf3(){for(let J of EE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => G4(qx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){R7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7628
- `)}function pf3(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 t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")tJ("experimental.agentMode",Z.mode)}function ea4(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 df3(J){try{return await sa4(J,"utf-8")}catch{return J}}async function s51(J,Z,Q){let Y=ea4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!Z31(X,S7.HARNESS_SYSTEM_PROMPT)&&!$o4(K))throw new P1("You are not allowed to do this.",1);tJ("systemPrompt",await df3(Y))}function $o4(J){return!!(J&&c10(J))}function Z31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t51(J){return(J.userEmail?sJ(J.userEmail):!1)||Z31(J.features,S7.DTW_TUI)}function da4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function e51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return t51({userEmail:Z.user.email,features:Z.features})}function $31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function cf3(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 Vq0(J){let Y=cf3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function ca4(J){if(!K5.write(J))await ff3(K5,"drain")}var la4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (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??uK,description:`Custom settings file path (overrides the default location ${uK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${eA})`},{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:n2(),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:hz.SMART.key,description:`Set the agent mode (${gz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",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}],ia4=(J)=>("deprecated"in J)&&J.deprecated===!0,lf3=(J)=>("hidden"in J)&&J.hidden===!0,if3=(J)=>("default"in J),nf3=(J)=>("default"in J)?J.default:void 0,Jo4=[{name:"toggle-skills-count",entryPoint:Pr0}];function af3(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 P1(M3.unknownCommand(Q),1,V)}}async function Q31(J){return{...J,getThreadEnvironment:LZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:N90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YQ(J.configService),pluginService:J.pluginService}}function Zo4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:LZ,filesystem:J.fileSystem,threadService:J.threadService}}var Gq0=Y1.file(ta4.homedir()),J31=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Gq0,".config");function of3(J){return UU4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){WU4(Z);let Q=wK0(),Y=pr0();if((!Q||Y||GS4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(RH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(RH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(wK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function rf3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function $2(J,Z,Q){let Y=Q?.deferAuth??!1;Fu1("0.0.1774590201-g775913");let X=Y40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Gq0,userConfigDir:J31});VS4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{K5.write(`No API key found. Starting login flow...
7628
+ `)}function pf3(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 t2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")tJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")tJ("experimental.agentMode",Z.mode)}function ea4(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 df3(J){try{return await sa4(J,"utf-8")}catch{return J}}async function s51(J,Z,Q){let Y=ea4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!Z31(X,S7.HARNESS_SYSTEM_PROMPT)&&!$o4(K))throw new P1("You are not allowed to do this.",1);tJ("systemPrompt",await df3(Y))}function $o4(J){return!!(J&&c10(J))}function Z31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t51(J){return(J.userEmail?sJ(J.userEmail):!1)||Z31(J.features,S7.DTW_TUI)}function da4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function e51(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return t51({userEmail:Z.user.email,features:Z.features})}function $31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function cf3(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 Vq0(J){let Y=cf3(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 P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function ca4(J){if(!K5.write(J))await ff3(K5,"drain")}var la4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (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??uK,description:`Custom settings file path (overrides the default location ${uK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${eA})`},{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:n2(),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:hz.SMART.key,description:`Set the agent mode (${gz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:gz().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",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}],ia4=(J)=>("deprecated"in J)&&J.deprecated===!0,lf3=(J)=>("hidden"in J)&&J.hidden===!0,if3=(J)=>("default"in J),nf3=(J)=>("default"in J)?J.default:void 0,Jo4=[{name:"toggle-skills-count",entryPoint:Pr0}];function af3(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 P1(M3.unknownCommand(Q),1,V)}}async function Q31(J){return{...J,getThreadEnvironment:LZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new mV(J.fileSystem),generateThreadTitle:N90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YQ(J.configService),pluginService:J.pluginService}}function Zo4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:LZ,filesystem:J.fileSystem,threadService:J.threadService}}var Gq0=Y1.file(ta4.homedir()),J31=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Gq0,".config");function of3(J){return UU4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){WU4(Z);let Q=wK0(),Y=pr0();if((!Q||Y||GS4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(RH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(RH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(wK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function rf3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function $2(J,Z,Q){let Y=Q?.deferAuth??!1;Fu1("0.0.1774599058-g7bb23d");let X=Y40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Gq0,userConfigDir:J31});VS4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let F0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(F0),P.info("API key lookup before login",{found:Boolean(F0),ampURL:J.ampURL,deferAuth:Y}),!F0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{K5.write(`No API key found. Starting login flow...
7629
7629
  `);let o=await sf3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:o,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!o)await JH(),process.exit(1);V=!0}}{let F0=await X.getLatest(),o=F0.settings.url,q0=F0.secrets.isSet?.[o];P.info("Config secrets state after login",{configURL:o,apiKeySet:q0?.apiKey??!1})}let G=M1(YQ(X).pipe(E5((F0)=>F0!=="pending"))),z=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(z),isError:pW(z),errorMessage:pW(z)?z.error.message:void 0});let{toolService:F,dispose:q}=VU4({configService:X}),W=new Map,U=()=>W.clear(),H=new cT0(X,J.settings.getWorkspaceRootPath()),D=Ue1({configService:X,filesystem:E8}),B=Go1({configService:X,trustStore:H,skillMCPServers:D.skillMCPServers,createOAuthProvider:async(F0,o,q0)=>{let L0=`${F0}:${o}`,G0=W.get(L0);if(G0)return P.debug("Reusing existing OAuth provider for server",{serverName:F0,serverUrl:o}),G0;P.debug("Creating OAuth provider for server",{serverName:F0,serverUrl:o});let $0=(async()=>{let W0=new TE(J.secrets),i=await W0.getClientInfo(F0,o),a=q0?.scopes??i?.scopes,t=gP4();P.info("OAuth headless mode check",{useHeadless:t,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:K5.isTTY});let e;if(t)e=J.executeMode?hP4():bP4(F0);let z0=new jI0({storage:W0,serverName:F0,serverUrl:o,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:a,headlessAuthHandler:e});return P.debug("OAuth provider created",{serverName:F0,serverUrl:o,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:a,headlessMode:t,executeMode:J.executeMode}),z0})();return W.set(L0,$0),$0}}),N=tm0({configService:X,filesystem:E8,spawn:wJ0}),w;if(J.executeMode){let F0=await qF4({toolService:F,providers:[B,N],initialTimeout:15000});w=F0.registrations;for(let[o,q0]of F0.initErrors)P.warn(`${o} provider initialization slow or failed:`,q0)}else w=em0({toolService:F,providers:[B,N]});if(Z.jetbrains)BE("JetBrains");else if(Z.ide&&jC4())BE("VS Code");else if(Z.ide&&RC4())BE("Neovim");else if(Z.ide){let F0=await mf3();if(F0){let o=H40(F0.ideName);if(o)BE(o)}}if(J.executeMode)qu1(!0);let L,O=E$.status.pipe(U1((F0)=>Boolean(F0.connected&&F0.authenticated&&F0.ideName&&eu1(F0.ideName))),y4()).subscribe((F0)=>{if(F0){if(!L)L=F.registerTool(FF4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let F0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new eZ0(process.cwd(),{alwaysIncludePaths:F0},!0)}else E=new class extends eZ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await Le1({isDevelopment:!1}),A=new ly0(M,X),j=new xk0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,T=e51(R,z),S=Boolean(T||Z.headless);if(S)P.info("DTW mode enabled: thread sync service disabled");let u=S?rf3():t04({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;E$.status.subscribe((F0)=>{m=F0});let x=new KR0({workspaceRoots:[Y1.file(process.cwd())],fileSystem:E8,getCurrentFile:()=>{if(!m?.openFile)return;try{return Y1.parse(m.openFile)}catch(F0){P.warn("Failed to parse current file URI",{uri:m.openFile,error:F0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let F0=m.openFile;return m.visibleFiles.filter((o)=>o!==F0).map((o)=>{try{return Y1.parse(o)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:o,error:q0}),null}}).filter((o)=>o!==null)}}),_=new lr0,f=process.env.PLUGINS??"off",p=Z.headless?lT4():void 0,d=p??new WK0({configService:X}),h=d instanceof WK0?d:void 0;if(h)h.pluginExecutorKind=T?"local":"unknown";let n=KS0({configService:X,fileSystem:E8,platform:d,internalPlugins:Jo4,pluginFilter:f}),c=Zr1({pluginService:n,toolService:F}),s={codebaseContextService:x,configService:X,toolService:F,mcpService:B,skillService:D,toolboxService:N,trustStore:H,threadService:A,threadHistoryService:j,threadSyncService:u,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:E8,terminal:_,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:z,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let F0 of w.values())F0.dispose();await s.mcpService.dispose(),U(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function sf3(J){if(!J.executeMode){if(!await zK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return K5.write(`Login cancelled. Run the command again to retry.
7630
7630
  `),!1}return await Qo4(J)}async function Qo4(J){let Z=xf3(32).toString("hex"),Q=await Iy(J.ampURL,Z),Y=new AbortController;try{await AV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await Iy(J.ampURL,Z,!1);K5.write(`If your browser does not open automatically, visit:
7631
7631
 
@@ -7633,7 +7633,7 @@ ${c0.blue.bold(X)}
7633
7633
 
7634
7634
  `);try{return await jT4(J.ampURL,Z,J.secrets,Y),K5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),R7.write(`
7635
7635
  Login failed: ${K instanceof Error?K.message:String(K)}
7636
- `),!1}}function na4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function tf3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function ef3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function $u3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!ef3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ju3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Zu3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Qu3(){let J=new oN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)Jj(),process.exit(0);let B=D.originalError??D;QL4(B)}),El4(J,{version:"0.0.1774590201-g775913",buildTimestamp:"2026-03-27T05:47:14.565Z",buildType:"'release'"}),J.addHelpText("after",EC4()),J.configureHelp({formatHelp:MC4}),J.command("logout").description("Log out by removing stored API key").action(async(D,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await Fu3(w)}),J.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 m3(N);await zu3(w,await Ro0(N,w.settings))}),J.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 m3(w);await _L4(D??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),J.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 m3(N);await TL4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7636
+ `),!1}}function na4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function tf3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!b9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function ef3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function $u3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!ef3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Ju3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Zu3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Qu3(){let J=new oN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((D)=>{if(D.code==="commander.help"||D.code==="commander.version"||D.exitCode===0)Jj(),process.exit(0);let B=D.originalError??D;QL4(B)}),El4(J,{version:"0.0.1774599058-g7bb23d",buildTimestamp:"2026-03-27T08:14:47.138Z",buildType:"'release'"}),J.addHelpText("after",EC4()),J.configureHelp({formatHelp:MC4}),J.command("logout").description("Log out by removing stored API key").action(async(D,B)=>{let N=B.optsWithGlobals(),w=await m3(N);await Fu3(w)}),J.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 m3(N);await zu3(w,await Ro0(N,w.settings))}),J.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 m3(w);await _L4(D??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),J.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 m3(N);await TL4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7637
7637
  Actions:
7638
7638
  create Create a new DTW thread and print its ID
7639
7639
  add-message <message> Send a user message and wait for message_added
@@ -7697,8 +7697,8 @@ ${E}
7697
7697
 
7698
7698
  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 Yu3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new _a({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:LZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new mV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function Xu3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Sy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Sy()).trimEnd(),stdinInput:null}}function Ku3(J,Z,Q){if(J.remote&&!Z)throw new P1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new P1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new P1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new P1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new P1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new P1("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 P1("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 P1("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"
7699
7699
  Or pipe via stdin: echo "your message" | amp --execute`)}async function zq0(J,Z,Q){let Y=process.hrtime.bigint(),X=(G0,$0)=>{let W0=Number(process.hrtime.bigint()-$0)/1e6,i=ZH4();P.info("Startup phase",{phase:G0,phaseMs:Math.round(W0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await Xu3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;Ku3({...Z,streamJson:G},J.executeMode,K),t2(Q,Z);let z=process.hrtime.bigint(),F=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&F;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:F,executeMode:J.executeMode,headless:Boolean(Z.headless)});let W=await $2(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",z),z=process.hrtime.bigint();let U=await Q31(W);X("runMainThread:createWorkerDeps",z);let{serverStatus:H}=W;if(!q&&pW(H)){let G0=Pk(Error(H.error.message));if(G0.message===M3.networkOffline||G0.message===M3.networkTimeout)throw Vq0(J.ampURL);throw new P1(M3.invalidAPIKey,1)}let D=m6(H)?H:null,B=D?.user.email,N=$o4(B),w=t51({userEmail:B,features:D?.features}),L=Z.takeMeBack?!1:void 0,O=D!==null&&e51(L,D);if(!q)await s51(Q,Z,H);let E=$31(H),M=E?.features??[],A=E?.team??null,j=FK0(Z,E);if(j instanceof Error)p3(j.message);if((J.executeMode||G)&&w8(Z.mode)&&!N)throw new P1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(D&&!wE(Z.mode,B))throw new P1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await aT4(K,V,W.configService),await W.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!sJ(B))throw new P1("Headless DTW mode is only available for Amp employees",1);let G0=await W.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new P1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!b9($0))throw new P1(`Invalid thread ID: ${$0}`,1);let W0=$0?void 0:await wu3({dependencies:W,visibility:j??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=$0??W0?.threadId;if(!i)throw new P1("Failed to resolve headless thread ID",1);let a=await cP4(i);if(a.status==="already-running")await W.asyncDispose(),await JH(),process.exit(0);try{await uP4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:i,ownerUserId:W0?.ownerUserId,threadVersion:W0?.threadVersion,agentMode:W0?.agentMode,initialToolDiscovery:Promise.all([W.mcpService.initialized,W.toolboxService.initialized]).then(()=>{return}),configService:W.configService,mcpService:W.mcpService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,pluginService:W.pluginService,pluginPlatform:W.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await a.release(),await W.asyncDispose()}await JH(),process.exit(0)}let R=J.executeMode?void 0:async(G0)=>to(G0,"interactive"),T={threadService:W.threadService,workerDeps:U,createThread:async()=>{let G0=q?await W.serverStatusPromise:H,$0=await hZ0(J.settings,process.cwd(),$31(G0),j);if($0 instanceof Error)p3($0.message);return V01(U,{threadMeta:$0?uG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(G0,$0)=>{if($0?.nonBlockingOwnershipCheck){aa4(G0,W.configService).catch((W0)=>{if(W0 instanceof P1){if($0.onOwnershipError){$0.onOwnershipError(W0,G0);return}Zj(W0,G0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})});return}try{await aa4(G0,W.configService)}catch(W0){if(W0 instanceof P1)throw W0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R,handleError:Zj},S=async(G0)=>{try{if(G0==="dtw")return Yu3({ampURL:J.ampURL,configService:W.configService,threadService:W.threadService,mcpService:W.mcpService,toolboxService:W.toolboxService,toolService:W.toolService,skillService:W.skillService,fileSystem:W.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Zb4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof P1)throw $0;throw await Zj($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")R7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7700
- `),await JH(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),$0=Ib(G0),W0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new $01:null,_,f=null;if(x)_=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await s51(Q,Z,G0);let $0=process.hrtime.bigint(),W0=e51(L,G0),i=m6(G0)?t51({userEmail:G0.user.email,features:G0.features}):!1;da4({dtwEnabled:W0,hasV2TUIAccess:i});let a=await S(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(a),K){let t=await M1(a.threadHandles$);if(!t)throw new P1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));x.setInitError($0),await Zj(G0,Z.threadId)});else z=process.hrtime.bigint(),da4({dtwEnabled:O,hasV2TUIAccess:w}),_=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",z);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),of3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(W4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",z),J.executeMode){fT4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await HL4({threadPool:_,...G0});if(await to($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Xb1();let G0=await AE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)E$.selectConfig($0)}else n=!0}z=process.hrtime.bigint();let c=io0("0.0.1774590201-g775913",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let s=new vk0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",z),z=process.hrtime.bigint();let F0=new Ir0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",z),K&&J.executeMode){let G0=await M1(_.threadHandles$);if(!G0)throw new P1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:K}]})}z=process.hrtime.bigint();let o=await HK0();X("runMainThread:loadSessionState",z),P.info("Loaded session state:",o);let q0={...o,launchCount:o.launchCount+1};lj((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await lb4({codebaseContextService:W.codebaseContextService,history:new Nl0,fuzzyServer:W.fuzzyServer,settingsStorage:W.settingsStorage,threadService:W.threadService,threadHistoryService:W.threadHistoryService,threadFuzzyIndexer:s,skillService:W.skillService,configService:W.configService,secretStorage:W.secretStorage,internalAPIClient:g6,threadPool:_,createSystemPromptDeps:async()=>Zo4(W),ideClient:E$,mcpService:W.mcpService,toolboxService:W.toolboxService,mcpTrustHandler:F0,updateService:c,pluginPlatform:W.pluginPlatform,pluginService:W.pluginService},{initialServerStatus:W.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:W.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-27T05:47:14.565Z"},(G0)=>new O01({...G0,threadPool:G0.threadPool},($0)=>new M61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",z),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(J){if(P.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)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7701
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Uo1({get:async(G)=>{if(G!==Og)return;try{let z=await sa4(r51,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==Og)return;await ra4(fL.dirname(r51),{recursive:!0}),await uf3(r51,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:uz()});Wu1(Y);let X=await QC4({...J,workspaceTrust:{current:!0,changes:Gb},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await vT4(J.mcpConfig);X=xT4(X,G)}let K=fL.dirname(X.getSettingsFilePath());qU4(wy,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Zu1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:eT4(await Ro0(J,X))}}function Vu3(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,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function Gu3(){JH4();let J=Vu3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));Hw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?gf3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(pf3(P),P.info("Starting Amp CLI.",{version:"0.0.1774590201-g775913",buildTimestamp:"2026-03-27T05:47:14.565Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Qu3().parseAsync(process.argv)}zU4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Gu3().catch(Zj)});async function zu3(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"),K5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7700
+ `),await JH(),process.exit(1);let u=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await W.configService.getLatest(),$0=Ib(G0),W0=await g6.getUserFreeTierStatus({},{config:W.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(G0){P.error("Failed to fetch free tier status:",G0);return}})(),x=!J.executeMode?new $01:null,_,f=null;if(x)_=x,f=(async()=>{let G0=q?await W.serverStatusPromise:W.serverStatus;await s51(Q,Z,G0);let $0=process.hrtime.bigint(),W0=e51(L,G0),i=m6(G0)?t51({userEmail:G0.user.email,features:G0.features}):!1;da4({dtwEnabled:W0,hasV2TUIAccess:i});let a=await S(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(a),K){let t=await M1(a.threadHandles$);if(!t)throw new P1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:K}]})}})(),f.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));x.setInitError($0),await Zj(G0,Z.threadId)});else z=process.hrtime.bigint(),da4({dtwEnabled:O,hasV2TUIAccess:w}),_=await S(O?"dtw":"worker"),X("runMainThread:createThreadPool",z);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;z=process.hrtime.bigint();let d=await W.configService.getLatest();if(X("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),of3({configService:W.configService,threadService:W.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(W4((G0)=>{if(!G0)return k0.of({});return D5(G0.thread$,G0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",z),J.executeMode){fT4(W.mcpService,J.settings);let G0={userInput:K,stdinInput:V,dependencies:W,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await HL4({threadPool:_,...G0});if(await to($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:W.configService});await W.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Xb1();let G0=await AE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)h=!await W.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)E$.selectConfig($0)}else n=!0}z=process.hrtime.bigint();let c=io0("0.0.1774599058-g7bb23d",W.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let s=new vk0(W.threadStorage);X("runMainThread:createThreadFuzzyIndexer",z),z=process.hrtime.bigint();let F0=new Ir0(W.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",z),K&&J.executeMode){let G0=await M1(_.threadHandles$);if(!G0)throw new P1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:K}]})}z=process.hrtime.bigint();let o=await HK0();X("runMainThread:loadSessionState",z),P.info("Loaded session state:",o);let q0={...o,launchCount:o.launchCount+1};lj((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&b9(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await lb4({codebaseContextService:W.codebaseContextService,history:new Nl0,fuzzyServer:W.fuzzyServer,settingsStorage:W.settingsStorage,threadService:W.threadService,threadHistoryService:W.threadHistoryService,threadFuzzyIndexer:s,skillService:W.skillService,configService:W.configService,secretStorage:W.secretStorage,internalAPIClient:g6,threadPool:_,createSystemPromptDeps:async()=>Zo4(W),ideClient:E$,mcpService:W.mcpService,toolboxService:W.toolboxService,mcpTrustHandler:F0,updateService:c,pluginPlatform:W.pluginPlatform,pluginService:W.pluginService},{initialServerStatus:W.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:W.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:u,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-27T08:14:47.138Z"},(G0)=>new O01({...G0,threadPool:G0.threadPool},($0)=>new M61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",z),f)await f}finally{}await W.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function m3(J){if(P.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)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7701
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Uo1({get:async(G)=>{if(G!==Og)return;try{let z=await sa4(r51,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==Og)return;await ra4(fL.dirname(r51),{recursive:!0}),await uf3(r51,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:uz()});Wu1(Y);let X=await QC4({...J,workspaceTrust:{current:!0,changes:Gb},getHook:process.env.AMP_URL?(G,z)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return z()}:void 0});if(J.mcpConfig){let G=await vT4(J.mcpConfig);X=xT4(X,G)}let K=fL.dirname(X.getSettingsFilePath());qU4(wy,K);let V=await X.get("url","global");if(!V)V=V2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jV(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Zu1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:eT4(await Ro0(J,X))}}function Vu3(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,z)=>z.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function Gu3(){JH4();let J=Vu3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));Hw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?gf3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(pf3(P),P.info("Starting Amp CLI.",{version:"0.0.1774599058-g7bb23d",buildTimestamp:"2026-03-27T08:14:47.138Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await Qu3().parseAsync(process.argv)}zU4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Gu3().catch(Zj)});async function zu3(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"),K5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7702
7702
  `);else if(!jV(J.ampURL))K5.write(`Logging in to ${new URL(J.ampURL).hostname}
7703
7703
  `);let Y=process.env.AMP_API_KEY;if(Y)K5.write(`API key found in environment variable, storing...
7704
7704
  `),await Z.set("apiKey",Y,J.ampURL),K5.write(`API key successfully stored.