@sourcegraph/amp 0.0.1774971219-g0fd6a8 → 0.0.1774987755-gb72e09

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 +13 -13
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4689,7 +4689,7 @@ ${F}`)}}if(J.skipParseResponse)return;try{let X=new Uint8Array(await Y.arrayBuff
4689
4689
  `))}await F.asyncDispose(),process.exit(0)}catch(q){await F.asyncDispose();let W=`Failed to analyze thread context: ${q instanceof Error?q.message:String(q)}`;z(W)}}var HL4=process.hrtime.bigint(),El0=null;function UL4(){El0=process.hrtime.bigint()}function BL4(){if(El0===null)return null;return Number(process.hrtime.bigint()-El0)/1e6}LV();d0();var AA4=H4(N4(),1),fY=H4(EA4(),1),jA4=H4(Dj(),1);import fQ0 from"node:fs";import Yn0 from"node:path";var MA4=Object.keys(C),n53=Yn0.join(jX,"logs"),Xn0=Yn0.join(n53,"cli.log"),a53=10485760;function o53(J){try{if(fQ0.statSync(J).size>a53)fQ0.truncateSync(J,0)}catch{}}var cl,Kn0=!1,dl=null;function r53(J){return J instanceof Error&&J.message.includes("write after end")}function pl(J,Z,Q,Y){if(Kn0)return;try{J[Z](Q,...Y)}catch(X){if(!r53(X))throw X}}function RA4(J){Kn0=!1,dl=null;let{logFile:Z,logLevel:Q}=J;if(!MA4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{fQ0.mkdirSync(Yn0.dirname(Z),{recursive:!0})}catch(G){console.error(`Failed to create log directory: ${G}`)}o53(Z);let Y=fY.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=fY.default.format((G)=>{return G.pid=process.pid,G}),K=[new fY.default.transports.File({filename:Z}),new IA4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new fY.default.transports.Console({level:"debug",format:fY.default.format.combine(fY.default.format.colorize(),fY.default.format.simple())}));cl=fY.default.createLogger({level:MA4.includes(Q)?Q:"info",format:fY.default.format.combine(fY.default.format.timestamp(),X(),Y(),fY.default.format.json(),fY.default.format.errors({stack:!0})),transports:K});let V=cl;return cv1({error:(G,...z)=>{pl(V,"error",G,z)},warn:(G,...z)=>{pl(V,"warn",G,z)},info:(G,...z)=>{pl(V,"info",G,z)},debug:(G,...z)=>{pl(V,"debug",G,z)},audit:(G,...z)=>{let F=typeof z[0]==="object"&&z[0]!==null?{audit:!0,...z[0]}:{audit:!0};pl(V,"info",G,[F])}}),Z}class IA4 extends jA4.default{log({message:J,...Z},Q){AA4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function zH(){if(dl)return dl;let J=cl;if(!J)return Promise.resolve();return Kn0=!0,dl=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,cl===J)cl=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),dl}d0();import{execFile as s53}from"node:child_process";import{promisify as t53}from"node:util";var e53=t53(s53),$33=["private","public","workspace"];function Vn0(J){return J.endsWith("/")?J.slice(0,-1):J}function J33(J){let Z=e$0(J);try{let X=new URL(Z);return Vn0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return Vn0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return Vn0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function TA4(J){try{let{stdout:Z}=await e53("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return J33(Q)}catch{return null}}function Z33(J){let Z=[...$33];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 PA4(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 Q33(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.
4690
4690
  `].join(""));return Error(`Group visibility is not available.
4691
4691
  `)}function CA4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
4692
- `].join("");return Error(Y)}function Y33(J,Z){return Z.includes(J)}function X33(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function _A4(J,Z,Q){if(J===void 0||J===null)return;let Y=Z33(Z);if(typeof J!=="string")return CA4(Q,Y);if(J==="group"&&!Y.includes("group"))return Q33(Z);if(Y33(J,Y))return J;return CA4(Q,Y)}async function K33(J,Z,Q){let Y=await TA4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){C.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return _A4(K,Q,Y)}async function uQ0(J,Z,Q,Y){if(Y)return Y;if(!X33(Q))return PA4(Q);let X=await K33(J,Z,Q);if(X instanceof Error)return X;return X??PA4(Q)}function SA4(J,Z){return _A4(J,Z)}async function kA4(J,Z,Q){let Y=await TA4(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}}n$();function bQ0(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")}v3();U4();FA0();n$();var Z8=v.string().min(1),hQ0=Z8.brand(),zn0=v.string().regex(/^[0-9A-Za-z]{22}$/),V33=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),ll=v.templateLiteral(["T-",V33]),G33=v.enum(["fork","handoff","mention"]),z33=v.enum(["parent","child"]),vA4=v.object({threadID:ll,type:G33,role:z33,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),a6=v.templateLiteral(["M-",zn0]);function zq(){return`M-${bQ0(rO())}`}var r8=v.templateLiteral(["TU-",zn0]);function yA4(){return`TU-${bQ0(rO())}`}var il=v.templateLiteral(["E-",zn0]);function Fn0(){return`E-${bQ0(rO())}`}var F33=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),q33=v.union([v.literal("builtin"),v.object({toolbox:Z8}).strict(),v.object({mcp:Z8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:Z8}).strict(),v.object({remote:Z8}).strict()]),W33=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(Z8).optional()}),xA4=v.looseObject({name:Z8,description:v.string(),inputSchema:F33,source:q33,meta:W33.optional()}),N89=v.object({id:Z8,category:Z8,title:Z8,description:v.string().optional(),pluginName:Z8}),qn0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),fA4=v.object({settings:qn0,workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),uA4=v.enum(["sandbox","local-client"]),nl=v.any().and(v.object({status:v.string()})),bA4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),Fq=Z8,hA4=30000,hk=Pz,D33=v.enum(["file","directory"]),H33=v.object({mtimeMs:v.number().nonnegative().optional()}),al=v.tuple([v.string(),D33,H33.nullish()]),U33=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),UN=v.object({code:U33,message:v.string()}),B33=v.object({ok:v.literal(!0),entries:v.array(al)}),w33=v.object({ok:v.literal(!1),error:UN}),L89=v.discriminatedUnion("ok",[B33,w33]),N33=v.object({ok:v.literal(!0),contentBase64:v.string()}),L33=v.object({ok:v.literal(!1),error:UN}),O89=v.discriminatedUnion("ok",[N33,L33]),O33=Z8,Wn0=v.object({key:Z8,dataType:O33,contentBase64:v.string()}),Dn0=Wn0.extend({toolCallId:r8.optional(),updatedAt:v.string()}),gk=v.looseObject({uri:Pz,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),gA4=v.object({name:Z8,description:v.string(),baseDir:Pz,frontmatter:v.object({name:Z8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),Hn0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),mA4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),mk=v.array(v.discriminatedUnion("type",[Hn0,mA4])),bk=v.record(v.string(),v.unknown()),pA4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),E33=pA4.extend({complete:v.literal(!0),input:bk,normalizedInput:bk.optional()}),M33=pA4.extend({complete:v.literal(!1),input:bk,inputIncomplete:bk,inputPartialJSON:v.object({json:v.string()}),normalizedInput:bk.optional()}),A33=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),j33=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:nl,userInput:A33.optional()}),R33=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),I33=v.object({type:v.literal("redacted_thinking"),data:v.string()}),P33=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:bk}),C33=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:nl,hidden:v.boolean().optional()}),T33=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:ll.optional()}),_33=v.object({uri:Pz,lineCount:v.number().int().nonnegative(),content:v.string().optional()}),S33=v.union([Hn0,mA4,j33]),k33=v.union([Hn0,R33,I33,E33,M33,P33]),Un0=v.array(S33),Bn0=v.array(k33),v33=v.array(C33),Gn0=v.looseObject({line:v.number().int(),column:v.number().int()}),y33=v.looseObject({start:Gn0,end:Gn0}),x33=v.looseObject({name:v.string(),repositoryURL:v.string()}),f33=v.looseObject({currentURL:v.string(),availableProjects:v.array(x33).optional()}),u33=v.object({treeOID:v.string(),repoRoot:v.string()}),wn0=v.looseObject({currentlyVisibleFiles:v.array(Pz),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:Gn0.optional(),cursorLocationLine:v.string().optional(),selectionRange:y33.optional(),snapshotOIDs:v.array(u33).optional(),aggmanContext:f33.optional()}),Nn0=v.custom((J)=>typeof J==="string"&&z$(J)!==void 0),b33=v.object({threadId:ll,role:v.literal("user"),content:Un0,agentMode:Nn0.optional(),discoveredGuidanceFiles:v.array(_33).optional(),meta:T33.optional(),userState:wn0.optional(),readAt:v.string().nullable().optional(),messageId:a6,createdAt:v.string().optional()}),Ln0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),h33=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),g33=v.object({threadId:ll,role:v.literal("assistant"),content:Bn0,state:h33.optional(),usage:Ln0.optional(),readAt:v.string().nullable().optional(),messageId:a6,createdAt:v.string().optional()}),m33=v.object({threadId:ll,role:v.literal("info"),content:v33,messageId:a6,createdAt:v.string().optional()}),dA4=v.discriminatedUnion("role",[b33,g33,m33]),ol=v.object({workspaceRoot:Pz.optional(),workingDirectory:Pz.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),updatedAt:v.string().optional()}),p33=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),d33=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:p33}),c33=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),cA4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(c33).optional(),files:v.array(d33),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),gQ0=v.object({id:v.string(),toolCallId:r8,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:r8.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),l33=v.object({type:v.literal("request"),id:Z8,method:Z8,params:v.unknown()}),i33=v.object({type:v.literal("response"),id:Z8,result:v.unknown().optional(),error:v.string().optional()}),n33=v.object({type:v.literal("event"),event:Z8,data:v.unknown(),span:v.string().optional()}),mQ0=v.discriminatedUnion("type",[l33,i33,n33]);var a33=v.object({type:v.literal("executor_connect"),clientId:hQ0,capabilities:fA4,executorType:uA4.optional()}),o33=v.object({type:v.literal("executor_settings_update"),settings:qn0}),r33=v.object({type:v.literal("executor_tools_register"),tools:v.array(xA4)}),s33=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(Z8)}),t33=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),e33=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:r8}),On0=v.object({type:v.literal("tool_progress"),toolCallId:r8,progress:v.union([bA4,v.unknown()]).optional(),parentToolCallId:r8.optional()}),$83=v.object({type:v.literal("executor_tool_result"),toolCallId:r8,run:nl}),J83=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:Z8,files:v.array(gk),isLast:v.boolean(),userConfigDir:v.any().optional()}),Z83=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:r8,files:v.array(gk),isLast:v.boolean()}),Q83=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:Z8,skills:v.array(gA4),isLast:v.boolean()}),Y83=v.object({type:v.literal("executor_rollback_ack"),editId:il,ok:v.boolean(),error:v.string().optional()}),X83=v.object({type:v.literal("executor_revocation_ack"),toolCallId:r8}),K83=v.object({type:v.literal("executor_environment_snapshot"),environment:ol}),V83=v.object({type:v.literal("executor_environment_update"),environment:ol}),G83=v.object({type:v.literal("executor_artifact_upsert"),artifact:Wn0,toolCallId:r8.optional()}),z83=v.object({type:v.literal("executor_artifact_delete"),key:Z8}),F83=v.object({type:v.literal("executor_tool_approval_request"),approval:gQ0}),q83=v.object({type:v.literal("executor_plugin_message"),message:mQ0}),W83=v.object({type:v.literal("client_append_user_msg"),content:mk,userState:wn0.optional(),discoveredGuidanceFiles:v.array(gk).optional(),agentMode:v.string().optional(),messageId:a6}),D83=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:a6}),H83=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:a6}),U83=v.object({type:v.literal("client_edit_message"),messageId:a6,editId:il,content:mk,agentMode:v.string().optional()}),B83=v.object({type:v.literal("client_mark_message_read"),messageId:a6}),w83=v.object({type:v.literal("client_mark_message_unread"),messageId:a6}),N83=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),L83=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),O83=v.object({endpoint:v.string().url(),keys:L83}),E83=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:O83,threadURL:v.string().min(1)}),M83=v.object({type:v.literal("client_filesystem_read_directory"),requestId:Fq,uri:hk}),A83=v.object({type:v.literal("client_filesystem_read_file"),requestId:Fq,uri:hk}),j83=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(al).optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),R83=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),I83=v.object({type:v.literal("client_resume"),version:v.number()}),P83=v.object({type:v.literal("client_retry")}),C83=v.object({type:v.literal("client_cancel")}),T83=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:nl,hidden:v.boolean().optional()}),_83=v.object({type:v.literal("client_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),S83=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),j89=v.enum(["agg-man"]),lA4=v.discriminatedUnion("type",[a33,o33,r33,s33,t33,e33,On0,$83,J83,Z83,Q83,Y83,X83,K83,V83,G83,z83,F83,q83,W83,D83,H83,U83,B83,w83,N83,E83,M83,A83,j83,R83,I83,P83,C83,T83,_83,S83]);n$();n$();var k83=v.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),v83=v.enum(["start","generating","tool_use","complete","error"]),y83=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),x83=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),f83=v.enum(["starting","running","failed"]),u83=v.object({cutMessageId:a6,createdAt:v.string()}),iA4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:a6,content:mk,userState:v.any().optional(),discoveredGuidanceFiles:v.array(gk).optional(),createdAt:v.string().optional()})}),b83=v.object({type:v.literal("agent_state"),state:k83,messageId:a6.optional()}),h83=v.object({type:v.literal("error"),message:v.string(),code:v.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()}),g83=v.object({type:v.literal("error_set"),seq:v.number(),error:y83}),m83=v.object({type:v.literal("error_cleared"),seq:v.number()}),p83=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:a6.optional()}),d83=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),c83=v.object({type:v.literal("retry_started")}),l83=v.object({type:v.literal("retry_cancelled")}),i83=v.object({type:v.literal("executor_connected"),executorId:hQ0,registeredToolCount:v.number(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),n83=v.object({type:v.literal("tool_lease"),toolCallId:r8,toolName:v.string(),args:v.unknown(),messageId:a6,parentToolCallId:r8.optional()}),a83=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:Fq,uri:hk}),o83=v.object({type:v.literal("executor_filesystem_read_file"),requestId:Fq,uri:hk}),r83=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(al).optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),s83=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),t83=v.object({type:v.literal("tool_approval_queue"),approvals:v.array(gQ0)}),e83=v.object({type:v.literal("executor_rollback_request"),editId:il,messageId:a6,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(r8)}),$93=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),J93=v.object({type:v.literal("plugin_message"),message:mQ0}),Z93=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),Q93=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),Y93=v.object({type:v.literal("delta"),messageId:a6,role:v.literal("assistant"),blocks:Bn0.optional(),state:v83,usage:Ln0.optional(),parentToolCallId:r8.optional()}),X93=v.object({type:v.literal("delta"),messageId:a6,role:v.literal("user"),blocks:Un0.optional(),state:v.literal("complete"),parentToolCallId:r8.optional()}),K93=v.discriminatedUnion("role",[Y93,X93]),V93=v.object({type:v.literal("queued_messages"),messages:v.array(iA4)}),G93=v.object({type:v.literal("queued_message_added"),message:iA4,seq:v.number()}),z93=v.object({type:v.literal("queued_message_removed"),queuedMessageId:a6,seq:v.number()}),F93=v.object({type:v.literal("message_added"),message:dA4,seq:v.number(),parentToolUseId:Z8.optional()}),q93=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),W93=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:a6,content:mk,truncateToMessageId:a6,reason:v.literal("message_edit"),agentMode:Nn0.optional()}),D93=v.looseObject({type:v.literal("cf_agent_state")}),H93=v.looseObject({type:v.literal("cf_agent_mcp_servers")}),U93=v.looseObject({type:v.literal("cf_agent_identity")}),B93=v.object({type:v.literal("observers"),count:v.number(),observers:v.array(x83),hasExecutor:v.boolean().optional()}),w93=v.object({type:v.literal("executor_status"),spawnId:v.string(),status:f83,message:v.string().optional(),executorId:v.string().optional()}),N93=v.object({type:v.literal("environment_update"),environment:ol}),L93=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(Dn0)}),O93=v.object({type:v.literal("artifact_upserted"),artifact:Dn0}),E93=v.object({type:v.literal("artifact_deleted"),key:Z8}),M93=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),A93=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),j93=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(vA4)}),R93=v.object({type:v.literal("compaction_started")}),I93=v.object({type:v.literal("compaction_complete"),cutMessageId:a6}),P93=v.object({type:v.literal("compaction_records"),records:v.array(u83)}),pQ0=v.discriminatedUnion("type",[b83,h83,g83,m83,p83,d83,c83,l83,i83,n83,a83,o83,r83,s83,t83,e83,$93,J93,Z93,On0,Q93,K93,V93,G93,z93,F93,q93,W93,D93,H93,U93,B93,w93,N93,L93,O93,E93,M93,A93,j93,R93,I93,P93]);var En0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)}),nA4=En0(lA4),C93=v.union([pQ0,v.array(pQ0)]),aA4=En0(pQ0),oA4=En0(C93);U4();function rA4(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(z1.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 sA4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Mn0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function T93(J){return J.replace(/\s+/g," ").trim()}function _93(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function S93(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 Mn0(JSON.stringify(J),120)}catch{return Mn0(String(J),120)}}function tA4(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 k93(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=tA4(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 eA4(J){for(let Z of J){let Q=k93(Z);if(Q)return Q}return null}function v93(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"||tA4(Q.path)==="type")})}function y93(J,Z){let Q=eA4(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 $j4(J,Z,Q){let Y=_93(Z),X=(()=>{let F=T93(J);if(F.length===0)return null;return Mn0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=eA4(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=S93(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(v93(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:y93(G,Y),messageType:G,typePreview:z,payloadPreview:X,issues:Y}}function sl(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 Jj4(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}}n$();var Zj4="[dtw-parse-error]",jn0="dtw-parse-error",x93=v.object({kind:v.literal(jn0),failureType:v.enum(sA4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),f93=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function An0(J){return{kind:jn0,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 Qj4(J){let Z=An0(J);return JSON.stringify(Z)}function Yj4(J,Z){let Q=$j4(J,Z);return Qj4({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 Rn0(J){let Z=J.startsWith(Zj4)?J.slice(Zj4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=x93.safeParse(Q);if(Y.success)return An0(Y.data);let X=f93.safeParse(Q);if(X.success)return An0(X.data);return null}E1();class In0 extends Error{constructor(J){super(J);this.name="DTWError"}}class s8 extends In0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}E1();var u93=1000,b93=30000,h93=5,g93=30000,m93=15000,p93=200,d93=30000,Xj4=["online","focus","pageshow","keydown","pointerdown"],Kj4=["visibilitychange"];function Cn0(){return globalThis}function Gj4(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 Vj4(){return Gj4(Cn0().window)}function Pn0(){let J=Cn0().document;if(!Gj4(J))return null;return J}function c93(){let J=Cn0().navigator;if(!J||typeof J!=="object")return null;return J}function l93(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 dQ0(J){return!!(J.apiKey&&J.WebSocketClass)}function Tn0(J){if(dQ0(J))return"one-step";return"two-step"}class _n0{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 F4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new F4([]);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??u93,maxReconnectDelayMs:J.maxReconnectDelayMs??b93,maxReconnectAttempts:J.maxReconnectAttempts??h93,pingIntervalMs:J.pingIntervalMs??g93,connectTimeoutMs:J.connectTimeoutMs??m93,WebSocketClass:J.WebSocketClass,useThreadActors:J.useThreadActors},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${Tn0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(J){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||J<=0)return Promise.resolve(!1);return new Promise((Z)=>{let Q=!1,Y=null,X=null,K=(V)=>{if(Q)return;if(Q=!0,Y)clearTimeout(Y),Y=null;X?.unsubscribe(),X=null,Z(V)};Y=setTimeout(()=>{K(!1)},J),X=this.connectionSubject.subscribe({next:(V)=>{if(V.state==="connected")K(!0)},error:()=>{K(!1)},complete:()=>{K(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=p93,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new s8("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(dQ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new s8("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 s8("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=${l93(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 s8(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new s8("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=setTimeout(()=>{X(),this.updateConnectionState("disconnected");try{if(J.readyState===WebSocket.CONNECTING)J.close()}catch{}Q(new s8(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),X=()=>{clearTimeout(Y),J.removeEventListener("open",K),J.removeEventListener("error",V),J.removeEventListener("close",G)},K=()=>{X(),Z()},V=(z)=>{X(),this.updateConnectionState("disconnected");let F="message"in z?z.message:("error"in z)&&z.error instanceof Error?z.error.message:z.type;Q(new s8(`WebSocket connection failed: ${F}`))},G=(z)=>{X(),this.updateConnectionState("disconnected"),Q(new s8(`WebSocket closed during connect: code=${z.code} reason=${z.reason||"none"}`))};if(J.addEventListener("open",K),J.addEventListener("error",V),J.addEventListener("close",G),J.readyState===WebSocket.OPEN)return K();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return G({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){if(J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now(),this.startPingIntervalOnce();return}this.startPingIntervalOnce(),this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.startPingIntervalOnce(),this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),!this.config.useThreadActors)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=Vj4(),Z=Pn0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=c93();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Pn0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=Vj4(),Z=Pn0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of Xj4)J?.addEventListener(Y,Q);for(let Y of Kj4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of Xj4)J?.removeEventListener(Y,Q);for(let Y of Kj4)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},d93)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}var i93=3000,n93=30000,a93=5;function o93(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 qq extends _n0{deltaSubject=new z4;errorSubject=new z4;errorEventSubject=new z4;cancelledSubject=new z4;agentStateSubject=new z4;messageAddedSubject=new z4;editRejectedSubject=new z4;messageEditedSubject=new z4;queuedMessagesSubject=new z4;retrySubject=new z4;toolLeaseSubject=new z4;toolLeaseRevokedSubject=new z4;toolApprovalQueueSubject=new z4;executorToolApprovalResponseSubject=new z4;toolProgressSubject=new z4;executorErrorSubject=new z4;executorConnectedSubject=new z4;executorRollbackRequestSubject=new z4;observersSubject=new z4;executorStatusSubject=new z4;environmentUpdateSubject=new z4;artifactsSubject=new z4;threadTitleSubject=new z4;threadStatusSubject=new z4;threadRelationshipsSubject=new z4;compactionSubject=new z4;compactionRecordsSubject=new z4;pluginMessageSubject=new z4;fileSystemReadDirectoryRequestSubject=new z4;fileSystemReadFileRequestSubject=new z4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;ensureConnectedPromise=null;constructor(J){super(J)}async ensureConnected(J){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(J);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(J){let Z=J?.baseDelayMs??i93,Q=J?.maxDelayMs??n93,Y=J?.maxAttempts??a93;if(J?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let X=0;X<Y;X++){try{await this.connect()}catch(z){if(this.getConnectionInfo().state!=="reconnecting")throw z;J?.onRetryableConnectError?.(z)}let K=J?.waitForConnectedTimeoutMs??Math.min(Z*2**X,Q);if(await this.waitForConnected(K))return!0;let G=X+1<Y?Math.min(Z*2**(X+1),Q):null;J?.onAttemptTimeout?.({attempt:X+1,maxAttempts:Y,nextDelayMs:G})}return!1}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??zq();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 s8("Transport is disposed");if(!this.hasOpenSocket())throw new s8("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=sl(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 s8("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new s8(`Filesystem request timed out: ${Z}`))},hA4);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(o93(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 s8(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new s8(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=oA4.safeDecode(J);if(!Z.success){let Y=aA4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:Yj4(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(nA4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new s8(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function r93(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 s93(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function t93(J){if(r93(J))return J.queuedMessage.messageId;if(s93(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function Sn0(J,Z,Q={}){let Y=Q.getQueuedMessageId??t93;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 e93=15000;function $73(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 kn0(J){let Z=J.workerUrl??d7(J.ampURL),Q=new qq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??e93;if(!await Q.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:Y}))throw Error(`Timed out waiting for DTW connection after ${Y}ms`);Q.resumeFromVersion(0);let K=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),V=$73(Q,K,Y);try{return{messageId:(await V.promise).message.messageId}}finally{V.dispose(),Q.dispose()}}import{watch as J73}from"node:fs";import{mkdir as Z73,readdir as Q73,readFile as Y73}from"node:fs/promises";import{createServer as X73}from"node:http";import vn0 from"node:path";function zj4(J){return J instanceof Error?J.message:String(J)}function wj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function K73(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function Fj4(J,Z){let Q=vn0.basename(Z),Y=Q.endsWith(".json")?vn0.join(J,Q):vn0.join(J,`${Q}.json`),X=await Y73(Y,"utf-8");return JSON.parse(X)}async function V73(J){let Z=await Q73(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await Fj4(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 G73(){return`<!doctype html>
4692
+ `].join("");return Error(Y)}function Y33(J,Z){return Z.includes(J)}function X33(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function _A4(J,Z,Q){if(J===void 0||J===null)return;let Y=Z33(Z);if(typeof J!=="string")return CA4(Q,Y);if(J==="group"&&!Y.includes("group"))return Q33(Z);if(Y33(J,Y))return J;return CA4(Q,Y)}async function K33(J,Z,Q){let Y=await TA4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){C.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return _A4(K,Q,Y)}async function uQ0(J,Z,Q,Y){if(Y)return Y;if(!X33(Q))return PA4(Q);let X=await K33(J,Z,Q);if(X instanceof Error)return X;return X??PA4(Q)}function SA4(J,Z){return _A4(J,Z)}async function kA4(J,Z,Q){let Y=await TA4(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}}n$();function bQ0(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")}v3();U4();FA0();n$();var Z8=v.string().min(1),hQ0=Z8.brand(),zn0=v.string().regex(/^[0-9A-Za-z]{22}$/),V33=v.templateLiteral([v.string().regex(/^[0-9a-f]{8}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{4}$/),"-",v.string().regex(/^[0-9a-f]{12}$/)]),ll=v.templateLiteral(["T-",V33]),G33=v.enum(["fork","handoff","mention"]),z33=v.enum(["parent","child"]),vA4=v.object({threadID:ll,type:G33,role:z33,messageIndex:v.number().int().nonnegative().optional(),blockIndex:v.number().int().nonnegative().optional(),createdAt:v.number().int().nonnegative(),comment:v.string().optional()}),a6=v.templateLiteral(["M-",zn0]);function zq(){return`M-${bQ0(rO())}`}var r8=v.templateLiteral(["TU-",zn0]);function yA4(){return`TU-${bQ0(rO())}`}var il=v.templateLiteral(["E-",zn0]);function Fn0(){return`E-${bQ0(rO())}`}var F33=v.looseObject({type:v.literal("object"),properties:v.record(v.string(),v.unknown()),required:v.array(v.string()).optional(),additionalProperties:v.boolean().optional()}),q33=v.union([v.literal("builtin"),v.object({toolbox:Z8}).strict(),v.object({mcp:Z8,target:v.enum(["global","workspace","flag","default"]).optional()}).strict(),v.object({plugin:Z8}).strict(),v.object({remote:Z8}).strict()]),W33=v.object({serial:v.boolean().optional(),deferred:v.boolean().optional(),skillNames:v.array(Z8).optional()}),xA4=v.looseObject({name:Z8,description:v.string(),inputSchema:F33,source:q33,meta:W33.optional()}),N89=v.object({id:Z8,category:Z8,title:Z8,description:v.string().optional(),pluginName:Z8}),qn0=v.strictObject({"agent.deepReasoningEffort":v.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":v.array(v.string()).optional(),"anthropic.thinking.enabled":v.boolean().optional(),"anthropic.interleavedThinking.enabled":v.boolean().optional(),"anthropic.temperature":v.number().optional(),"anthropic.effort":v.enum(["low","medium","high","max"]).optional(),"anthropic.speed":v.enum(["standard","fast"]).optional(),"anthropic.provider":v.enum(["anthropic","vertex"]).optional(),"openai.speed":v.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":v.number().min(0).max(100).optional(),"internal.model":v.union([v.string(),v.record(v.string(),v.string())]).optional(),"internal.oracleReasoningEffort":v.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":v.enum(["minimal","low","medium","high"]).optional(),"tools.disable":v.array(v.string()).optional(),"tools.enable":v.array(v.string()).optional()}),fA4=v.object({settings:qn0,workspaceId:v.string(),workingDirectory:v.string(),environment:v.object({os:v.enum(["darwin","linux","windows"]),hasDocker:v.boolean().optional(),hasBrowser:v.boolean().optional()}).strict(),tags:v.array(v.string())}).strict(),uA4=v.enum(["sandbox","local-client"]),nl=v.any().and(v.object({status:v.string()})),bA4=v.discriminatedUnion("type",[v.object({type:v.literal("delta"),blocks:v.array(v.unknown()).optional(),state:v.enum(["start","generating","tool_use","complete","error"])}),v.object({type:v.literal("snapshot"),value:v.unknown()})]),Fq=Z8,hA4=30000,hk=Pz,D33=v.enum(["file","directory"]),H33=v.object({mtimeMs:v.number().nonnegative().optional()}),al=v.tuple([v.string(),D33,H33.nullish()]),U33=v.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),UN=v.object({code:U33,message:v.string()}),B33=v.object({ok:v.literal(!0),entries:v.array(al)}),w33=v.object({ok:v.literal(!1),error:UN}),L89=v.discriminatedUnion("ok",[B33,w33]),N33=v.object({ok:v.literal(!0),contentBase64:v.string()}),L33=v.object({ok:v.literal(!1),error:UN}),O89=v.discriminatedUnion("ok",[N33,L33]),O33=Z8,Wn0=v.object({key:Z8,dataType:O33,contentBase64:v.string()}),Dn0=Wn0.extend({toolCallId:r8.optional(),updatedAt:v.string()}),gk=v.looseObject({uri:Pz,content:v.string().optional(),lineCount:v.int().optional(),hash:v.string().optional()}),gA4=v.object({name:Z8,description:v.string(),baseDir:Pz,frontmatter:v.object({name:Z8,description:v.string()}).catchall(v.unknown()),files:v.array(v.string()).optional()}),Hn0=v.object({type:v.literal("text"),text:v.string(),hidden:v.boolean().optional()}),mA4=v.looseObject({type:v.literal("image"),source:v.discriminatedUnion("type",[v.object({type:v.literal("base64"),mediaType:v.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:v.string()}),v.object({type:v.literal("url"),url:v.string()})]),sourcePath:v.string()}),mk=v.array(v.discriminatedUnion("type",[Hn0,mA4])),bk=v.record(v.string(),v.unknown()),pA4=v.object({type:v.literal("tool_use"),id:v.string().min(1),name:v.string().min(1),normalizedName:v.string().optional(),metadata:v.record(v.string(),v.unknown()).optional()}),E33=pA4.extend({complete:v.literal(!0),input:bk,normalizedInput:bk.optional()}),M33=pA4.extend({complete:v.literal(!1),input:bk,inputIncomplete:bk,inputPartialJSON:v.object({json:v.string()}),normalizedInput:bk.optional()}),A33=v.object({accepted:v.boolean(),askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}),j33=v.object({type:v.literal("tool_result"),toolUseID:v.string().min(1),run:nl,userInput:A33.optional()}),R33=v.object({type:v.literal("thinking"),thinking:v.string(),signature:v.string()}),I33=v.object({type:v.literal("redacted_thinking"),data:v.string()}),P33=v.object({type:v.literal("server_tool_use"),id:v.string().min(1),name:v.string().min(1),input:bk}),C33=v.object({type:v.literal("manual_bash_invocation"),args:v.object({cmd:v.string(),args:v.array(v.string()).readonly().optional(),cwd:v.string().optional()}),toolRun:nl,hidden:v.boolean().optional()}),T33=v.object({sentAt:v.number().int().nonnegative().optional(),fromAggman:v.boolean().optional(),fromExecutorThreadID:ll.optional()}),_33=v.object({uri:Pz,lineCount:v.number().int().nonnegative(),content:v.string().optional()}),S33=v.union([Hn0,mA4,j33]),k33=v.union([Hn0,R33,I33,E33,M33,P33]),Un0=v.array(S33),Bn0=v.array(k33),v33=v.array(C33),Gn0=v.looseObject({line:v.number().int(),column:v.number().int()}),y33=v.looseObject({start:Gn0,end:Gn0}),x33=v.looseObject({name:v.string(),repositoryURL:v.string()}),f33=v.looseObject({currentURL:v.string(),availableProjects:v.array(x33).optional()}),u33=v.object({treeOID:v.string(),repoRoot:v.string()}),wn0=v.looseObject({currentlyVisibleFiles:v.array(Pz),runningTerminalCommands:v.array(v.string()).optional(),activeEditor:v.any().optional(),cursorLocation:Gn0.optional(),cursorLocationLine:v.string().optional(),selectionRange:y33.optional(),snapshotOIDs:v.array(u33).optional(),aggmanContext:f33.optional()}),Nn0=v.custom((J)=>typeof J==="string"&&z$(J)!==void 0),b33=v.object({threadId:ll,role:v.literal("user"),content:Un0,agentMode:Nn0.optional(),discoveredGuidanceFiles:v.array(_33).optional(),meta:T33.optional(),userState:wn0.optional(),readAt:v.string().nullable().optional(),messageId:a6,createdAt:v.string().optional()}),Ln0=v.object({model:v.string().optional(),maxInputTokens:v.number(),inputTokens:v.number(),outputTokens:v.number(),cacheCreationInputTokens:v.number().nullable(),cacheReadInputTokens:v.number().nullable(),totalInputTokens:v.number(),thinkingBudget:v.number().optional(),timestamp:v.string().optional()}),h33=v.union([v.object({type:v.literal("complete")}),v.object({type:v.literal("cancelled")})]),g33=v.object({threadId:ll,role:v.literal("assistant"),content:Bn0,state:h33.optional(),usage:Ln0.optional(),readAt:v.string().nullable().optional(),messageId:a6,createdAt:v.string().optional()}),m33=v.object({threadId:ll,role:v.literal("info"),content:v33,messageId:a6,createdAt:v.string().optional()}),dA4=v.discriminatedUnion("role",[b33,g33,m33]),ol=v.object({workspaceRoot:Pz.optional(),workingDirectory:Pz.optional(),rootDirectoryListing:v.string().nullable().optional(),trees:v.array(v.any()).optional(),platform:v.any().optional(),tags:v.array(v.string()).optional(),updatedAt:v.string().optional()}),p33=v.object({added:v.number().int().nonnegative(),deleted:v.number().int().nonnegative(),changed:v.number().int().nonnegative()}),d33=v.object({path:v.string(),previousPath:v.string().optional(),changeType:v.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:v.boolean(),diff:v.string(),fullFileDiff:v.string().optional(),oldContent:v.string().optional(),newContent:v.string().optional(),diffStat:p33}),c33=v.object({hash:v.string(),shortHash:v.string(),subject:v.string()}),cA4=v.object({provider:v.literal("git"),capturedAt:v.number(),available:v.boolean(),repositoryRoot:v.string().nullable(),repositoryName:v.string().nullable(),branch:v.string().nullable(),head:v.string().nullable(),baseRef:v.string().nullable().optional(),baseRefHead:v.string().nullable().optional(),aheadCount:v.number().int().nonnegative().optional(),behindCount:v.number().int().nonnegative().optional(),aheadCommits:v.array(c33).optional(),files:v.array(d33),unavailableReason:v.string().optional(),unchanged:v.boolean().optional()}),gQ0=v.object({id:v.string(),toolCallId:r8,toolName:v.string(),args:v.record(v.string(),v.unknown()),reason:v.string().optional(),toAllow:v.array(v.string()).optional(),context:v.enum(["thread","subagent"]),subagentToolName:v.string().optional(),parentToolCallId:r8.optional(),timestamp:v.number(),matchedRule:v.object({tool:v.string(),action:v.string(),matches:v.record(v.string(),v.unknown()).optional()}).optional(),ruleSource:v.enum(["user","built-in"]).optional()}),l33=v.object({type:v.literal("request"),id:Z8,method:Z8,params:v.unknown()}),i33=v.object({type:v.literal("response"),id:Z8,result:v.unknown().optional(),error:v.string().optional()}),n33=v.object({type:v.literal("event"),event:Z8,data:v.unknown(),span:v.string().optional()}),mQ0=v.discriminatedUnion("type",[l33,i33,n33]);var a33=v.object({type:v.literal("executor_connect"),clientId:hQ0,capabilities:fA4,executorType:uA4.optional()}),o33=v.object({type:v.literal("executor_settings_update"),settings:qn0}),r33=v.object({type:v.literal("executor_tools_register"),tools:v.array(xA4)}),s33=v.object({type:v.literal("executor_tools_unregister"),toolNames:v.array(Z8)}),t33=v.object({type:v.literal("executor_tools_bootstrap_complete"),ok:v.boolean(),error:v.string().optional()}),e33=v.object({type:v.literal("executor_tool_lease_ack"),toolCallId:r8}),On0=v.object({type:v.literal("tool_progress"),toolCallId:r8,progress:v.union([bA4,v.unknown()]).optional(),parentToolCallId:r8.optional()}),$83=v.object({type:v.literal("executor_tool_result"),toolCallId:r8,run:nl}),J83=v.object({type:v.literal("executor_guidance_snapshot"),snapshotId:Z8,files:v.array(gk),isLast:v.boolean(),userConfigDir:v.any().optional()}),Z83=v.object({type:v.literal("executor_guidance_discovery"),toolCallId:r8,files:v.array(gk),isLast:v.boolean()}),Q83=v.object({type:v.literal("executor_skill_snapshot"),snapshotId:Z8,skills:v.array(gA4),isLast:v.boolean()}),Y83=v.object({type:v.literal("executor_rollback_ack"),editId:il,ok:v.boolean(),error:v.string().optional()}),X83=v.object({type:v.literal("executor_revocation_ack"),toolCallId:r8}),K83=v.object({type:v.literal("executor_environment_snapshot"),environment:ol}),V83=v.object({type:v.literal("executor_environment_update"),environment:ol}),G83=v.object({type:v.literal("executor_artifact_upsert"),artifact:Wn0,toolCallId:r8.optional()}),z83=v.object({type:v.literal("executor_artifact_delete"),key:Z8}),F83=v.object({type:v.literal("executor_tool_approval_request"),approval:gQ0}),q83=v.object({type:v.literal("executor_plugin_message"),message:mQ0}),W83=v.object({type:v.literal("client_append_user_msg"),content:mk,userState:wn0.optional(),discoveredGuidanceFiles:v.array(gk).optional(),agentMode:v.string().optional(),messageId:a6}),D83=v.object({type:v.literal("client_remove_queued_msg"),queuedMessageId:a6}),H83=v.object({type:v.literal("client_interrupt_queued_msg"),queuedMessageId:a6}),U83=v.object({type:v.literal("client_edit_message"),messageId:a6,editId:il,content:mk,agentMode:v.string().optional()}),B83=v.object({type:v.literal("client_mark_message_read"),messageId:a6}),w83=v.object({type:v.literal("client_mark_message_unread"),messageId:a6}),N83=v.object({type:v.literal("client_set_thread_title"),title:v.string().trim().min(1).max(256)}),L83=v.object({auth:v.string().min(1),p256dh:v.string().min(1)}),O83=v.object({endpoint:v.string().url(),keys:L83}),E83=v.object({type:v.literal("client_upsert_notification_subscription"),subscription:O83,threadURL:v.string().min(1)}),M83=v.object({type:v.literal("client_filesystem_read_directory"),requestId:Fq,uri:hk}),A83=v.object({type:v.literal("client_filesystem_read_file"),requestId:Fq,uri:hk}),j83=v.object({type:v.literal("executor_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(al).optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),R83=v.object({type:v.literal("executor_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),I83=v.object({type:v.literal("client_resume"),version:v.number()}),P83=v.object({type:v.literal("client_retry")}),C83=v.object({type:v.literal("client_cancel")}),T83=v.object({type:v.literal("client_append_manual_bash_invocation"),args:v.object({cmd:v.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:v.array(v.string()).optional(),cwd:v.string().optional()}),run:nl,hidden:v.boolean().optional()}),_83=v.object({type:v.literal("client_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),S83=v.object({type:v.literal("client_spawn_executor"),requestId:v.string().optional(),repositoryURL:v.string().optional(),projectID:v.uuid().optional(),additionalRepositories:v.array(v.object({name:v.string(),url:v.string()})).optional()}),j89=v.enum(["agg-man"]),lA4=v.discriminatedUnion("type",[a33,o33,r33,s33,t33,e33,On0,$83,J83,Z83,Q83,Y83,X83,K83,V83,G83,z83,F83,q83,W83,D83,H83,U83,B83,w83,N83,E83,M83,A83,j83,R83,I83,P83,C83,T83,_83,S83]);n$();n$();var k83=v.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),v83=v.enum(["start","generating","tool_use","complete","error"]),y83=v.object({message:v.string(),code:v.string().optional(),stack:v.string().optional(),retryAt:v.number().optional(),attempt:v.number().optional()}),x83=v.object({userId:v.string(),name:v.string(),avatarURL:v.string().optional()}),f83=v.enum(["starting","running","failed"]),u83=v.object({cutMessageId:a6,createdAt:v.string()}),iA4=v.object({interrupt:v.boolean(),queuedMessage:v.object({role:v.literal("user"),messageId:a6,content:mk,userState:v.any().optional(),discoveredGuidanceFiles:v.array(gk).optional(),createdAt:v.string().optional()})}),b83=v.object({type:v.literal("agent_state"),state:k83,messageId:a6.optional()}),h83=v.object({type:v.literal("error"),message:v.string(),code:v.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()}),g83=v.object({type:v.literal("error_set"),seq:v.number(),error:y83}),m83=v.object({type:v.literal("error_cleared"),seq:v.number()}),p83=v.object({type:v.literal("cancelled"),seq:v.number(),messageId:a6.optional()}),d83=v.object({type:v.literal("retry_scheduled"),retryAt:v.number(),attempt:v.number(),maxAttempts:v.number(),reason:v.string()}),c83=v.object({type:v.literal("retry_started")}),l83=v.object({type:v.literal("retry_cancelled")}),i83=v.object({type:v.literal("executor_connected"),executorId:hQ0,registeredToolCount:v.number(),rejectedTools:v.array(v.object({name:v.string(),reason:v.string()})).optional()}),n83=v.object({type:v.literal("tool_lease"),toolCallId:r8,toolName:v.string(),args:v.unknown(),messageId:a6,parentToolCallId:r8.optional()}),a83=v.object({type:v.literal("executor_filesystem_read_directory"),requestId:Fq,uri:hk}),o83=v.object({type:v.literal("executor_filesystem_read_file"),requestId:Fq,uri:hk}),r83=v.object({type:v.literal("client_filesystem_read_directory_result"),requestId:Fq,ok:v.boolean(),entries:v.array(al).optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:v.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),s83=v.object({type:v.literal("client_filesystem_read_file_result"),requestId:Fq,ok:v.boolean(),contentBase64:v.string().optional(),error:UN.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:v.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:v.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),t83=v.object({type:v.literal("tool_approval_queue"),approvals:v.array(gQ0)}),e83=v.object({type:v.literal("executor_rollback_request"),editId:il,messageId:a6,reason:v.literal("message_edit"),toolUseIdsToRevert:v.array(r8)}),$93=v.object({type:v.literal("executor_tool_lease_revoked"),toolCallId:r8,reason:v.enum(["executor_disconnected","reassigned","user_canceled"])}),J93=v.object({type:v.literal("plugin_message"),message:mQ0}),Z93=v.object({type:v.literal("executor_tool_approval_response"),toolCallId:r8,accepted:v.boolean(),input:v.object({askAnswers:v.record(v.string(),v.string()).optional(),denyFeedback:v.string().optional()}).optional()}),Q93=v.object({type:v.literal("executor_error"),message:v.string(),code:v.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),Y93=v.object({type:v.literal("delta"),messageId:a6,role:v.literal("assistant"),blocks:Bn0.optional(),state:v83,usage:Ln0.optional(),parentToolCallId:r8.optional()}),X93=v.object({type:v.literal("delta"),messageId:a6,role:v.literal("user"),blocks:Un0.optional(),state:v.literal("complete"),parentToolCallId:r8.optional()}),K93=v.discriminatedUnion("role",[Y93,X93]),V93=v.object({type:v.literal("queued_messages"),messages:v.array(iA4)}),G93=v.object({type:v.literal("queued_message_added"),message:iA4,seq:v.number()}),z93=v.object({type:v.literal("queued_message_removed"),queuedMessageId:a6,seq:v.number()}),F93=v.object({type:v.literal("message_added"),message:dA4,seq:v.number(),parentToolUseId:Z8.optional()}),q93=v.object({type:v.literal("edit_rejected"),editId:v.string(),message:v.string()}),W93=v.object({type:v.literal("message_edited"),seq:v.number(),editId:v.string(),messageId:a6,content:mk,truncateToMessageId:a6,reason:v.literal("message_edit"),agentMode:Nn0.optional()}),D93=v.looseObject({type:v.literal("cf_agent_state")}),H93=v.looseObject({type:v.literal("cf_agent_mcp_servers")}),U93=v.looseObject({type:v.literal("cf_agent_identity")}),B93=v.object({type:v.literal("observers"),count:v.number(),observers:v.array(x83),hasExecutor:v.boolean().optional()}),w93=v.object({type:v.literal("executor_status"),spawnId:v.string(),status:f83,message:v.string().optional(),executorId:v.string().optional()}),N93=v.object({type:v.literal("environment_update"),environment:ol}),L93=v.object({type:v.literal("artifacts_snapshot"),artifacts:v.array(Dn0)}),O93=v.object({type:v.literal("artifact_upserted"),artifact:Dn0}),E93=v.object({type:v.literal("artifact_deleted"),key:Z8}),M93=v.object({type:v.literal("thread_title"),title:v.string().nullable()}),A93=v.object({type:v.literal("thread_status"),status:v.union([v.literal("merging"),v.literal("merged"),v.null()])}),j93=v.object({type:v.literal("thread_relationships"),seq:v.number(),relationships:v.array(vA4)}),R93=v.object({type:v.literal("compaction_started")}),I93=v.object({type:v.literal("compaction_complete"),cutMessageId:a6}),P93=v.object({type:v.literal("compaction_records"),records:v.array(u83)}),pQ0=v.discriminatedUnion("type",[b83,h83,g83,m83,p83,d83,c83,l83,i83,n83,a83,o83,r83,s83,t83,e83,$93,J93,Z93,On0,Q93,K93,V93,G93,z93,F93,q93,W93,D93,H93,U93,B93,w93,N93,L93,O93,E93,M93,A93,j93,R93,I93,P93]);var En0=(J)=>v.codec(v.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),v.NEVER}},encode:(Z)=>JSON.stringify(Z)}),nA4=En0(lA4),C93=v.union([pQ0,v.array(pQ0)]),aA4=En0(pQ0),oA4=En0(C93);U4();function rA4(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(z1.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 sA4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Mn0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function T93(J){return J.replace(/\s+/g," ").trim()}function _93(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function S93(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 Mn0(JSON.stringify(J),120)}catch{return Mn0(String(J),120)}}function tA4(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 k93(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=tA4(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 eA4(J){for(let Z of J){let Q=k93(Z);if(Q)return Q}return null}function v93(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"||tA4(Q.path)==="type")})}function y93(J,Z){let Q=eA4(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 $j4(J,Z,Q){let Y=_93(Z),X=(()=>{let F=T93(J);if(F.length===0)return null;return Mn0(F,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let F=eA4(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=S93(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(v93(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:y93(G,Y),messageType:G,typePreview:z,payloadPreview:X,issues:Y}}function sl(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 Jj4(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}}n$();var Zj4="[dtw-parse-error]",jn0="dtw-parse-error",x93=v.object({kind:v.literal(jn0),failureType:v.enum(sA4).nullable().optional(),source:v.string().nullable().optional(),direction:v.string().nullable().optional(),stage:v.string().nullable().optional(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),typePreview:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough(),f93=v.object({source:v.string(),direction:v.string(),stage:v.string(),summary:v.string().nullable().optional(),messageType:v.string().nullable().optional(),payloadPreview:v.string().nullable().optional(),issues:v.array(v.unknown()).optional()}).passthrough();function An0(J){return{kind:jn0,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 Qj4(J){let Z=An0(J);return JSON.stringify(Z)}function Yj4(J,Z){let Q=$j4(J,Z);return Qj4({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 Rn0(J){let Z=J.startsWith(Zj4)?J.slice(Zj4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=x93.safeParse(Q);if(Y.success)return An0(Y.data);let X=f93.safeParse(Q);if(X.success)return An0(X.data);return null}E1();class In0 extends Error{constructor(J){super(J);this.name="DTWError"}}class s8 extends In0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}E1();var u93=1000,b93=30000,h93=5,g93=30000,m93=15000,p93=200,d93=30000,Xj4=["online","focus","pageshow","keydown","pointerdown"],Kj4=["visibilitychange"];function Cn0(){return globalThis}function Gj4(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 Vj4(){return Gj4(Cn0().window)}function Pn0(){let J=Cn0().document;if(!Gj4(J))return null;return J}function c93(){let J=Cn0().navigator;if(!J||typeof J!=="object")return null;return J}function l93(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 dQ0(J){return!!(J.apiKey&&J.WebSocketClass)}function Tn0(J){if(dQ0(J))return"one-step";return"two-step"}class _n0{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 F4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new F4([]);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??u93,maxReconnectDelayMs:J.maxReconnectDelayMs??b93,maxReconnectAttempts:J.maxReconnectAttempts??h93,pingIntervalMs:J.pingIntervalMs??g93,connectTimeoutMs:J.connectTimeoutMs??m93,WebSocketClass:J.WebSocketClass,useThreadActors:J.useThreadActors},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${Tn0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}waitForConnected(J){if(this.connectionInfo.state==="connected")return Promise.resolve(!0);if(this.disposed||J<=0)return Promise.resolve(!1);return new Promise((Z)=>{let Q=!1,Y=null,X=null,K=(V)=>{if(Q)return;if(Q=!0,Y)clearTimeout(Y),Y=null;X?.unsubscribe(),X=null,Z(V)};Y=setTimeout(()=>{K(!1)},J),X=this.connectionSubject.subscribe({next:(V)=>{if(V.state==="connected")K(!0)},error:()=>{K(!1)},complete:()=>{K(!1)}})})}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=p93,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new s8("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(dQ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new s8("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 s8("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=${l93(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 s8(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new s8("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=setTimeout(()=>{X(),this.updateConnectionState("disconnected");try{if(J.readyState===WebSocket.CONNECTING)J.close()}catch{}Q(new s8(`WebSocket connection timed out after ${this.config.connectTimeoutMs}ms`))},this.config.connectTimeoutMs),X=()=>{clearTimeout(Y),J.removeEventListener("open",K),J.removeEventListener("error",V),J.removeEventListener("close",G)},K=()=>{X(),Z()},V=(z)=>{X(),this.updateConnectionState("disconnected");let F="message"in z?z.message:("error"in z)&&z.error instanceof Error?z.error.message:z.type;Q(new s8(`WebSocket connection failed: ${F}`))},G=(z)=>{X(),this.updateConnectionState("disconnected"),Q(new s8(`WebSocket closed during connect: code=${z.code} reason=${z.reason||"none"}`))};if(J.addEventListener("open",K),J.addEventListener("error",V),J.addEventListener("close",G),J.readyState===WebSocket.OPEN)return K();if(J.readyState===WebSocket.CLOSED||J.readyState===WebSocket.CLOSING)return G({code:1006,reason:"Socket already closed before connect"})})}setupWebSocketHandlers(J){if(J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now(),this.startPingIntervalOnce();return}this.startPingIntervalOnce(),this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.startPingIntervalOnce(),this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),!this.config.useThreadActors)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=Vj4(),Z=Pn0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=c93();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Pn0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=Vj4(),Z=Pn0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of Xj4)J?.addEventListener(Y,Q);for(let Y of Kj4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of Xj4)J?.removeEventListener(Y,Q);for(let Y of Kj4)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},d93)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingIntervalOnce(){if(this.pingIntervalID)return;this.startPingInterval()}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}var i93=3000,n93=30000,a93=5;function o93(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 qq extends _n0{deltaSubject=new z4;errorSubject=new z4;errorEventSubject=new z4;cancelledSubject=new z4;agentStateSubject=new z4;messageAddedSubject=new z4;editRejectedSubject=new z4;messageEditedSubject=new z4;queuedMessagesSubject=new z4;retrySubject=new z4;toolLeaseSubject=new z4;toolLeaseRevokedSubject=new z4;toolApprovalQueueSubject=new z4;executorToolApprovalResponseSubject=new z4;toolProgressSubject=new z4;executorErrorSubject=new z4;executorConnectedSubject=new z4;executorRollbackRequestSubject=new z4;observersSubject=new z4;executorStatusSubject=new z4;environmentUpdateSubject=new z4;artifactsSubject=new z4;threadTitleSubject=new z4;threadStatusSubject=new z4;threadRelationshipsSubject=new z4;compactionSubject=new z4;compactionRecordsSubject=new z4;pluginMessageSubject=new z4;fileSystemReadDirectoryRequestSubject=new z4;fileSystemReadFileRequestSubject=new z4;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;ensureConnectedPromise=null;constructor(J){super(J)}async ensureConnected(J){if(this.ensureConnectedPromise)return this.ensureConnectedPromise;this.ensureConnectedPromise=this.ensureConnectedInternal(J);try{return await this.ensureConnectedPromise}finally{this.ensureConnectedPromise=null}}async ensureConnectedInternal(J){let Z=J?.baseDelayMs??i93,Q=J?.maxDelayMs??n93,Y=J?.maxAttempts??a93;if(J?.forceReconnectWhenReconnecting&&this.getConnectionInfo().state==="reconnecting")this.disconnect();for(let X=0;X<Y;X++){try{await this.connect()}catch(z){if(this.getConnectionInfo().state!=="reconnecting")throw z;J?.onRetryableConnectError?.(z)}let K=J?.waitForConnectedTimeoutMs??Math.min(Z*2**X,Q);if(await this.waitForConnected(K))return!0;let G=X+1<Y?Math.min(Z*2**(X+1),Q):null;J?.onAttemptTimeout?.({attempt:X+1,maxAttempts:Y,nextDelayMs:G})}return!1}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??zq();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 s8("Transport is disposed");if(!this.hasOpenSocket())throw new s8("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")))},Q?.useThreadActors?30000:1e4)})}ackToolLease(J){this.send({type:"executor_tool_lease_ack",toolCallId:J})}sendToolProgress(J,Z){let Q=sl(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 s8("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new s8(`Filesystem request timed out: ${Z}`))},hA4);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(o93(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 s8(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new s8(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=oA4.safeDecode(J);if(!Z.success){let Y=aA4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:Yj4(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(nA4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new s8(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function r93(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 s93(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function t93(J){if(r93(J))return J.queuedMessage.messageId;if(s93(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function Sn0(J,Z,Q={}){let Y=Q.getQueuedMessageId??t93;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 e93=15000;function $73(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 kn0(J){let Z=J.workerUrl??d7(J.ampURL),Q=new qq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??e93;if(!await Q.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:Y}))throw Error(`Timed out waiting for DTW connection after ${Y}ms`);Q.resumeFromVersion(0);let K=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),V=$73(Q,K,Y);try{return{messageId:(await V.promise).message.messageId}}finally{V.dispose(),Q.dispose()}}import{watch as J73}from"node:fs";import{mkdir as Z73,readdir as Q73,readFile as Y73}from"node:fs/promises";import{createServer as X73}from"node:http";import vn0 from"node:path";function zj4(J){return J instanceof Error?J.message:String(J)}function wj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function K73(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function Fj4(J,Z){let Q=vn0.basename(Z),Y=Q.endsWith(".json")?vn0.join(J,Q):vn0.join(J,`${Q}.json`),X=await Y73(Y,"utf-8");return JSON.parse(X)}async function V73(J){let Z=await Q73(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await Fj4(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 G73(){return`<!doctype html>
4693
4693
  <html lang="en">
4694
4694
  <head>
4695
4695
  <meta charset="utf-8" />
@@ -6086,11 +6086,11 @@ password=${K}
6086
6086
  [GNUPG:] SIG_CREATED
6087
6087
  `)}d0();y7();sd();jT();d4();function Oj(J){return J.toolUseId}function Q23(J){return J.parentToolUseId}function eQ0(J){let Z=Oj(J);return{id:J.id||Z,toolCallId:Z,toolName:J.toolName,args:J.args,reason:J.reason,toAllow:J.toAllow,context:J.context,subagentToolName:J.subagentToolName,parentToolCallId:Q23(J),timestamp:J.timestamp,matchedRule:J.matchedRule,ruleSource:J.ruleSource}}CW();F3();d4();U4();E1();MA();d4();async function cj4(J){let Z=await VZ(),Q=R7(J)?J:m3(),Y=await eh0({filesystem:n8},Z,Q);return{...Z,...Y,updatedAt:new Date().toISOString()}}function Y23(J){return new TextEncoder().encode(JSON.stringify(J)).length}function lk(J,Z,Q){if(J.length===0)return[];let Y=[],X=[];for(let K of J){let V=[...X,K],G=Y23(Q(V));if(X.length>0&&G>Z){Y.push(X),X=[K];continue}X=V}if(X.length>0)Y.push(X);return Y}var ij4=1048576;function lj4(J){let Z=new Map;for(let Q of J)Z.set(Q.name,{schema:Q,serializedSchema:JSON.stringify(Q)});return Z}function X23(J){let Z={...J.executionProfile?.serial!==void 0?{serial:J.executionProfile.serial}:{},...J.meta?.deferred!==void 0?{deferred:J.meta.deferred}:{},...J.meta?.skillNames!==void 0?{skillNames:[...J.meta.skillNames]}:{}};return Object.keys(Z).length>0?Z:void 0}function K23(J){return{name:J.name,description:J.description??"",inputSchema:{type:"object",properties:J.inputSchema.properties??{},required:J.inputSchema.required,additionalProperties:J.inputSchema.additionalProperties},source:J.source,meta:X23(J)}}function ik(J){return J.map((Z)=>K23(Z.spec))}function nj4(J,Z){let Q=lj4(J),Y=lj4(Z);return{toolsToRegister:Z.filter((X)=>{let K=Q.get(X.name),V=Y.get(X.name);return K?.serializedSchema!==V?.serializedSchema}),toolNamesToUnregister:[...Q.keys()].filter((X)=>!Y.has(X))}}function aj4(J,Z=ij4){return lk(J,Z,(Q)=>({type:"executor_tools_register",tools:Q}))}function oj4(J,Z=ij4){return lk(J,Z,(Q)=>({type:"executor_tools_unregister",toolNames:Q}))}import{execFile as V23}from"node:child_process";import{readFile as G23,stat as z23}from"node:fs/promises";import{basename as F23,join as q23}from"node:path";import JR4 from"node:process";import{promisify as W23}from"node:util";async function rj4(J,Z,Q){let Y=[];for(let X=0;X<J.length;X+=Z){let K=J.slice(X,X+Z);Y.push(...await Promise.all(K.map(Q)))}return Y}var D23=W23(V23),ak=20971520,H23=["GIT_CONFIG","GIT_CONFIG_COUNT","GIT_CONFIG_PARAMETERS"],$Y0=["-c","core.quotepath=false","diff","--no-color","--no-ext-diff"],U23=999999,sj4="refs/remotes/origin/",B23=20,w23=10;function JY0(J){return J.replace(/\n+$/,"")}var dn0=JR4.platform==="win32"?"NUL":"/dev/null";function N23(J=JR4.env,Z={}){let{isolateGitConfig:Q=!0}=Z,Y={...J};if(Q){for(let X of Object.keys(Y))if(H23.includes(X)||X.startsWith("GIT_CONFIG_KEY_")||X.startsWith("GIT_CONFIG_VALUE_"))delete Y[X];Y.GIT_CONFIG_NOSYSTEM="1",Y.GIT_CONFIG_SYSTEM=dn0,Y.GIT_CONFIG_GLOBAL=dn0}return Y}function tj4(J,Z){return{provider:"git",capturedAt:J,available:!1,repositoryRoot:null,repositoryName:null,branch:null,head:null,files:[],unavailableReason:Z}}function L23(J){return J instanceof Error}async function nk(J,Z,Q={}){try{let{stdout:Y}=await D23("git",Z,{cwd:J,env:N23(),maxBuffer:Q.maxBufferBytes??ak});return Y}catch(Y){if(Q?.allowExitCodeOne&&L23(Y)&&(Y.code===1||Y.code==="1")&&typeof Y.stdout==="string")return Y.stdout;throw Y}}async function qH(J,Z){try{return await nk(J,Z)}catch{return null}}function O23(J){if(J==="??")return"untracked";let Z=J[0]??" ",Q=J[1]??" ";if(Z==="U"||Q==="U"||J==="AA"||J==="DD")return"unmerged";if(Z==="R"||Q==="R")return"renamed";if(Z==="C"||Q==="C")return"copied";if(Z==="A"||Q==="A")return"added";if(Z==="D"||Q==="D")return"deleted";if(Z==="T"||Q==="T")return"type_changed";return"modified"}function cn0(J){let Z=[],Q=J.split("\x00");for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X||X.length<4)continue;let K=X.slice(0,2),V=X.slice(3);if(!V)continue;let G=O23(K);if(G==="renamed"||G==="copied"){let z=Q[Y+1];if(z){Z.push({path:V,previousPath:z,changeType:G}),Y+=1;continue}}Z.push({path:V,changeType:G})}return Z.sort((Y,X)=>Y.path.localeCompare(X.path))}function E23(J){let Z=0,Q=0,Y=0,X=0,K=0,V=()=>{if(X===0&&K===0)return;Y+=Math.min(X,K),X=0,K=0};for(let G of J.split(`
6088
6088
  `)){if(G.startsWith("+")&&!G.startsWith("+++")){Z+=1,X+=1;continue}if(G.startsWith("-")&&!G.startsWith("---")){Q+=1,K+=1;continue}V()}return V(),{added:Z,deleted:Q,changed:Y}}async function ej4(J,Z,Q,Y,X=ak){let K=Y!==void 0?[`--unified=${Y}`]:[];if(Q)return nk(J,[...$Y0,...K,"HEAD","--",Z],{maxBufferBytes:X});let[V,G]=await Promise.all([nk(J,[...$Y0,...K,"--cached","--",Z],{maxBufferBytes:X}).catch(()=>""),nk(J,[...$Y0,...K,"--",Z],{maxBufferBytes:X}).catch(()=>"")]);return[JY0(V),JY0(G)].filter(Boolean).join(`
6089
- `)}async function M23(J,Z,Q=ak){return nk(J,[...$Y0,"--no-index","--",dn0,Z],{allowExitCodeOne:!0,maxBufferBytes:Q})}async function A23(J,Z,Q,Y=ak){let X=Q??"HEAD";try{return await nk(J,["show",`${X}:${Z}`],{maxBufferBytes:Y})}catch{return}}async function j23(J,Z,Q=ak){try{let Y=q23(J,Z);if((await z23(Y)).size>Q)return;return await G23(Y,"utf-8")}catch{return}}function $R4(J){let Z=Number.parseInt(J.trim(),10);if(!Number.isFinite(Z))return null;return Z}async function R23(J){let Z=(await qH(J,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Z?.startsWith(sj4))return null;let Q=Z.slice(sj4.length);if(!Q)return null;let Y=`origin/${Q}`,K=(await qH(J,["rev-parse","--verify","--quiet",`${Y}^{commit}`]))?.trim();if(!K)return null;return{baseRef:Q,comparisonRef:Y,baseRefHead:K}}function I23(J){let Z=J.split("\x00"),Q=[];for(let Y=0;Y+1<Z.length;Y+=2){let X=Z[Y],K=Z[Y+1]??"";if(!X)continue;Q.push({hash:X,shortHash:X.slice(0,12),subject:K})}return Q}async function P23(J,Z){let Q=await qH(J,["log","-z",`--max-count=${B23}`,"--format=%H%x00%s",`${Z}..HEAD`]);if(!Q)return[];return I23(Q)}async function C23(J,Z){if(!Z)return null;let Q=await R23(J);if(!Q)return null;let Y=await qH(J,["rev-list","--count",`${Q.comparisonRef}..HEAD`]);if(!Y)return null;let X=await qH(J,["rev-list","--count",`HEAD..${Q.comparisonRef}`]);if(!X)return null;let K=$R4(Y);if(K===null)return null;let V=$R4(X);if(V===null)return null;return{baseRef:Q.baseRef,comparisonRef:Q.comparisonRef,baseRefHead:Q.baseRefHead,aheadCount:K,behindCount:V}}async function ZY0(J,Z={}){let{maxDiffBufferBytes:Q=ak}=Z,Y=Date.now(),X=await qH(J,["rev-parse","--show-toplevel"]);if(!X)return tj4(Y,"not a git repository");let K=X.trim(),V=F23(K),[G,z,F]=await Promise.all([qH(K,["rev-parse","--verify","HEAD"]),qH(K,["symbolic-ref","--short","HEAD"]),qH(K,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(F===null)return tj4(Y,"failed to read git status");let q=G?.trim()||null,W=z?.trim()||null,D=cn0(F),H=await C23(K,q),U=H?.aheadCount&&H.aheadCount>0?await P23(K,H.comparisonRef):[],B=await rj4(D,w23,async(w)=>{let N=JY0(w.changeType==="untracked"?await M23(K,w.path,Q).catch(()=>""):await ej4(K,w.path,q,void 0,Q).catch(()=>"")),L=JY0(w.changeType==="modified"?await ej4(K,w.path,q,U23,Q).catch(()=>""):N),O=w.changeType!=="added"&&w.changeType!=="untracked"?await A23(K,w.previousPath??w.path,q,Q):void 0,E=w.changeType!=="deleted"?await j23(K,w.path,Q):void 0;return{path:w.path,previousPath:w.previousPath,changeType:w.changeType,created:w.changeType==="added"||w.changeType==="untracked",diff:N,fullFileDiff:L,oldContent:O,newContent:E,diffStat:E23(N)}});return{provider:"git",capturedAt:Y,available:!0,repositoryRoot:K,repositoryName:V,branch:W,head:q,baseRef:H?.baseRef??null,baseRefHead:H?.baseRefHead??null,aheadCount:H?.aheadCount??0,behindCount:H?.behindCount,aheadCommits:U,files:B}}function QY0(J){let Z={provider:J.provider,capturedAt:J.capturedAt,available:J.available,repositoryRoot:J.repositoryRoot,repositoryName:J.repositoryName,branch:J.branch,head:J.head,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,behindCount:J.behindCount,...J.unavailableReason!==void 0?{unavailableReason:J.unavailableReason}:{},aheadCommits:J.aheadCommits??[],files:J.files.map((Y)=>({path:Y.path,previousPath:Y.previousPath,changeType:Y.changeType,created:Y.created,diff:Y.diff,fullFileDiff:Y.fullFileDiff,oldContent:Y.oldContent,newContent:Y.newContent,diffStat:Y.diffStat}))},Q=Buffer.from(JSON.stringify(Z),"utf8").toString("base64");return{key:X$0,dataType:"application/json",contentBase64:Q}}var ZR4=1048576;function QR4(J,Z,Q,Y=ZR4){return lk(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function YY0(J,Z,Q=ZR4){return lk(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}function T23(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}async function _23(J){let Z=await J.getLatest();return eA0(Z.settings)}function Yi(J){let Z=J.previouslyAdvertisedTools??[],{toolsToRegister:Q,toolNamesToUnregister:Y}=nj4(Z,J.nextTools),X=J.forceRegisterAll?[...J.nextTools]:Q;for(let K of aj4(X))J.logMessage?.("SEND",{type:"executor_tools_register",tools:K.map((V)=>V.name)}),J.transport.registerTools(K);for(let K of oj4(Y))J.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:K}),J.transport.unregisterTools(K);return[...J.nextTools]}async function XY0(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:K}=J,V=J.fileSystem??n8,G=J.resumeFromVersion??0,F={settings:await _23(Y),workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:T23(process.platform)},tags:[]};K?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:F,executorType:J.executorType});let q=await Z.executorHandshake(J.executorClientID,F,{executorType:J.executorType});K?.("RECV",q);try{if(Q){let U=await cj4(Q);K?.("SEND",{type:"executor_environment_snapshot",environment:U}),Z.sendEnvironmentSnapshot(U);let w={trees:U.workspaceRoot?[{uri:U.workspaceRoot}]:[],platform:U.platform,tags:U.tags};await S23(Z,V,Y,w,K)}await k23(Z,X,K),await J.initialToolDiscovery;let W=await R1(J.toolService.tools),D=ik(W),H=Yi({transport:Z,nextTools:D,previouslyAdvertisedTools:J.previouslyAdvertisedTools,forceRegisterAll:!0,logMessage:K});if(J.subscribeToThreadEvents!==!1)K?.("SEND",{type:"client_resume",version:G}),Z.resumeFromVersion(G);if(J.sendGitSnapshot!==!1)try{let U=await ZY0(J.workspaceRoot);K?.("SEND",{type:"executor_artifact_upsert",available:U.available,fileCount:U.files.length,branch:U.branch,head:U.head}),Z.sendExecutorArtifactUpsert(QY0(U))}catch{}return K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0),{advertisedTools:H}}catch(W){let D=W instanceof Error?W.message:String(W);throw K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:D}),Z.sendExecutorToolsBootstrapComplete(!1,D),W}}function KY0(J,Z,Q){let Y=eA0(Z.settings),X=JSON.stringify(Y);if(X===Q)return Q;let K=J.getConnectionInfo();if(K.state!=="connected"||K.role!=="executor")return Q;try{return J.sendExecutorSettingsUpdate(Y),X}catch{return Q}}async function S23(J,Z,Q,Y,X){let V=(await $F({filesystem:Z,configService:Q,threadService:{observe:()=>k0.of({id:m3(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
6089
+ `)}async function M23(J,Z,Q=ak){return nk(J,[...$Y0,"--no-index","--",dn0,Z],{allowExitCodeOne:!0,maxBufferBytes:Q})}async function A23(J,Z,Q,Y=ak){let X=Q??"HEAD";try{return await nk(J,["show",`${X}:${Z}`],{maxBufferBytes:Y})}catch{return}}async function j23(J,Z,Q=ak){try{let Y=q23(J,Z);if((await z23(Y)).size>Q)return;return await G23(Y,"utf-8")}catch{return}}function $R4(J){let Z=Number.parseInt(J.trim(),10);if(!Number.isFinite(Z))return null;return Z}async function R23(J){let Z=(await qH(J,["symbolic-ref","--quiet","refs/remotes/origin/HEAD"]))?.trim();if(!Z?.startsWith(sj4))return null;let Q=Z.slice(sj4.length);if(!Q)return null;let Y=`origin/${Q}`,K=(await qH(J,["rev-parse","--verify","--quiet",`${Y}^{commit}`]))?.trim();if(!K)return null;return{baseRef:Q,comparisonRef:Y,baseRefHead:K}}function I23(J){let Z=J.split("\x00"),Q=[];for(let Y=0;Y+1<Z.length;Y+=2){let X=Z[Y],K=Z[Y+1]??"";if(!X)continue;Q.push({hash:X,shortHash:X.slice(0,12),subject:K})}return Q}async function P23(J,Z){let Q=await qH(J,["log","-z",`--max-count=${B23}`,"--format=%H%x00%s",`${Z}..HEAD`]);if(!Q)return[];return I23(Q)}async function C23(J,Z){if(!Z)return null;let Q=await R23(J);if(!Q)return null;let Y=await qH(J,["rev-list","--count",`${Q.comparisonRef}..HEAD`]);if(!Y)return null;let X=await qH(J,["rev-list","--count",`HEAD..${Q.comparisonRef}`]);if(!X)return null;let K=$R4(Y);if(K===null)return null;let V=$R4(X);if(V===null)return null;return{baseRef:Q.baseRef,comparisonRef:Q.comparisonRef,baseRefHead:Q.baseRefHead,aheadCount:K,behindCount:V}}async function ZY0(J,Z={}){let{maxDiffBufferBytes:Q=ak}=Z,Y=Date.now(),X=await qH(J,["rev-parse","--show-toplevel"]);if(!X)return tj4(Y,"not a git repository");let K=X.trim(),V=F23(K),[G,z,F]=await Promise.all([qH(K,["rev-parse","--verify","HEAD"]),qH(K,["symbolic-ref","--short","HEAD"]),qH(K,["status","--porcelain=v1","--untracked-files=all","-z"])]);if(F===null)return tj4(Y,"failed to read git status");let q=G?.trim()||null,W=z?.trim()||null,D=cn0(F),H=await C23(K,q),U=H?.aheadCount&&H.aheadCount>0?await P23(K,H.comparisonRef):[],B=await rj4(D,w23,async(w)=>{let N=JY0(w.changeType==="untracked"?await M23(K,w.path,Q).catch(()=>""):await ej4(K,w.path,q,void 0,Q).catch(()=>"")),L=JY0(w.changeType==="modified"?await ej4(K,w.path,q,U23,Q).catch(()=>""):N),O=w.changeType!=="added"&&w.changeType!=="untracked"?await A23(K,w.previousPath??w.path,q,Q):void 0,E=w.changeType!=="deleted"?await j23(K,w.path,Q):void 0;return{path:w.path,previousPath:w.previousPath,changeType:w.changeType,created:w.changeType==="added"||w.changeType==="untracked",diff:N,fullFileDiff:L,oldContent:O,newContent:E,diffStat:E23(N)}});return{provider:"git",capturedAt:Y,available:!0,repositoryRoot:K,repositoryName:V,branch:W,head:q,baseRef:H?.baseRef??null,baseRefHead:H?.baseRefHead??null,aheadCount:H?.aheadCount??0,behindCount:H?.behindCount,aheadCommits:U,files:B}}function QY0(J){let Z={provider:J.provider,capturedAt:J.capturedAt,available:J.available,repositoryRoot:J.repositoryRoot,repositoryName:J.repositoryName,branch:J.branch,head:J.head,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,behindCount:J.behindCount,...J.unavailableReason!==void 0?{unavailableReason:J.unavailableReason}:{},aheadCommits:J.aheadCommits??[],files:J.files.map((Y)=>({path:Y.path,previousPath:Y.previousPath,changeType:Y.changeType,created:Y.created,diff:Y.diff,fullFileDiff:Y.fullFileDiff,oldContent:Y.oldContent,newContent:Y.newContent,diffStat:Y.diffStat}))},Q=Buffer.from(JSON.stringify(Z),"utf8").toString("base64");return{key:X$0,dataType:"application/json",contentBase64:Q}}var ZR4=1048576;function QR4(J,Z,Q,Y=ZR4){return lk(J,Y,(X)=>({type:"executor_guidance_snapshot",snapshotId:Z,files:X,isLast:!1,userConfigDir:Q}))}function YY0(J,Z,Q=ZR4){return lk(J,Q,(Y)=>({type:"executor_guidance_discovery",toolCallId:Z,files:Y,isLast:!1}))}function T23(J){if(J==="darwin")return"darwin";if(J==="win32")return"windows";return"linux"}async function _23(J){let Z=await J.getLatest();return eA0(Z.settings)}function Yi(J){let Z=J.previouslyAdvertisedTools??[],{toolsToRegister:Q,toolNamesToUnregister:Y}=nj4(Z,J.nextTools),X=J.forceRegisterAll?[...J.nextTools]:Q;for(let K of aj4(X))J.logMessage?.("SEND",{type:"executor_tools_register",tools:K.map((V)=>V.name)}),J.transport.registerTools(K);for(let K of oj4(Y))J.logMessage?.("SEND",{type:"executor_tools_unregister",toolNames:K}),J.transport.unregisterTools(K);return[...J.nextTools]}async function XY0(J){let{transport:Z,threadId:Q,configService:Y,skillService:X,logMessage:K}=J,V=J.fileSystem??n8,z={settings:await _23(Y),workspaceId:J.workspaceRoot,workingDirectory:J.workspaceRoot,environment:{os:T23(process.platform)},tags:[]};K?.("SEND",{type:"executor_connect",clientId:J.executorClientID,capabilities:z,executorType:J.executorType});let F=await Z.executorHandshake(J.executorClientID,z,{executorType:J.executorType});K?.("RECV",F);try{if(Q){let H=await cj4(Q);K?.("SEND",{type:"executor_environment_snapshot",environment:H}),Z.sendEnvironmentSnapshot(H);let B={trees:H.workspaceRoot?[{uri:H.workspaceRoot}]:[],platform:H.platform,tags:H.tags};await S23(Z,V,Y,B,K)}await k23(Z,X,K),await J.initialToolDiscovery;let q=await R1(J.toolService.tools),W=ik(q),D=Yi({transport:Z,nextTools:W,previouslyAdvertisedTools:J.previouslyAdvertisedTools,forceRegisterAll:!0,logMessage:K});if(J.sendGitSnapshot!==!1)try{let H=await ZY0(J.workspaceRoot);K?.("SEND",{type:"executor_artifact_upsert",available:H.available,fileCount:H.files.length,branch:H.branch,head:H.head}),Z.sendExecutorArtifactUpsert(QY0(H))}catch{}return K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!0}),Z.sendExecutorToolsBootstrapComplete(!0),{advertisedTools:D}}catch(q){let W=q instanceof Error?q.message:String(q);throw K?.("SEND",{type:"executor_tools_bootstrap_complete",ok:!1,error:W}),Z.sendExecutorToolsBootstrapComplete(!1,W),q}}function KY0(J,Z,Q){let Y=eA0(Z.settings),X=JSON.stringify(Y);if(X===Q)return Q;let K=J.getConnectionInfo();if(K.state!=="connected"||K.role!=="executor")return Q;try{return J.sendExecutorSettingsUpdate(Y),X}catch{return Q}}async function S23(J,Z,Q,Y,X){let V=(await $F({filesystem:Z,configService:Q,threadService:{observe:()=>k0.of({id:m3(),created:Date.now(),v:0,messages:[],env:{initial:Y}})}},{messages:[],env:{initial:Y}})).map((q)=>({uri:q.uri,content:q.content,lineCount:q.content.split(`
6090
6090
  `).length})),G=crypto.randomUUID(),z=Q.userConfigDir?l1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:[],isLast:!0,userConfigDir:z});return}let F=QR4(V,G,z);for(let q=0;q<F.length;q++){let W=F[q];if(!W)continue;let D=q===F.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:W.length,isLast:D}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:W,isLast:D,userConfigDir:z})}}async function k23(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((G)=>({name:G.name,description:G.description,baseDir:G.baseDir,frontmatter:G.frontmatter,files:G.files}));if(V.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let G=0;G<V.length;G+=20){let z=V.slice(G,G+20),F=G+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:z.length,isLast:F}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:z,isLast:F})}}lJ();U4();import Xi from"node:path";class Ej extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function XR4(J,Z){let Q=z1.parse(J);if(Q.scheme!=="file")throw new Ej("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new Ej("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((z)=>z===".."))throw new Ej("ACCESS_DENIED","File URI resolves outside workspace root");let X=Xi.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new Ej("ACCESS_DENIED","File URI resolves outside workspace root");let K=Xi.resolve(Z),V=X.length>0?Xi.resolve(K,X):K,G=Xi.relative(K,V);if(G.startsWith("..")||Xi.isAbsolute(G))throw new Ej("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function GY0(J,Z){try{let Q=XR4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(z1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",G=V==="file"?await v23(J.fileSystem,K.uri):void 0;return[X1.basename(K.uri),V,G]}))}}catch(Q){return{ok:!1,error:KR4(Q,"read_directory")}}}async function v23(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function zY0(J,Z){try{let Q=XR4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(z1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:KR4(Q,"read_file")}}}function KR4(J,Z){if(J instanceof Ej)return{code:J.code,message:J.message};if(E9(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(VY0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(VY0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":YR4(J)};if(VY0(J,"EACCES")||VY0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:YR4(J)}}function VY0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function YR4(J){if(J instanceof Error)return J.message;return String(J)}var ok={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function FY0(J,Z){if(J>=Z.maxAttempts)return null;let Q=Math.max(1,J);return Math.min(Z.baseDelayMs*2**(Q-1),Z.maxDelayMs)}function y23(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}class Ki{options;inFlight=null;readyWaiter=null;retryTimer=null;attempt=0;generation=0;lastInfo=null;disposed=!1;baseDelayMs;maxDelayMs;maxAttempts;constructor(J){this.options=J;this.baseDelayMs=J.baseDelayMs??ok.baseDelayMs,this.maxDelayMs=J.maxDelayMs??ok.maxDelayMs,this.maxAttempts=J.maxAttempts??ok.maxAttempts}ensureHandshake(J){return this.tryHandshake(J)}ensureReady(J){if(this.disposed)return Promise.reject(Error("Executor handshake manager is disposed"));if(this.isReady())return Promise.resolve();if(!this.readyWaiter)this.readyWaiter=y23();this.tryHandshake("connect");let Z=this.readyWaiter.promise;if(!J?.timeoutMs)return Z;let Q=J.timeoutMessage??`Timed out waiting for handshake after ${J.timeoutMs}ms`;return this.withTimeout(Z,J.timeoutMs,Q)}handleConnectionChange(J){if(this.lastInfo=J,J.state!=="connected"){this.reset("disconnected");return}if(J.role==="executor"){this.reset("executor"),this.resolveReadyWaiter();return}this.tryHandshake("connect")}dispose(){this.disposed=!0,this.generation++,this.clearRetryTimer(),this.rejectReadyWaiter(Error("Executor handshake manager is disposed"))}isReady(){return this.lastInfo?.state==="connected"&&this.lastInfo.role==="executor"}resolveReadyWaiter(){let J=this.readyWaiter;if(!J)return;this.readyWaiter=null,J.resolve()}rejectReadyWaiter(J){let Z=this.readyWaiter;if(!Z)return;this.readyWaiter=null,Z.reject(J)}reset(J){this.generation++,this.attempt=0,this.clearRetryTimer()}clearRetryTimer(){if(!this.retryTimer)return;clearTimeout(this.retryTimer),this.retryTimer=null}async withTimeout(J,Z,Q){let Y=null;try{return await Promise.race([J,new Promise((X,K)=>{Y=setTimeout(()=>{K(Error(Q))},Z)})])}finally{if(Y)clearTimeout(Y)}}tryHandshake(J){if(this.disposed||this.inFlight)return this.inFlight;let Z=this.generation,Q=this.options.handshake(J);return this.inFlight=Q,Q.then(()=>{if(this.disposed||Z!==this.generation)return;this.attempt=0,this.clearRetryTimer(),this.resolveReadyWaiter()}).catch((Y)=>{if(this.disposed||Z!==this.generation)return;this.scheduleRetry(J,Y)}).finally(()=>{if(this.inFlight===Q)this.inFlight=null}),Q}scheduleRetry(J,Z){if(this.disposed)return;if(!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.attempt+=1;let Q=FY0(this.attempt,{baseDelayMs:this.baseDelayMs,maxDelayMs:this.maxDelayMs,maxAttempts:this.maxAttempts});if(Q===null){this.clearRetryTimer(),this.options.onExhausted?.({attempt:this.attempt,maxAttempts:this.maxAttempts,error:Z}),this.rejectReadyWaiter(Z instanceof Error?Z:Error("Executor handshake failed and exhausted retries"));return}this.clearRetryTimer(),this.options.onError?.({trigger:J,attempt:this.attempt,delayMs:Q,error:Z}),this.retryTimer=setTimeout(()=>{if(this.retryTimer=null,!this.lastInfo||this.lastInfo.state!=="connected"||this.lastInfo.role==="executor")return;this.tryHandshake("retry")},Q)}}d4();class Vi{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;pendingTerminalResults=new Map;gitStatusQueue={inFlight:!1,queued:!1,queuedToolCallId:void 0};disposing=!1;constructor(J){this.options=J;this.clientID=J.clientID,this.transport=J.transport}async handleToolLease(J){if(this.disposing)return;let{toolCallId:Z,toolName:Q}=J;if(this.activeTools.has(Z)){this.options.log.info(`${this.clientID} ignoring duplicate active lease`,{toolCallId:Z,toolName:Q});return}let Y=this.pendingTerminalResults.get(Z);if(Y){this.options.log.info(`${this.clientID} replaying pending terminal result for duplicate lease`,{toolCallId:Z,toolName:Q}),this.sendTerminalResult(Z,Y,"flush");return}let X=Date.now();this.options.log.info(`${this.clientID} executing tool: ${Q}`,{toolCallId:Z}),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_lease_ack",toolCallId:Z}),this.transport.ackToolLease(Z);let K=new AbortController,V={subscription:{unsubscribe:()=>{}},abortController:K};this.activeTools.set(Z,V);let G=()=>{this.activeTools.delete(Z)};try{let z=await this.options.invokeTool(J);this.options.log.info(`${this.clientID} tool service returned observable`,{toolCallId:Z,toolName:Q,elapsedMs:Date.now()-X});let F=z.subscribe({next:(q)=>{if(K.signal.aborted)return;let W=q.status==="in-progress"?q.progress??q.result:void 0;if(W!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:W}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,W),{toolCallId:Z});if(c8(q.status))this.sendToolResult(Z,q),G(),F.unsubscribe();if(q.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(q)=>{if(K.signal.aborted){G();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,q);let W={status:"error",error:{message:q instanceof Error?q.message:"Unknown error"}};this.sendToolResult(Z,W),G()}});V.subscription=F}catch(z){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,z);let F={status:"error",error:{message:z instanceof Error?z.message:String(z)}};this.sendToolResult(Z,F),G()}}flushBufferedTerminalResults(){if(this.disposing||this.pendingTerminalResults.size===0)return;for(let[J,Z]of this.pendingTerminalResults)this.sendTerminalResult(J,Z,"flush")}handleToolRevocation(J){if(this.disposing)return;let{toolCallId:Z,reason:Q}=J;this.options.log.info(`${this.clientID} lease revoked: ${Z}`,{reason:Q});let Y=this.activeTools.get(Z);if(Y)Y.abortController.abort(),Y.subscription.unsubscribe(),this.activeTools.delete(Z);this.sentApprovalRequests.delete(Z),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_revocation_ack",toolCallId:Z}),this.sendTransportMessage("executor_revocation_ack",()=>this.transport.sendRevocationAck(Z),{toolCallId:Z})}async handleRollbackRequest(J,Z,Q){if(this.disposing)return;try{if(Z.length>0)await Q(new Set(Z));this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!0}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!0),{editId:J}),this.queueGitStatusSnapshot()}catch(Y){let X=Y instanceof Error?Y.message:String(Y);this.options.log.error(`${this.clientID} rollback failed`,Y),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_rollback_ack",editId:J,ok:!1,error:X}),this.sendTransportMessage("executor_rollback_ack",()=>this.transport.sendExecutorRollbackAck(J,!1,X),{editId:J})}}triggerGitStatus(J){this.queueGitStatusSnapshot(J)}dispose(){this.disposing=!0;for(let[,J]of this.activeTools)J.abortController.abort(),J.subscription.unsubscribe();this.activeTools.clear(),this.pendingTerminalResults.clear()}sendToolResult(J,Z){let Q=Date.now(),Y=this.toToolRun(Z),{run:X,files:K}=this.extractGuidanceFromRun(Y);if(K.length>0)this.sendGuidanceDiscovery(J,K);this.sendTerminalResult(J,X,"live",{guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}sendTerminalResult(J,Z,Q,Y){this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:Z});let X=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,Z),{toolCallId:J,source:Q});if(X)this.pendingTerminalResults.delete(J);else this.pendingTerminalResults.set(J,Z);return this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:Z.status,sent:X,source:Q,...Y}),X}sendGuidanceDiscovery(J,Z){let Q=this.options.batchGuidanceFiles(Z,J);for(let Y=0;Y<Q.length;Y++){let X=Q[Y];if(!X)continue;let K=Y===Q.length-1;if(this.options.log.wsMessage("SEND",this.clientID,{type:"executor_guidance_discovery",toolCallId:J,fileCount:X.length,isLast:K}),!this.sendTransportMessage("executor_guidance_discovery",()=>this.transport.sendExecutorGuidanceDiscovery({toolCallId:J,files:X,isLast:K}),{toolCallId:J,isLast:K,fileCount:X.length}))return}}queueGitStatusSnapshot(J){if(this.disposing||!this.options.captureGitStatus)return;if(this.gitStatusQueue.inFlight){if(this.gitStatusQueue.queued=!0,J)this.gitStatusQueue.queuedToolCallId=J;return}this.gitStatusQueue.inFlight=!0,this.sendGitStatusSnapshot(J).finally(()=>{if(this.gitStatusQueue.inFlight=!1,!this.gitStatusQueue.queued)return;let Z=this.gitStatusQueue.queuedToolCallId;this.gitStatusQueue.queued=!1,this.gitStatusQueue.queuedToolCallId=void 0,this.queueGitStatusSnapshot(Z)})}async sendGitStatusSnapshot(J){try{if(!this.options.captureGitStatus)return;let Z=await this.options.captureGitStatus();this.options.log.wsMessage("SEND",this.clientID,{type:"executor_artifact_upsert",available:Z.available,fileCount:Z.files.length,toolCallId:J,branch:Z.branch,head:Z.head}),this.transport.sendExecutorArtifactUpsert(QY0(Z),J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}toToolRun(J){switch(J.status){case"done":return{status:"done",result:J.result,progress:J.progress,trackFiles:J.trackFiles?[...J.trackFiles]:void 0};case"error":return{status:"error",error:{message:J.error?this.options.renderToolRunError(J.error):"Tool execution failed"}};case"rejected-by-user":return{status:"rejected-by-user",reason:J.reason};case"cancelled":return{status:"cancelled",reason:J.reason};default:return{status:"error",error:{message:`Unexpected status: ${J.status}`}}}}extractGuidanceFromRun(J){if(J.status!=="done")return{run:J,files:[]};if(!J.result||typeof J.result!=="object"||Array.isArray(J.result))return{run:J,files:[]};let Z=J.result;if(!("discoveredGuidanceFiles"in Z))return{run:J,files:[]};let Q=rA4(Z.discoveredGuidanceFiles),{discoveredGuidanceFiles:Y,...X}=Z;return{run:{...J,result:X},files:Q}}sendTransportMessage(J,Z,Q){try{return Z(),!0}catch(Y){if(Y instanceof s8)return this.options.log.info(`${this.clientID} dropped ${J} while reconnecting`,{messageType:J,...Q}),this.options.onTransportSendFailure?.(this.clientID,J,Y,Q),!1;return this.options.log.error(`${this.clientID} failed to send ${J}`,Y),!1}}}d0();function qY0(J){return{async createHandoffDraft(Z){let Q=await GR4(J,Z.signal);return VR4(Q,Z.parentThread.id,Z.goal,Z.images)},createHandoffThread:async(Z)=>{let Q=await GR4(J,Z.signal),Y=await VR4(Q,Z.parentThread.id,Z.goal,Z.images),X=await b23(Q,Z,Y);if(await u23(X.http,X.threadID,X.prompt,X.agentMode),Z.follow&&J.onFollow)try{await J.onFollow({sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}catch(K){C.error("Failed to follow handoff thread",{error:K,sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}return X.threadID}}}function x23(J){let Z=new Headers({"Content-Type":"application/json"});if(J)Z.set("Authorization",`Bearer ${J}`);return Z}async function ln0(J,Z,Q){return fetch(`${J.workerURL}${Z}`,{method:"POST",headers:x23(J.apiKey),body:JSON.stringify(Q),signal:J.signal})}async function VR4(J,Z,Q,Y){let X=await ln0(J,`/threads/${Z}/handoff`,{goal:Q,images:Y});if(!X.ok)throw Error(`Failed to generate handoff prompt: ${X.status} ${await X.text()}`);return await X.json()}async function f23(J,Z,Q,Y){let X=await ln0(J,"/threads",{...Z?{repositoryURL:Z}:{},...Q?{agentMode:Q}:{},relationship:Y});if(!X.ok)throw Error(`Failed to create handoff thread: ${X.status} ${await X.text()}`);let K=await X.json();if(!K.threadId)throw Error("Thread creation response missing threadId");return K.threadId}async function u23(J,Z,Q,Y){let X=await ln0(J,`/threads/${Z}/message`,{content:Q,...Y?{agentMode:Y}:{}});if(!X.ok)throw Error(`Failed to start handoff thread: ${X.status} ${await X.text()}`)}async function GR4(J,Z){let Q=await J.configService.getLatest(),Y=J.apiKey??await Q.secrets.getToken("apiKey",Q.settings.url),X=J.workerURL??process.env.AMP_WORKER_URL??d7(Q.settings.url);return{apiKey:Y,workerURL:X,signal:Z}}async function b23(J,Z,Q){let Y=Z.agentMode??Q.sourceAgentMode??Z.parentThread.agentMode,X=Z.relationshipMessageIndex??Q.parentMessageIndex,K=Z.relationshipComment??Z.goal,V={threadID:Q.parentThreadID,type:"handoff",...X!==void 0?{messageIndex:X}:{},...Z.relationshipBlockIndex!==void 0?{blockIndex:Z.relationshipBlockIndex}:{},comment:K},G=Z.parentThread.env?.initial?.trees?.[0]?.repository?.url,z=await f23(J,G,Y??void 0,V);return{http:J,threadID:z,prompt:Q.content,agentMode:Y??void 0}}fX();sd();jT();lh0();d4();U4();E1();async function WH(J){let{toolName:Z,threadSnapshot:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,configService:K,toolService:V,mcpService:G,skillService:z,fsTracker:F,toolUseID:q,discoveredGuidanceFileURIs:W}=J,D=z1.file(process.cwd()),H=q??Sz(),U=await K.getLatest(),B,w;if(F)B=F.trackedFileSystem(H),w=F.tracker;else w=Y$0(JS0,Q.id,async()=>{}),B=ih0(n8,w,H);return{dir:D,tool:Z,thread:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,trackedFiles:new t$,toolUseID:H,todos:void 0,configService:K,toolService:V,mcpService:G,config:U,filesystem:B,fileChangeTracker:w,getAllTrackedChanges:async()=>w.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>k0.of(Q),get:()=>Promise.resolve(Q),getPrimitiveProperty:(N,L)=>Promise.resolve(Q[L]),flushVersion:()=>Promise.resolve(),updateThreadMeta:()=>Promise.resolve()},getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:n8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:JS0,discoveredGuidanceFileURIs:W??new Set,skillService:z??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function in0(){return new Date().toISOString()}var nn0=process.stderr.isTTY,zR4=3000;function h23(J){let Z=J.trim();if(!(Z.startsWith("{")&&Z.endsWith("}")||Z.startsWith("[")&&Z.endsWith("]")))return null;try{return JSON.parse(Z)}catch{return null}}function an0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=h23(J);if(Z!==null)return JSON.stringify(Z,null,2);return J}if(J===void 0)return"";try{return JSON.stringify(J,null,2)}catch{return String(J)}}function Q8(J,Z,Q){if(C.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!nn0)return;let Y=p0.dim(`[${in0()}]`),X=p0.magenta(`[${Z}]`),K=J==="SEND"?p0.green(">>>"):p0.yellow("<<<"),V=an0(Q);process.stderr.write(`${Y} ${X} ${K} ${V}
6091
6091
  `)}function P$(J,Z){if(Z)C.info(`[headless-dtw] ${J}`,Z);else C.info(`[headless-dtw] ${J}`);if(!nn0)return;let Q=p0.dim(`[${in0()}]`),Y=p0.cyan("[INFO]"),X=Z?` ${an0(Z)}`:"";process.stderr.write(`${Q} ${Y} ${J}${X}
6092
6092
  `)}function CG(J,Z){if(Z!==void 0)C.error(`[headless-dtw] ${J}`,{error:Z});else C.error(`[headless-dtw] ${J}`);if(!nn0)return;let Q=p0.dim(`[${in0()}]`),Y=p0.red("[ERROR]"),X=an0(Z);process.stderr.write(`${Q} ${Y} ${J} ${X}
6093
- `)}function g23(J){let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCode=J.code;if(J.reason)Z.reconnectReason=J.reason;if(J.error)Z.reconnectError=J.error;return Z}function m23(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class FR4{options;clients=new Map;clientCounter=0;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;toolSyncSubscription=null;resolveRunLoop=null;constructor(J){this.options=J}bindClientThread(J,Z){let Q=J.threadId!==Z;if(J.threadId=Z,J.fsTracker&&!Q)return;let Y=this.options.fileSystem??n8,X=new bV(Y);J.fsTracker=RS({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){let Y=await J.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:zR4});if(!Y){let X=J.getConnectionInfo();P$(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason,waitedMs:zR4})}return Y}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,P$(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{let K=X.transport.getConnectionInfo();if(K.state==="connecting"||K.state==="authenticating"||K.state==="reconnecting"){P$(`${J} recovery waiting for in-flight connection`,{connectionState:K.state,reconnectCauseType:K.reconnectCause?.type,reconnectCauseCode:K.reconnectCause?.code,reconnectCauseReason:K.reconnectCause?.reason});return}if(K.state==="connected")X.transport.disconnect();let V=await this.connectTransport(X.transport,J,"recovery"),G=X.transport.getThreadId();if(G)this.bindClientThread(X,G);if(!V)return;X.handshakeManager.ensureHandshake("retry")}catch(K){CG(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){P$("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??d7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=ik(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);P$("Initial client created",{clientId:J.id,threadId:J.threadId}),this.logThreadURL(J.threadId);let Z=await this.runLoop();if(Z!==0)throw Error(`Headless DTW harness exited with code ${Z}`)}catch(J){throw CG("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=m23(this.options.ampURL,J);P$(`Thread URL: ${p0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)P$(Z);else CG(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:K}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:V,toolCallId:G,args:z}=Z,F=typeof z==="object"&&z!==null?z:{},q=qY0({configService:Y,apiKey:this.options.apiKey}),W={upsertArtifact:(H,U)=>{let B=r8.safeParse(U);J.transport.sendExecutorArtifactUpsert(H,B.success?B.data:void 0)},deleteArtifact:(H)=>{J.transport.sendExecutorArtifactDelete(H)}},D=await WH({toolName:V,threadSnapshot:{id:J.threadId??m3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:W,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:G,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:F},D)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??d7(this.options.ampURL),X=this.options.useThreadActors?process.env.THREAD_ACTORS_URL??Pk(this.options.ampURL):void 0;P$(`Creating client ${Z}`,{threadId:J,workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)",options:this.options});let K;if(this.options.useThreadActors&&X){let H=Ik({endpoint:X});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await H.threadActor.getOrCreate([J],{params:{apiKey:this.options.apiKey,threadId:J,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:J,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000,useThreadActors:!0}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new qq(K),G=(H)=>({...H??{},threadId:J}),z,F=new Vi({clientID:Z,transport:V,invokeTool:(H)=>this.invokeToolForClient(z,H),captureGitStatus:()=>ZY0(this.options.workspaceRoot),batchGuidanceFiles:YY0,renderToolRunError:Lm,onTransportSendFailure:(H,U,B,w)=>{this.recoverTransport(H,U,B,w)},log:{info:(H,U)=>P$(H,G(U)),error:CG,wsMessage:(H,U,B)=>{Q8(H,U,G(typeof B==="object"&&B!==null?B:{message:B}))}}}),q=this.createHandshakeManager(()=>z,Z);z={id:Z,transport:V,threadId:J,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:q,toolRunner:F,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,z),this.subscribeToTransportEvents(z),P$(`Connecting ${Z}...`);let W=await this.connectTransport(V,Z,"startup"),D=V.getThreadId();if(D)this.bindClientThread(z,D);if(W)P$(`Connected ${Z}`,{threadId:D});if(W)z.handshakeManager.ensureHandshake("connect");return z}async connectAsExecutor(J,Z){P$(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await XY0({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,resumeFromVersion:0,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,subscribeToThreadEvents:!1,executorType:"sandbox",previouslyAdvertisedTools:J.advertisedExecutorTools,initialToolDiscovery:this.options.initialToolDiscovery,logMessage:(Y,X)=>{Q8(Y,J.id,X)}});if(J.advertisedExecutorTools=Q,J.toolRunner.flushBufferedTerminalResults(),!J.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw CG(`${J.id} executor bootstrap failed`,Q),Q}}setNotifyForwarder(J){let Z=this.options.pluginPlatform;if(!Z)return;Z.setNotifyForwarder(async(Q)=>{let Y={type:"event",event:"ui.notify",data:{message:Q}};try{Q8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){CG(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,P$(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Ki({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{CG(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=KY0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Yi({transport:J.transport,nextTools:Z,previouslyAdvertisedTools:J.advertisedExecutorTools,logMessage:(Y,X)=>{Q8(Y,J.id,X)}})}syncApprovalRequests(J,Z){if(!J.threadId)return;let Q=Z.filter((X)=>X.threadId===J.threadId||X.mainThreadId===J.threadId),Y=new Set(Q.map(Oj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Oj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=eQ0(X);Q8("SEND",J.id,{type:"executor_tool_approval_request",toolCallId:V.toolCallId,toolName:V.toolName}),J.transport.sendExecutorToolApprovalRequest(V),J.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J,Z){let{toolService:Q}=this.options;if(!Q){CG(`${J.id} received approval response without tool service`);return}P$(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted,Z.input?.denyFeedback)}subscribeToTransportEvents(J){let{transport:Z,id:Q}=J;Z.deltas().subscribe({next:(X)=>Q8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.connectionChanges().subscribe({next:(X)=>{if(X.state==="connected"&&X.threadId)this.bindClientThread(J,X.threadId);let V={role:X.role??"unclaimed"};if(X.state==="reconnecting"&&X.reconnectCause)Object.assign(V,g23(X.reconnectCause));P$(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{Q8("RECV",Q,X),CG(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{Q8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{Q8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{Q8("RECV",Q,X),CG(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.fileSystemReadDirectoryRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorFileSystemReadDirectoryRequest(J,X)}}),Z.fileSystemReadFileRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorFileSystemReadFileRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>Q8("RECV",Q,X)});let{toolService:Y}=this.options;if(Y)Y.pendingApprovals$.subscribe((X)=>{this.syncApprovalRequests(J,X)})}async handleExecutorRollbackRequest(J,Z){let{id:Q,fsTracker:Y}=J,{editId:X,toolUseIdsToRevert:K}=Z;if(!Y){CG(`${Q} rollback failed: no file tracker`),Q8("SEND",Q,{type:"executor_rollback_ack",editId:X,ok:!1,error:"File tracker not initialized"}),J.transport.sendExecutorRollbackAck(X,!1,"File tracker not initialized");return}await J.toolRunner.handleRollbackRequest(X,K,(V)=>Y.tracker.revertChanges(V))}async handleExecutorFileSystemReadDirectoryRequest(J,Z){let Q=await GY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);Q8("SEND",J.id,{type:"executor_filesystem_read_directory_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadDirectoryResult(Z.requestId,Q)}async handleExecutorFileSystemReadFileRequest(J,Z){let Q=await zY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);Q8("SEND",J.id,{type:"executor_filesystem_read_file_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadFileResult(Z.requestId,Q)}async runLoop(){if(P$("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((J)=>{let Z=!1,Q=(K)=>{if(Z){P$(`Received ${K} while shutdown is already in progress`);return}Z=!0,this.shutdown(0,`Received ${K}, shutting down harness...`)},Y=()=>Q("SIGINT"),X=()=>Q("SIGTERM");this.resolveRunLoop=(K)=>{process.off("SIGINT",Y),process.off("SIGTERM",X),J(K)},process.on("SIGINT",Y),process.on("SIGTERM",X)})}getClients(){return Array.from(this.clients.values())}dispose(){this.disposed=!0,this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=null,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function qR4(J){await new FR4(J).start()}import{stderr as TG,stdin as c23}from"node:process";import{createInterface as l23}from"node:readline";import{stdout as p23}from"node:process";function d23(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function WY0(){if(!p23.isTTY)return!0;if(d23())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var DY0=[],on0=null;function rn0(J){if(on0=J,J&&DY0.length>0){for(let Z of DY0)J(Z);DY0=[]}}function WR4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(on0)on0(K);else DY0.push(K)})}}function DR4(){return async(J,Z)=>{return TG.write(`
6093
+ `)}function g23(J){let Z={reconnectCauseType:J.type,reconnectCauseAt:new Date(J.at).toISOString()};if(J.code!==void 0)Z.reconnectCode=J.code;if(J.reason)Z.reconnectReason=J.reason;if(J.error)Z.reconnectError=J.error;return Z}function m23(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class FR4{options;clients=new Map;clientCounter=0;disposed=!1;pluginsBootstrapped=!1;pendingExitCode=null;toolSyncSubscription=null;resolveRunLoop=null;constructor(J){this.options=J}bindClientThread(J,Z){let Q=J.threadId!==Z;if(J.threadId=Z,J.fsTracker&&!Q)return;let Y=this.options.fileSystem??n8,X=new bV(Y);J.fsTracker=RS({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){let Y=await J.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:zR4});if(!Y){let X=J.getConnectionInfo();P$(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason,waitedMs:zR4})}return Y}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,P$(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{let K=X.transport.getConnectionInfo();if(K.state==="connecting"||K.state==="authenticating"||K.state==="reconnecting"){P$(`${J} recovery waiting for in-flight connection`,{connectionState:K.state,reconnectCauseType:K.reconnectCause?.type,reconnectCauseCode:K.reconnectCause?.code,reconnectCauseReason:K.reconnectCause?.reason});return}if(K.state==="connected")X.transport.disconnect();let V=await this.connectTransport(X.transport,J,"recovery"),G=X.transport.getThreadId();if(G)this.bindClientThread(X,G);if(!V)return;X.handshakeManager.ensureHandshake("retry")}catch(K){CG(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){P$("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??d7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=ik(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);P$("Initial client created",{clientId:J.id,threadId:J.threadId}),this.logThreadURL(J.threadId);let Z=await this.runLoop();if(Z!==0)throw Error(`Headless DTW harness exited with code ${Z}`)}catch(J){throw CG("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=m23(this.options.ampURL,J);P$(`Thread URL: ${p0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)P$(Z);else CG(Z);this.dispose()}if(this.resolveRunLoop){let Q=this.resolveRunLoop;this.resolveRunLoop=null,Q(J);return}if(this.pendingExitCode===null||J>this.pendingExitCode)this.pendingExitCode=J}async invokeToolForClient(J,Z){let{toolService:Q,configService:Y,mcpService:X,skillService:K}=this.options;if(!Q||!Y||!X)throw Error("Tool service not available");let{toolName:V,toolCallId:G,args:z}=Z,F=typeof z==="object"&&z!==null?z:{},q=qY0({configService:Y,apiKey:this.options.apiKey}),W={upsertArtifact:(H,U)=>{let B=r8.safeParse(U);J.transport.sendExecutorArtifactUpsert(H,B.success?B.data:void 0)},deleteArtifact:(H)=>{J.transport.sendExecutorArtifactDelete(H)}},D=await WH({toolName:V,threadSnapshot:{id:J.threadId??m3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:W,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:G,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:F},D)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??d7(this.options.ampURL),X=this.options.useThreadActors?process.env.THREAD_ACTORS_URL??Pk(this.options.ampURL):void 0;P$(`Creating client ${Z}`,{threadId:J,workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)",options:this.options});let K;if(this.options.useThreadActors&&X){let H=Ik({endpoint:X});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await H.threadActor.getOrCreate([J],{params:{apiKey:this.options.apiKey,threadId:J,executorClientId:Q},...this.options.ownerUserId&&typeof this.options.threadVersion==="number"?{createWithInput:{threadId:J,ownerUserId:this.options.ownerUserId,threadVersion:this.options.threadVersion}}:{}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000,useThreadActors:!0}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new qq(K),G=(H)=>({...H??{},threadId:J}),z,F=new Vi({clientID:Z,transport:V,invokeTool:(H)=>this.invokeToolForClient(z,H),captureGitStatus:()=>ZY0(this.options.workspaceRoot),batchGuidanceFiles:YY0,renderToolRunError:Lm,onTransportSendFailure:(H,U,B,w)=>{this.recoverTransport(H,U,B,w)},log:{info:(H,U)=>P$(H,G(U)),error:CG,wsMessage:(H,U,B)=>{Q8(H,U,G(typeof B==="object"&&B!==null?B:{message:B}))}}}),q=this.createHandshakeManager(()=>z,Z);z={id:Z,transport:V,threadId:J,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:q,toolRunner:F,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,z),this.subscribeToTransportEvents(z),P$(`Connecting ${Z}...`);let W=await this.connectTransport(V,Z,"startup"),D=V.getThreadId();if(D)this.bindClientThread(z,D);if(W)P$(`Connected ${Z}`,{threadId:D});if(W)z.handshakeManager.ensureHandshake("connect");return z}async connectAsExecutor(J,Z){P$(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await XY0({transport:J.transport,executorClientID:J.executorClientId,workspaceRoot:this.options.workspaceRoot,threadId:J.threadId,configService:this.options.configService,toolService:this.options.toolService,skillService:this.options.skillService,fileSystem:this.options.fileSystem,executorType:"sandbox",previouslyAdvertisedTools:J.advertisedExecutorTools,initialToolDiscovery:this.options.initialToolDiscovery,logMessage:(Y,X)=>{Q8(Y,J.id,X)}});if(J.advertisedExecutorTools=Q,J.toolRunner.flushBufferedTerminalResults(),!J.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw CG(`${J.id} executor bootstrap failed`,Q),Q}}setNotifyForwarder(J){let Z=this.options.pluginPlatform;if(!Z)return;Z.setNotifyForwarder(async(Q)=>{let Y={type:"event",event:"ui.notify",data:{message:Q}};try{Q8("SEND",J.id,{type:"executor_plugin_message",message:Y}),J.transport.sendPluginMessage(Y)}catch(X){CG(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,P$(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Ki({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{CG(`${Z} executor handshake failed`,{error:Q,attempt:Y,delayMs:X})},onExhausted:({error:Q,maxAttempts:Y})=>{this.shutdown(1,`${Z} executor handshake failed after ${Y} attempts: ${Q instanceof Error?Q.message:String(Q)}`)}})}startSettingsSync(J){if(J.settingsSubscription)return;J.settingsSubscription=this.options.configService.config.subscribe({next:(Z)=>{J.lastSentSettingsJSON=KY0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Yi({transport:J.transport,nextTools:Z,previouslyAdvertisedTools:J.advertisedExecutorTools,logMessage:(Y,X)=>{Q8(Y,J.id,X)}})}syncApprovalRequests(J,Z){if(!J.threadId)return;let Q=Z.filter((X)=>X.threadId===J.threadId||X.mainThreadId===J.threadId),Y=new Set(Q.map(Oj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Oj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=eQ0(X);Q8("SEND",J.id,{type:"executor_tool_approval_request",toolCallId:V.toolCallId,toolName:V.toolName}),J.transport.sendExecutorToolApprovalRequest(V),J.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J,Z){let{toolService:Q}=this.options;if(!Q){CG(`${J.id} received approval response without tool service`);return}P$(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted,Z.input?.denyFeedback)}subscribeToTransportEvents(J){let{transport:Z,id:Q}=J;Z.deltas().subscribe({next:(X)=>Q8("RECV",Q,{eventType:"delta",...X})}),Z.agentStates().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.messageEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.queuedMessages().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.retryEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.connectionChanges().subscribe({next:(X)=>{if(X.state==="connected"&&X.threadId)this.bindClientThread(J,X.threadId);let V={role:X.role??"unclaimed"};if(X.state==="reconnecting"&&X.reconnectCause)Object.assign(V,g23(X.reconnectCause));P$(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{Q8("RECV",Q,X),CG(`${Q} error`,X.message)}}),Z.errorEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.cancelledEvents().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.toolLeases().subscribe({next:(X)=>{Q8("RECV",Q,X),J.toolRunner.handleToolLease(X)}}),Z.toolLeaseRevoked().subscribe({next:(X)=>{Q8("RECV",Q,X),J.toolRunner.handleToolRevocation(X)}}),Z.toolApprovalQueue().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorToolApprovalResponses().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorToolApprovalResponse(J,X)}}),Z.toolProgress().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorErrors().subscribe({next:(X)=>{Q8("RECV",Q,X),CG(`${Q} executor error`,X.message)}}),Z.executorConnected().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.executorRollbackRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorRollbackRequest(J,X)}}),Z.fileSystemReadDirectoryRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorFileSystemReadDirectoryRequest(J,X)}}),Z.fileSystemReadFileRequests().subscribe({next:(X)=>{Q8("RECV",Q,X),this.handleExecutorFileSystemReadFileRequest(J,X)}}),Z.messageEdited().subscribe({next:(X)=>Q8("RECV",Q,X)}),Z.editRejected().subscribe({next:(X)=>Q8("RECV",Q,X)});let{toolService:Y}=this.options;if(Y)Y.pendingApprovals$.subscribe((X)=>{this.syncApprovalRequests(J,X)})}async handleExecutorRollbackRequest(J,Z){let{id:Q,fsTracker:Y}=J,{editId:X,toolUseIdsToRevert:K}=Z;if(!Y){CG(`${Q} rollback failed: no file tracker`),Q8("SEND",Q,{type:"executor_rollback_ack",editId:X,ok:!1,error:"File tracker not initialized"}),J.transport.sendExecutorRollbackAck(X,!1,"File tracker not initialized");return}await J.toolRunner.handleRollbackRequest(X,K,(V)=>Y.tracker.revertChanges(V))}async handleExecutorFileSystemReadDirectoryRequest(J,Z){let Q=await GY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);Q8("SEND",J.id,{type:"executor_filesystem_read_directory_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadDirectoryResult(Z.requestId,Q)}async handleExecutorFileSystemReadFileRequest(J,Z){let Q=await zY0({fileSystem:this.options.fileSystem??n8,workspaceRoot:this.options.workspaceRoot},Z.uri);Q8("SEND",J.id,{type:"executor_filesystem_read_file_result",requestId:Z.requestId,...Q}),J.transport.sendExecutorFileSystemReadFileResult(Z.requestId,Q)}async runLoop(){if(P$("Harness running. Press Ctrl+C to exit."),this.pendingExitCode!==null)return this.pendingExitCode;return await new Promise((J)=>{let Z=!1,Q=(K)=>{if(Z){P$(`Received ${K} while shutdown is already in progress`);return}Z=!0,this.shutdown(0,`Received ${K}, shutting down harness...`)},Y=()=>Q("SIGINT"),X=()=>Q("SIGTERM");this.resolveRunLoop=(K)=>{process.off("SIGINT",Y),process.off("SIGTERM",X),J(K)},process.on("SIGINT",Y),process.on("SIGTERM",X)})}getClients(){return Array.from(this.clients.values())}dispose(){this.disposed=!0,this.toolSyncSubscription?.unsubscribe(),this.toolSyncSubscription=null,this.options.pluginPlatform?.setNotifyForwarder(null);for(let J of this.clients.values())J.toolRunner.dispose(),J.settingsSubscription?.unsubscribe(),J.handshakeManager.dispose(),J.transport.dispose();this.clients.clear()}}async function qR4(J){await new FR4(J).start()}import{stderr as TG,stdin as c23}from"node:process";import{createInterface as l23}from"node:readline";import{stdout as p23}from"node:process";function d23(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function WY0(){if(!p23.isTTY)return!0;if(d23())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var DY0=[],on0=null;function rn0(J){if(on0=J,J&&DY0.length>0){for(let Z of DY0)J(Z);DY0=[]}}function WR4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(on0)on0(K);else DY0.push(K)})}}function DR4(){return async(J,Z)=>{return TG.write(`
6094
6094
  `),TG.write(p0.yellow.bold(`OAuth Authorization Required
6095
6095
  `)),TG.write(p0.dim("─".repeat(60)+`
6096
6096
  `)),TG.write(`
@@ -6222,11 +6222,11 @@ ${H}`))}},error:(D)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${D.message}`))}
6222
6222
  ${H}`;if(X==="pnpm"&&H.includes("Unable to find the global bin directory"))U+=`
6223
6223
 
6224
6224
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
6225
- npm install -g @sourcegraph/amp`;G(Error(U))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();cM();async function MY0(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=RI4(J,F),W=q<0,D,H;if(z.time){let U=z.time[J],B=z.time[F],w=Date.now();if(U)D=Math.floor((w-new Date(U).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var jJ3="https://static.ampcode.com/cli/cli-version.txt";async function AY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${jJ3}?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=RI4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var RJ3=604800000;function jI4(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>RJ3)return{ageMs:Q};return null}function RI4(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 Na0(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?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function La0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await EF(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 EF(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 EY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let D=W?await AY0(J):await MY0(J,jj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let H=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!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!==Wa0()){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 wi(D.latestVersion,q);let U=await LN(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await EF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}cM();import{stderr as _G}from"node:process";function II4(J){let Z=new hw().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 Ga0(Y.force||!1,Y.verbose||!1,"0.0.1774971219-g0fd6a8"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new hw("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 IJ3(Y.targetVersion)});J.addCommand(Q)}async function IJ3(J){let Z=process.platform==="win32"&&OY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_G.write(p0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6225
+ npm install -g @sourcegraph/amp`;G(Error(U))}},error:(D)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${D.message}`))},complete:()=>{if(!q)q=!0,V()}})})}d0();d0();cM();async function MY0(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=RI4(J,F),W=q<0,D,H;if(z.time){let U=z.time[J],B=z.time[F],w=Date.now();if(U)D=Math.floor((w-new Date(U).getTime())/3600000);if(B)H=Math.floor((w-new Date(B).getTime())/3600000)}return C.info("NPM version comparison",{currentVersion:J,latestVersion:F,compareResult:q,hasUpdate:W,currentVersionAge:D,latestVersionAge:H}),{hasUpdate:W,latestVersion:F,currentVersion:J,currentVersionAge:D,latestVersionAge:H,source:"npm"}}catch(G){return C.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var jJ3="https://static.ampcode.com/cli/cli-version.txt";async function AY0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${jJ3}?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=RI4(J,X),V=K<0;return C.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return C.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var RJ3=604800000;function jI4(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>RJ3)return{ageMs:Q};return null}function RI4(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 Na0(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?MF(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function La0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new Cz().scoped("update"),V=Q.startDelayMs??0;if(V>0)await EF(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 EF(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 EY0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:F,packageManager:q,isBinaryDistribution:W});let D=W?await AY0(J):await MY0(J,jj());if(!(D.latestVersion&&D.hasUpdate)){K.debug("no update available");return}let H=()=>{if(D.currentVersionAge!==void 0&&D.latestVersionAge!==void 0){let U=D.currentVersionAge-D.latestVersionAge,B=0.5;if(Math.abs(U)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:D.currentVersionAge,latestVersionAge:D.latestVersionAge,ageDifferenceHours:U}),!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!==Wa0()){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 wi(D.latestVersion,q);let U=await LN(D.latestVersion),B={from:D.currentVersion,to:D.latestVersion,...U};if(U.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(U){Y.next("update-error")}}catch(z){K.debug("check failed",{error:z})}finally{await EF(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}cM();import{stderr as _G}from"node:process";function II4(J){let Z=new hw().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 Ga0(Y.force||!1,Y.verbose||!1,"0.0.1774987755-gb72e09"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new hw("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 IJ3(Y.targetVersion)});J.addCommand(Q)}async function IJ3(J){let Z=process.platform==="win32"&&OY0(),Q=Z?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")_G.write(p0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
6226
6226
 
6227
6227
  `));try{if(!J){_G.write(p0.blue(`Checking for updates...
6228
- `));let{hasUpdate:K,latestVersion:V}=OY0()?await AY0("0.0.1774971219-g0fd6a8"):await MY0("0.0.1774971219-g0fd6a8",jj());if(!K){let G=Na0("0.0.1774971219-g0fd6a8"),z=G?.age?`released ${G.age} ago`:`built ${MF(new Date("2026-03-31T15:37:53.749Z"))} ago`;_G.write(p0.green(`✓ Amp is already up to date on version ${"0.0.1774971219-g0fd6a8"} (${z})
6229
- `));let F=await LN("0.0.1774971219-g0fd6a8",Q);if(F.warning)_G.write(`
6228
+ `));let{hasUpdate:K,latestVersion:V}=OY0()?await AY0("0.0.1774987755-gb72e09"):await MY0("0.0.1774987755-gb72e09",jj());if(!K){let G=Na0("0.0.1774987755-gb72e09"),z=G?.age?`released ${G.age} ago`:`built ${MF(new Date("2026-03-31T20:13:01.309Z"))} ago`;_G.write(p0.green(`✓ Amp is already up to date on version ${"0.0.1774987755-gb72e09"} (${z})
6229
+ `));let F=await LN("0.0.1774987755-gb72e09",Q);if(F.warning)_G.write(`
6230
6230
  `+p0.yellow(F.warning)+`
6231
6231
  `);process.exit(0)}if(!V)_G.write(p0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}_G.write(p0.blue(`Updating to version ${J}...
6232
6232
  `)),await wi(J,void 0,(K)=>{_G.write(p0.dim(`Running: ${K}
@@ -6235,7 +6235,7 @@ Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm in
6235
6235
  `));let X=await LN(J);if(X.warning)_G.write(`
6236
6236
  `+p0.yellow(X.warning)+`
6237
6237
  `);process.exit(0)}catch(Y){let X=Y instanceof Error?Y.message:String(Y);_G.write(p0.red.bold("Error: ")+X+`
6238
- `),process.exit(1)}}import{execFile as RQ3}from"node:child_process";import{lstat as xP4,mkdir as IQ3,readFile as PQ3,rm as aa0,writeFile as CQ3}from"node:fs/promises";import pY from"node:path";import _$ from"node:process";import{createInterface as TQ3}from"node:readline";import{promisify as _Q3}from"node:util";class Z3{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)}}d0();P7();U4();d0();lZ();E1();import{mkdir as PJ3,writeFile as CJ3}from"node:fs/promises";import TJ3 from"node:path";function _J3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function SJ3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function kJ3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${SJ3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Oa0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Ea0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=_J3(J.traceName),Y=kJ3(Z,Q);this.traceFilePath=TJ3.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Oa0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Oa0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Oa0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await PJ3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await CJ3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function PI4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.artifacts().subscribe({next:(Y)=>Z("artifacts",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}function RY0(J){return typeof J==="object"&&J!==null}function Ma0(J){if(!Array.isArray(J))return;return J}function CI4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return Ma0(Q)}catch{return}}function jY0(J){if(typeof J==="string")return J;if(!RY0(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=jY0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=jY0(J.error);if(Z!==void 0)return Z}if("value"in J)return jY0(J.value);return}function vJ3(J){return J.type==="text"}function TI4(J){if(J===void 0)return;let Z;try{Z=sl(J,"snapshot")}catch{return}if(Z.type==="snapshot")return jY0(Z.value);let Q=(Z.blocks??[]).filter(vJ3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var yJ3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function xJ3(J){return typeof J==="string"&&yJ3.includes(J)}function _I4(J){if(J===void 0)return;let Z;try{Z=sl(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!RY0(Q))return;if(!("status"in Q)||!xJ3(Q.status))return;return Q.status}function SI4(J){let Z=Ma0(J);if(Z!==void 0)return Z;if(!RY0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=Ma0(Y);if(X!==void 0)return X;if(typeof Y==="string")return CI4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!RY0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return CI4(Q)}function xI4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:zq(),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:zq(),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:zq(),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:zq(),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 fJ3(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 HH(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 r7("/api/durable-thread-workers",fI4({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 uJ3(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??xI4(J),G=Y.workerURL??d7(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 bJ3(J,Z,Q){let Y=await r7(`/api/durable-thread-workers/${J}`,fI4({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 Ei(J,Z){let Q=await Z.get(J);if(!Q)throw Error(`Failed to fetch thread snapshot: thread ${J} not found`);return Q}function fI4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function Oi(J){let Z=a6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=a6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function hJ3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=Oi(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function gJ3(J){let Z=new Set;for(let Q of J){let Y=Oi(Q);if(Y)Z.add(Y)}return Z}function Ni(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 mJ3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function pJ3(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=Ni(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=Ni([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Ni(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=Ni([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Ni(Z.streamingBlocks,J.blocks)}}function dJ3(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 cJ3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function Aa0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:cJ3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function lJ3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>Oi(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:Aa0(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:Aa0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function iJ3(J,Z){let Q=Z.findIndex((G)=>Oi(G)===J.messageId),Y=Z.findIndex((G)=>Oi(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 kI4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function Li(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 vI4(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:Aa0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function nJ3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>vI4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:vI4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function aJ3(J,Z){let Q=nJ3(Z);return Sn0(Li(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function oJ3(J,Z){if(J.useThreadActors){let Q=Pk(J.ampURL),Y=Ik({endpoint:Q});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>HH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await HH(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,useThreadActors:!0}}return{baseURL:J.workerUrl??d7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>HH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function yI4(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 IY0{threadSubject;agentLoopStateSubject=new F4("idle");executorReadySubject=new F4(!1);editErrorSubject=new z4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new F4(new Map);toolProgressSubject=new z4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new F4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;executorHandshakeManager=null;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Li(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=Jj4(Y),this.threadSubject=new F4(J),this.subscribeToTransport()}static async create(J){let Z=await HH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await Ei(Z.threadId,J.threadService);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let z=xI4(Q),F=await uJ3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:z});if(await bJ3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=fJ3(Q,z)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=hJ3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Li(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new qq(await oJ3(J,Z)),G=new IY0(K,V,X,Q.v);try{if(J.connectOnCreate??!0)await G.transport.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:0,onRetryableConnectError:(z)=>{let F=G.transport.getConnectionInfo();C.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:G.threadId,connectionState:F.state,...yI4(F.reconnectCause),error:z})}}),G.emitThread();return G}catch(z){throw G.dispose(),z}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionState(){return this.lastConnectionInfo?.state??this.transport.getConnectionInfo().state}getConnectionRole(){return this.lastConnectionInfo?.role??this.transport.getConnectionInfo().role}isExecutorConnected(){let J=this.transport.getConnectionInfo();return J.state==="connected"&&J.role==="executor"}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)}configureExecutorHandshake(J){this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=new Ki(J);let Z=this.transport.getConnectionInfo();this.executorHandshakeManager.handleConnectionChange(Z),this.executorReadySubject.next(Z.state==="connected"&&Z.role==="executor")}ensureExecutorReady(J){if(!this.executorHandshakeManager)return Promise.reject(Error("Executor handshake manager is not configured"));return this.executorHandshakeManager.ensureReady(J)}disconnectTransport(){this.transport.disconnect()}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let X=J==="client-write"?"client write action":"executor action";C.info(`Forcing transport reconnect before ${X}`)}if(await this.transport.ensureConnected({forceReconnectWhenReconnecting:!0,onAttemptTimeout:({attempt:X,maxAttempts:K,nextDelayMs:V})=>{C.info("[dtw] Connection attempt timed out, retrying",{attempt:X,maxAttempts:K,nextDelayMs:V,threadId:this.threadId})}}))return;let Y=this.transport.getConnectionInfo().state;throw Error(Y==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}editUserMessage(...J){this.transport.editUserMessage(...J)}setThreadTitle(...J){this.transport.setThreadTitle(...J)}cancelAgentLoop(...J){this.transport.cancelAgentLoop(...J)}retryAgentLoop(...J){this.transport.retryAgentLoop(...J)}appendManualBashInvocation(...J){this.transport.appendManualBashInvocation(...J)}resolveToolApproval(...J){this.transport.resolveToolApproval(...J)}ackToolLease(...J){this.transport.ackToolLease(...J)}sendToolProgress(...J){this.transport.sendToolProgress(...J)}sendExecutorToolResult(...J){this.transport.sendExecutorToolResult(...J)}sendRevocationAck(...J){this.transport.sendRevocationAck(...J)}sendExecutorRollbackAck(...J){this.transport.sendExecutorRollbackAck(...J)}sendExecutorGuidanceDiscovery(...J){this.transport.sendExecutorGuidanceDiscovery(...J)}sendExecutorToolApprovalRequest(...J){if(!this.isExecutorConnected())return!1;return this.transport.sendExecutorToolApprovalRequest(...J),!0}sendExecutorArtifactUpsert(...J){this.transport.sendExecutorArtifactUpsert(...J)}sendExecutorArtifactDelete(...J){this.transport.sendExecutorArtifactDelete(...J)}sendExecutorFileSystemReadDirectoryResult(...J){this.transport.sendExecutorFileSystemReadDirectoryResult(...J)}sendExecutorFileSystemReadFileResult(...J){this.transport.sendExecutorFileSystemReadFileResult(...J)}errorEvents(){return this.transport.errorEvents()}errors(){return this.transport.errors()}cancelledEvents(){return this.transport.cancelledEvents()}toolLeases(){return this.transport.toolLeases()}toolLeaseRevoked(){return this.transport.toolLeaseRevoked()}executorRollbackRequests(){return this.transport.executorRollbackRequests()}fileSystemReadDirectoryRequests(){return this.transport.fileSystemReadDirectoryRequests()}fileSystemReadFileRequests(){return this.transport.fileSystemReadFileRequests()}executorToolApprovalResponses(){return this.transport.executorToolApprovalResponses()}connectExecutor(J){return XY0({...J,transport:this.transport})}syncExecutorToolRegistrations(J){if(!this.isExecutorConnected())return[...J.previouslyAdvertisedTools??[]];return Yi({...J,transport:this.transport})}sendSettingsUpdate(J,Z){return KY0(this.transport,J,Z)}subscribeToProtocolEvents(J){return PI4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=mJ3(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?Li(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G),this.reconcilePendingClientWrites(G),this.replayPendingClientWritesIfNeeded(G)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=a6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=a6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=a6.safeParse(Q.queuedMessage.dtwMessageID);if(X.success)Z.add(X.data)}for(let Q of Z)this.pendingClientWritesByMessageID.delete(Q)}replayPendingClientWritesIfNeeded(J){if(this.pendingClientWritesByMessageID.size===0){this.pendingClientWriteReplayGeneration=null;return}if(this.pendingClientWriteReplayGeneration!==this.connectedTransportGeneration)return;if(this.transport.getConnectionInfo().state!=="connected")return;let Q=!1;for(let[Y,X]of this.pendingClientWritesByMessageID)try{this.sendUserMessage(X.content,X.agentMode,X.userState,Y,X.discoveredGuidanceFiles)}catch(K){Q=!0,C.warn("Failed to replay pending client write",{threadId:this.threadId,messageID:Y,error:K});break}if(!Q)this.pendingClientWriteReplayGeneration=null;this.reconcilePendingClientWrites(J)}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);C.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.lastConnectionState,Q=this.lastConnectionInfo,Y=J.state!==this.lastConnectionState,X=Q!==null&&(J.role!==Q.role||J.clientId!==Q.clientId);if(!Y&&!X)return;if(Y)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Q)this.logConnectionRoleTransition(Q,J);let K=J.state,V=K==="connected"&&this.lastConnectionState!=="connected";if(V)this.threadResumeCursor.reset();this.lastConnectionState=K,this.lastConnectionInfo={...J},this.executorHandshakeManager?.handleConnectionChange(J);let G=J.state==="connected"&&J.role==="executor";if(this.executorReadySubject.next(G),G&&Q?.role!=="executor"||V&&!this.executorHandshakeManager)this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(K==="connected"&&Z!=="connected")this.connectedTransportGeneration+=1,this.pendingClientWriteReplayGeneration=this.connectedTransportGeneration,this.replayPendingClientWritesIfNeeded(this.threadSubject.getValue())})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Rn0(J.message):null;if(C.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(pJ3(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=dJ3(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=TI4(J.progress),Y=_I4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?SI4(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=kI4(J);if(this.messages=lJ3(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=kI4(J);this.messages=iJ3(J,this.messages),this.processedIds=gJ3(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=aJ3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...yI4(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"){C.info("[dtw] Transport reconnected",Q);return}C.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){C.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){C.warn("[dtw] Transport disconnected",Q);return}C.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;C.info("[dtw] Transport role changed",Q)}sendUserMessage(J,Z,Q,Y,X){this.setAgentMode(Z);let K=this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X});return this.pendingClientWritesByMessageID.set(K,{content:J,agentMode:Z,userState:Q,discoveredGuidanceFiles:X}),K}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Li(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>a6.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.executorHandshakeManager?.dispose(),this.executorHandshakeManager=null,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as rJ3,readFile as sJ3,rm as ja0,writeFile as tJ3}from"node:fs/promises";import eJ3 from"node:path";d4();var $Z3=5000,JZ3=100;function ZZ3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function Ra0(J,Z){return J.code===Z}function QZ3(J){return J instanceof Error?J.message:String(J)}function bI4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function YZ3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function XZ3(J,Z){return bI4(Reflect.get(J,Z))}function KZ3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=YZ3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=XZ3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!R7(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function VZ3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
6238
+ `),process.exit(1)}}import{execFile as RQ3}from"node:child_process";import{lstat as xP4,mkdir as IQ3,readFile as PQ3,rm as aa0,writeFile as CQ3}from"node:fs/promises";import pY from"node:path";import _$ from"node:process";import{createInterface as TQ3}from"node:readline";import{promisify as _Q3}from"node:util";class Z3{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)}}d0();P7();U4();d0();lZ();E1();import{mkdir as PJ3,writeFile as CJ3}from"node:fs/promises";import TJ3 from"node:path";function _J3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function SJ3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function kJ3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${SJ3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function Oa0(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class Ea0{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=_J3(J.traceName),Y=kJ3(Z,Q);this.traceFilePath=TJ3.join(J.traceDir,`${Y}.json`),this.session={schemaVersion:1,sessionID:Y,createdAt:Z,runtimeMode:J.runtimeMode,...Q?{traceName:Q}:{},threadId:J.threadId,scriptedCommands:[...J.scriptedCommands??[]],protocolEvents:[],providerStateEvents:[],adapterStateEvents:[],commandEvents:[],timeline:[]}}nextTimelineIndex(){return this.session.timeline.length}recordProtocolEvent(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,eventName:J,payload:Oa0(Z)};this.session.protocolEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"protocol",protocolIndex:this.session.protocolEvents.length-1})}recordProviderState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Oa0(Z)};this.session.providerStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"provider_state",providerStateIndex:this.session.providerStateEvents.length-1})}recordAdapterState(J,Z){let Q=this.nextTimelineIndex(),Y=Date.now(),X={timelineIndex:Q,timestamp:Y,reason:J,state:Oa0(Z)};this.session.adapterStateEvents.push(X),this.session.timeline.push({timelineIndex:Q,timestamp:Y,kind:"adapter_state",adapterStateIndex:this.session.adapterStateEvents.length-1})}recordCommand(J){let Z=this.nextTimelineIndex(),Q=Date.now();this.session.commandEvents.push({timelineIndex:Z,timestamp:Q,command:J}),this.session.timeline.push({timelineIndex:Z,timestamp:Q,kind:"command",commandIndex:this.session.commandEvents.length-1})}async flush(){await PJ3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await CJ3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function PI4(J,Z){let Q=[J.connectionChanges().subscribe({next:(Y)=>Z("connection_changes",Y)}),J.errors().subscribe({next:(Y)=>Z("errors",Y)}),J.errorEvents().subscribe({next:(Y)=>Z("error_events",Y)}),J.agentStates().subscribe({next:(Y)=>Z("agent_states",Y)}),J.deltas().subscribe({next:(Y)=>Z("deltas",Y)}),J.messageEvents().subscribe({next:(Y)=>Z("message_events",Y)}),J.messageEdited().subscribe({next:(Y)=>Z("message_edited",Y)}),J.editRejected().subscribe({next:(Y)=>Z("edit_rejected",Y)}),J.threadTitles().subscribe({next:(Y)=>Z("thread_titles",Y)}),J.queuedMessages().subscribe({next:(Y)=>Z("queued_messages",Y)}),J.retryEvents().subscribe({next:(Y)=>Z("retry_events",Y)}),J.cancelledEvents().subscribe({next:(Y)=>Z("cancelled_events",Y)}),J.toolLeases().subscribe({next:(Y)=>Z("tool_leases",Y)}),J.toolLeaseRevoked().subscribe({next:(Y)=>Z("tool_lease_revoked",Y)}),J.toolApprovalQueue().subscribe({next:(Y)=>Z("tool_approval_queue",Y)}),J.executorToolApprovalResponses().subscribe({next:(Y)=>Z("executor_tool_approval_responses",Y)}),J.toolProgress().subscribe({next:(Y)=>Z("tool_progress",Y)}),J.executorErrors().subscribe({next:(Y)=>Z("executor_errors",Y)}),J.executorConnected().subscribe({next:(Y)=>Z("executor_connected",Y)}),J.executorRollbackRequests().subscribe({next:(Y)=>Z("executor_rollback_requests",Y)}),J.observers().subscribe({next:(Y)=>Z("observers",Y)}),J.executorStatuses().subscribe({next:(Y)=>Z("executor_statuses",Y)}),J.environmentUpdates().subscribe({next:(Y)=>Z("environment_updates",Y)}),J.artifacts().subscribe({next:(Y)=>Z("artifacts",Y)}),J.compactionEvents().subscribe({next:(Y)=>Z("compaction_events",Y)}),J.compactionRecords().subscribe({next:(Y)=>Z("compaction_records",Y)})];return{unsubscribe:()=>{for(let Y of Q)Y.unsubscribe()}}}function RY0(J){return typeof J==="object"&&J!==null}function Ma0(J){if(!Array.isArray(J))return;return J}function CI4(J){let Z=J.trim();if(Z.length===0)return;try{let Q=JSON.parse(Z);return Ma0(Q)}catch{return}}function jY0(J){if(typeof J==="string")return J;if(!RY0(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=jY0(J.result);if(Z!==void 0)return Z}if("error"in J){let Z=jY0(J.error);if(Z!==void 0)return Z}if("value"in J)return jY0(J.value);return}function vJ3(J){return J.type==="text"}function TI4(J){if(J===void 0)return;let Z;try{Z=sl(J,"snapshot")}catch{return}if(Z.type==="snapshot")return jY0(Z.value);let Q=(Z.blocks??[]).filter(vJ3).map((Y)=>Y.text).join("");return Q.length>0?Q:void 0}var yJ3=["queued","blocked-on-user","in-progress","rejected-by-user","cancellation-requested","cancelled","done","error"];function xJ3(J){return typeof J==="string"&&yJ3.includes(J)}function _I4(J){if(J===void 0)return;let Z;try{Z=sl(J,"snapshot")}catch{return}if(Z.type!=="snapshot")return;let Q=Z.value;if(!RY0(Q))return;if(!("status"in Q)||!xJ3(Q.status))return;return Q.status}function SI4(J){let Z=Ma0(J);if(Z!==void 0)return Z;if(!RY0(J)||typeof J.type!=="string")return;if(J.type==="snapshot"){let Y=J.value,X=Ma0(Y);if(X!==void 0)return X;if(typeof Y==="string")return CI4(Y);return}if(J.type!=="delta"||!Array.isArray(J.blocks))return;let Q=J.blocks.map((Y)=>{if(!RY0(Y)||Y.type!=="text"||typeof Y.text!=="string")return"";return Y.text}).join("");return CI4(Q)}function xI4(J){let Z=[],Q=0;for(let X of J.messages){if(X.role==="user"){Z.push({messageId:zq(),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:zq(),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:zq(),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:zq(),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 fJ3(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 HH(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 r7("/api/durable-thread-workers",fI4({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 uJ3(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??xI4(J),G=Y.workerURL??d7(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 bJ3(J,Z,Q){let Y=await r7(`/api/durable-thread-workers/${J}`,fI4({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 Ei(J,Z){let Q=await Z.get(J);if(!Q)throw Error(`Failed to fetch thread snapshot: thread ${J} not found`);return Q}function fI4(J,Z){if(!Z)return J;return{...J,headers:{...J?.headers,Authorization:`Bearer ${Z}`}}}function Oi(J){let Z=a6.safeParse(J.dtwMessageID);if(Z.success)return Z.data;let Q=a6.safeParse(`${J.messageId}`);return Q.success?Q.data:null}function hJ3(J){let Z=[],Q=new Set;for(let[Y,X]of J.messages.entries()){let K=Oi(X);if(K)Q.add(K);Z.push({...X,messageId:Y})}return{messages:Z,processedIds:Q}}function gJ3(J){let Z=new Set;for(let Q of J){let Y=Oi(Q);if(Y)Z.add(Y)}return Z}function Ni(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 mJ3(J,Z,Q,Y){if(!J||Z.length===0)return null;return{role:"assistant",content:Z,state:{type:"streaming"},messageId:Q,parentToolUseId:Y}}function pJ3(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=Ni(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=Ni([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Ni(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=Ni([],J.blocks??[]),Z.streamingParentToolCallId=Q;else if(J.blocks)Z.streamingBlocks=Ni(Z.streamingBlocks,J.blocks)}}function dJ3(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 cJ3(J){if(typeof J!=="number"||!Number.isFinite(J))return 0;return Math.max(0,Math.trunc(J))}function Aa0(J){if(!J||J.length===0)return;return J.map((Z)=>({uri:Z.uri,lineCount:cJ3(Z.lineCount),...typeof Z.content==="string"?{content:Z.content}:{}}))}function lJ3(J,Z,Q){let Y=J.message.messageId;if(Q.has(Y)){let K=Z.findIndex((G)=>Oi(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:Aa0(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:Aa0(J.message.discoveredGuidanceFiles),messageId:X,dtwMessageID:Y,parentToolUseId:J.parentToolUseId}]}function iJ3(J,Z){let Q=Z.findIndex((G)=>Oi(G)===J.messageId),Y=Z.findIndex((G)=>Oi(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 kI4(J){if(J.type==="message_edited")return J.agentMode;if(J.message.role==="user")return J.message.agentMode;return}function Li(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 vI4(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:Aa0(Z.discoveredGuidanceFiles),meta:Z.createdAt?{sentAt:Date.parse(Z.createdAt)}:void 0,messageId:-1,dtwMessageID:Z.messageId}}}function nJ3(J){if(J.type==="queued_messages")return{type:"queued_messages",messages:J.messages.map((Z)=>vI4(Z))};if(J.type==="queued_message_added")return{type:"queued_message_added",message:vI4(J.message)};return{type:"queued_message_removed",queuedMessageId:J.queuedMessageId}}function aJ3(J,Z){let Q=nJ3(Z);return Sn0(Li(J)??[],Q,{dedupeAdded:!0,getQueuedMessageId:(Y)=>Y.id})}async function oJ3(J,Z){if(J.useThreadActors){let Q=Pk(J.ampURL),Y=Ik({endpoint:Q});return{baseURL:Q,threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>HH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),webSocketProvider:async()=>{let X=await HH(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,useThreadActors:!0}}return{baseURL:J.workerUrl??d7(J.ampURL),threadId:Z.threadId,wsToken:Z.wsToken,wsTokenProvider:async()=>HH(Z.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL}),WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}function yI4(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 IY0{threadSubject;agentLoopStateSubject=new F4("idle");executorReadySubject=new F4(!1);editErrorSubject=new z4;deltaState={streamingMessageId:null,streamingBlocks:[],completedMessages:[]};toolProgressByToolUseIDSubject=new F4(new Map);toolProgressSubject=new z4;subscriptions=[];threadResumeCursor;messages;queuedMessages;relationships;threadTitle;processedIds;agentLoopState="idle";toolProgressByToolUseID=new Map;compactionStateSubject=new F4("idle");compactionState="idle";lastConnectionState="disconnected";lastConnectionInfo=null;executorHandshakeManager=null;connectionMode;pendingClientWritesByMessageID=new Map;connectedTransportGeneration=0;pendingClientWriteReplayGeneration=null;transport;threadId;constructor(J,Z,Q,Y,X){this.threadId=J.id,this.threadTitle=J.title,this.messages=[...J.messages],this.queuedMessages=Li(J.queuedMessages)??[],this.relationships=J.relationships??[],this.processedIds=Q,this.transport=Z,this.threadResumeCursor=Jj4(Y),this.threadSubject=new F4(J),this.connectionMode=X?.connectionMode??"observer",this.subscribeToTransport()}static async create(J){let Z=await HH(J.threadId,J.configService,J.apiKey,{repositoryURL:J.repositoryURL,executorType:J.executorType,usesThreadActors:J.useThreadActors}),Q=await Ei(Z.threadId,J.threadService);if(!Z.usesDtw){if(J.useThreadActors)throw Error("TODO: Importing threads into rivet thread actors isn't supported");J.onLegacyImportStateChange?.("importing");try{let z=xI4(Q),F=await uJ3(Q,J.configService,J.apiKey,{ampURL:J.ampURL,workerURL:J.workerUrl,payload:z});if(await bJ3(Z.threadId,J.configService,J.apiKey),F==="imported")Q=fJ3(Q,z)}finally{J.onLegacyImportStateChange?.("idle")}}let{messages:Y,processedIds:X}=hJ3(Q),K={...Q,id:Z.threadId,messages:Y,queuedMessages:Li(Q.queuedMessages),relationships:Q.relationships?[...Q.relationships]:void 0},V=new qq(await oJ3(J,Z)),G=new IY0(K,V,X,Q.v,{connectionMode:J.connectionMode});try{if(J.connectOnCreate??!0)await G.transport.ensureConnected({maxAttempts:1,waitForConnectedTimeoutMs:0,onRetryableConnectError:(z)=>{let F=G.transport.getConnectionInfo();C.warn("[dtw] Initial transport connect failed; waiting for reconnect",{threadId:G.threadId,connectionState:F.state,...yI4(F.reconnectCause),error:z})}}),G.emitThread();return G}catch(z){throw G.dispose(),z}}threadChanges(){return this.threadSubject}agentLoopStateChanges(){return this.agentLoopStateSubject}executorReadyChanges(){return this.executorReadySubject}toolProgressByToolUseIDChanges(){return this.toolProgressByToolUseIDSubject}toolProgressChanges(){return this.toolProgressSubject}editErrors(){return this.editErrorSubject}getThread(){return this.threadSubject.getValue()}getAgentLoopState(){return this.agentLoopState}getConnectionState(){return this.lastConnectionInfo?.state??this.transport.getConnectionInfo().state}getConnectionRole(){return this.lastConnectionInfo?.role??this.transport.getConnectionInfo().role}isExecutorConnected(){let J=this.transport.getConnectionInfo();return J.state==="connected"&&J.role==="executor"}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)}configureExecutorHandshake(J){this.executorHandshakeManager?.dispose(),this.executorHandshakeManager=new Ki(J);let Z=this.transport.getConnectionInfo();this.executorHandshakeManager.handleConnectionChange(Z),this.executorReadySubject.next(Z.state==="connected"&&Z.role==="executor")}ensureExecutorReady(J){if(!this.executorHandshakeManager)return Promise.reject(Error("Executor handshake manager is not configured"));return this.executorHandshakeManager.ensureReady(J)}disconnectTransport(){this.transport.disconnect()}async ensureConnectedForAction(J){if(this.transport.getConnectionInfo().state==="reconnecting"){let X=J==="client-write"?"client write action":"executor action";C.info(`Forcing transport reconnect before ${X}`)}if(await this.transport.ensureConnected({forceReconnectWhenReconnecting:!0,onAttemptTimeout:({attempt:X,maxAttempts:K,nextDelayMs:V})=>{C.info("[dtw] Connection attempt timed out, retrying",{attempt:X,maxAttempts:K,nextDelayMs:V,threadId:this.threadId})}}))return;let Y=this.transport.getConnectionInfo().state;throw Error(Y==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}editUserMessage(...J){this.transport.editUserMessage(...J)}setThreadTitle(...J){this.transport.setThreadTitle(...J)}cancelAgentLoop(...J){this.transport.cancelAgentLoop(...J)}retryAgentLoop(...J){this.transport.retryAgentLoop(...J)}appendManualBashInvocation(...J){this.transport.appendManualBashInvocation(...J)}resolveToolApproval(...J){this.transport.resolveToolApproval(...J)}ackToolLease(...J){this.transport.ackToolLease(...J)}sendToolProgress(...J){this.transport.sendToolProgress(...J)}sendExecutorToolResult(...J){this.transport.sendExecutorToolResult(...J)}sendRevocationAck(...J){this.transport.sendRevocationAck(...J)}sendExecutorRollbackAck(...J){this.transport.sendExecutorRollbackAck(...J)}sendExecutorGuidanceDiscovery(...J){this.transport.sendExecutorGuidanceDiscovery(...J)}sendExecutorToolApprovalRequest(...J){if(!this.isExecutorConnected())return!1;return this.transport.sendExecutorToolApprovalRequest(...J),!0}sendExecutorArtifactUpsert(...J){this.transport.sendExecutorArtifactUpsert(...J)}sendExecutorArtifactDelete(...J){this.transport.sendExecutorArtifactDelete(...J)}sendExecutorFileSystemReadDirectoryResult(...J){this.transport.sendExecutorFileSystemReadDirectoryResult(...J)}sendExecutorFileSystemReadFileResult(...J){this.transport.sendExecutorFileSystemReadFileResult(...J)}errorEvents(){return this.transport.errorEvents()}errors(){return this.transport.errors()}cancelledEvents(){return this.transport.cancelledEvents()}toolLeases(){return this.transport.toolLeases()}toolLeaseRevoked(){return this.transport.toolLeaseRevoked()}executorRollbackRequests(){return this.transport.executorRollbackRequests()}fileSystemReadDirectoryRequests(){return this.transport.fileSystemReadDirectoryRequests()}fileSystemReadFileRequests(){return this.transport.fileSystemReadFileRequests()}executorToolApprovalResponses(){return this.transport.executorToolApprovalResponses()}connectExecutor(J){return XY0({...J,transport:this.transport})}syncExecutorToolRegistrations(J){if(!this.isExecutorConnected())return[...J.previouslyAdvertisedTools??[]];return Yi({...J,transport:this.transport})}sendSettingsUpdate(J,Z){return KY0(this.transport,J,Z)}subscribeToProtocolEvents(J){return PI4(this.transport,J)}emitThread(J){let Z=this.threadSubject.getValue(),Q=J?.agentMode??Z.agentMode,Y=mJ3(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?Li(this.queuedMessages):void 0,relationships:this.relationships.length>0?[...this.relationships]:void 0,nextMessageId:Math.max(V,0)};this.threadSubject.next(G),this.reconcilePendingClientWrites(G),this.replayPendingClientWritesIfNeeded(G)}reconcilePendingClientWrites(J){if(this.pendingClientWritesByMessageID.size===0)return;let Z=new Set;for(let Q of J.messages){let Y=a6.safeParse(Q.dtwMessageID);if(Y.success)Z.add(Y.data)}for(let Q of J.queuedMessages??[]){let Y=a6.safeParse(Q.id);if(Y.success)Z.add(Y.data);let X=a6.safeParse(Q.queuedMessage.dtwMessageID);if(X.success)Z.add(X.data)}for(let Q of Z)this.pendingClientWritesByMessageID.delete(Q)}replayPendingClientWritesIfNeeded(J){if(this.pendingClientWritesByMessageID.size===0){this.pendingClientWriteReplayGeneration=null;return}if(this.pendingClientWriteReplayGeneration!==this.connectedTransportGeneration)return;if(this.transport.getConnectionInfo().state!=="connected")return;let Q=!1;for(let[Y,X]of this.pendingClientWritesByMessageID)try{this.sendUserMessage(X.content,X.agentMode,X.userState,Y,X.discoveredGuidanceFiles)}catch(K){Q=!0,C.warn("Failed to replay pending client write",{threadId:this.threadId,messageID:Y,error:K});break}if(!Q)this.pendingClientWriteReplayGeneration=null;this.reconcilePendingClientWrites(J)}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);C.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.lastConnectionState,Q=this.lastConnectionInfo,Y=J.state!==this.lastConnectionState,X=Q!==null&&(J.role!==Q.role||J.clientId!==Q.clientId);if(!Y&&!X)return;if(Y)this.logConnectionStateTransition(this.lastConnectionState,J);else if(X&&Q)this.logConnectionRoleTransition(Q,J);let K=J.state,V=K==="connected"&&this.lastConnectionState!=="connected";if(V)this.threadResumeCursor.reset();this.lastConnectionState=K,this.lastConnectionInfo={...J},this.executorHandshakeManager?.handleConnectionChange(J);let G=J.state==="connected"&&J.role==="executor";this.executorReadySubject.next(G);let z=G&&Q?.role!=="executor";if(V&&this.connectionMode==="observer"||z&&this.connectionMode==="executor+observer")this.transport.resumeFromVersion(this.threadResumeCursor.getVersion());if(K==="connected"&&Z!=="connected")this.connectedTransportGeneration+=1,this.pendingClientWriteReplayGeneration=this.connectedTransportGeneration,this.replayPendingClientWritesIfNeeded(this.threadSubject.getValue())})}}),this.transport.errors().subscribe({next:(J)=>{this.runTransportHandler("errors",()=>{let Z=J.code==="PARSE_ERROR"?Rn0(J.message):null;if(C.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(pJ3(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=dJ3(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=TI4(J.progress),Y=_I4(J.progress),X=this.toolProgressByToolUseID.get(Z),K=J.progress!==void 0?SI4(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=kI4(J);if(this.messages=lJ3(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=kI4(J);this.messages=iJ3(J,this.messages),this.processedIds=gJ3(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=aJ3(this.queuedMessages,J),this.emitThread()})}}))}logConnectionStateTransition(J,Z){let Q={threadId:this.threadId,from:J,to:Z.state,threadVersion:this.threadResumeCursor.getVersion(),...yI4(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"){C.info("[dtw] Transport reconnected",Q);return}C.info("[dtw] Transport connected",Q);return}if(Z.state==="reconnecting"){C.warn("[dtw] Transport reconnecting",Q);return}if(Z.state==="disconnected"){C.warn("[dtw] Transport disconnected",Q);return}C.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;C.info("[dtw] Transport role changed",Q)}sendUserMessage(J,Z,Q,Y,X){this.setAgentMode(Z);let K=this.transport.sendUserMessage(J,Z,{userState:Q,messageId:Y,discoveredGuidanceFiles:X});return this.pendingClientWritesByMessageID.set(K,{content:J,agentMode:Z,userState:Q,discoveredGuidanceFiles:X}),K}interruptQueuedMessage(J){this.transport.interruptQueuedMessage(J)}discardQueuedMessages(){let J=Li(this.queuedMessages);if(this.queuedMessages.length===0)return;let Z=this.queuedMessages.map((Q)=>a6.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.executorHandshakeManager?.dispose(),this.executorHandshakeManager=null,this.pendingClientWritesByMessageID.clear(),this.pendingClientWriteReplayGeneration=null,this.compactionStateSubject.complete(),this.agentLoopStateSubject.complete(),this.executorReadySubject.complete(),this.toolProgressByToolUseIDSubject.complete(),this.toolProgressSubject.complete(),this.transport.dispose()}}import{mkdir as rJ3,readFile as sJ3,rm as ja0,writeFile as tJ3}from"node:fs/promises";import eJ3 from"node:path";d4();var $Z3=5000,JZ3=100;function ZZ3(J){try{return process.kill(J,0),!0}catch(Z){return Z.code==="EPERM"}}function Ra0(J,Z){return J.code===Z}function QZ3(J){return J instanceof Error?J.message:String(J)}function bI4(J){if(typeof J!=="string")return null;let Z=J.trim();return Z.length>0?Z:null}function YZ3(J,Z){let Q=Reflect.get(J,Z);if(typeof Q!=="number")return;return Number.isSafeInteger(Q)&&Q>0?Q:void 0}function XZ3(J,Z){return bI4(Reflect.get(J,Z))}function KZ3(J){let Z;try{Z=JSON.parse(J)}catch{return}if(!Z||typeof Z!=="object")return;let Q=YZ3(Z,"pid"),Y=Reflect.get(Z,"threadId"),X=XZ3(Z,"threadTitle");if(Q===void 0||typeof Y!=="string"||!R7(Y))return;return{pid:Q,threadId:Y,threadTitle:X}}function VZ3(J){let Z={pid:J.pid,threadId:J.threadId};if(J.threadTitle)Z.threadTitle=J.threadTitle;return`${JSON.stringify(Z)}
6239
6239
  `}function GZ3(J){return{pid:J.currentPID??process.pid,threadId:J.currentThreadId,threadTitle:bI4(J.currentThreadTitle)}}async function hI4(J){try{let Z=await sJ3(J,"utf-8"),Q=KZ3(Z);if(Q===void 0)return{kind:"invalid",value:Z.trim()};return{kind:"valid",contents:Q}}catch(Z){if(Ra0(Z,"ENOENT"))return{kind:"missing"};throw Z}}async function gI4(J,Z){let Q=await hI4(J);if(Q.kind!=="valid"||Q.contents.pid!==Z)return;await ja0(J,{force:!0})}async function zZ3(J){try{process.kill(J,"SIGTERM")}catch(Z){if(Ra0(Z,"ESRCH"))return;throw Z}}async function FZ3(J,Z){let Q=Date.now()+$Z3;while(Date.now()<Q){if(!Z(J))return!0;await WZ3(JZ3)}return!Z(J)}function qZ3(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(`
6240
6240
  `)}function uI4(J,Z){return{status:"claimed",pidFilePath:J,release:async()=>gI4(J,Z)}}function WZ3(J){return new Promise((Z)=>{setTimeout(Z,J)})}async function mI4(J){let Z=J.currentPID??process.pid,Q=GZ3(J),Y=J.isProcessRunning??ZZ3,X=J.killProcess??zZ3,K=J.waitForProcessExit??((V)=>FZ3(V,Y));await rJ3(eJ3.dirname(J.pidFilePath),{recursive:!0});while(!0){let V=await hI4(J.pidFilePath);if(V.kind==="valid"){if(V.contents.pid===Z)return uI4(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})??qZ3({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 C1(`Couldn't stop live-sync PID ${V.contents.pid}: ${QZ3(F)}`,1)}if(!await K(V.contents.pid))throw new C1(`Timed out waiting for live-sync PID ${V.contents.pid} to stop.`,1);await gI4(J.pidFilePath,V.contents.pid);continue}await ja0(J.pidFilePath,{force:!0});continue}if(V.kind==="invalid"){await ja0(J.pidFilePath,{force:!0});continue}try{return await tJ3(J.pidFilePath,VZ3(Q),{encoding:"utf-8",flag:"wx",mode:384}),uI4(J.pidFilePath,Z)}catch(G){if(Ra0(G,"EEXIST"))continue;throw G}}}d0();class gY{static instance=null;logs=[];maxLogs=1000;listeners=new Set;constructor(){}static getInstance(){if(!gY.instance)gY.instance=new gY;return gY.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 pI4(){try{if(gY.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 $6(J,...Z){if(!J){let Q=Z.join(" "),Y=Error(Q);C.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;pI4(),console.error("FATAL TUI ERROR:",Q),console.error("Stack trace:",Y.stack),console.error("Context:",{meta:Z}),process.exit(1)}}}var Ia0=null,Pa0=null;function dI4(J,Z){Ia0=J,Pa0=Z}function cI4(){return typeof process<"u"&&(process.env.BUN_TEST==="1"||globalThis.Bun?.jest!==void 0||typeof globalThis.test==="function")}function lI4(){if(!Ia0){if(cI4())return{scheduleBuildFor:()=>{}};throw Error("Build scheduler not initialized. Make sure WidgetsBinding is created.")}return Ia0}function PY0(){if(!Pa0){if(cI4())return{requestLayout:()=>{},requestPaint:()=>{},removeFromQueues:()=>{}};throw Error("Paint scheduler not initialized. Make sure WidgetsBinding is created.")}return Pa0}class Rj{_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 PY0().requestLayout(this)}markNeedsPaint(){if(this._needsPaint)return;if(!this._attached)return;this._needsPaint=!0,PY0().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(){PY0().removeFromQueues(this),this._cachedDepth=void 0,this._parent=void 0,this._children.length=0}}class h4 extends Rj{_size={width:0,height:0};get size(){return{...this._size}}setSize(J,Z){$6(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 h4){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 Mi(J,Z=0){return Number.isFinite(J)?J:Z}class I1{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 I1(J,J,Z,Z)}static loose(J,Z){return new I1(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 $6(isFinite(J),`BoxConstraints.constrain received infinite width: ${J}. This indicates a layout bug where a widget is not properly calculating its desired size.`),$6(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 I1(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 I1(0,this.maxWidth,0,this.maxHeight)}tighten({width:J,height:Z}={}){return new I1(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 I1(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 Uq=H4(iI4(),1),HZ3=globalThis;HZ3.Prism=Uq.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(i,c){return i.replace(/<<(\d+)>>/g,function(o,H0){return"(?:"+c[+H0]+")"})}function Q(i,c,o){return RegExp(Z(i,c),o||"")}function Y(i,c){for(var o=0;o<c;o++)i=i.replace(/<<self>>/g,function(){return"(?:"+i+")"});return i.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(i){return"\\b(?:"+i.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),D=/@?\b[A-Za-z_]\w*\b/.source,H=Z(/<<0>>(?:\s*<<1>>)?/.source,[D,q]),U=Z(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[z,H]),B=/\[\s*(?:,\s*)*\]/.source,w=Z(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[U,B]),N=Z(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[q,W,B]),L=Z(/\(<<0>>+(?:,<<0>>+)+\)/.source,[N]),O=Z(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[L,U,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,[U]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[D,O]),lookbehind:!0,inside:E},{pattern:Q(/(\busing\s+)<<0>>(?=\s*=)/.source,[D]),lookbehind:!0},{pattern:Q(/(\b<<0>>\s+)<<1>>/.source,[V,H]),lookbehind:!0,inside:E},{pattern:Q(/(\bcatch\s*\(\s*)<<0>>/.source,[U]),lookbehind:!0,inside:E},{pattern:Q(/(\bwhere\s+)<<0>>/.source,[D]),lookbehind:!0},{pattern:Q(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[w]),lookbehind:!0,inside:E},{pattern:Q(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[O,F,D]),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,[D]),lookbehind:!0,alias:"punctuation"}}),J.languages.insertBefore("csharp","class-name",{namespace:{pattern:Q(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[D]),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,U]),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,[D,q]),inside:{function:Q(/^<<0>>/.source,[D]),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,D,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 I=A+"|"+M,S=Z(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[I]),T=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[S]),2),b=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,m=Z(/<<0>>(?:\s*\(<<1>>*\))?/.source,[U,T]);J.languages.insertBefore("csharp","class-name",{attribute:{pattern:Q(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[b,m]),lookbehind:!0,greedy:!0,inside:{target:{pattern:Q(/^<<0>>(?=\s*:)/.source,[b]),alias:"keyword"},"attribute-arguments":{pattern:Q(/\(<<0>>*\)/.source,[T]),inside:J.languages.csharp},"class-name":{pattern:RegExp(U),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var x=/:[^}\r\n]+/.source,k=Y(Z(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[S]),2),f=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[k,x]),d=Y(Z(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[I]),2),p=Z(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[d,x]);function h(i,c){return{interpolation:{pattern:Q(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[i]),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,k)},{pattern:Q(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[p]),lookbehind:!0,greedy:!0,inside:h(p,d)}],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,w){w=w||0;for(var N=0;N<B.length;N++){var L=X(N+w);if(!L||L.type!==B[N])return!1}return!0}function V(B,w){var N=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))N++;else if(w.test(E)){if(N--,N===0)return L}}}return-1}function G(B,w){var N=B.alias;if(!N)B.alias=N=[];else if(!Array.isArray(N))B.alias=N=[N];N.push(w)}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 D=V(/^\{$/,/^\}$/);if(D===-1)continue;for(var H=Y;H<D;H++){var U=Q[H];if(U.type==="variable"&&F.indexOf(U.content)>=0)G(U,"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],D=!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 D=!0;if(D||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(D){if(!D||typeof D==="string")return;for(var H=0,U=D.length;H<U;H++){var B=D[H];if(B.type!=="code"){W(B.content);continue}var w=B.content[1],N=B.content[3];if(w&&N&&w.type==="code-language"&&N.type==="code-block"&&typeof w.content==="string"){var L=w.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");L=(/[a-z][\w-]*/i.exec(L)||[""])[0].toLowerCase();var O="language-"+L;if(!N.alias)N.alias=[O];else if(typeof N.alias==="string")N.alias=[N.alias,O];else N.alias.push(O)}}}W(q.tokens)}),J.hooks.add("wrap",function(q){if(q.type!=="code-block")return;var W="";for(var D=0,H=q.classes.length;D<H;D++){var U=q.classes[D],B=/language-(.+)/.exec(U);if(B){W=B[1];break}}var w=J.languages[W];if(!w){if(W&&W!=="none"&&J.plugins.autoloader){var N="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*10000000000000000);q.attributes.id=N,J.plugins.autoloader.loadLanguages(W,function(){var L=document.getElementById(N);if(L)L.innerHTML=J.highlight(L.textContent,J.languages[W],W)})}}else q.content=J.highlight(F(q.content),w,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(D,H){if(H=H.toLowerCase(),H[0]==="#"){var U;if(H[1]==="x")U=parseInt(H.slice(2),16);else U=Number(H.slice(1));return z(U)}else{var B=G[H];if(B)return B;return D}}),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 UZ3(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 BZ3(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 TY0="unknown",nI4;function _Y0(J,Z){TY0=J,nI4=Z}function EN(){return TY0}function aI4(){return nI4}function oI4(J,Z,Q){if(TY0==="unknown")return null;if(J.type!=="rgb"||Z.type!=="rgb")return null;let Y=TY0==="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 wZ3(J,Z,Q){let Y=[];function X(K,V){if(typeof K==="string")Y.push({content:K,color:V});else{let G=V??BZ3(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 MN(J,Z,Q){try{let Y=Q?UZ3(Q):"plain";if(Y==="plain"||!Uq.default.languages[Y])return[{content:J}];let X=Uq.default.tokenize(J,Uq.default.languages[Y]);return wZ3(X,Z)}catch(Y){return[{content:J}]}}var ji=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 AN=F6(" ",{});function NZ3(J,Z){return J.char===Z.char&&J.width===Z.width&&sI4(J.style,Z.style)&&Ri(J.hyperlink,Z.hyperlink)}function sI4(J,Z){return rI4(J.fg,Z.fg)&&rI4(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 Ri(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 Ai(J){if(J.type==="none")return;return J.alpha}function rI4(J,Z){if(J===Z)return!0;if(J===void 0||Z===void 0)return!1;if(J.type!==Z.type)return!1;if(Ai(J)!==Ai(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 Ca0(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 SY0(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=aI4(),W=EN(),D=q??(W==="light"?{r:255,g:255,b:255}:{r:0,g:0,b:0}),H=Ca0(J,Q);if(!H)return J;let U=Math.round(H.r*F+D.r*(1-F)),B=Math.round(H.g*F+D.g*(1-F)),w=Math.round(H.b*F+D.b*(1-F));return{type:"rgb",value:{r:Math.max(0,Math.min(255,U)),g:Math.max(0,Math.min(255,B)),b:Math.max(0,Math.min(255,w))}}}let Y=J.alpha??1;if(Y>=1)return J;if(Y<=0)return Z;let X=Ca0(J,Q),K=Ca0(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 LZ3(J,Z,Q,Y,X){let K={...Z};if(J.fg)if(Z.fg)K.fg=SY0(J.fg,Z.fg,X);else K.fg=SY0(J.fg,Y,X);if(J.bg){let V=Ai(J.bg);if(J.bg.type==="none"||V===0){if(Z.bg)K.bg=Z.bg}else if(Z.bg)K.bg=SY0(J.bg,Z.bg,X);else K.bg=SY0(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 Ta0{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(()=>AN))}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?Ai(Q.style.fg):void 0,X=Q.style.bg?Ai(Q.style.bg):void 0;if(Y!==void 0&&Y<1||X!==void 0&&X<1){let V=this.cells[Z]?.[J]||AN,G=LZ3(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]=AN}}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 UH{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 Ta0(J,Z),this.backBuffer=new Ta0(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(),Y=(X,K,V)=>{if(V.width<=1)return!1;for(let G=1;G<V.width;G++){let z=X[K+G];if(!z)return!1;if(!(z.char===" "&&z.width===1&&sI4(z.style,V.style)&&Ri(z.hyperlink,V.hyperlink)))return!1}return!0};if(this.needsFullRefresh){for(let X=0;X<this.height;X++){let K=Q[X];if(!K)continue;for(let V=0;V<this.width;V++){let G=K[V]??AN;if(J.push({x:V,y:X,cell:G}),Y(K,V,G))V+=G.width-1}}return this.needsFullRefresh=!1,J}for(let X=0;X<this.height;X++){let K=Z[X],V=Q[X];if(!K||!V)continue;for(let G=0;G<this.width;G++){let z=K[G]??AN,F=V[G]??AN;if(z===AN&&F===AN)continue;if(!NZ3(z,F)){if(J.push({x:G,y:X,cell:F}),Y(V,G,F))G+=F.width-1}else if(Y(V,G,F))G+=F.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 OZ3=0;function EZ3(){return`amp-${++OZ3}`}function kY0(J,Z){return{uri:J,id:Z??EZ3()}}function tI4(J){return`\x1B]8;id=${J.id};${J.uri}\x1B\\`}function vY0(){return"\x1B]8;;\x1B\\"}class Ii{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 BH="\x1B",E6="\x1B[",eI4=E6+"0m",MZ3=E6+"m",$P4=(J,Z)=>E6+`${J+1};${Z+1}H`,AZ3=E6+"H",jZ3=E6+"?25l",RZ3=E6+"?25h",IZ3=E6+"2J",PZ3=E6+"?2026h",CZ3=E6+"?2026l",TZ3=E6+"?2004h",_Z3=E6+"?2004l",JP4=[...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]})],ZP4=new Map;function Pi(J,Z,Q){let Y=`${J},${Z},${Q}`,X=ZP4.get(Y);if(X!==void 0)return X;let K=16,V=1/0;for(let G=0;G<JP4.length;G++){let[z,F,q]=JP4[G],W=(J-z)**2+(Z-F)**2+(Q-q)**2;if(W<V)V=W,K=G+16}return ZP4.set(Y,K),K}var SZ3=E6+"?1049h",kZ3=E6+"?1049l",vZ3=E6+"?1002h"+E6+"?1003h"+E6+"?1004h"+E6+"?1006h",yZ3=E6+"?1002l"+E6+"?1003l"+E6+"?1004l"+E6+"?1006l",xZ3=E6+"?1016h",fZ3=E6+"?1016l",uZ3=E6+"?2027h",bZ3=E6+"?2027l",hZ3=E6+"?2048h",gZ3=E6+"?2048l",mZ3=E6+">5u",pZ3=E6+"<u",dZ3=E6+">4;1m",cZ3=E6+">4;0m",lZ3=(J)=>BH+`]22;${J}`+BH+"\\",iZ3=(J)=>BH+`]0;${J}\x07`;function nZ3(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 aZ3(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 oZ3=BH+"]9;4;3"+BH+"\\",YP4=BH+"]9;4;0"+BH+"\\",rZ3=BH+"]9;4;4"+BH+"\\",sZ3=(J)=>E6+`${J} q`;function tZ3(J){return vZ3+(J?xZ3:"")}function eZ3(){return yZ3+fZ3}function xY0(J){return iZ3(J)}function XP4(){return YP4}function QP4(J,Z,Q){if(!J)return"";switch(J.type){case"none":return"";case"default":return E6+(Z?"39":"49")+"m";case"index":return E6+`${Z?"38":"48"};5;${J.value}m`;case"rgb":{if(Q&&!Q.canRgb){let{r:G,g:z,b:F}=J.value,q=Pi(G,z,F);return E6+`${Z?"38":"48"};5;${q}m`}let Y=Z?"38":"48",{r:X,g:K,b:V}=J.value;return E6+`${Y};2;${X};${K};${V}m`}default:return""}}function $Q3(J,Z,Q){let Y="";if(!yY0(J.fg,Z.fg)){if(J.fg===void 0&&Z.fg!==void 0)Y+=E6+"39m";else Y+=QP4(J.fg,!0,Q);Z.fg=J.fg}if(!yY0(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+=E6+"49m";else if(!X)Y+=QP4(J.bg,!1,Q);Z.bg=J.bg}if(J.bold!==Z.bold){if(Y+=J.bold?E6+"1m":E6+"22m",Z.bold=J.bold,!J.bold&&J.dim)Y+=E6+"2m"}if(J.italic!==Z.italic)Y+=J.italic?E6+"3m":E6+"23m",Z.italic=J.italic;if(J.underline!==Z.underline){if(Q?.underlineSupport!=="none")Y+=J.underline?E6+"4m":E6+"24m";Z.underline=J.underline}if(J.strikethrough!==Z.strikethrough)Y+=J.strikethrough?E6+"9m":E6+"29m",Z.strikethrough=J.strikethrough;if(J.reverse!==Z.reverse)Y+=J.reverse?E6+"7m":E6+"27m",Z.reverse=J.reverse;if(J.dim!==Z.dim){if(Y+=J.dim?E6+"2m":E6+"22m",Z.dim=J.dim,!J.dim&&J.bold)Y+=E6+"1m"}return Y}function JQ3(J,Z){let Q="";if(!Ri(J,Z.hyperlink)){if(Z.hyperlink)Q+=vY0();if(J)Q+=tI4(J);Z.hyperlink=J}return Q}function yY0(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 ZQ3(J,Z){return yY0(J.fg,Z.fg)&&yY0(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 QQ3=" ".repeat(ji);function YQ3(J,Z){if(J.char==="\t"){if(J.width===ji)return QQ3;return" ".repeat(Math.max(1,J.width))}if(Z?.kittyExplicitWidth&&J.width>1)return`\x1B]66;w=${J.width};${J.char}\x1B\\`;return J.char}class _a0{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 Ii,Q=null,Y,X=-1,K=-1;for(let V of J){let G=V.cell.char,z=nZ3(G),F=z?aZ3(G):G;if($6(!z,`Cell contains disallowed control at (${V.x}, ${V.y}):`,`U+${G.codePointAt(0)?.toString(16).toUpperCase().padStart(4,"0")}`),!(Q!==null&&V.y===K&&V.x===X&&ZQ3(Q,V.cell.style)&&Ri(Y,V.cell.hyperlink))){if(this.currentX!==V.x||this.currentY!==V.y)Z.append($P4(V.y,V.x)),this.currentX=V.x,this.currentY=V.y;Z.append($Q3(V.cell.style,this.currentStyle,this.capabilities)),Z.append(JQ3(V.cell.hyperlink,this.currentStyle)),Q=V.cell.style,Y=V.cell.hyperlink}let W=z?{...V.cell,char:F}:V.cell;Z.append(YQ3(W,this.capabilities)),this.currentX+=V.cell.width,X=V.x+V.cell.width,K=V.y}return Z.toString()}clearScreen(){return this.currentX=0,this.currentY=0,this.currentStyle={},eI4+vY0()+IZ3+AZ3}hideCursor(){return jZ3}showCursor(){return RZ3}setCursorShape(J){if(this.capabilities?.supportsCursorShape===!1)return"";return sZ3(J)}reset(){return this.currentStyle={},eI4+vY0()}moveTo(J,Z){return this.currentX=J,this.currentY=Z,$P4(Z,J)}getCursorPosition(){return{x:this.currentX,y:this.currentY}}resetState(){this.currentStyle={},this.currentX=0,this.currentY=0}startSync(){return PZ3}endSync(){return CZ3}enterAltScreen(){return SZ3+this.clearScreen()}exitAltScreen(){return kZ3}resetCursor(){return MZ3}enableMouse(J=!1){return tZ3(J)}disableMouse(){return eZ3()}enableEmojiWidth(){return uZ3}disableEmojiWidth(){return bZ3}enableInBandResize(){return hZ3}disableInBandResize(){return gZ3}enableBracketedPaste(){return TZ3}disableBracketedPaste(){return _Z3}enableKittyKeyboard(){return mZ3}disableKittyKeyboard(){return pZ3}enableModifyOtherKeys(){return dZ3}disableModifyOtherKeys(){return cZ3}setMouseShape(J){return lZ3(J)}setProgressBarIndeterminate(){return oZ3}setProgressBarOff(){return YP4}setProgressBarPaused(){return rZ3}}class fY0{constructor(){}}class Q3 extends fY0{value;constructor(J){super();this.value=J}equals(J){if(!(J instanceof Q3))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 wJ extends fY0{static _registry=new Map;static _counter=0;_id;_currentElement;constructor(J){super();if(J)this._id=`${J}_${wJ._counter++}`;else this._id=`GlobalKey_${wJ._counter++}`;wJ._registry.set(this._id,this)}equals(J){if(!(J instanceof wJ))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){$6(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,wJ._registry.delete(this._id)}toString(){return`GlobalKey(${this._id})`}static _clearRegistry(){wJ._registry.clear(),wJ._counter=0}}class NJ{key;_debugData={};constructor({key:J}={}){if(this.constructor===NJ)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 mY{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 wJ)this.widget.key._setElement(this)}unmount(){if(this.widget.key instanceof wJ)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,lI4().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 tk extends NJ{constructor({key:J}={}){super(J!==void 0?{key:J}:{})}createElement(){return new Ci(this)}updateRenderObject(J){}}class N8 extends tk{child;constructor({key:J,child:Z}={}){super(J?{key:J}:{});this.child=Z}createElement(){return new Bq(this)}}class DZ extends tk{children;constructor({key:J,children:Z=[]}={}){super(J?{key:J}:{});this.children=[...Z]}createElement(){return new uY0(this)}}class C$ extends tk{constructor({key:J}={}){super(J?{key:J}:{})}createElement(){return new vK(this)}}class Ci extends mY{_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 Bq extends Ci{_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 uY0 extends Ci{_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 D=W.widget.key.toString();z.set(D,W),F.set(D,q)}}for(let q=X;q<=V;q++){let W=Z[q];if(!W)continue;let D;if(W.key){let H=W.key.toString();if(D=z.get(H),D){z.delete(H);let U=F.get(H);if(U!==void 0)J[U]=null;if(D.widget===W);else if(D.widget.canUpdate(W))D.update(W);else this.deactivateChild(D),D=this.createChildElement(W)}else D=this.createChildElement(W)}else{let H=!1;for(let U=Y;U<=K;U++){let B=J[U];if(B&&!B.widget.key){if(B.widget===W){D=B,J[U]=null,H=!0;break}else if(B.widget.canUpdate(W)){D=B,J[U]=null,D.update(W),H=!0;break}}}if(!H)D=this.createChildElement(W)}if(D)Q.push(D)}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,D)=>W!==z[D]))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 vK extends Ci{constructor(J){super(J)}get leafWidget(){return this.widget}performRebuild(){}}class i0{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 SG{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 Rj?J:void 0}return}}class n0 extends NJ{createElement(){return new Sa0(this)}}class Sa0 extends mY{_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 SG(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 Y3={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 ka0{static hitTest(J,Z){let Q=new KP4;return J.hitTest(Q,Z),Q}}class KP4{_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 XQ3(){let J=Rj.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,D=Q.y>=q&&Q.y<q+G.height;if(W&&D){let H={x:Q.x-F,y:Q.y-q};Z.add({target:this,localPosition:H});let U=this.children,B=!0;for(let w=U.length-1;w>=0;w--)if(U[w].hitTest(Z,Q,F,q))B=!0;return B}if(this.allowHitTestOutsideBounds){let H=!1,U=this.children;for(let B=U.length-1;B>=0;B--)if(U[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}}XQ3();function wH(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 VP4(J,Z,Q,Y=1){return{type:"click",button:J.button==="left"?"left":J.button==="middle"?"middle":J.button==="right"?"right":"left",clickCount:Y,...wH(J,Z,Q)}}function bY0(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,...wH(J,Z,Q)}}class L8{static _instance=null;static SCROLL_SESSION_TIMEOUT=200;_rootRenderObject=null;_hoveredRegions=new Set;_vaxis=null;_currentCursor=Y3.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=L8.DOUBLE_CLICK_DISTANCE*L8.DOUBLE_CLICK_DISTANCE;_scratchCurrentRegions=new Set;_scratchEnteredRegions=new Set;_scratchExitedRegions=new Set;constructor(){}static get instance(){if(!L8._instance)L8._instance=new L8;return L8._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=ka0.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 jQ&&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,...wH(J,Z,V)};X.handleMouseEvent(G)}else for(let{target:X,localPosition:K}of Q){let V={type:"release",button:Y,...wH(J,Z,K)};if(X.handleMouseEvent(V),X instanceof jQ&&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,...wH(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=VP4(J,Z,K,Y);if(X.handleMouseEvent(V),X instanceof jQ&&X.opaque)break}}_handleScroll(J,Z,Q){let Y=Date.now();if(this._scrollSessionTarget&&this._scrollSessionTarget.attached&&Y-this._scrollSessionLastEvent<=L8.SCROLL_SESSION_TIMEOUT&&this._scrollSessionTarget){let V=Q.find((G)=>G.target===this._scrollSessionTarget);if(V){let G=bY0(J,Z,V.localPosition);this._scrollSessionTarget.onScroll?.(G)}else{let G=this._scrollSessionTarget.globalToLocal(Z),z=bY0(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=bY0(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 jQ),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",...wH(J,Z,Z)};G.handleMouseEvent(z)}for(let{target:G,localPosition:z}of Y)if(V.has(G)&&G.onEnter){let F={type:"enter",...wH(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",...wH(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=Y3.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 jQ&&Y.target.onScroll)Z.push({target:Y.target,localPosition:Y.localPosition});Q=K}return Z}_canHandleMouseEvents(J){if(J instanceof jQ)return!0;return typeof J.handleMouseEvent==="function"}clearHoverState(){if(this._hoveredRegions.clear(),this._dragTargets=[],this._vaxis&&this._currentCursor!==Y3.DEFAULT)this._currentCursor=Y3.DEFAULT,this._vaxis.setMouseCursor(Y3.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<=L8.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<=L8.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(),L8._instance=null}}class K4 extends N8{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 GP4(this)}createRenderObject(){return new jQ({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 GP4 extends Bq{get mouseRegionWidget(){return this.widget}get renderObject(){return super.renderObject}}class jQ extends h4{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($6(!!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(){L8.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 C3 extends NJ{child;constructor({key:J,child:Z}){super(J!==void 0?{key:J}:{});this.child=Z}createElement(){return new zP4(this)}}class zP4 extends mY{_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 jN{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:D,copyHighlight:H,tableBorder:U}){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=D,this.copyHighlight=H,this.tableBorder=U}static default(){return new jN({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 jN({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 c9{colorScheme;constructor({colorScheme:J}){this.colorScheme=J}static default(){return new c9({colorScheme:jN.default()})}static withRgb(J){return new c9({colorScheme:jN.fromRgb(J)})}}class m1 extends C3{data;constructor({key:J,data:Z,child:Q}){super({key:J,child:Q});this.data=Z}static of(J){let Z=J.dependOnInheritedWidgetOfExactType(m1);if(Z)return Z.widget.data;return c9.default()}static maybeOf(J){let Z=J.dependOnInheritedWidgetOfExactType(m1);if(Z)return Z.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}function va0(J,Z,Q){return J+(Z-J)*Q}function hY0(J,Z,Q){let Y=Math.max(0,Math.min(1,Q));return{r:Math.round(va0(J.r,Z.r,Y)),g:Math.round(va0(J.g,Z.g,Y)),b:Math.round(va0(J.b,Z.b,Y))}}F$();var jP4=H4(MP4(),1),AP4=20;function ga0(J){let Z=z$(J??"smart")??z$("smart");if(Z?.uiHints?.primaryColor&&Z.uiHints.secondaryColor)return{primary:Z.uiHints.primaryColor,secondary:Z.uiHints.secondaryColor};return{primary:kx1,secondary:vx1}}function ma0(J,Z,Q){let Y=Math.max(0,Math.min(1,J)),{primary:X,secondary:K}=Q??ga0(Z),V=hY0(X,K,Y);return{type:"rgb",value:{r:V.r,g:V.g,b:V.b}}}class Nq{_noise2D;_seed;constructor(J){this._seed=J??Date.now(),this._noise2D=jP4.makeNoise2D(this._seed)}get seed(){return this._seed}sample(J,Z,Q,Y=1){return(this._noise2D(J/AP4,Z/AP4+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 ma0(J,Z,Q)}}var pa0=" .:-=+*#%@",jQ3=" ",Ij=64,RP4=0.5,RN=1,da0=30,Pj=3;class ca0 extends n0{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:D,onFrame:H,fps:U=30,seed:B,glow:w,shockwaves:N,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=D,this.onFrame=H,this.fps=U,this.seed=B,this.glow=w,this.shockwaves=N,this.onShockwave=L,this.onClick=O}createState(){return new IP4}}class IP4 extends i0{_t=0;_timer=null;_internalShockwaves=[];_glow;initState(){if(super.initState(),this._glow=this.widget.glow??new Nq(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<RN),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.glow!==J.glow)this._glow=this.widget.glow??new Nq(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=m1.of(J),Q=this.widget.backgroundColor??Z.colorScheme.background,Y=new PP4({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 K4({onClick:this.handleClick,child:Y})}}class PP4 extends C${props;constructor(J,Z){super(Z?{key:Z}:{});this.props=J}createElement(){return new vK(this)}createRenderObject(){return new ek(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 ek extends h4{_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,D,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=D;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:Ij},(X,K)=>{let V=K/(Ij-1);return ma0(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,D,H=[]){let U=!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,U=!0;if(this._time=V,this._agentMode=G,this._colorMode=z,this._primaryColor=F,this._secondaryColor=q,this._backgroundColor=W,this._glow=D,this._shockwaves=H,this.getPaletteSignature(G,F,q)!==this._paletteSignature)this.rebuildPalette(G,F,q);if(U)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;$6(!!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(Ij-1,Math.floor(Y*Ij))}return Math.min(Ij-1,Math.floor(J*Ij))}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,D=K/2,H=V/2,U=Math.max(1,K/2-1),B=Math.max(1,V/(2*RP4)-1),w=Math.min(U,B),N=w*w,L=1/N,O=1/RP4,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 I=(A-H)*O,S=I*I;if(S>=N)continue;let T=Math.sqrt(N-S),b=Math.max(0,Math.floor(D-T)),m=Math.min(K-1,Math.ceil(D+T));for(let x=b;x<=m;x++){let k=x-D,f=k*k+S;if(f>=N)continue;let d=1-f*L,h=this._glow.sample(x,A,this._time,E)*d;if(h<=0)continue;if(M){let D0=f*L;if(D0<0.9025)for(let L0 of this._shockwaves){let G0=this._time-L0.startTime;if(G0<0||G0>RN)continue;let $0=x-L0.x,F0=(A-L0.y)*O,n=$0*$0+F0*F0,a=G0*da0,t=Math.max(0,a-Pj),e=a+Pj;if(n<t*t||n>e*e)continue;let z0=Math.sqrt(n),K0=Math.abs(z0-a);if(K0>=Pj)continue;let Z0=1-G0/RN,Y0=(1-K0/Pj)*Z0,N0=Math.sqrt(D0),X0=1-D0*N0;h=Math.min(1,h+Y0*0.8*X0)}}let i=Math.min(pa0.length-1,Math.floor(h*pa0.length)),c=pa0[i]||jQ3,o=this.getPaletteIndex(h,I,w),H0=W[o]||W[Ij-1],r=Y+x;if(r<0||r>=z)continue;J.setCell(r,j,{char:c,width:1,style:{fg:H0,bg:q}})}}}}var SQ3=_Q3(RQ3),kQ3=Number.MAX_SAFE_INTEGER,vQ3=30000,yQ3=60000,xQ3=14400000,fQ3=10,uQ3=1000,bQ3=5,hQ3=3000,gQ3=80,mQ3=3,CP4=3,fP4="Watching this thread for changes. Press Ctrl-C to stop.",pQ3="Live sync paused after 4 hours to save the connection. Press Enter to resume.",Cj=14,IN=7,dQ3=42,oa0="[y/N]: ",uP4=pY.posix.join(".amp","live-sync.pid"),$v=Symbol("live-sync-archived-transition"),ki=Symbol("live-sync-session-paused"),Jv=Symbol("live-sync-stop-requested"),cQ3="\x1B[0m",lQ3=/^Filesystem error \(([^)]+)\):/;function iQ3(J,Z){let Q=new Map;for(let V of J?.available?J.files:[])Q.set(V.path,_P4(V));let Y=new Set(Z.files.map((V)=>V.path)),X=Z.files.filter((V)=>Q.get(V.path)!==_P4(V)),K=hP4([...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 la0(J){let Z=J.filter((X)=>X.changeType==="untracked").length,Q=J.length-Z,Y=[];if(Q>0)Y.push(`${Q} changed ${i4(Q,"file")}`);if(Z>0)Y.push(`${Z} untracked ${i4(Z,"file")}`);return Y.length>0?Y.join(" and "):"0 files"}function nQ3(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 aQ3(J,Z=fQ3){let Q=J.slice(0,Z).map((X)=>` ${nQ3(X)}`),Y=J.length-Q.length;if(Y>0)Q.push(` ...and ${Y} more ${i4(Y,"file")}`);return Q.join(`
6241
6241
  `)}async function oY0(J){let Z=await CN(J,["status","--porcelain=v1","-z","--untracked-files=all"]);return cn0(Z.stdout).filter((Q)=>Q.path!==uP4).map((Q)=>({path:Q.path,changeType:Q.changeType,previousPath:Q.previousPath}))}async function oQ3(J){await CN(J,["reset","--hard","HEAD"]),await CN(J,["clean","-fd","-e",uP4])}async function rQ3(J){let Z=await oY0(J.repoRoot);if(Z.length===0)return;if(!await J.promptForYesNo([`Local checkout has ${la0(Z)}:`,aQ3(Z),"Clean them up before live sync starts?","This will discard tracked changes and delete untracked files.",oa0].join(`
@@ -7051,7 +7051,7 @@ ${Y}`}async function gw3(J,Z){if(!Z?.forceExternal&&Z?.onShowImagePreview&&Vx4(J
7051
7051
  `).trim()});return Q}function TH(J){return J.replace(lw3,"").replace(iw3,"").replace(cw3,"").trim()}function aY(J){if(TH(J.thinking).length>0)return!0;return J.signature.trim().length>0}function hK0(J){let Z=J.split(`
7052
7052
  `);for(let Q=0;Q<Z.length;Q++){let Y=Z[Q]?.trim();if(!Y)continue;let X=Y.match(Hx4);if(X?.[1]){let V=X[1].trim();if(V)return{header:V,lineIndex:Q}}let K=Y.match(Ux4);if(K?.[1]){let V=K[1].trim();if(V)return{header:V,lineIndex:Q}}break}return{}}function Bx4(J,Z){if(Z===void 0)return J;let Q=J.split(`
7053
7053
  `);return Q.splice(Z,1),Q.join(`
7054
- `).trim()}function wx4(J){let Z=TH(J),Q=hK0(Z);return Bx4(Z,Q.lineIndex)}class _H extends n0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:K=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=K}createState(){return new Nx4}}class Nx4 extends i0{_animationTimer;_spinner=new Z3;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=m1.of(J).colorScheme,Y=this.widget.isCancelled,X,K;if(Y)X=Q.warning,K="";else if(this.isComplete)X=Q.success,K="✓ ";else X=Q.accent,K=`${this._spinner.toBraille()} `;let V=TH(this.widget.thinkingBlock.thinking),G=hK0(V),z=Bx4(V,G.lineIndex),F=z.trim().length>0,q=F?new J0({text:new _(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,W=Y?Q.warning:Q.foreground,D=new g({color:Y?X:Q.foreground,dim:!Y}),H=[new _(K,D),new _(G.header??"Thinking",new g({color:W,dim:!Y}))];if(Y)H.push(new _(" (interrupted)",new g({color:Q.warning,italic:!0})));let U=[new J0({text:new _("",void 0,H)})];if(q)U.push(new I0({width:1}),q);let B=new N1({mainAxisSize:"min",children:U}),w={...fv(J),text:new g({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new g({color:Q.foreground,dim:!0,italic:!0}),link:new g({color:Q.foreground,dim:!0,italic:!0,underline:!0})},N=()=>{if(this.isComplete&&!this.expanded)return;let I=O.map((S)=>{let T=[];if(T.push(new J0({text:new _(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)T.push(new l0({padding:C0.vertical(1),child:new V3({markdown:S.content,styleScheme:w})}));return new h0({crossAxisAlignment:"start",children:T})});return new l0({padding:C0.only({left:2}),child:new mK({children:I})})},L=()=>{if(!this.expanded)return;return new l0({padding:C0.only({left:2}),child:new V3({markdown:z,styleScheme:w})})},O=nw3(z),M=O.length>0&&!!O[0]?.header?N():L(),j=[F?new K4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new h0({crossAxisAlignment:"start",children:[B]})}):new h0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new h0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function oN(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},items:[],todosList:[],mainThread:null}}function KR(J){let{thread:Z,viewState:Q,resolvedTokenUsage:Y}=J;if(!Z)return oN();let{items:X}=gK0(Z),K=uP({messages:Z.messages}),V=Array.isArray(K)?K:[];return{viewState:Q,subagentContentByParentID:$N3(X,Z),items:X,todosList:V,mainThread:Z,resolvedTokenUsage:Y??I7(Z)}}function aw3(J){return J===N9||J===N3||J===A7||J===d8||J===kP}function ow3(J){return J.content.filter((Z)=>Z.type==="text")}function rw3(J){return J.type==="text"&&J.text.trim().length>0||J.type==="thinking"&&aY(J)}function sw3(J){if(J.meta?.openAIResponsePhase==="commentary")return;switch(J.state.type){case"error":return;case"cancelled":{let Z=ow3(J);if(k8(Z).trim().length===0)return;return{...J,content:Z}}case"streaming":case"complete":{let Z=J.content.filter(rw3);if(Z.length===0)return;return{...J,content:Z}}}}function tw3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=sw3(Q.message);if(!Y)continue;Z=Y}return Z}function ew3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function $N3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&aw3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,z)=>{let F=Y.get(G);if(!F||F.status!=="cancelled"||c8(z.status))return z;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,z]of K){let F=[],q;if(z.status==="in-progress"||z.status==="done"||z.status==="error"||z.status==="cancelled")q=z.progress;if(Array.isArray(q)){let W=0;for(let D of q)if(D.tool_uses)for(let H of D.tool_uses){let U=JN3(H,G,W);if(!H.id||H.id.length===0)W++;let B=ZN3(H),w=H.normalized_name??H.tool_name,N=ew3(H.input),L=Q?.get(U);F.push({toolUse:gU(w,N,U),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:F}}if(Z){let G=new Map;for(let z of Z.messages){let F=z.parentToolUseId;if(!F)continue;let q=G.get(F)??[];q.push(z),G.set(F,q)}for(let[z,F]of G){let{items:q}=gK0({id:Z.id,messages:F},{includeSubagentMessages:!0}),W=q.filter((U)=>U.type==="toolResult").map((U)=>({toolUse:U.toolUse,toolRun:X(z,U.toolResult.run),toolProgress:Q?.get(U.toolUse.id)})),D=tw3(q),H=V[z]??{tools:[]};V[z]={tools:W.length>0?W:H.tools,...D?{terminalAssistantMessage:D}:{}}}}return V}function JN3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function ZN3(J){if(J.status==="done"&&J.result!==void 0)return{status:"done",result:J.result};if(J.status==="error")return{status:"error",error:{message:typeof J.error==="string"&&J.error.length>0?J.error:"Subagent tool failed"}};return{status:J.status}}function gK0(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())Y.add(V);else for(let[V,G]of J.messages.entries())if(!G.parentToolUseId)Y.add(V);let X=new Map,K=new Set;for(let[V,G]of J.messages.entries()){if(!Y.has(V))continue;let z=`${G.role}-${V}`;switch(G.role){case"assistant":{let F=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(X.set(W.id,W),F)K.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"&&aY(W)))Q.push({type:"message",id:z,message:G});for(let W of G.content){if(W.type!=="tool_use")continue;let D=!1;for(let H=V+1;H<J.messages.length;H++){if(!Y.has(H))continue;let U=J.messages[H];if(!U)continue;for(let B of U.content)if(B.type==="tool_result"&&B.toolUseID===W.id){D=!0;break}if(D)break}if(D)continue;Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:"in-progress"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:z,message:G});break}case"user":{let F=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=X.get(q.toolUseID)??uJ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(F)Q.push({type:"message",id:z,message:G});break}}}return{items:Q}}function uv(J){let Z=J.toolProgressByToolUseID$.pipe(w1(NX0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,z=()=>{let H=Q();if(!H?.autoSubmitDraft)return!1;return q8({messages:H.messages})===0},F=()=>{let H=Q();if(!H)return;if(q8({messages:H.messages})>0)return;return u00(H,"handoff")?.threadID},q=()=>q8({messages:K()})===0,W=()=>{let H=K().at(-1);return H?.role==="assistant"&&H.state.type==="streaming"},D=F5(J.thread$,J.threadViewState$).pipe(w1(([H,U])=>KR({thread:H,viewState:U,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return D},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getCurrentThread(){return J.getCurrentThread},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},getThreadID(){return Q()?.id},getThreadTitle(){return Y()},getAgentMode(){return X()},getMessages(){return K()},getQueuedMessages(){return V()},getInitialTreeURI(){return G()},shouldAutoSubmitDraft(){return z()},getEmptyHandoffParentThreadID(){return F()},isThreadEmpty(){return q()},isStreaming(){return W()},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getDraft:J.getDraft,setDraft:J.setDraft,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var Lx4="Loading thread...";function QN3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class Tt0{placeholderThreadID;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new F4({});legacyHandoffNavigationSubject=new z4;initializationStatusSubject=new F4({pending:!0,message:Lx4});pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=m3()){this.placeholderThreadID=J;let Z=new F4(QN3(this.placeholderThreadID)),Q=new F4(new Map),Y=new F4(e_(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new F4(uv({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,getCurrentThread:()=>Z.getValue(),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setTitle:async(X)=>(await this.waitForActiveHandle()).setTitle(X),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,K,V)=>(await this.waitForActiveHandle()).resolveApproval(X,K,V),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getDraft:async()=>(await this.waitForActiveHandle()).getDraft(),setDraft:async(X)=>(await this.waitForActiveHandle()).setDraft(X),getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,K)=>{this.readyResolve=X,this.readyReject=K}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}isThreadActorsMode(){return this.attachedPool?.isThreadActorsMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getTransportConnectionRole(){if(!this.attachedPool?.getTransportConnectionRole)return;return this.attachedPool.getTransportConnectionRole()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.legacyHandoffNavigation$?[J.legacyHandoffNavigation$.subscribe((Y)=>{this.legacyHandoffNavigationSubject.next(Y)})]:[],...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:Lx4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}canNavigateBack(){return this.attachedPool?.canNavigateBack()??!1}canNavigateForward(){return this.attachedPool?.canNavigateForward()??!1}async navigateBack(){return(await this.waitForAttach()).navigateBack()}async navigateForward(){return(await this.waitForAttach()).navigateForward()}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return R1(J.threadHandles$.pipe(y5((Z)=>Z!==null)))}}d0();sd();d4();E1();d0();F3();y7();KB();R30();d4();WD();Jg0();T4();U4();E1();JJ();d4();function YN3(J){let Z=J.messages.filter((V)=>!V.parentToolUseId),Q=-1;for(let V=Z.length-1;V>=0;V--)if(Z[V]?.role==="assistant"){Q=V;break}if(Q<0)return{running:0,blocked:0};let Y=Z[Q];if(!Y)return{running:0,blocked:0};let X=new Map;for(let V of Z.slice(Q+1)){if(V.role!=="user")continue;for(let G of V.content)if(G.type==="tool_result")X.set(G.toolUseID,G.run)}let K=0;for(let V of Y.content){if(V.type!=="tool_use")continue;let G=X.get(V.id);if(!G||!c8(G.status))K++}return{running:K,blocked:0}}function XN3(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function KN3(J){let Z=XN3(J);if(Z)return Z;return!1}function bv(J,Z,Q={files:[]},Y=void 0){let X=YN3(J),K=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let V=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:V>0?"tool-running":!1,toolState:{running:V,blocked:K}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:K}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:KN3(J),toolState:{running:X.running,blocked:K}}}d4();class _t0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J);case"drop-submit":return this.dropOptimisticSubmit(J);case"update-submit-guidance":return this.updateOptimisticSubmitGuidance(J)}}updateOptimisticSubmitGuidance(J){let Z=!1;if(this.pendingMessageSubmits=this.pendingMessageSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}}),!Z)this.pendingQueuedSubmits=this.pendingQueuedSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}});return this.buildProjection()}dropOptimisticSubmit(J){let Z=this.pendingMessageSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID),Q=this.pendingQueuedSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID);if(Z.length===this.pendingMessageSubmits.length&&Q.length===this.pendingQueuedSubmits.length)return this.buildProjection();return this.pendingMessageSubmits=Z,this.pendingQueuedSubmits=Q,this.buildProjection()}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>(Y.queuedMessage.dtwMessageID??Y.id)===J.queuedMessageID);if(!Q||St0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(NN3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(PN3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=LA0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:UN3(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return GN3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=HN3(this.authoritativeThread);this.pendingMessageSubmits=LN3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=AN3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=jN3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=RN3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return VN3(this.authoritativeThread,(Z)=>zN3(Z,J),(Z)=>FN3(Z,this.pendingMessageSubmits),(Z)=>qN3(Z,this.pendingQueuedSubmits),(Z)=>WN3(Z,this.pendingQueuedInterruptMessageIDs))}}function VN3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function GN3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function zN3(J,Z){if(!Z)return J;let Q=yy1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,K=J.messages.slice(0,Y+1);return K[Y]={...X,content:Z.content},{...J,messages:K,nextMessageId:NA0({messages:K,nextMessageId:J.nextMessageId})}}function FN3(J,Z){if(Z.length===0)return J;let Q=NA0(J),Y=Z.map((X,K)=>Ex4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function qN3(J,Z){if(Z.length===0)return J;let Q=Z.map(DN3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function WN3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=pK0(X);if(!K||!Z.has(K)||St0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Ex4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function DN3(J){return{id:J.clientMessageID,queuedMessage:Ex4(J,-1)}}function HN3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=mK0(K);if(V){if(X.add(V),K.role==="user")Z.add(V),Y.set(V,K)}}for(let K of J.queuedMessages??[]){let V=pK0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function UN3(J,Z){return J.messages.slice(Z+1).map((Q)=>mK0(Q)).filter((Q)=>Q!==void 0)}function BN3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&mK0(Q)===Z)}function wN3(J,Z){return(J.queuedMessages??[]).some((Q)=>pK0(Q)===Z)}function St0(J){return"interrupt"in J&&J.interrupt===!0}function NN3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||BN3(Q,Y)||wN3(Q,Y)}function LN3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=ON3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=EN3(J,Z);if(!V)return X;let G=MN3(V,K,X.length);return X.slice(G)}function ON3(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function EN3(J,Z){let Q=Ox4(J),Y=Ox4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function MN3(J,Z,Q){let Y=0;for(let X of J){let K=mK0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Ox4(J){return J.messages.filter((Z)=>Z.role==="user")}function AN3(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let K=Y.findIndex((V)=>OA0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function jN3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=pK0(V);if(!G)return;return[G,V]}).filter((V)=>V!==void 0)),X=new Set(Z.map((V)=>V.clientMessageID)),K=new Set;for(let V of Q){let G=Y.get(V);if(!G){if(X.has(V))K.add(V);continue}if(St0(G))continue;K.add(V)}return K}function RN3(J,Z){if(!Z)return;return IN3(J,Z)?void 0:Z}function IN3(J,Z){let Q=a6.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!OA0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=a6.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function mK0(J){let Z=a6.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function pK0(J){let Z=a6.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=a6.safeParse(J.id);if(Q.success)return Q.data;return}function PN3(J){return CN3.has(J)}var CN3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var TN3=1e4;class kt0{deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID;toolRunner;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);inferenceErrorsSubject=new z4;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};currentAgentLoopState;activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z){this.deps=Z;this.provider=J,this.clientID=Z.clientID;let Q=xU("info"),Y=xU("error"),X=(z)=>({...z??{},threadId:this.provider.threadId});this.toolRunner=new Vi({clientID:this.clientID,transport:this.provider,invokeTool:(z)=>this.invokeToolForLease(z),batchGuidanceFiles:YY0,renderToolRunError:Lm,log:{info:(z,F)=>Q(z,X(F)),error:(z,F)=>Y(z,X({error:F})),wsMessage:(z,F,q)=>{C.debug("DTW executor tool runner message",X({direction:z,clientID:F,...typeof q==="object"&&q!==null?q:{message:q}}))}}}),this.provider.configureExecutorHandshake({handshake:(z)=>this.sendExecutorHandshake(z),onError:({error:z,attempt:F,delayMs:q})=>{C.warn("DTW executor handshake failed",{error:z,attempt:F,delayMs:q})},onExhausted:(z)=>{this.handleHandshakeExhausted(z)}}),this.currentAgentLoopState=J.getAgentLoopState();let K=J.getThread();this.optimisticThreadProjection=new _t0(K,this.currentAgentLoopState);let V=this.optimisticThreadProjection.resolve(K),G=bv(V,this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError());this.threadSubject=new F4(V),this.thread$=this.threadSubject,this.threadStateSubject=new F4(KR({thread:V,viewState:G,resolvedTokenUsage:I7(V)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new F4(G),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(w1(NX0)),this.transportSubscriptions.push(this.threadSubject.subscribe((z)=>{this.rebuildThreadState(z)}),this.threadViewStateSubject.subscribe((z)=>{let F=this.threadStateSubject.getValue();if(F.viewState===z)return;this.threadStateSubject.next({...F,viewState:z})})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Z.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.currentAgentLoopState=Y,this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.currentAgentLoopState=this.provider.getAgentLoopState(),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getCurrentThread(){return this.threadSubject.getValue()}getThreadID(){return this.getCurrentThread().id}getThreadTitle(){return this.getCurrentThread().title}getAgentMode(){return this.getCurrentThread().agentMode}getMessages(){return this.getCurrentThread().messages}getQueuedMessages(){return this.getCurrentThread().queuedMessages??[]}getInitialTreeURI(){return this.getCurrentThread().env?.initial.trees?.[0]?.uri}shouldAutoSubmitDraft(){let J=this.getCurrentThread();if(!J.autoSubmitDraft)return!1;return q8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(q8(J)>0)return;return u00(J,"handoff")?.threadID}isThreadEmpty(){return q8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return I7(this.thread$.getValue())}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.toolRunner.dispose(),this.provider.dispose(),this.threadSubject.complete(),this.threadStateSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.ensureProviderReadyForExecutorActions();let K=this.thread$.getValue(),V=K.messages[J.editIndex];if(!V||V.role!=="user"||!V.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let G=K.messages.findIndex((q)=>q.role==="user");if(J.editIndex===G&&J.agentMode&&K.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((q)=>{q.agentMode=J.agentMode});this.provider.editUserMessage(V.dtwMessageID,J.content,Fn0(),J.agentMode);let F=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(F);return}let Z=this.thread$.getValue();if(!Z.messages.some((K)=>K.role==="user")&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=zq(),X=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Y,content:J.content});this.writeThread(X);try{let K=J.prepareContentForSend?await J.prepareContentForSend(J.content):J.content;await this.ensureProviderConnectedForClientWrites();let V=await this.discoverGuidanceFilesForUserMessage(K);if(V&&V.length>0){let z=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),F=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:z});this.writeThread(F)}let G=await this.collectUserState();this.provider.sendUserMessage(K,J.agentMode,G,Y,V)}catch(K){throw this.rollbackOptimisticSubmit(Y),K}}async restoreTo(J){await this.ensureProviderReadyForExecutorActions();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((V)=>V.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((V)=>V.type==="text"||V.type==="image").map((V)=>{if(V.type==="image")return{...V,source:{...V.source}};return{...V}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.editUserMessage(Y.dtwMessageID,X,Fn0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=zq(),Q=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Z,content:J});this.writeThread(Q);try{await this.ensureProviderConnectedForClientWrites();let Y=await this.discoverGuidanceFilesForUserMessage(J);if(Y&&Y.length>0){let K=Y.map((G)=>({uri:G.uri,lineCount:G.lineCount??0,...typeof G.content==="string"?{content:G.content}:{}})),V=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Z,discoveredGuidanceFiles:K});this.writeThread(V)}let X=await this.collectUserState();this.provider.sendUserMessage(J,void 0,X,Z,Y)}catch(Y){throw this.rollbackOptimisticSubmit(Z),Y}}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.ensureProviderReadyForExecutorActions(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async ensureProviderConnectedForClientWrites(){await this.provider.ensureConnectedForAction("client-write")}async ensureProviderReadyForExecutorActions(J){await this.provider.ensureConnectedForAction("executor-action"),await this.provider.ensureExecutorReady({timeoutMs:TN3,timeoutMessage:"Timed out waiting for executor readiness. Please retry."})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){await this.deps.threadService.updateThreadMeta(this.provider.threadId,vG(J));let Z=await this.deps.threadService.get(this.provider.threadId);if(Z)this.writeThread(Z)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=v9(this.threadSubject.getValue(),J),Q=this.optimisticThreadProjection.resolve(Z);this.writeThread(Q)}async cancelTurn(){this.provider.cancelAgentLoop()}async cancelStreaming(){this.provider.cancelAgentLoop()}async retryTurn(){this.provider.retryAgentLoop()}invokeBashTool(J,Z){let Q=yA4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(W){C.warn("Failed to append manual bash invocation to DTW thread",{error:W}),this.activeError={message:`Failed to sync bash result to thread: ${W instanceof Error?W.message:String(W)}`},this.updateThreadViewStateFromProvider()}},G=(q,W={emitRun:!0})=>{if(X)return;if(X=!0,V(q),W.emitRun)Y.next(q);Y.complete()},z=(q)=>q instanceof Error?q.message:String(q),F=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",F),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await WH({toolName:g6,threadSnapshot:this.provider.getThread(),dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;let W={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(g6,{args:J,userInput:{accepted:!0}},W).subscribe({next:(D)=>{if(X)return;if(Y.next(D),D.status!=="in-progress")G(D,{emitRun:!1})},error:(D)=>{G({status:"error",error:{message:z(D)}})}})}catch(q){G({status:"error",error:{message:z(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",F)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=r8.safeParse(J);if(!Y.success)return;this.provider.resolveToolApproval(Y.data,Z,{denyFeedback:Q})}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async getDraft(){let J=this.thread$.getValue().draft;if(!J)return null;let Z=xP(J);if(!Z.text&&Z.images.length===0)return null;return Z}async setDraft(J){this.updateThread((Z)=>{if(!J||!J.text&&J.images.length===0){delete Z.draft,delete Z.autoSubmitDraft;return}let Q=[];if(J.text)Q.push({type:"text",text:J.text});if(J.images.length>0)Q.push(...J.images);Z.draft=Q,Z.autoSubmitDraft=!1})}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await $F({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((K)=>{if(K.role==="user"){for(let V of K.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of K.content)if(V.type==="tool_use")Q.add(V.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[K]of X.entries())if(!Q.has(K))Y.add(K);return Y}async collectUserState(){try{return await V$0()??wm}catch(J){return C.warn("Failed to collect IDE user state for DTW message",{error:J}),wm}}resolveUserMessageGuidanceContext(){let J=z1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?P6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=z1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(s$(J))return z1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return X1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=k8(J);if(!Z.trim())return;let{paths:Q}=K$0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let z=this.resolveMentionedPathToURI(G,Y);if(!z||!X1.hasPrefix(z,Y.workspaceRoot))continue;let F=z.toString();if(K.has(F))continue;K.add(F);let q=await XQ({stat:(W,D)=>this.deps.filesystem.stat(W,D),readFile:(W,D)=>this.deps.filesystem.readFile(W,D)},z,Y.workspaceRoot,null,X);for(let W of q){if(V.some((D)=>D.uri===W.uri))continue;X.add(W.uri),V.push({uri:W.uri,content:W.content,lineCount:W.lineCount})}}return V.length>0?V:void 0}handleHandshakeExhausted(J){C.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(Oj));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Oj(X);if(this.toolRunner.sentApprovalRequests.has(K))continue;let V=eQ0(X);if(this.provider.sendExecutorToolApprovalRequest(V))this.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted,J.input?.denyFeedback)}syncExecutorTools(J){this.advertisedExecutorTools=this.provider.syncExecutorToolRegistrations({nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.executorReadyChanges().subscribe({next:(J)=>{if(J)this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(ik(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){C.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await this.provider.connectExecutor({executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,subscribeToThreadEvents:!1,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.toolRunner.flushBufferedTerminalResults(),this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=this.provider.sendSettingsUpdate(Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await VZ();this.provider.setEnvironment({initial:J})}catch(J){C.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=r8.safeParse(Z);this.provider.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await WH({toolName:J.toolName,threadSnapshot:this.provider.getThread(),dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});C.info("DTW TUI tool run environment ready",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q});let X=this.deps.toolService.invokeTool(J.toolName,{args:Z},Y);return C.info("DTW TUI tool service returned observable",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q}),X}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await GY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await zY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await j30(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(bv(this.threadSubject.getValue(),this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}rebuildThreadState(J){this.threadStateSubject.next(KR({thread:J,viewState:this.threadViewStateSubject.getValue(),resolvedTokenUsage:I7(J)}))}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}d4();E1();function Mx4(J){let Z=new F4(J.thread),Q=new F4(bv(J.thread,"idle")),Y=new F4(new Map),X=new F4([]),K=new F4([]),V=(F)=>{let W={...Z.getValue()};if(!F||!F.text&&F.images.length===0)delete W.draft,delete W.autoSubmitDraft;else{let D=[];if(F.text)D.push({type:"text",text:F.text});if(F.images.length>0)D.push(...F.images);W.draft=D,W.autoSubmitDraft=!1}Z.next(W),Q.next(bv(W,"idle"))};return{handle:uv({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(F)=>(await J.materialize()).sendMessage(F),restoreTo:async(F)=>(await J.materialize()).restoreTo(F),queueMessage:async(F)=>(await J.materialize()).queueMessage(F),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(F)=>(await J.materialize()).setTitle(F),setVisibility:async(F)=>(await J.materialize()).setVisibility(F),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(F)=>{K.next([...K.getValue(),F])},removePendingSkill:(F)=>{K.next(K.getValue().filter((q)=>q.name!==F))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>_N3(Z.getValue()),setDraft:async(F)=>V(F),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function _N3(J){if(!J.draft)return null;let Z=xP(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var dK0="Loading thread...",SN3="Importing thread";class hn{deps;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});activeThreadHandleSubject=new F4(null);allConnectedThreadActivityStatusesSubject=new F4({});initializationStatusSubject=new F4({pending:!1,message:dK0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=qY0({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){if(!this.activeThreadContextID)throw Error("No active thread context");let J=this.threadHandleMap.get(this.activeThreadContextID)??this.pendingHandoffThreads.get(this.activeThreadContextID)?.optimisticHandle.handle;if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){if(!this.activeThreadContextID)return;return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}isThreadActorsMode(){return this.deps.useThreadActors??!1}getTransportConnectionState(){return this.activeProvider?.getConnectionState()??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionRole()??null}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}async switchThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await this.handoffService.createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let V=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},z=m3(),F=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:F,comment:Z.goal}],W={id:z,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},D=Mx4({thread:W,materialize:()=>this.materializePendingHandoffThread(z)});return this.pendingHandoffThreads.set(z,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:D,materializingPromise:null}),z}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();for(let J of this.pendingHandoffThreads.values())await J.optimisticHandle.dispose();this.threadHandleMap.clear(),this.pendingHandoffThreads.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J,Z){C.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Q=J?this.threadHandleMap.get(J):void 0;if(Q){let X=Q.thread$.getValue().id;this.activeThreadContextID=X,this.activeThreadHandleSubject.next(Q),this.addToRecentThreads(X),this.syncAllConnectedThreadActivityStatuses(),C.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:X,handleCount:this.threadHandleMap.size});return}let Y=J?this.pendingHandoffThreads.get(J):void 0;if(J&&Y){this.activeThreadContextID=J,this.activeThreadHandleSubject.next(Y.optimisticHandle.handle),this.syncAllConnectedThreadActivityStatuses(),C.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:dK0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=RS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),V=new kt0(X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,clientID:this.deps.clientID,initialToolDiscovery:this.deps.initialToolDiscovery,fs:K,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,V),V.startProviderSubscription((G)=>{this.applyProviderState(X.threadId,G)}),this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(X.threadId),C.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:dK0})}}async activateThreadWithNavigation(J,Z){let Q=this.activeThreadContextID;await this.activateThread(J);let Y=this.activeThreadContextID;if(Z.recordNavigation&&Q!==null&&Y!==null&&Q!==Y)this.recordNavigation(Q)}applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y);let X=this.threadTitlesSubject.getValue();if(X[J]!==Y.title)this.threadTitlesSubject.next({...X,[J]:Y.title});this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();for(let[Z,Q]of this.pendingHandoffThreads.entries())J[Z]=Q.optimisticHandle.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return IY0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:SN3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:dK0})},repositoryURL:Z,threadService:this.deps.threadService,threadId:J,workerUrl:process.env.AMP_WORKER_URL,useThreadActors:this.deps.useThreadActors})}async materializePendingHandoffThread(J){let Z=this.pendingHandoffThreads.get(J);if(!Z)throw Error(`No pending handoff thread for ${J}`);if(!Z.materializingPromise){let K=(async()=>{let{threadId:V}=await HH(void 0,this.deps.configService,void 0,{repositoryURL:Z.repositoryURL,agentMode:Z.agentMode,relationship:Z.relationship,executorType:"local-client"});if(this.activeThreadContextID===J)await this.activateThread(V,{threadRelationships:Z.threadRelationships});return V})();Z.materializingPromise=K,K.catch(()=>{let V=this.pendingHandoffThreads.get(J);if(V?.materializingPromise===K)V.materializingPromise=null})}let Q=await Z.materializingPromise,Y=this.threadHandleMap.get(Q);if(!Y)await this.activateThread(Q,{threadRelationships:Z.threadRelationships}),Y=this.threadHandleMap.get(Q);if(!Y)throw Error(`No DTW thread handle for ${Q}`);let X=this.pendingHandoffThreads.get(J);if(X)this.pendingHandoffThreads.delete(J),await X.optimisticHandle.dispose(),this.syncAllConnectedThreadActivityStatuses();return Y}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}Uo0();import{randomBytes as xN3}from"node:crypto";import{readFile as fN3}from"node:fs/promises";import uN3 from"node:readline";import{setTimeout as bN3}from"node:timers/promises";v3();jT();d4();cD();E1();F3();d4();cD();E1();class Ax4{stateSubject;constructor(J){this.stateSubject=new F4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function kN3(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,{status:Y.run.status,content:X});continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,{status:Y.run.status,content:X.output})}}return Z}function vN3(J){if(!J.draft)return null;let Z=xP(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function yN3(J){if(!J||!J.text&&J.images.length===0)return"";let Z=[];if(J.text)Z.push({type:"text",text:J.text});if(J.images.length>0)Z.push(...J.images);return Z}async function vt0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??m3(),K=b9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let z=await J.threadService.exclusiveSyncReadWriter(X);z.write(Q),await z.asyncDispose(),V=Q}let G=K??await b9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||q8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadService.updateThreadMeta(X,Y);if(Y&&!Q){let z=J.threadService.observe(X).subscribe((F)=>{if(F.messages.length===0)return;z.unsubscribe(),J.threadService.updateThreadMeta(X,Y).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let z=J.threadService.observe(X).subscribe(async(F)=>{if(L9(F,"assistant"))await Z.onFirstAssistantMessage?.(X),z.unsubscribe()})}return await G.resume(),G}async function jx4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;return vt0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?vG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function Rx4(J,Z,Q){let Y=Z?await jx4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new cK0(J,Y)}class cK0{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new F4([]);pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);threadViewStatesSubject=new F4({});threadTitlesSubject=new F4({});legacyHandoffNavigationSubject=new z4;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Ax4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new F4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(w1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.switchToWorker(J,{recordNavigation:!0})}async switchThread(J){await this.switchToThreadByID(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.currentWorker.thread.id,Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.currentWorker.thread.id,Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return uv({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(w1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(w1((X)=>X.state==="active"?X.ephemeralError:void 0),y5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(w1((X)=>kN3(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>I7(Z.thread),sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.threadService.flushVersion(J,Z.thread.v)},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadService.updateThreadMeta(J,vG(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v;await this.deps.threadService.flushVersion(J,X)},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,K,V)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,K,V)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getDraft:async()=>{return Q("getDraft"),vN3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:yN3(X)})},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let K=this.stateTracker.state.currentThread;if(!K)return[];return(await $F({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},K,X)).map((G)=>({uri:G.uri,type:G.type}))},invokeBashTool:(X,K)=>{Q("invokeBashTool");let V=Z.invokeBashTool(X,K.abortController.signal,K.hidden);return new k0((G)=>{let z=!1,F=V.subscribe({next:(q)=>G.next(q),error:(q)=>{z=!0,G.error(q)},complete:()=>{z=!0,G.complete()}});return()=>{if(!z)K.abortController.abort();F.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((K)=>K?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((V)=>V.type==="thinking"&&aY(V)))return}for(let K=Z.messages.length-1;K>=0;K--){let V=Z.messages[K];if(V?.role==="user"&&!V.interrupted){J.handle({type:"user:message:interrupt",messageIndex:K});let G=[...Z.messages];G[K]={...V,interrupted:!0};let z={...Z,messages:G};this.refreshDerivedState(z),this.updateInterruptedMessage(z,K);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,K)=>{if(K!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.threadService.flushVersion(this.currentThreadID,this.currentWorker.thread.v)};setVisibility=async(J)=>{await this.deps.workerDeps.threadService.updateThreadMeta(this.currentThreadID,vG(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((V)=>V?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new k0((Y)=>{let X=!1,K=Q.subscribe({next:(V)=>Y.next(V),error:(V)=>{X=!0,Y.error(V)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();K.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await b9.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),await b9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observe(J.thread.id).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=b9.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=b9.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.maybeEmitLegacyHandoffNavigation(J),this.emitActiveThreadHandleIfNeeded()}maybeEmitLegacyHandoffNavigation(J){let Z=J.pendingNavigation;if(!Z||J.id!==this.currentThreadID)return;if(this.pendingNavigationInFlightThreadID===Z)return;this.pendingNavigationInFlightThreadID=Z,this.legacyHandoffNavigationSubject.next(Z),this.currentWorker.handle({type:"clearPendingNavigation"}).catch(()=>{return}).finally(()=>{if(this.pendingNavigationInFlightThreadID===Z)this.pendingNavigationInFlightThreadID=null})}buildPoolState(J,Z){let Q=e_(J,this.latestStatus);return{threadState:KR({thread:J,viewState:Q,resolvedTokenUsage:I7(J)}),currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}switchToWorker(J,Z){let Q=this.currentWorker.thread.id;if(this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J),Z.recordNavigation&&J.thread.id!==Q)this.recordNavigation(Q)}async switchToThreadByID(J,Z){let Q=this.workersByThreadID.get(J)??await jx4(this.deps,J);this.switchToWorker(Q,Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function g4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
7054
+ `).trim()}function wx4(J){let Z=TH(J),Q=hK0(Z);return Bx4(Z,Q.lineIndex)}class _H extends n0{thinkingBlock;expanded;onToggle;isStreaming;isCancelled;constructor({key:J,thinkingBlock:Z,expanded:Q,onToggle:Y,isStreaming:X=!1,isCancelled:K=!1}){super(J?{key:J}:{});this.thinkingBlock=Z,this.expanded=Q,this.onToggle=Y,this.isStreaming=X,this.isCancelled=K}createState(){return new Nx4}}class Nx4 extends i0{_animationTimer;_spinner=new Z3;_localExpanded=!1;get isComplete(){return!this.widget.isStreaming}get expanded(){return this._localExpanded}initState(){if(super.initState(),this._localExpanded=this.widget.expanded??!1,!this.isComplete)this._startAnimation()}didUpdateWidget(J){if(super.didUpdateWidget(J),J.isStreaming&&!this.widget.isStreaming)this._stopAnimation();else if(!J.isStreaming&&this.widget.isStreaming)this._startAnimation();if(J.thinkingBlock.thinking!==this.widget.thinkingBlock.thinking)this.setState(()=>{});if(this.widget.expanded!==void 0&&this.widget.expanded!==J.expanded)this._localExpanded=this.widget.expanded}dispose(){this._stopAnimation(),super.dispose()}_startAnimation(){this._animationTimer=setInterval(()=>{this.setState(()=>{this._spinner.step()})},200)}_stopAnimation(){if(this._animationTimer)clearInterval(this._animationTimer),this._animationTimer=void 0}build(J){let Q=m1.of(J).colorScheme,Y=this.widget.isCancelled,X,K;if(Y)X=Q.warning,K="";else if(this.isComplete)X=Q.success,K="✓ ";else X=Q.accent,K=`${this._spinner.toBraille()} `;let V=TH(this.widget.thinkingBlock.thinking),G=hK0(V),z=Bx4(V,G.lineIndex),F=z.trim().length>0,q=F?new J0({text:new _(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,W=Y?Q.warning:Q.foreground,D=new g({color:Y?X:Q.foreground,dim:!Y}),H=[new _(K,D),new _(G.header??"Thinking",new g({color:W,dim:!Y}))];if(Y)H.push(new _(" (interrupted)",new g({color:Q.warning,italic:!0})));let U=[new J0({text:new _("",void 0,H)})];if(q)U.push(new I0({width:1}),q);let B=new N1({mainAxisSize:"min",children:U}),w={...fv(J),text:new g({color:Q.foreground,dim:!0,italic:!0}),inlineCode:new g({color:Q.foreground,dim:!0,italic:!0,bold:!0}),codeBlock:new g({color:Q.foreground,dim:!0,italic:!0}),link:new g({color:Q.foreground,dim:!0,italic:!0,underline:!0})},N=()=>{if(this.isComplete&&!this.expanded)return;let I=O.map((S)=>{let T=[];if(T.push(new J0({text:new _(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)T.push(new l0({padding:C0.vertical(1),child:new V3({markdown:S.content,styleScheme:w})}));return new h0({crossAxisAlignment:"start",children:T})});return new l0({padding:C0.only({left:2}),child:new mK({children:I})})},L=()=>{if(!this.expanded)return;return new l0({padding:C0.only({left:2}),child:new V3({markdown:z,styleScheme:w})})},O=nw3(z),M=O.length>0&&!!O[0]?.header?N():L(),j=[F?new K4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new h0({crossAxisAlignment:"start",children:[B]})}):new h0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new h0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function oN(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},items:[],todosList:[],mainThread:null}}function KR(J){let{thread:Z,viewState:Q,resolvedTokenUsage:Y}=J;if(!Z)return oN();let{items:X}=gK0(Z),K=uP({messages:Z.messages}),V=Array.isArray(K)?K:[];return{viewState:Q,subagentContentByParentID:$N3(X,Z),items:X,todosList:V,mainThread:Z,resolvedTokenUsage:Y??I7(Z)}}function aw3(J){return J===N9||J===N3||J===A7||J===d8||J===kP}function ow3(J){return J.content.filter((Z)=>Z.type==="text")}function rw3(J){return J.type==="text"&&J.text.trim().length>0||J.type==="thinking"&&aY(J)}function sw3(J){if(J.meta?.openAIResponsePhase==="commentary")return;switch(J.state.type){case"error":return;case"cancelled":{let Z=ow3(J);if(k8(Z).trim().length===0)return;return{...J,content:Z}}case"streaming":case"complete":{let Z=J.content.filter(rw3);if(Z.length===0)return;return{...J,content:Z}}}}function tw3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=sw3(Q.message);if(!Y)continue;Z=Y}return Z}function ew3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function $N3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&aw3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,z)=>{let F=Y.get(G);if(!F||F.status!=="cancelled"||c8(z.status))return z;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,z]of K){let F=[],q;if(z.status==="in-progress"||z.status==="done"||z.status==="error"||z.status==="cancelled")q=z.progress;if(Array.isArray(q)){let W=0;for(let D of q)if(D.tool_uses)for(let H of D.tool_uses){let U=JN3(H,G,W);if(!H.id||H.id.length===0)W++;let B=ZN3(H),w=H.normalized_name??H.tool_name,N=ew3(H.input),L=Q?.get(U);F.push({toolUse:gU(w,N,U),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:F}}if(Z){let G=new Map;for(let z of Z.messages){let F=z.parentToolUseId;if(!F)continue;let q=G.get(F)??[];q.push(z),G.set(F,q)}for(let[z,F]of G){let{items:q}=gK0({id:Z.id,messages:F},{includeSubagentMessages:!0}),W=q.filter((U)=>U.type==="toolResult").map((U)=>({toolUse:U.toolUse,toolRun:X(z,U.toolResult.run),toolProgress:Q?.get(U.toolUse.id)})),D=tw3(q),H=V[z]??{tools:[]};V[z]={tools:W.length>0?W:H.tools,...D?{terminalAssistantMessage:D}:{}}}}return V}function JN3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function ZN3(J){if(J.status==="done"&&J.result!==void 0)return{status:"done",result:J.result};if(J.status==="error")return{status:"error",error:{message:typeof J.error==="string"&&J.error.length>0?J.error:"Subagent tool failed"}};return{status:J.status}}function gK0(J,Z){let Q=[],Y=new Set;if(Z?.includeSubagentMessages)for(let[V]of J.messages.entries())Y.add(V);else for(let[V,G]of J.messages.entries())if(!G.parentToolUseId)Y.add(V);let X=new Map,K=new Set;for(let[V,G]of J.messages.entries()){if(!Y.has(V))continue;let z=`${G.role}-${V}`;switch(G.role){case"assistant":{let F=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(X.set(W.id,W),F)K.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"&&aY(W)))Q.push({type:"message",id:z,message:G});for(let W of G.content){if(W.type!=="tool_use")continue;let D=!1;for(let H=V+1;H<J.messages.length;H++){if(!Y.has(H))continue;let U=J.messages[H];if(!U)continue;for(let B of U.content)if(B.type==="tool_result"&&B.toolUseID===W.id){D=!0;break}if(D)break}if(D)continue;Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:"in-progress"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:z,message:G});break}case"user":{let F=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=X.get(q.toolUseID)??uJ(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(F)Q.push({type:"message",id:z,message:G});break}}}return{items:Q}}function uv(J){let Z=J.toolProgressByToolUseID$.pipe(w1(NX0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,z=()=>{let H=Q();if(!H?.autoSubmitDraft)return!1;return q8({messages:H.messages})===0},F=()=>{let H=Q();if(!H)return;if(q8({messages:H.messages})>0)return;return u00(H,"handoff")?.threadID},q=()=>q8({messages:K()})===0,W=()=>{let H=K().at(-1);return H?.role==="assistant"&&H.state.type==="streaming"},D=F5(J.thread$,J.threadViewState$).pipe(w1(([H,U])=>KR({thread:H,viewState:U,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return D},get threadViewState$(){return J.threadViewState$},get inferenceErrors$(){return J.inferenceErrors$},get toolProgressByToolUseID$(){return Z},get pendingApprovals$(){return J.pendingApprovals$},get pendingSkills$(){return J.pendingSkills$},get getCurrentThread(){return J.getCurrentThread},get getResolvedTokenUsage(){return J.getResolvedTokenUsage},getThreadID(){return Q()?.id},getThreadTitle(){return Y()},getAgentMode(){return X()},getMessages(){return K()},getQueuedMessages(){return V()},getInitialTreeURI(){return G()},shouldAutoSubmitDraft(){return z()},getEmptyHandoffParentThreadID(){return F()},isThreadEmpty(){return q()},isStreaming(){return W()},sendMessage:J.sendMessage,restoreTo:J.restoreTo,queueMessage:J.queueMessage,discardQueuedMessages:J.discardQueuedMessages,interruptQueuedMessage:J.interruptQueuedMessage,setTitle:J.setTitle,setVisibility:J.setVisibility,cancelTurn:J.cancelTurn,cancelStreaming:J.cancelStreaming,retryTurn:J.retryTurn,dismissEphemeralError:J.dismissEphemeralError,preExecuteMode:J.preExecuteMode,postExecuteMode:J.postExecuteMode,setTestEphemeralError:J.setTestEphemeralError,resolveApproval:J.resolveApproval,addPendingSkill:J.addPendingSkill,removePendingSkill:J.removePendingSkill,clearPendingSkills:J.clearPendingSkills,getDraft:J.getDraft,setDraft:J.setDraft,getFilesAffectedByTruncation:J.getFilesAffectedByTruncation,clearPendingNavigation:J.clearPendingNavigation,getGuidanceFiles:J.getGuidanceFiles,invokeBashTool:J.invokeBashTool}}var Lx4="Loading thread...";function QN3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class Tt0{placeholderThreadID;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new F4({});legacyHandoffNavigationSubject=new z4;initializationStatusSubject=new F4({pending:!0,message:Lx4});pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=m3()){this.placeholderThreadID=J;let Z=new F4(QN3(this.placeholderThreadID)),Q=new F4(new Map),Y=new F4(e_(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new F4(uv({thread$:Z,threadViewState$:Y,toolProgressByToolUseID$:Q,pendingApprovals$:this.pendingApprovalsSubject,pendingSkills$:this.pendingSkillsSubject,getCurrentThread:()=>Z.getValue(),sendMessage:async(X)=>(await this.waitForActiveHandle()).sendMessage(X),restoreTo:async(X)=>(await this.waitForActiveHandle()).restoreTo(X),queueMessage:async(X)=>(await this.waitForActiveHandle()).queueMessage(X),discardQueuedMessages:async()=>(await this.waitForActiveHandle()).discardQueuedMessages(),setTitle:async(X)=>(await this.waitForActiveHandle()).setTitle(X),setVisibility:async(X)=>(await this.waitForActiveHandle()).setVisibility(X),cancelTurn:async()=>(await this.waitForActiveHandle()).cancelTurn(),cancelStreaming:async()=>(await this.waitForActiveHandle()).cancelStreaming(),retryTurn:async()=>(await this.waitForActiveHandle()).retryTurn(),dismissEphemeralError:()=>{},preExecuteMode:async()=>(await this.waitForActiveHandle()).preExecuteMode?.(),postExecuteMode:async()=>(await this.waitForActiveHandle()).postExecuteMode?.(),resolveApproval:async(X,K,V)=>(await this.waitForActiveHandle()).resolveApproval(X,K,V),addPendingSkill:()=>{},removePendingSkill:()=>{},clearPendingSkills:()=>{},getDraft:async()=>(await this.waitForActiveHandle()).getDraft(),setDraft:async(X)=>(await this.waitForActiveHandle()).setDraft(X),getFilesAffectedByTruncation:async(X)=>(await this.waitForActiveHandle()).getFilesAffectedByTruncation(X),clearPendingNavigation:async()=>(await this.waitForActiveHandle()).clearPendingNavigation(),getGuidanceFiles:async(X)=>(await this.waitForActiveHandle()).getGuidanceFiles(X)})),this.readyPromise=new Promise((X,K)=>{this.readyResolve=X,this.readyReject=K}),this.readyPromise.catch(()=>{return})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.threadHandlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get queueOnSubmitByDefault(){return this.attachedPool?.queueOnSubmitByDefault??!1}hasPendingInitialization(){return this.attachedPool===null}isDTWMode(){return this.attachedPool?.isDTWMode?.()===!0}isThreadActorsMode(){return this.attachedPool?.isThreadActorsMode?.()===!0}getTransportConnectionState(){if(!this.attachedPool?.getTransportConnectionState)return;return this.attachedPool.getTransportConnectionState()}getTransportConnectionRole(){if(!this.attachedPool?.getTransportConnectionRole)return;return this.attachedPool.getTransportConnectionRole()}getCompactionStatus(){if(!this.attachedPool?.getCompactionStatus)return;return this.attachedPool.getCompactionStatus()}attach(J){if(this.attached)throw Error("DeferredThreadPool is already attached");this.attached=!0,this.attachedPool=J;let Z=null,Q=null;this.attachedPoolSubscriptions=[J.recentThreadIDs$.subscribe((Y)=>this.recentThreadIDsSubject.next(Y)),J.threadTitles$.subscribe((Y)=>this.threadTitlesSubject.next(Y)),J.allConnectedThreadActivityStatuses$.subscribe((Y)=>this.allConnectedThreadActivityStatusesSubject.next(Y)),...J.legacyHandoffNavigation$?[J.legacyHandoffNavigation$.subscribe((Y)=>{this.legacyHandoffNavigationSubject.next(Y)})]:[],...J.initializationStatus$?[J.initializationStatus$.subscribe((Y)=>this.initializationStatusSubject.next(Y))]:[(()=>{return this.initializationStatusSubject.next({pending:!1,message:Lx4}),{unsubscribe:()=>{}}})()],J.threadHandles$.subscribe((Y)=>{if(Y)Z?.unsubscribe(),Z=Y.pendingApprovals$.subscribe((X)=>this.pendingApprovalsSubject.next(X)),Q?.unsubscribe(),Q=Y.pendingSkills$.subscribe((X)=>this.pendingSkillsSubject.next(X)),this.threadHandlesSubject.next(Y)}),{unsubscribe:()=>{Z?.unsubscribe(),Q?.unsubscribe()}}],this.readyResolve?.(J),this.readyResolve=null,this.readyReject=null}setInitError(J){if(this.attached)return;this.readyReject?.(J),this.readyResolve=null,this.readyReject=null}async createThread(){return(await this.waitForAttach()).createThread()}async switchThread(J){return(await this.waitForAttach()).switchThread(J)}canNavigateBack(){return this.attachedPool?.canNavigateBack()??!1}canNavigateForward(){return this.attachedPool?.canNavigateForward()??!1}async navigateBack(){return(await this.waitForAttach()).navigateBack()}async navigateForward(){return(await this.waitForAttach()).navigateForward()}async createHandoff(J,Z){return(await this.waitForAttach()).createHandoff(J,Z)}async deleteThread(J){let Z=await this.waitForAttach();if(Z.deleteThread)await Z.deleteThread(J)}async dispose(){for(let J of this.attachedPoolSubscriptions)J.unsubscribe();if(this.attachedPoolSubscriptions=[],this.attachedPool)await this.attachedPool.dispose();this.recentThreadIDsSubject.complete(),this.threadTitlesSubject.complete(),this.threadHandlesSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.initializationStatusSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}waitForAttach(){if(this.attachedPool)return Promise.resolve(this.attachedPool);return this.readyPromise}async waitForActiveHandle(){let J=await this.waitForAttach();return R1(J.threadHandles$.pipe(y5((Z)=>Z!==null)))}}d0();sd();d4();E1();d0();F3();y7();KB();R30();d4();WD();Jg0();T4();U4();E1();JJ();d4();function YN3(J){let Z=J.messages.filter((V)=>!V.parentToolUseId),Q=-1;for(let V=Z.length-1;V>=0;V--)if(Z[V]?.role==="assistant"){Q=V;break}if(Q<0)return{running:0,blocked:0};let Y=Z[Q];if(!Y)return{running:0,blocked:0};let X=new Map;for(let V of Z.slice(Q+1)){if(V.role!=="user")continue;for(let G of V.content)if(G.type==="tool_result")X.set(G.toolUseID,G.run)}let K=0;for(let V of Y.content){if(V.type!=="tool_use")continue;let G=X.get(V.id);if(!G||!c8(G.status))K++}return{running:K,blocked:0}}function XN3(J){let Z=J.messages.at(-1);if(!Z)return"user-message-initial";if(Z.role==="assistant")return Z.state.type==="complete"&&Z.state.stopReason==="end_turn"?"user-message-reply":!1;return!1}function KN3(J){let Z=XN3(J);if(Z)return Z;return!1}function bv(J,Z,Q={files:[]},Y=void 0){let X=YN3(J),K=Z==="awaiting_approval"?1:0;if(Z==="working"||Z==="streaming")return{state:"active",inferenceState:"running",fileChanges:Q,ephemeralError:Y,interactionState:!1,toolState:{running:0,blocked:0}};if(Z==="tool_use"||Z==="running_tools"){let V=X.running;return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:V>0?"tool-running":!1,toolState:{running:V,blocked:K}}}if(Z==="awaiting_approval")return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:"user-tool-approval",toolState:{running:X.running,blocked:K}};return{state:"active",inferenceState:"idle",fileChanges:Q,ephemeralError:Y,interactionState:KN3(J),toolState:{running:X.running,blocked:K}}}d4();class _t0{authoritativeThread;currentAgentLoopState;pendingMessageSubmits=[];pendingQueuedSubmits=[];pendingQueuedInterruptMessageIDs=new Set;pendingEdit;constructor(J,Z){this.authoritativeThread=J,this.currentAgentLoopState=Z}setAgentLoopState(J){this.currentAgentLoopState=J}optimisticUpdate(J){switch(J.type){case"submit":return this.optimisticSubmit(J);case"discard-queued":return this.pendingQueuedSubmits=[],this.pendingQueuedInterruptMessageIDs.clear(),this.buildProjection();case"interrupt-queued":return this.optimisticInterruptQueued(J);case"edit":return this.optimisticEdit(J);case"drop-submit":return this.dropOptimisticSubmit(J);case"update-submit-guidance":return this.updateOptimisticSubmitGuidance(J)}}updateOptimisticSubmitGuidance(J){let Z=!1;if(this.pendingMessageSubmits=this.pendingMessageSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}}),!Z)this.pendingQueuedSubmits=this.pendingQueuedSubmits.map((Q)=>{if(Q.clientMessageID!==J.clientMessageID)return Q;return Z=!0,{...Q,discoveredGuidanceFiles:J.discoveredGuidanceFiles}});return this.buildProjection()}dropOptimisticSubmit(J){let Z=this.pendingMessageSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID),Q=this.pendingQueuedSubmits.filter((Y)=>Y.clientMessageID!==J.clientMessageID);if(Z.length===this.pendingMessageSubmits.length&&Q.length===this.pendingQueuedSubmits.length)return this.buildProjection();return this.pendingMessageSubmits=Z,this.pendingQueuedSubmits=Q,this.buildProjection()}optimisticInterruptQueued(J){let Z=this.buildProjection(),Q=(Z.queuedMessages??[]).find((Y)=>(Y.queuedMessage.dtwMessageID??Y.id)===J.queuedMessageID);if(!Q||St0(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(NN3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.authoritativeThread,J.clientMessageID))return this.buildProjection();let Z={clientMessageID:J.clientMessageID,content:J.content,userState:J.userState,sentAt:J.sentAt??Date.now()};if(PN3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=LA0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:UN3(Z,Q)},this.buildProjection()}resolve(J){if(!this.hasPendingOverlay())return this.authoritativeThread=J,J;let Z=this.authoritativeThread;return this.authoritativeThread=J,this.reconcilePending(Z),this.buildProjection()}hasPendingOverlay(){return GN3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=HN3(this.authoritativeThread);this.pendingMessageSubmits=LN3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=AN3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=jN3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=RN3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return VN3(this.authoritativeThread,(Z)=>zN3(Z,J),(Z)=>FN3(Z,this.pendingMessageSubmits),(Z)=>qN3(Z,this.pendingQueuedSubmits),(Z)=>WN3(Z,this.pendingQueuedInterruptMessageIDs))}}function VN3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function GN3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function zN3(J,Z){if(!Z)return J;let Q=yy1(J,Z.targetMessageID);if(!Q)return J;let{index:Y,message:X}=Q,K=J.messages.slice(0,Y+1);return K[Y]={...X,content:Z.content},{...J,messages:K,nextMessageId:NA0({messages:K,nextMessageId:J.nextMessageId})}}function FN3(J,Z){if(Z.length===0)return J;let Q=NA0(J),Y=Z.map((X,K)=>Ex4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function qN3(J,Z){if(Z.length===0)return J;let Q=Z.map(DN3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function WN3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=pK0(X);if(!K||!Z.has(K)||St0(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Ex4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function DN3(J){return{id:J.clientMessageID,queuedMessage:Ex4(J,-1)}}function HN3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=mK0(K);if(V){if(X.add(V),K.role==="user")Z.add(V),Y.set(V,K)}}for(let K of J.queuedMessages??[]){let V=pK0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function UN3(J,Z){return J.messages.slice(Z+1).map((Q)=>mK0(Q)).filter((Q)=>Q!==void 0)}function BN3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&mK0(Q)===Z)}function wN3(J,Z){return(J.queuedMessages??[]).some((Q)=>pK0(Q)===Z)}function St0(J){return"interrupt"in J&&J.interrupt===!0}function NN3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||BN3(Q,Y)||wN3(Q,Y)}function LN3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=ON3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=EN3(J,Z);if(!V)return X;let G=MN3(V,K,X.length);return X.slice(G)}function ON3(J,Z){let Q=new Set,Y=[];for(let X of J){if(Z.has(X.clientMessageID)){Q.add(X.clientMessageID);continue}Y.push(X)}return{unmatchedPendingSubmits:Y,acknowledgedByID:Q}}function EN3(J,Z){let Q=Ox4(J),Y=Ox4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function MN3(J,Z,Q){let Y=0;for(let X of J){let K=mK0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Ox4(J){return J.messages.filter((Z)=>Z.role==="user")}function AN3(J,Z,Q){if(Q.length===0)return[];let Y=[...J.queuedMessages??[]];return Q.filter((X)=>{if(Z.queuedMessageIDs.has(X.clientMessageID)||Z.userMessageIDs.has(X.clientMessageID))return!1;let K=Y.findIndex((V)=>OA0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function jN3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=pK0(V);if(!G)return;return[G,V]}).filter((V)=>V!==void 0)),X=new Set(Z.map((V)=>V.clientMessageID)),K=new Set;for(let V of Q){let G=Y.get(V);if(!G){if(X.has(V))K.add(V);continue}if(St0(G))continue;K.add(V)}return K}function RN3(J,Z){if(!Z)return;return IN3(J,Z)?void 0:Z}function IN3(J,Z){let Q=a6.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!OA0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=a6.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function mK0(J){let Z=a6.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function pK0(J){let Z=a6.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=a6.safeParse(J.id);if(Q.success)return Q.data;return}function PN3(J){return CN3.has(J)}var CN3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var TN3=1e4;class kt0{deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID;toolRunner;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);inferenceErrorsSubject=new z4;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};currentAgentLoopState;activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z){this.deps=Z;this.provider=J,this.clientID=Z.clientID;let Q=xU("info"),Y=xU("error"),X=(z)=>({...z??{},threadId:this.provider.threadId});this.toolRunner=new Vi({clientID:this.clientID,transport:this.provider,invokeTool:(z)=>this.invokeToolForLease(z),batchGuidanceFiles:YY0,renderToolRunError:Lm,log:{info:(z,F)=>Q(z,X(F)),error:(z,F)=>Y(z,X({error:F})),wsMessage:(z,F,q)=>{C.debug("DTW executor tool runner message",X({direction:z,clientID:F,...typeof q==="object"&&q!==null?q:{message:q}}))}}}),this.provider.configureExecutorHandshake({handshake:(z)=>this.sendExecutorHandshake(z),onError:({error:z,attempt:F,delayMs:q})=>{C.warn("DTW executor handshake failed",{error:z,attempt:F,delayMs:q})},onExhausted:(z)=>{this.handleHandshakeExhausted(z)}}),this.currentAgentLoopState=J.getAgentLoopState();let K=J.getThread();this.optimisticThreadProjection=new _t0(K,this.currentAgentLoopState);let V=this.optimisticThreadProjection.resolve(K),G=bv(V,this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError());this.threadSubject=new F4(V),this.thread$=this.threadSubject,this.threadStateSubject=new F4(KR({thread:V,viewState:G,resolvedTokenUsage:I7(V)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new F4(G),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(w1(NX0)),this.transportSubscriptions.push(this.threadSubject.subscribe((z)=>{this.rebuildThreadState(z)}),this.threadViewStateSubject.subscribe((z)=>{let F=this.threadStateSubject.getValue();if(F.viewState===z)return;this.threadStateSubject.next({...F,viewState:z})})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Z.handoffService}startProviderSubscription(J){this.providerSubscriptions?.unsubscribe();let Z=this.provider.threadChanges().subscribe({next:(Y)=>{J(Y),this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}}),Q=this.provider.agentLoopStateChanges().subscribe({next:(Y)=>{if(this.currentAgentLoopState=Y,this.optimisticThreadProjection.setAgentLoopState(Y),Y==="error")this.inferenceErrorsSubject.next(Error("Agent failed to complete the request."));this.updateThreadViewStateFromProvider()}});this.providerSubscriptions={unsubscribe:()=>{Z.unsubscribe(),Q.unsubscribe()}}}writeThread(J){this.currentAgentLoopState=this.provider.getAgentLoopState(),this.threadSubject.next(J)}providerThread(){return this.provider.getThread()}resolveAuthoritativeThread(J){return this.optimisticThreadProjection.resolve(J)}getThreadViewState(){return this.threadViewStateSubject.getValue()}getCurrentThread(){return this.threadSubject.getValue()}getThreadID(){return this.getCurrentThread().id}getThreadTitle(){return this.getCurrentThread().title}getAgentMode(){return this.getCurrentThread().agentMode}getMessages(){return this.getCurrentThread().messages}getQueuedMessages(){return this.getCurrentThread().queuedMessages??[]}getInitialTreeURI(){return this.getCurrentThread().env?.initial.trees?.[0]?.uri}shouldAutoSubmitDraft(){let J=this.getCurrentThread();if(!J.autoSubmitDraft)return!1;return q8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(q8(J)>0)return;return u00(J,"handoff")?.threadID}isThreadEmpty(){return q8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return I7(this.thread$.getValue())}async dispose(){this.providerSubscriptions?.unsubscribe(),this.providerSubscriptions=null;for(let J of this.transportSubscriptions)J.unsubscribe();this.transportSubscriptions.length=0,this.clearRetryCountdownTimer(),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null,this.toolRunner.dispose(),this.provider.dispose(),this.threadSubject.complete(),this.threadStateSubject.complete(),this.threadViewStateSubject.complete(),this.inferenceErrorsSubject.complete(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete()}async sendMessage(J){if(J.editIndex!==void 0){await this.ensureProviderReadyForExecutorActions();let K=this.thread$.getValue(),V=K.messages[J.editIndex];if(!V||V.role!=="user"||!V.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let G=K.messages.findIndex((q)=>q.role==="user");if(J.editIndex===G&&J.agentMode&&K.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((q)=>{q.agentMode=J.agentMode});this.provider.editUserMessage(V.dtwMessageID,J.content,Fn0(),J.agentMode);let F=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(F);return}let Z=this.thread$.getValue();if(!Z.messages.some((K)=>K.role==="user")&&J.agentMode&&Z.agentMode!==J.agentMode)this.provider.setAgentMode(J.agentMode,{overwrite:!0}),this.updateThread((K)=>{K.agentMode=J.agentMode});let Y=zq(),X=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Y,content:J.content});this.writeThread(X);try{let K=J.prepareContentForSend?await J.prepareContentForSend(J.content):J.content;await this.ensureProviderConnectedForClientWrites();let V=await this.discoverGuidanceFilesForUserMessage(K);if(V&&V.length>0){let z=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),F=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:z});this.writeThread(F)}let G=await this.collectUserState();this.provider.sendUserMessage(K,J.agentMode,G,Y,V)}catch(K){throw this.rollbackOptimisticSubmit(Y),K}}async restoreTo(J){await this.ensureProviderReadyForExecutorActions();let Y=[...this.thread$.getValue().messages.slice(0,J+1)].reverse().find((V)=>V.role==="user");if(!Y?.dtwMessageID)throw Error("Unable to edit message: missing DTW message ID");let X=Y.content.filter((V)=>V.type==="text"||V.type==="image").map((V)=>{if(V.type==="image")return{...V,source:{...V.source}};return{...V}});if(X.length===0)throw Error("Unable to edit message: no editable content found");this.provider.editUserMessage(Y.dtwMessageID,X,Fn0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=zq(),Q=this.optimisticThreadProjection.optimisticUpdate({type:"submit",clientMessageID:Z,content:J});this.writeThread(Q);try{await this.ensureProviderConnectedForClientWrites();let Y=await this.discoverGuidanceFilesForUserMessage(J);if(Y&&Y.length>0){let K=Y.map((G)=>({uri:G.uri,lineCount:G.lineCount??0,...typeof G.content==="string"?{content:G.content}:{}})),V=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Z,discoveredGuidanceFiles:K});this.writeThread(V)}let X=await this.collectUserState();this.provider.sendUserMessage(J,void 0,X,Z,Y)}catch(Y){throw this.rollbackOptimisticSubmit(Z),Y}}async discardQueuedMessages(){let J=this.optimisticThreadProjection.optimisticUpdate({type:"discard-queued"});this.writeThread(J),this.provider.discardQueuedMessages()}async interruptQueuedMessage(J){await this.ensureProviderReadyForExecutorActions(),this.provider.interruptQueuedMessage(J);let Z=this.optimisticThreadProjection.optimisticUpdate({type:"interrupt-queued",queuedMessageID:J});this.writeThread(Z)}async ensureProviderConnectedForClientWrites(){await this.provider.ensureConnectedForAction("client-write")}async ensureProviderReadyForExecutorActions(J){await this.provider.ensureConnectedForAction("executor-action"),await this.provider.ensureExecutorReady({timeoutMs:TN3,timeoutMessage:"Timed out waiting for executor readiness. Please retry."})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){await this.deps.threadService.updateThreadMeta(this.provider.threadId,vG(J));let Z=await this.deps.threadService.get(this.provider.threadId);if(Z)this.writeThread(Z)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=v9(this.threadSubject.getValue(),J),Q=this.optimisticThreadProjection.resolve(Z);this.writeThread(Q)}async cancelTurn(){this.provider.cancelAgentLoop()}async cancelStreaming(){this.provider.cancelAgentLoop()}async retryTurn(){this.provider.retryAgentLoop()}invokeBashTool(J,Z){let Q=yA4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(W){C.warn("Failed to append manual bash invocation to DTW thread",{error:W}),this.activeError={message:`Failed to sync bash result to thread: ${W instanceof Error?W.message:String(W)}`},this.updateThreadViewStateFromProvider()}},G=(q,W={emitRun:!0})=>{if(X)return;if(X=!0,V(q),W.emitRun)Y.next(q);Y.complete()},z=(q)=>q instanceof Error?q.message:String(q),F=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",F),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await WH({toolName:g6,threadSnapshot:this.provider.getThread(),dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:Q,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});if(X)return;let W={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(g6,{args:J,userInput:{accepted:!0}},W).subscribe({next:(D)=>{if(X)return;if(Y.next(D),D.status!=="in-progress")G(D,{emitRun:!1})},error:(D)=>{G({status:"error",error:{message:z(D)}})}})}catch(q){G({status:"error",error:{message:z(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",F)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=r8.safeParse(J);if(!Y.success)return;this.provider.resolveToolApproval(Y.data,Z,{denyFeedback:Q})}addPendingSkill(J){this.pendingSkillsSubject.next([...this.pendingSkillsSubject.getValue(),J])}removePendingSkill(J){this.pendingSkillsSubject.next(this.pendingSkillsSubject.getValue().filter((Z)=>Z.name!==J))}clearPendingSkills(){this.pendingSkillsSubject.next([])}async getDraft(){let J=this.thread$.getValue().draft;if(!J)return null;let Z=xP(J);if(!Z.text&&Z.images.length===0)return null;return Z}async setDraft(J){this.updateThread((Z)=>{if(!J||!J.text&&J.images.length===0){delete Z.draft,delete Z.autoSubmitDraft;return}let Q=[];if(J.text)Q.push({type:"text",text:J.text});if(J.images.length>0)Q.push(...J.images);Z.draft=Q,Z.autoSubmitDraft=!1})}async clearPendingNavigation(){}async getGuidanceFiles(J){let Z=this.thread$.getValue();return(await $F({filesystem:this.deps.filesystem,configService:this.deps.configService,threadService:this.deps.threadService},Z,J)).map((Y)=>({uri:Y.uri,type:Y.type}))}async getFilesAffectedByTruncation(J){let Z=this.thread$.getValue(),Q=await this.getToolUsesToRevert(Z,J);return Q.size>0?this.deps.fs.tracker.getFilesForToolUses(Q):[]}async getToolUsesToRevert(J,Z){let Q=new Set;J.messages.slice(0,Z).forEach((K)=>{if(K.role==="user"){for(let V of K.content)if(V.type==="tool_result")Q.add(V.toolUseID)}else for(let V of K.content)if(V.type==="tool_use")Q.add(V.id)});let Y=new Set,X=await this.deps.fs.tracker.getAllRecords();for(let[K]of X.entries())if(!Q.has(K))Y.add(K);return Y}async collectUserState(){try{return await V$0()??wm}catch(J){return C.warn("Failed to collect IDE user state for DTW message",{error:J}),wm}}resolveUserMessageGuidanceContext(){let J=z1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?P6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=z1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(s$(J))return z1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return X1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=k8(J);if(!Z.trim())return;let{paths:Q}=K$0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let z=this.resolveMentionedPathToURI(G,Y);if(!z||!X1.hasPrefix(z,Y.workspaceRoot))continue;let F=z.toString();if(K.has(F))continue;K.add(F);let q=await XQ({stat:(W,D)=>this.deps.filesystem.stat(W,D),readFile:(W,D)=>this.deps.filesystem.readFile(W,D)},z,Y.workspaceRoot,null,X);for(let W of q){if(V.some((D)=>D.uri===W.uri))continue;X.add(W.uri),V.push({uri:W.uri,content:W.content,lineCount:W.lineCount})}}return V.length>0?V:void 0}handleHandshakeExhausted(J){C.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((X)=>X.threadId===Z||X.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(Oj));for(let X of[...this.toolRunner.sentApprovalRequests])if(!Y.has(X))this.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=Oj(X);if(this.toolRunner.sentApprovalRequests.has(K))continue;let V=eQ0(X);if(this.provider.sendExecutorToolApprovalRequest(V))this.toolRunner.sentApprovalRequests.add(K)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted,J.input?.denyFeedback)}syncExecutorTools(J){this.advertisedExecutorTools=this.provider.syncExecutorToolRegistrations({nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.executorReadyChanges().subscribe({next:(J)=>{if(J)this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.errorEvents().subscribe({next:(J)=>{if(this.activeError=J.type==="error_set"?J.error:null,J.type==="error_set")this.inferenceErrorsSubject.next(J.error);this.syncRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(ik(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){C.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await this.provider.connectExecutor({executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,sendGitSnapshot:!1,executorType:"local-client",previouslyAdvertisedTools:this.advertisedExecutorTools,initialToolDiscovery:this.deps.initialToolDiscovery});this.advertisedExecutorTools=Z,this.toolRunner.flushBufferedTerminalResults(),this.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=this.provider.sendSettingsUpdate(Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await VZ();this.provider.setEnvironment({initial:J})}catch(J){C.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=r8.safeParse(Z);this.provider.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await WH({toolName:J.toolName,threadSnapshot:this.provider.getThread(),dtwHandoffService:this.handoffService,dtwArtifactSyncService:this.createDTWArtifactSyncService(),configService:this.deps.configService,toolService:this.deps.toolService,mcpService:this.deps.mcpService,skillService:this.deps.skillService,fsTracker:this.deps.fs,toolUseID:J.toolCallId,discoveredGuidanceFileURIs:this.toolRunner.discoveredGuidanceFileURIs});C.info("DTW TUI tool run environment ready",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q});let X=this.deps.toolService.invokeTool(J.toolName,{args:Z},Y);return C.info("DTW TUI tool service returned observable",{toolCallId:J.toolCallId,toolName:J.toolName,threadId:this.provider.getThread().id,elapsedMs:Date.now()-Q}),X}async handleRollbackRequest(J){await this.toolRunner.handleRollbackRequest(J.editId,J.toolUseIdsToRevert,(Z)=>this.deps.fs.tracker.revertChanges(Z)),await this.refreshProviderFileChanges(),this.updateThreadViewStateFromProvider()}async handleFileSystemReadDirectoryRequest(J){let Z=await GY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await zY0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await j30(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(bv(this.threadSubject.getValue(),this.currentAgentLoopState,this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}rebuildThreadState(J){this.threadStateSubject.next(KR({thread:J,viewState:this.threadViewStateSubject.getValue(),resolvedTokenUsage:I7(J)}))}syncRetryCountdownTimer(){let J=this.activeError?.retryAt;if(J===void 0||J<=Date.now()){this.clearRetryCountdownTimer();return}if(this.retryCountdownTimer!==null)return;this.retryCountdownTimer=setInterval(()=>{let Z=this.activeError?.retryAt;if(Z===void 0){this.clearRetryCountdownTimer();return}if(this.updateThreadViewStateFromProvider(),Z<=Date.now())this.clearRetryCountdownTimer()},1000)}clearRetryCountdownTimer(){if(this.retryCountdownTimer===null)return;clearInterval(this.retryCountdownTimer),this.retryCountdownTimer=null}currentEphemeralError(){if(!this.activeError)return;let J=this.activeError.retryAt!==void 0?Math.max(0,Math.ceil((this.activeError.retryAt-Date.now())/1000)):void 0,Z=this.activeError.code!==void 0||this.activeError.attempt!==void 0?{code:this.activeError.code,attempt:this.activeError.attempt}:void 0;return{message:this.activeError.message,stack:this.activeError.stack,error:Z,retryCountdownSeconds:J}}}d4();E1();function Mx4(J){let Z=new F4(J.thread),Q=new F4(bv(J.thread,"idle")),Y=new F4(new Map),X=new F4([]),K=new F4([]),V=(F)=>{let W={...Z.getValue()};if(!F||!F.text&&F.images.length===0)delete W.draft,delete W.autoSubmitDraft;else{let D=[];if(F.text)D.push({type:"text",text:F.text});if(F.images.length>0)D.push(...F.images);W.draft=D,W.autoSubmitDraft=!1}Z.next(W),Q.next(bv(W,"idle"))};return{handle:uv({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(F)=>(await J.materialize()).sendMessage(F),restoreTo:async(F)=>(await J.materialize()).restoreTo(F),queueMessage:async(F)=>(await J.materialize()).queueMessage(F),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(F)=>(await J.materialize()).setTitle(F),setVisibility:async(F)=>(await J.materialize()).setVisibility(F),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(F)=>{K.next([...K.getValue(),F])},removePendingSkill:(F)=>{K.next(K.getValue().filter((q)=>q.name!==F))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>_N3(Z.getValue()),setDraft:async(F)=>V(F),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function _N3(J){if(!J.draft)return null;let Z=xP(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var dK0="Loading thread...",SN3="Importing thread";class hn{deps;recentThreadIDsSubject=new F4([]);threadTitlesSubject=new F4({});activeThreadHandleSubject=new F4(null);allConnectedThreadActivityStatusesSubject=new F4({});initializationStatusSubject=new F4({pending:!1,message:dK0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=qY0({configService:this.deps.configService,onFollow:this.followHandoffIfSourceActive})}get recentThreadIDs$(){return this.recentThreadIDsSubject}get threadTitles$(){return this.threadTitlesSubject}get threadHandles$(){return this.activeThreadHandleSubject}get allConnectedThreadActivityStatuses$(){return this.allConnectedThreadActivityStatusesSubject}get initializationStatus$(){return this.initializationStatusSubject}get activeThreadHandle(){if(!this.activeThreadContextID)throw Error("No active thread context");let J=this.threadHandleMap.get(this.activeThreadContextID)??this.pendingHandoffThreads.get(this.activeThreadContextID)?.optimisticHandle.handle;if(!J)throw Error(`No thread handle for ${this.activeThreadContextID}`);return J}get activeProvider(){if(!this.activeThreadContextID)return;return this.threadHandleMap.get(this.activeThreadContextID)?.provider}hasPendingInitialization(){return this.initializationStatusSubject.getValue().pending}isDTWMode(){return!0}isThreadActorsMode(){return this.deps.useThreadActors??!1}getTransportConnectionState(){return this.activeProvider?.getConnectionState()??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionRole()??null}getCompactionStatus(){let J=this.activeProvider;if(!J)return;return{compactionState:J.getCompactionState()}}async createThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}async switchThread(J){await this.activateThreadWithNavigation(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.activeThreadContextID;if(!J)return;let Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.activateThreadWithNavigation(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}followHandoffIfSourceActive=async(J)=>{if(this.activeThreadContextID!==J.sourceThreadID)return;await this.switchThread(J.targetThreadID)};async createHandoff(J,Z){let Y=this.threadHandleMap.get(J)?.provider.getThread()??this.activeProvider?.getThread();if(!Y||Y.id!==J)throw Error("No thread available for handoff");let X=Y.env?.initial?.trees?.[0]?.repository?.url??(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,K=await this.handoffService.createHandoffDraft({parentThread:Y,goal:Z.goal,images:Z.images,signal:Z.signal});Z.signal?.throwIfAborted();let V=Z.agentMode??K.sourceAgentMode??Y.agentMode,G={threadID:K.parentThreadID,type:"handoff",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},comment:Z.goal},z=m3(),F=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:F,comment:Z.goal}],W={id:z,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},D=Mx4({thread:W,materialize:()=>this.materializePendingHandoffThread(z)});return this.pendingHandoffThreads.set(z,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:D,materializingPromise:null}),z}async dispose(){for(let J of this.threadHandleMap.values())await J.dispose();for(let J of this.pendingHandoffThreads.values())await J.optimisticHandle.dispose();this.threadHandleMap.clear(),this.pendingHandoffThreads.clear(),this.activeThreadHandleSubject.complete(),this.allConnectedThreadActivityStatusesSubject.complete(),this.initializationStatusSubject.complete(),this.threadTitlesSubject.complete(),this.recentThreadIDsSubject.complete()}async activateThread(J,Z){C.info("[dtw-thread-pool] activateThread:start",{requestedThreadID:J,hasExistingHandle:Boolean(J&&this.threadHandleMap.get(J))});let Q=J?this.threadHandleMap.get(J):void 0;if(Q){let X=Q.thread$.getValue().id;this.activeThreadContextID=X,this.activeThreadHandleSubject.next(Q),this.addToRecentThreads(X),this.syncAllConnectedThreadActivityStatuses(),C.info("[dtw-thread-pool] activateThread:reused",{activeThreadID:X,handleCount:this.threadHandleMap.size});return}let Y=J?this.pendingHandoffThreads.get(J):void 0;if(J&&Y){this.activeThreadContextID=J,this.activeThreadHandleSubject.next(Y.optimisticHandle.handle),this.syncAllConnectedThreadActivityStatuses(),C.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:dK0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=RS({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),V=new kt0(X,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,clientID:this.deps.clientID,initialToolDiscovery:this.deps.initialToolDiscovery,fs:K,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,V),V.startProviderSubscription((G)=>{this.applyProviderState(X.threadId,G)}),this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(V),this.addToRecentThreads(X.threadId),C.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:dK0})}}async activateThreadWithNavigation(J,Z){let Q=this.activeThreadContextID;await this.activateThread(J);let Y=this.activeThreadContextID;if(Z.recordNavigation&&Q!==null&&Y!==null&&Q!==Y)this.recordNavigation(Q)}applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y);let X=this.threadTitlesSubject.getValue();if(X[J]!==Y.title)this.threadTitlesSubject.next({...X,[J]:Y.title});this.syncAllConnectedThreadActivityStatuses()}syncAllConnectedThreadActivityStatuses(){let J={};for(let[Z,Q]of this.threadHandleMap.entries())J[Z]=Q.getThreadViewState();for(let[Z,Q]of this.pendingHandoffThreads.entries())J[Z]=Q.optimisticHandle.getThreadViewState();this.allConnectedThreadActivityStatusesSubject.next(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}async createProvider(J){let Z=J?void 0:(await this.deps.getThreadEnvironment()).trees?.[0]?.repository?.url,Q=J?void 0:"local-client";return IY0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:SN3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:dK0})},repositoryURL:Z,threadService:this.deps.threadService,threadId:J,workerUrl:process.env.AMP_WORKER_URL,useThreadActors:this.deps.useThreadActors,connectionMode:"executor+observer"})}async materializePendingHandoffThread(J){let Z=this.pendingHandoffThreads.get(J);if(!Z)throw Error(`No pending handoff thread for ${J}`);if(!Z.materializingPromise){let K=(async()=>{let{threadId:V}=await HH(void 0,this.deps.configService,void 0,{repositoryURL:Z.repositoryURL,agentMode:Z.agentMode,relationship:Z.relationship,executorType:"local-client"});if(this.activeThreadContextID===J)await this.activateThread(V,{threadRelationships:Z.threadRelationships});return V})();Z.materializingPromise=K,K.catch(()=>{let V=this.pendingHandoffThreads.get(J);if(V?.materializingPromise===K)V.materializingPromise=null})}let Q=await Z.materializingPromise,Y=this.threadHandleMap.get(Q);if(!Y)await this.activateThread(Q,{threadRelationships:Z.threadRelationships}),Y=this.threadHandleMap.get(Q);if(!Y)throw Error(`No DTW thread handle for ${Q}`);let X=this.pendingHandoffThreads.get(J);if(X)this.pendingHandoffThreads.delete(J),await X.optimisticHandle.dispose(),this.syncAllConnectedThreadActivityStatuses();return Y}setInitializationStatus(J){let Z=this.initializationStatusSubject.getValue();if(Z.pending===J.pending&&Z.message===J.message)return;this.initializationStatusSubject.next(J)}}Uo0();import{randomBytes as xN3}from"node:crypto";import{readFile as fN3}from"node:fs/promises";import uN3 from"node:readline";import{setTimeout as bN3}from"node:timers/promises";v3();jT();d4();cD();E1();F3();d4();cD();E1();class Ax4{stateSubject;constructor(J){this.stateSubject=new F4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function kN3(J){let Z=new Map;for(let Q of J.messages){if(Q.role!=="user")continue;for(let Y of Q.content){if(Y.type!=="tool_result")continue;if(!("progress"in Y.run))continue;let X=Y.run.progress;if(typeof X==="string"){Z.set(Y.toolUseID,{status:Y.run.status,content:X});continue}if(X&&typeof X==="object"&&"output"in X&&typeof X.output==="string")Z.set(Y.toolUseID,{status:Y.run.status,content:X.output})}}return Z}function vN3(J){if(!J.draft)return null;let Z=xP(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function yN3(J){if(!J||!J.text&&J.images.length===0)return"";let Z=[];if(J.text)Z.push({type:"text",text:J.text});if(J.images.length>0)Z.push(...J.images);return Z}async function vt0(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??m3(),K=b9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let z=await J.threadService.exclusiveSyncReadWriter(X);z.write(Q),await z.asyncDispose(),V=Q}let G=K??await b9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||q8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadService.updateThreadMeta(X,Y);if(Y&&!Q){let z=J.threadService.observe(X).subscribe((F)=>{if(F.messages.length===0)return;z.unsubscribe(),J.threadService.updateThreadMeta(X,Y).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let z=J.threadService.observe(X).subscribe(async(F)=>{if(L9(F,"assistant"))await Z.onFirstAssistantMessage?.(X),z.unsubscribe()})}return await G.resume(),G}async function jx4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;return vt0(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?vG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function Rx4(J,Z,Q){let Y=Z?await jx4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new cK0(J,Y)}class cK0{deps;queueOnSubmitByDefault=!1;restoreTo=this.truncateThread.bind(this);stateTracker;activeThreadHandleSubject;workersByThreadID=new Map;currentWorker;activeThreadHandleValue;activeThreadHandleThreadID;latestStatus={state:"initial"};threadSubscription=null;statusSubscription=null;pendingSkillsSubscription=null;recentThreadIDsSubject=new F4([]);pendingApprovalsSubject=new F4([]);pendingSkillsSubject=new F4([]);threadViewStatesSubject=new F4({});threadTitlesSubject=new F4({});legacyHandoffNavigationSubject=new z4;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Ax4(this.buildPoolState(Z.thread,this.recentThreadIDsSubject.getValue())),this.workersByThreadID.set(Z.thread.id,Z),this.activeThreadHandleValue=this.createHandle(Z.thread.id,Z),this.activeThreadHandleThreadID=Z.thread.id,this.activeThreadHandleSubject=new F4(this.activeThreadHandleValue),this.refreshDerivedState(Z.thread),this.addToRecentThreads(Z.thread.id),this.subscribeToWorker(Z),this.subscribeToPendingApprovals(),this.subscribeToGlobalWorkerStates(),this.subscribeToWorkerTitles()}get threadHandles$(){return this.activeThreadHandleSubject}get threadState$(){return this.stateTracker.state$.pipe(w1((J)=>J.threadState))}get currentThreadState(){return this.stateTracker.state.threadState}get currentThread(){return this.stateTracker.state.currentThread}get currentThreadID(){return this.stateTracker.state.currentThreadID}get recentThreadIDs$(){return this.recentThreadIDsSubject}get recentThreadIDs(){return this.stateTracker.state.recentThreadIDs}get threadTitles$(){return this.threadTitlesSubject}get legacyHandoffNavigation$(){return this.legacyHandoffNavigationSubject}get allConnectedThreadActivityStatuses$(){return this.threadViewStatesSubject}get pendingApprovals$(){return this.pendingApprovalsSubject}get pendingSkills$(){return this.pendingSkillsSubject}getWorkerForExecuteMode(){return this.currentWorker}async createThread(){let J=await this.deps.createThread();this.switchToWorker(J,{recordNavigation:!0})}async switchThread(J){await this.switchToThreadByID(J,{recordNavigation:!0})}canNavigateBack(){return this.threadBackStack.length>0}canNavigateForward(){return this.threadForwardStack.length>0}async navigateBack(){if(!this.canNavigateBack())return;let J=this.currentWorker.thread.id,Z=this.threadBackStack.pop();if(!Z)return;this.threadForwardStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadForwardStack.pop(),this.threadBackStack.push(Z),Q}}async navigateForward(){if(!this.canNavigateForward())return;let J=this.currentWorker.thread.id,Z=this.threadForwardStack.pop();if(!Z)return;this.threadBackStack.push(J);try{await this.switchToThreadByID(Z,{recordNavigation:!1})}catch(Q){throw this.threadBackStack.pop(),this.threadForwardStack.push(Z),Q}}async sendMessage(J){await this.currentWorker.handle({type:"user:message",index:J.editIndex,message:{content:J.content,agentMode:J.agentMode}}),this.maybeMarkLastUserMessageInterrupted(this.currentWorker)}async truncateThread(J){await this.currentWorker.handle({type:"thread:truncate",fromIndex:J})}createHandle(J,Z){let Q=(X)=>{if(this.currentThreadID!==J)throw Error(`ThreadHandle.${X} called for inactive thread ${J}. Current thread is ${this.currentThreadID}.`)},Y=async(X)=>{await Z.handle({type:"thread:truncate",fromIndex:X})};return uv({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(w1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(w1((X)=>X.state==="active"?X.ephemeralError:void 0),y5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(w1((X)=>kN3(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>I7(Z.thread),sendMessage:async(X)=>{Q("sendMessage"),await Z.handle({type:"user:message",index:X.editIndex,message:{content:X.content,agentMode:X.agentMode}}),this.maybeMarkLastUserMessageInterrupted(Z)},restoreTo:async(X)=>{Q("restoreTo"),await Y(X)},queueMessage:async(X)=>{Q("queueMessage"),await Z.handle({type:"user:message-queue:enqueue",message:{content:X}})},discardQueuedMessages:async()=>{Q("discardQueuedMessages"),await Z.handle({type:"user:message-queue:discard"})},setTitle:async(X)=>{Q("setTitle"),await Z.handle({type:"title",value:X}),await this.deps.threadService.flushVersion(J,Z.thread.v)},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadService.updateThreadMeta(J,vG(X))},cancelTurn:async()=>{Q("cancelTurn"),await this.maybeCancelActiveTurn(Z)},cancelStreaming:async()=>{Q("cancelStreaming"),await this.maybeCancelActiveTurn(Z)},retryTurn:async()=>{Q("retryTurn"),await Z.retry()},dismissEphemeralError:()=>{Q("dismissEphemeralError"),Z.dismissEphemeralError()},preExecuteMode:async()=>{Q("preExecuteMode"),Z.continueInferenceAfterRejection(!0)},postExecuteMode:async()=>{Q("postExecuteMode");let X=Z.thread.v;await this.deps.threadService.flushVersion(J,X)},setTestEphemeralError:(X)=>{Q("setTestEphemeralError"),Z.setTestEphemeralError(X)},resolveApproval:async(X,K,V)=>{Q("resolveApproval"),this.deps.workerDeps.toolService.resolveApproval(X,K,V)},addPendingSkill:(X)=>{Q("addPendingSkill"),Z.addPendingSkill(X)},removePendingSkill:(X)=>{Q("removePendingSkill"),Z.removePendingSkill(X)},clearPendingSkills:()=>{Q("clearPendingSkills"),Z.clearPendingSkills()},getDraft:async()=>{return Q("getDraft"),vN3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:yN3(X)})},getFilesAffectedByTruncation:async(X)=>{return Q("getFilesAffectedByTruncation"),Z.getFilesAffectedByTruncation(X)},clearPendingNavigation:async()=>{Q("clearPendingNavigation"),await Z.handle({type:"clearPendingNavigation"})},getGuidanceFiles:async(X)=>{let K=this.stateTracker.state.currentThread;if(!K)return[];return(await $F({filesystem:this.getFilesystemReader(),configService:this.deps.workerDeps.configService,threadService:this.deps.threadService},K,X)).map((G)=>({uri:G.uri,type:G.type}))},invokeBashTool:(X,K)=>{Q("invokeBashTool");let V=Z.invokeBashTool(X,K.abortController.signal,K.hidden);return new k0((G)=>{let z=!1,F=V.subscribe({next:(q)=>G.next(q),error:(q)=>{z=!0,G.error(q)},complete:()=>{z=!0,G.complete()}});return()=>{if(!z)K.abortController.abort();F.unsubscribe()}})}})}maybeMarkLastUserMessageInterrupted(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Q=Z.messages.findLast((K)=>K?.role==="assistant"),Y=Q?.state.type==="streaming";if(!(this.latestStatus.inferenceState==="running"||Y))return;if(Y){if(Q.content.some((V)=>V.type==="thinking"&&aY(V)))return}for(let K=Z.messages.length-1;K>=0;K--){let V=Z.messages[K];if(V?.role==="user"&&!V.interrupted){J.handle({type:"user:message:interrupt",messageIndex:K});let G=[...Z.messages];G[K]={...V,interrupted:!0};let z={...Z,messages:G};this.refreshDerivedState(z),this.updateInterruptedMessage(z,K);break}}}updateInterruptedMessage(J,Z){let Q=J.messages[Z];if(!Q||Q.role!=="user"||Q.interrupted)return;let Y=J.messages.map((X,K)=>{if(K!==Z)return X;return{...X,interrupted:!0}});this.refreshDerivedState({...J,messages:Y})}async queueMessage(J){await this.currentWorker.handle({type:"user:message-queue:enqueue",message:{content:J}})}async discardQueuedMessages(){await this.currentWorker.handle({type:"user:message-queue:discard"})}setTitle=async(J)=>{await this.currentWorker.handle({type:"title",value:J}),await this.deps.threadService.flushVersion(this.currentThreadID,this.currentWorker.thread.v)};setVisibility=async(J)=>{await this.deps.workerDeps.threadService.updateThreadMeta(this.currentThreadID,vG(J))};async cancelTurn(){await this.maybeCancelActiveTurn(this.currentWorker)}async cancelStreaming(){await this.maybeCancelActiveTurn(this.currentWorker)}async maybeCancelActiveTurn(J){let Z=this.stateTracker.state.currentThread;if(!Z)return;if(this.latestStatus.state!=="active")return;let Y=Z.messages.findLast((V)=>V?.role==="assistant")?.state.type==="streaming",X=this.hasActiveTools(Z);if(!(this.latestStatus.inferenceState==="running"||this.latestStatus.inferenceState==="retrying"||Boolean(Y)||X))return;this.maybeMarkLastUserMessageInterrupted(J),await J.cancel()}hasActiveTools(J){for(let Z of J.messages){if(Z?.role!=="user")continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;if(Q.run.status==="in-progress"||Q.run.status==="queued")return!0}}return!1}async retryTurn(){await this.currentWorker.retry()}dismissEphemeralError(){this.currentWorker.dismissEphemeralError()}async resolveApproval(J,Z,Q){this.deps.workerDeps.toolService.resolveApproval(J,Z,Q)}addPendingSkill(J){this.currentWorker.addPendingSkill(J)}removePendingSkill(J){this.currentWorker.removePendingSkill(J)}clearPendingSkills(){this.currentWorker.clearPendingSkills()}async getFilesAffectedByTruncation(J){return this.currentWorker.getFilesAffectedByTruncation(J)}invokeBashTool(J,Z){let Q=this.currentWorker.invokeBashTool(J,Z.abortController.signal,Z.hidden);return new k0((Y)=>{let X=!1,K=Q.subscribe({next:(V)=>Y.next(V),error:(V)=>{X=!0,Y.error(V)},complete:()=>{X=!0,Y.complete()}});return()=>{if(!X)Z.abortController.abort();K.unsubscribe()}})}async createHandoff(J,Z){let Q={toolService:this.deps.workerDeps.toolService,configService:this.deps.workerDeps.configService,skillService:this.deps.workerDeps.skillService,getThreadEnvironment:this.deps.workerDeps.getThreadEnvironment,filesystem:this.getFilesystemReader(),threadService:this.deps.workerDeps.threadService};return(await b9.handoff(this.deps.workerDeps,{threadID:J,goal:Z.goal,images:Z.images,mode:"draft",navigate:!1,agentMode:Z.agentMode??void 0,queuedMessages:Z.queuedMessages,clearQueuedMessages:!0,blockIndex:0,buildSystemPromptDeps:Q,signal:Z.signal,filesystem:this.getFilesystemReader()})).threadID}async clearPendingNavigation(){await this.currentWorker.handle({type:"clearPendingNavigation"})}getFilesystemReader(){return this.deps.workerDeps.osFileSystem}setTestEphemeralError(J){this.currentWorker.setTestEphemeralError(J)}setTestRetryCountdown(J){let Z=Math.max(0,Math.ceil((J.retryAt-Date.now())/1000));this.currentWorker.setTestEphemeralError(Object.assign(Error(J.message),{retryCountdownSeconds:Z}))}async getThreadEnvironment(){return await this.deps.workerDeps.getThreadEnvironment()}async dispose(){if(this.disposing)return;this.disposing=!0,this.cleanupSubscriptions(),await Promise.all(Array.from(this.workersByThreadID.values()).map((J)=>J.asyncDispose())),this.workersByThreadID.clear(),this.pendingApprovalsSubject.complete(),this.pendingSkillsSubject.complete(),this.threadViewStatesSubject.complete(),this.threadTitlesSubject.complete(),this.legacyHandoffNavigationSubject.complete(),this.recentThreadIDsSubject.complete(),this.activeThreadHandleSubject.complete(),this.disposing=!1}async deleteThread(J){if(this.currentWorker.thread.id===J)return;this.workersByThreadID.delete(J),await b9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observe(J.thread.id).subscribe((Z)=>{this.refreshDerivedState(Z)}),this.statusSubscription=J.status.subscribe((Z)=>{this.latestStatus=Z,this.updateThreadState(this.stateTracker.state.currentThread)}),this.pendingSkillsSubscription=J.pendingSkills.subscribe((Z)=>{this.pendingSkillsSubject.next(Z)})}subscribeToPendingApprovals(){let J=this.deps.workerDeps.toolService.pendingApprovals$.subscribe((Z)=>{let Q=this.stateTracker.state.currentThreadID,Y=Z.filter((X)=>X.threadId===Q||X.mainThreadId===Q);this.pendingApprovalsSubject.next(Y)});this.subscriptions.push(J)}subscribeToGlobalWorkerStates(){let J=b9.statuses.subscribe((Z)=>{this.threadViewStatesSubject.next(Z)});this.subscriptions.push(J)}subscribeToWorkerTitles(){let J=async(Z)=>{let Q={};await Promise.all(Array.from(Z.keys()).map(async(Y)=>{Q[Y]=await this.deps.threadService.getPrimitiveProperty(Y,"title")??void 0})),this.threadTitlesSubject.next(Q)};this.workerSubscription=b9.workers.subscribe((Z)=>{J(Z)})}setCurrentWorker(J){if(this.workersByThreadID.set(J.thread.id,J),J.thread.id!==this.currentWorker.thread.id)this.addToRecentThreads(J.thread.id);this.currentWorker=J,this.latestStatus={state:"initial"},this.refreshDerivedState(J.thread),this.subscribeToWorker(J)}refreshDerivedState(J){let Z=this.buildPoolState(J,this.recentThreadIDsSubject.getValue());this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[J.id]:J.title??void 0}),this.stateTracker.update(Z),this.maybeEmitLegacyHandoffNavigation(J),this.emitActiveThreadHandleIfNeeded()}maybeEmitLegacyHandoffNavigation(J){let Z=J.pendingNavigation;if(!Z||J.id!==this.currentThreadID)return;if(this.pendingNavigationInFlightThreadID===Z)return;this.pendingNavigationInFlightThreadID=Z,this.legacyHandoffNavigationSubject.next(Z),this.currentWorker.handle({type:"clearPendingNavigation"}).catch(()=>{return}).finally(()=>{if(this.pendingNavigationInFlightThreadID===Z)this.pendingNavigationInFlightThreadID=null})}buildPoolState(J,Z){let Q=e_(J,this.latestStatus);return{threadState:KR({thread:J,viewState:Q,resolvedTokenUsage:I7(J)}),currentThread:J,currentThreadID:J.id,recentThreadIDs:Z}}updateThreadState(J){this.refreshDerivedState(J)}addToRecentThreads(J){let Z=[...this.recentThreadIDsSubject.getValue()],Q=Z.indexOf(J);if(Q!==-1)Z.splice(Q,1);if(Z.unshift(J),Z.length>50)Z.pop();this.recentThreadIDsSubject.next(Z),this.stateTracker.update({...this.stateTracker.state,recentThreadIDs:Z})}switchToWorker(J,Z){let Q=this.currentWorker.thread.id;if(this.workersByThreadID.set(J.thread.id,J),this.setCurrentWorker(J),Z.recordNavigation&&J.thread.id!==Q)this.recordNavigation(Q)}async switchToThreadByID(J,Z){let Q=this.workersByThreadID.get(J)??await jx4(this.deps,J);this.switchToWorker(Q,Z)}recordNavigation(J){this.threadBackStack.push(J),this.threadForwardStack=[]}cleanupSubscriptions(){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.workerSubscription?.unsubscribe(),this.threadSubscription=null,this.statusSubscription=null,this.pendingSkillsSubscription=null,this.workerSubscription=null;for(let J of this.subscriptions)J.unsubscribe();this.subscriptions=[]}emitActiveThreadHandleIfNeeded(){if(this.activeThreadHandleThreadID!==this.currentThreadID)this.activeThreadHandleValue=this.createHandle(this.currentThreadID,this.currentWorker),this.activeThreadHandleThreadID=this.currentThreadID;this.activeThreadHandleSubject.next(this.activeThreadHandleValue)}}function g4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
7055
7055
  `)}function Px4(J,Z){process.stdout.write(`${JSON.stringify({type:"state",reason:J,state:Z})}
7056
7056
  `)}function lK0(J,Z){process.stdout.write(`${JSON.stringify({type:J,...Z})}
7057
7057
  `)}function hN3(J){if(!J)return[];return gN3(J).map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function gN3(J){let Z=[],Q="";for(let Y of J){if(Y===";"||Y===`
@@ -7397,7 +7397,7 @@ Ctrl-X, Y, Z to unlock`;if(D){let f=F.text.replace(/`([^`]+)`/g,"$1")+`
7397
7397
  `),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 _(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new _(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new _(`
7398
7398
  `))}return new o0({decoration:{color:Q.colorScheme.background,border:Q4.all(new r1(Y.app.keybind,1,"rounded"))},child:new l0({padding:C0.symmetric(0,1),child:new J0({text:new _(void 0,void 0,K)})})})}}class ue0 extends C${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=VG0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new xe0({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 jb4(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?C9: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?C9: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 oA3(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?C9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let D=Math.max(1,Math.floor(q/X)),H=F+Z*D+Math.floor(D/2),U=G>0?V/G:0,B=Math.round((1-U)*(W-1));return{x:H,y:B}}case"line":case"sparkline":case"stacked-area":{let F=K?C9:0,q=Q-F,W=Y-(K?z:0);if(q<=0||W<=0)return null;let D=X>1?F+Math.round(Z/(X-1)*(q-1)):F+Math.floor(q/2),H=G>0?V/G:0,U=Math.round((1-H)*(W-1));return{x:D,y:U}}default:return null}}function rA3(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 sA3(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 tA3(J,Z,Q,Y,X,K,V){let G;try{let U=m1.of(J),B=u0.of(J);G={foreground:U.colorScheme.foreground,background:U.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=[],D=new g({color:G.foreground,underline:!0}),H=(U,B)=>new _(B,D,void 0,kY0(U),()=>{f3(J,U)});if(Y.length<=1){if(W.push(new _(`${Z.label}: `,z)),Z.link)W.push(H(Z.link,K(Z.value)));else W.push(new _(K(Z.value),F));if(Z.meta)W.push(new _(` (${Z.meta})`,q))}else{let U=V==="stacked-bar"||V==="stacked-area";W.push(new _(`${Z.label}
7399
7399
  `,z));let B=0;for(let w=0;w<Y.length;w++){let N=Y[w],L=N.points[Q];if(!L)continue;B+=L.value;let O=N.color??X[w%X.length]??G.foreground;if(W.push(new _("● ",new g({color:O}))),W.push(new _(`${N.name}: `,q)),L.link)W.push(H(L.link,K(L.value)));else W.push(new _(K(L.value),F));if(w<Y.length-1||U)W.push(new _(`
7400
- `))}if(U)W.push(new _(" ",q)),W.push(new _("Total: ",q)),W.push(new _(K(B),F))}return new o0({decoration:{color:G.background,border:Q4.all(new r1(G.border,1,"rounded"))},child:new J0({text:new _(void 0,void 0,W)})})}ZE();d0();P7();GE();F$();v3();j2();Kd();PX();lZ();$Y();rZ();MA();d4();Rg();PP();E1();d0();lZ();class be0{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.1774971219-g0fd6a8"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await J40(Z,this.configService)}catch(Z){C.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 GL extends n0{props;constructor(J){super();this.props=J}createState(){return new Rb4}}class Rb4 extends i0{_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 Ib4 extends i0{controller=new o2;focusNode=new N6({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Q4.all(new r1(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let U=H.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:z})]}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new _("Enter",new g({color:Y.keybind}))),W.push(new _(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new _("Esc",new g({color:Y.keybind}))),W.push(new _(" to cancel",new g({color:Q.foreground,dim:!0})));let D=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,W)})});return new o0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new h0({children:[q,new I0({height:1}),F,new x3,D]})})}}class Fa extends n0{props;constructor(J){super();this.props=J}createState(){return new Ib4}}rZ();import{mkdtemp as Jj3,readFile as Zj3,rmdir as Qj3,unlink as Yj3,writeFile as Xj3}from"node:fs/promises";import{tmpdir as Kj3}from"node:os";import xb4 from"node:path";d0();d0();class Pb4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class UR extends Pb4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Cb4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class he0{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class ge0 extends N8{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Tb4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Tb4 extends h4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if($6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}class me0 extends N8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new _b4(this.link)}updateRenderObject(J){J.link=this.link}}class _b4 extends h4{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Z=this.offset.y,Q=this.parent;while(Q&&Q instanceof h4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if($6(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}d0();class pe0{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Z){C.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var eA3=500;class de0{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new UR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=M6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},eA3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class qa{}class Wa{}class Da{}class zG0{}class FG0 extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sb4(this.props)}}class Sb4 extends i0{props;controller;stateListener=null;overlayEntry=null;layerLink=new pe0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new de0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Cb4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)o6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof qa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Wa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Da)return this.controller.acceptSelected(),"handled";if(J instanceof zG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new sY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new oY({shortcuts:new Map([[new m4("ArrowDown"),new qa],[new m4("ArrowUp"),new Wa],[new m4("n",{ctrl:!0}),new qa],[new m4("p",{ctrl:!0}),new Wa],[new m4("Enter"),new Da],[new m4("Escape"),new zG0],[new m4("Tab"),new Da]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new y$({actions:new Map([[qa,new h6(this.invoke)],[Wa,new h6(this.invoke)],[Da,new h6(this.invoke)],[zG0,new h6(this.invoke)]]),child:Q});return new me0({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new he0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new _(Q,new g({color:u0.of(J).app.command})),new _(" ",new g({color:Z})));return X.push(new _(Y,new g({color:Z}))),[{child:new J0({text:new _(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=m1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=O4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let I=this.props.controller.getCursorVisualRow(),S=G+I+1;q=V-S-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,D=Math.min(Z.options.length,W+K),H=[],U=0;for(let I=W;I<D;I++){let S=Z.options[I];if(!S)continue;let T=I===Z.selectedIndex,b,m;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(J,S,T);let f=this.props.displayStringForOption?.(S)??String(S),d="",p=f,h=S;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(S)??String(S),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();b=new J0({text:new _(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let x=O4.of(J),k=C5(m,x.supportsEmojiWidth);U=Math.max(U,k),H.push(b)}let B=O4.sizeOf(J).width,w=U+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({width:L,child:new o0({height:M,decoration:new t4(Y),child:new U2({decoration:{border:Q4.all(new r1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new h0({crossAxisAlignment:"start",children:H})})})});return new ge0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kb4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function vb4(J){switch(J.type){case"file":return J.path;case"hint":return`${$j3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function $j3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=M6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7400
+ `))}if(U)W.push(new _(" ",q)),W.push(new _("Total: ",q)),W.push(new _(K(B),F))}return new o0({decoration:{color:G.background,border:Q4.all(new r1(G.border,1,"rounded"))},child:new J0({text:new _(void 0,void 0,W)})})}ZE();d0();P7();GE();F$();v3();j2();Kd();PX();lZ();$Y();rZ();MA();d4();Rg();PP();E1();d0();lZ();class be0{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.1774987755-gb72e09"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await J40(Z,this.configService)}catch(Z){C.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 GL extends n0{props;constructor(J){super();this.props=J}createState(){return new Rb4}}class Rb4 extends i0{_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 Ib4 extends i0{controller=new o2;focusNode=new N6({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=u0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Q4.all(new r1(Q.foreground,1,"solid")),z=new sY({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(H)=>{let U=H.trim();if(X&&U.length===0)return;this.widget.props.onSubmit(U)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),F=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:z})]}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new _("Enter",new g({color:Y.keybind}))),W.push(new _(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new _("Esc",new g({color:Y.keybind}))),W.push(new _(" to cancel",new g({color:Q.foreground,dim:!0})));let D=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,W)})});return new o0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new h0({children:[q,new I0({height:1}),F,new x3,D]})})}}class Fa extends n0{props;constructor(J){super();this.props=J}createState(){return new Ib4}}rZ();import{mkdtemp as Jj3,readFile as Zj3,rmdir as Qj3,unlink as Yj3,writeFile as Xj3}from"node:fs/promises";import{tmpdir as Kj3}from"node:os";import xb4 from"node:path";d0();d0();class Pb4{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Z of J)try{Z()}catch(Q){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class UR extends Pb4{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Z=typeof J==="object"||this._value!==J;if(this._value=J,Z)this.notifyListeners()}}function Cb4(J,Z){let Q=()=>{Z()};return J.addListener(Q),{dispose:()=>J.removeListener(Q)}}class he0{builder;maintainState;_overlayState;_needsBuild=!0;constructor(J,Z=!1){this.builder=J;this.maintainState=Z}get mounted(){return this._overlayState!==void 0}remove(){if(this._overlayState)this._overlayState.remove(this)}markNeedsBuild(){if(this._needsBuild=!0,this._overlayState)this._overlayState._markNeedsRebuild()}_setOverlayState(J){this._overlayState=J}_needsRebuild(){return this._needsBuild}_clearNeedsRebuild(){this._needsBuild=!1}}class ge0 extends N8{link;showWhenUnlinked;offset;constructor({key:J,link:Z,showWhenUnlinked:Q=!0,offset:Y={x:0,y:0},child:X}){super({key:J,child:X});this.link=Z,this.showWhenUnlinked=Q,this.offset=Y}createElement(){return new Bq(this)}createRenderObject(){return new Tb4(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class Tb4 extends h4{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;constructor(J,Z,Q){super();this._link=J,this._showWhenUnlinked=Z,this._followerOffset=Q}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if($6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Z=this.calculatePosition();if(this._cachedPosition=Z,Z)this.setOffset(Z.x,Z.y);if(this.children.length>0){let Q=this.children[0];Q.layout(J);let Y=Q.size;this.setSize(Y.width,Y.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Z){super.setOffset(J,Z)}paint(J,Z=0,Q=0){super.paint(J,Z,Q)}}class me0 extends N8{link;constructor({key:J,link:Z,child:Q}){super({key:J,child:Q});this.link=Z}createElement(){return new Bq(this)}createRenderObject(){return new _b4(this.link)}updateRenderObject(J){J.link=this.link}}class _b4 extends h4{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Z=this.offset.y,Q=this.parent;while(Q&&Q instanceof h4)J+=Q.offset.x,Z+=Q.offset.y,Q=Q.parent;return{x:J,y:Z}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if($6(!!J,"performLayout called without constraints"),this.children.length>0){let Z=this.children[0];Z.layout(J);let Q=Z.size;this.setSize(Q.width,Q.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}d0();class pe0{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Z){C.error("Error in LayerLink follower callback:",Z)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}d0();var eA3=500;class de0{_state;_textController=null;_lastText="";_triggers=[];_optionsBuilder=null;_onSelected=null;_pendingBuildTimer=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new UR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Z,optionsBuilder:Q,onSelected:Y}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._lastText=J.text,this._triggers=Z,this._optionsBuilder=Q,this._onSelected=Y||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Z})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Z=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Z})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Z=J.options[J.selectedIndex];if(!Z)return;if(this.dismiss(),this._onSelected)this._onSelected(Z)}dismiss(){this._clearPendingBuildTimer(),this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this.currentState.trigger,Z=this._textController.text,Q=Z!==this._lastText;if(this._lastText=Z,!Q&&!this.currentState.isActive)return;let Y=this._textController.cursorPosition,X=null;for(let G of this._triggers){let z=G.detect(Z,Y);if(z&&(!X||z.start>X.start))X=z}if(!this.currentState.isActive&&X&&X.query.length>0){let G=M6(Z),z=Y,F=z;while(F<G.length){let q=G[F];if(q&&/[\s)\]}@]/.test(q))break;F++}if(F>z){let W=[...G.slice(0,z),...G.slice(F)].join("");this._textController.text=W,this._textController.cursorPosition=Y;return}}if(!X){if(this.currentState.isActive)this.dismiss();else this._clearPendingBuildTimer();return}let K=Q&&this._shouldDebounceBuild(J,X),V=this.currentState.generationId+1;if(this._updateState({trigger:X,generationId:V,options:K?[]:this.currentState.options,isActive:!K,selectedIndex:-1}),K){this._scheduleDebouncedBuild(X.query,V);return}this._clearPendingBuildTimer(),this._buildOptions(X.query,V)};async _buildOptions(J,Z){if(!this._optionsBuilder)return;try{let Q=await this._optionsBuilder(J);if(this.currentState.generationId===Z&&!this._disposed)this._updateState({options:Q,selectedIndex:Q.length>0?0:-1,isActive:Q.length>0})}catch(Q){if(C.error("Error building autocomplete options:",Q),this.currentState.generationId===Z&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_scheduleDebouncedBuild(J,Z){this._clearPendingBuildTimer(),this._pendingBuildTimer=setTimeout(()=>{this._pendingBuildTimer=null,this._buildOptions(J,Z)},eA3)}_shouldDebounceBuild(J,Z){if(!J)return!1;if(J.trigger!==Z.trigger||J.start!==Z.start)return!1;return Z.query.length<J.query.length}_clearPendingBuildTimer(){if(this._pendingBuildTimer)clearTimeout(this._pendingBuildTimer),this._pendingBuildTimer=null}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._clearPendingBuildTimer(),this._textController)this._textController.removeListener(this._handleTextChange)}}class qa{}class Wa{}class Da{}class zG0{}class FG0 extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Sb4(this.props)}}class Sb4 extends i0{props;controller;stateListener=null;overlayEntry=null;layerLink=new pe0;scrollOffset=0;_effectiveFocusNode;_cachedMaxVisibleOptions=0;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({debugLabel:"AutocompleteFocusOwned"}),this.controller=new de0,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=Cb4(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.handle)this.props.handle.dismiss=()=>this.controller.dismiss();if(this.props.autofocus??!0)o6.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Z=J.props,Q=this.widget.props;if(this.props=Q,Z.controller!==Q.controller||Z.triggers!==Q.triggers||Z.optionsBuilder!==Q.optionsBuilder||Z.textFieldProps!==Q.textFieldProps||Z.onSelected!==Q.onSelected)this.controller.initialize({textController:Q.controller,triggers:Q.triggers,optionsBuilder:Q.optionsBuilder,onSelected:Q.onSelected});if(Z.handle!==Q.handle){if(Q.handle)Q.handle.dismiss=()=>this.controller.dismiss()}this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof qa)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Wa)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Da)return this.controller.acceptSelected(),"handled";if(J instanceof zG0)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Z=J.selectedIndex,Q=J.options.length,Y=this._cachedMaxVisibleOptions||Q;if(Y>=Q){this.scrollOffset=0;return}let X=Z-this.scrollOffset,K=1,V=this.scrollOffset;if(X>=Y-K)V=Math.max(0,Z-(Y-K-1));if(X<K)V=Math.max(0,Z-K);let G=Math.max(0,Q-Y);V=Math.min(V,G),this.scrollOffset=V}build(J){let Z=new sY({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Q=new oY({shortcuts:new Map([[new m4("ArrowDown"),new qa],[new m4("ArrowUp"),new Wa],[new m4("n",{ctrl:!0}),new qa],[new m4("p",{ctrl:!0}),new Wa],[new m4("Enter"),new Da],[new m4("Escape"),new zG0],[new m4("Tab"),new Da]]),focusNode:this._effectiveFocusNode,child:Z}),Y=new y$({actions:new Map([[qa,new h6(this.invoke)],[Wa,new h6(this.invoke)],[Da,new h6(this.invoke)],[zG0,new h6(this.invoke)]]),child:Q});return new me0({link:this.layerLink,child:Y})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new he0((J)=>{let Z=this.controller.currentState;return this.buildOverlayContent(J,Z)});try{WR.of(this.context).insert(this.overlayEntry)}catch(J){C.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayHints(J,Z){if(this.props.overlayHint!==void 0){if(this.props.overlayHint===null)return[];let{prefix:Q,suffix:Y}=this.props.overlayHint,X=[];if(Q)X.push(new _(Q,new g({color:u0.of(J).app.command})),new _(" ",new g({color:Z})));return X.push(new _(Y,new g({color:Z}))),[{child:new J0({text:new _(" ",new g({dim:!0}),X)}),position:"top",alignment:"center"}]}return[]}buildOverlayContent(J,Z){let Q=m1.maybeOf(J),Y=Q?.colorScheme.background??M0.default(),X=this.props.overlayBorderColor??Q?.colorScheme.border??M0.default(),K=Z.options.length,V=O4.sizeOf(J).height,G=0;try{let I=this.layerLink.getTargetTransform();if(I)G=I.position.y}catch{}let z=this.props.autoOverlayPosition?G<V/3:!1,F=2,q;if(z){let I=this.props.controller.getCursorVisualRow(),S=G+I+1;q=V-S-F}else q=G-F;K=Math.min(K,Math.max(1,q)),this._cachedMaxVisibleOptions=K,this.updateScrollPosition();let W=this.scrollOffset,D=Math.min(Z.options.length,W+K),H=[],U=0;for(let I=W;I<D;I++){let S=Z.options[I];if(!S)continue;let T=I===Z.selectedIndex,b,m;if(this.props.optionViewBuilder){b=this.props.optionViewBuilder(J,S,T);let f=this.props.displayStringForOption?.(S)??String(S),d="",p=f,h=S;if(h&&typeof h==="object"&&"type"in h)switch(h.type){case"file":d="@",p=h.path||f;break;case"artifact":d="",p=h.label||f;break}m=d+p}else{let f=this.props.displayStringForOption?.(S)??String(S),d=Q?.colorScheme.selection??M0.default(),p=Q?.colorScheme.foreground??M0.default();b=new J0({text:new _(f,new g({color:p,backgroundColor:T?d:void 0}))}),m=f}let x=O4.of(J),k=C5(m,x.supportsEmojiWidth);U=Math.max(U,k),H.push(b)}let B=O4.sizeOf(J).width,w=U+4,N=Math.floor(B*0.9),L=Math.max(Math.min(w,N),Math.min(30,N)),M=H.length+2,A;if(z)A=this.props.controller.getCursorVisualRow()+1;else A=-M;let j=new I0({width:L,child:new o0({height:M,decoration:new t4(Y),child:new U2({decoration:{border:Q4.all(new r1(X,1,"rounded"))},padding:C0.symmetric(1,0),overlays:this.buildOverlayHints(J,X),child:new h0({crossAxisAlignment:"start",children:H})})})});return new ge0({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:A},child:j})}}function kb4(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function vb4(J){switch(J.type){case"file":return J.path;case"hint":return`${$j3(J.kind)} ${J.message}`;case"commit":return`${J.shortHash} ${J.message} (${J.relativeDate})`}}function yb4(J){switch(J.type){case"file":return;case"hint":return;case"commit":return}}function $j3(J){switch(J){case"commit":return"@:";case"thread":return"@@"}}class vq{detect(J,Z){if(!J||Z<1)return null;let Q=M6(J);if(Z>Q.length)return null;let Y=this.findWordStart(Q,Z);if(Y>=Q.length||Q[Y]!=="@")return null;let X=Q.slice(Y+1,Z).join("");if(X.includes(" ")||X.includes("\t")||X.includes(`
7401
7401
  `))return null;return{start:Y,end:Z,query:X,trigger:"@"}}findWordStart(J,Z){let Q=Z;for(let Y=Z-1;Y>=0;Y--){let X=J[Y];if(!X||/[\s([{]/.test(X)){Q=Y+1;break}if(Y===0)Q=0}return Q}}class BR extends n0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new fb4(this.props)}}var Vj3=":";class fb4 extends i0{props;_effectiveFocusNode;_textChangeListener=null;_isCommitMode=!1;_imageUploadSpinner=new Z3;_imageUploadSpinnerInterval=null;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=new vq().detect(Z,Q);if(X&&this.props.completionBuilder){if(X.query==="@"&&this.props.onDoubleAtTrigger)return this.props.onDoubleAtTrigger(this.props.controller),[];let G=X.query.toLowerCase().startsWith(Vj3);if(G!==this._isCommitMode)this._isCommitMode=G,this.setState();return await this.props.completionBuilder.buildOptions(X)}if(this._isCommitMode)this._isCommitMode=!1,this.setState();return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=J.kind==="commit"?"@:":"@@",z=K+G+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length}return}case"file":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=K+`@${J.path} `+V;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=X+1+J.path.length+1}break}case"commit":{let Z=this.props.controller.text,Q=this.props.controller.cursorPosition,X=Z.slice(0,Q).lastIndexOf("@");if(X!==-1){let K=Z.slice(0,X),V=Z.slice(Q),G=`git-commit(${J.hash})`,z=K+G+" "+V;this.props.controller.clear(),this.props.controller.insertText(z),this.props.controller.cursorPosition=X+G.length+1}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new N6({debugLabel:"PromptEditorFocus"}),this._textChangeListener=()=>{this.setState()},this.props.controller.addListener(this._textChangeListener),this.props.controller.onInsertText=(J,Z)=>{if(J.length<=3)return!0;let Q=Iu4(J);if(Q.length===0)return!0;if(this.props.onInsertImage){for(let Y of Q)this.props.onInsertImage(Y);return!1}return!0},this.syncImageUploadSpinner()}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props,this.syncImageUploadSpinner()}dispose(){if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null;if(this._textChangeListener)this.props.controller.removeListener(this._textChangeListener),this._textChangeListener=null;if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}syncImageUploadSpinner(){if(this.props.showImageUploadSpinner===!0){if(!this._imageUploadSpinnerInterval)this._imageUploadSpinnerInterval=setInterval(()=>{this._imageUploadSpinner.step(),this.setState()},120);return}if(this._imageUploadSpinnerInterval)clearInterval(this._imageUploadSpinnerInterval),this._imageUploadSpinnerInterval=null}_handleOpenInEditor=async(J)=>{try{let Z=await Jj3(xb4.join(Kj3(),"amp-edit-")),Q=xb4.join(Z,"message.amp.md");await Xj3(Q,J,"utf-8"),await uK(Q);try{let Y=await Zj3(Q,"utf-8");this.props.controller.text=Y}catch(Y){if(Y?.code!=="ENOENT")C.error("Failed to read temporary file",Y)}try{await Yj3(Q),await Qj3(Z)}catch(Y){C.warn("Failed to clean up temporary file",Y)}}catch(Z){C.error("Error opening editor:",Z)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;if((this.props.pendingSkills??[]).length>0&&this.props.popSkill)return this.props.popSkill(),!0;return!1};_handleSubmitted=(J)=>{if(this.props.previousThreadId&&J.trim()===""){this.props.onPreviousThreadHintAccepted?.();return}this.props.onSubmitted?.(J)};build(J){let Z=this.props.theme,Q=this.props.pendingSkills??[],Y=this.props.imageAttachments.length>0,X=Q.length>0?new N1({mainAxisSize:"min",children:[new J0({text:new _("Skills: ",new g({color:Z.foreground,dim:!0}))}),...Q.flatMap((z,F)=>{let q=new K4({onClick:()=>{this.props.onSkillClick?.(F)},cursor:"pointer",child:new J0({text:new _(z.name,new g({color:Z.success,underline:!0}))})});if(F<Q.length-1)return[q,new J0({text:new _(" ")})];return[q]})]}):null,K=Y?new N1({mainAxisSize:"min",children:[new J0({text:new _("Images: ",new g({color:Z.foreground,dim:!0}))}),...this.props.imageAttachments.flatMap((z,F)=>{let q=this.props.onImageClick!==void 0,W=new K4({onClick:q?()=>{this.props.onImageClick?.(F)}:void 0,cursor:q?"pointer":void 0,child:new J0({text:new _(`[Image ${F+1}]`,new g({color:Z.success,underline:!0}))})});if(F<this.props.imageAttachments.length-1)return[W,new J0({text:new _(" ")})];return[W]}),...this.props.showImageUploadSpinner?[new J0({text:new _(" ")}),new J0({text:new _(this._imageUploadSpinner.toBraille(),new g({color:Z.foreground,dim:!0}))})]:[]]}):null,V=new FG0({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(z)=>vb4(z),overlayBorderColor:Z.border,focusNode:this._effectiveFocusNode,autofocus:this.props.autofocus??!0,autoOverlayPosition:this.props.autoOverlayPosition,handle:this.props.autocompleteHandle,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:this.props.minLines??3,maxLines:null,expands:!0,autofocus:!1,enabled:this.props.enabled??!0,onSubmitted:this._handleSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:this.props.submitKey??{character:"Enter"},prompts:this.props.shellPromptRules,style:{backgroundColor:Z.background,border:null,padding:C0.all(0),textColor:this.props.textColor??Z.foreground,cursorColor:Z.cursor,placeholderColor:Z.mutedForeground,selectionBackgroundColor:Z.selection},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(z,F,q)=>{let W=q?Z.selection:void 0,D=Z.secondary,H=Z.foreground,U=Z.foreground,B=Z.warning;if(F.type==="commit")return new o0({decoration:new t4(W),child:new N1({children:[new p1({child:new J0({text:new _("",void 0,[new _(F.shortHash,new g({color:Z.secondary})),new _(" ",new g({})),new _(F.message,new g({color:H}))]),maxLines:1,overflow:"ellipsis"})}),new J0({text:new _(` ${F.relativeDate}`,new g({color:U,dim:!0}))})]})});let w=[];switch(F.type){case"file":w.push(new _("@",new g({color:D}))),w.push(new _(F.path,new g({color:H})));break;case"hint":w.push(new _(F.kind==="commit"?"@:":"@@",new g({color:B}))),w.push(new _(" ",new g({}))),w.push(new _(F.message,new g({color:B})));break}let N=yb4(F);if(N)w.push(new _(" - ",new g({color:U,dim:!0}))),w.push(new _(N,new g({color:U,dim:!0})));return new o0({decoration:new t4(W),child:new J0({text:new _("",void 0,w),maxLines:1,overflow:"ellipsis"})})}}),G=[];if(this.props.topWidget)G.push(this.props.topWidget);if(X||K){let z=[];if(X)z.push(X);if(X&&K)z.push(new J0({text:new _(" ")}));if(K)z.push(K);let F=new o0({padding:C0.only({bottom:1}),child:new N1({mainAxisSize:"min",children:z})});G.push(F)}if(G.push(new p1({child:V})),this.props.bottomWidget)G.push(this.props.bottomWidget);return new h0({crossAxisAlignment:"start",children:G})}requestFocus(){this._effectiveFocusNode.requestFocus()}}class ub4 extends i0{controller=new o2;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new N6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=IV)return!1;let Z=await QL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=u0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new BR({controller:this.controller,triggers:[new vq],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(H)=>{this.widget.props.onSubmit(H.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:Z6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),z=new K6({focusNode:this.focusNode,child:G}),F=new o0({constraints:new I1({maxHeight:V}),padding:C0.symmetric(1,0),child:z}),q=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _("",void 0,[new _("Command: ",new g({color:Q.foreground})),new _(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new o0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new _("",void 0,[new _("Esc",new g({color:Y.keybind})),new _(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new _("",void 0,[new _("Press ",new g({color:Q.foreground,dim:!0})),new _("Enter",new g({color:Y.keybind})),new _(" to submit, ",new g({color:Q.foreground,dim:!0})),new _("Esc",new g({color:Y.keybind})),new _(" to clear",new g({color:Q.foreground,dim:!0}))])})}),D=[q,new I0({height:1}),new p1({child:F}),new I0({height:1}),W];return new o0({decoration:{border:Q4.all(new r1(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new h0({children:D})})}}class ce0 extends n0{props;constructor(J){super();this.props=J}createState(){return new ub4}}import{isDeepStrictEqual as le0}from"node:util";var Gj3=/[\\/_ +.#"@[({&]/,zj3=/[\\/_ +.#"@[({&]/g,Fj3=/[\s-]/,bb4=/[\s-]/g;function WG0(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,D,H,U;while(F>=0){if(W=WG0(J,Z,Q,Y,F+1,K+1,V),W>q){if(F===X)W*=1;else if(Fj3.test(J.charAt(F-1))){if(W*=0.9,U=J.slice(X,F-1).match(bb4),U&&X>0)W*=0.999**U.length}else if(Gj3.test(J.charAt(F-1))){if(W*=0.8,H=J.slice(X,F-1).match(zj3),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(D=WG0(J,Z,Q,Y,F+1,K+2,V),D*0.1>W)W=D*0.1}if(W>q)q=W;F=Q.indexOf(z,F+1)}return V[G]=q,q}function qG0(J){return J.toLowerCase().replace(bb4," ")}function hb4(J,Z){let Q=WG0(J,Z,qG0(J),qG0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let z=WG0(J,G,qG0(J),qG0(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 Vy{}class Gy{}class DG0{}class HG0{}class gb4 extends n0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new mb4}}class mb4 extends i0{build(J){return this.widget.onContext(J),this.widget.child}}function qj3(J,Z){if(J==="")return{matches:!0,score:1};let Q=hb4(Z,J);return{matches:Q>0.15,score:Q}}class n9 extends n0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new pb4}}class pb4 extends i0{textController;focusNode;scrollController=new n5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new o2(this.widget.props.controller?.query??""),this.focusNode=new N6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),o6.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)=>le0(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!le0(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>le0(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 Vy){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),o6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof Gy){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),o6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof DG0){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 HG0)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,...qj3(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;pV0(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(),o6.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=u0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=Q4.all(new r1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new sY({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 oY({shortcuts:new Map([[new m4("ArrowDown"),new Vy],[new m4("ArrowUp"),new Gy],[new m4("Tab"),new Vy],[new m4("Tab",{shift:!0}),new Gy],[new m4("n",{ctrl:!0}),new Vy],[new m4("p",{ctrl:!0}),new Gy],[new m4("Enter"),new DG0],[new m4("Escape"),new HG0]]),focusNode:this.focusNode,child:G}),F=new y$({actions:new Map([[Vy,new h6(this.invoke)],[Gy,new h6(this.invoke)],[DG0,new h6(this.invoke)],[HG0,new h6(this.invoke)]]),child:z}),q=new N1({children:[new o0({decoration:{color:Q.background},child:new J0({text:new _(">",new g({color:Q.foreground}))})}),new p1({child:F})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let w=this.widget.props.loadingText??"Loading...";W=new I0({height:10,child:new Z4({child:new J0({text:new _(w,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)W=new p1({child:new Z4({child:new J0({text:new _(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let w=Y.map((N,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(N)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(N,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new o0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new _(this.widget.props.getLabel(N),new g({color:j,dim:E}))})})}return new gb4(new K4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});W=new h0({children:w,crossAxisAlignment:"start"})}let D=new K4({onScroll:this.handleScroll,opaque:!1,child:new r6({controller:this.scrollController,autofocus:!1,child:W})}),H=[];if(this.widget.props.title){let w=new o0({padding:C0.symmetric(1,0),child:new J0({text:new _(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});H.push(w)}if(!K)H.push(q,new I0({height:1}));if(this.textController.text!==""){let w=Y.length>0?Y[this.selectedIndex]:void 0,N=w&&this.widget.props.buildDisabledReasonWidget?.(w,J);H.push(new p1({child:new h0({mainAxisAlignment:"spaceBetween",children:[new p1({child:D}),new o0({padding:C0.only({top:1}),child:new Z4({child:N??new I0({height:1})})})]})}))}else H.push(new p1({child:D}));if(this.widget.props.footer)H.push(this.widget.props.footer);return new o0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new h0({children:H})})}}function db4(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 ie0 extends J4{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)=>db4(X.pubDate).length));return new n9({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=u0.of(G),{colors:F}=z,q=z.app,W=K?q.selectionBackground:void 0,D=K?q.selectionForeground:F.foreground,H=F.mutedForeground,U=(B,w)=>new I0({width:w,child:N1.end([new J0({text:new _(B,new g({color:H}))})])});return new o0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[new p1({child:new J0({text:new _(X.title,new g({color:D})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),U(db4(X.pubDate),Q)]})})}})}}eO();class ne0 extends n0{createState(){return new cb4}}class cb4 extends i0{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=u0.of(J).colors;return new J0({text:new _("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function Wj3(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 bK0.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 ae0(J,Z,Q){return new J0({text:new _(`${J}${Z}`,new g({color:Q})),maxLines:1})}function Dj3(J,Z,Q,Y){return[ae0("+",J,Y.success),x3.horizontal(1),ae0("~",Z,Y.warning),x3.horizontal(1),ae0("-",Q,Y.destructive)]}function Hj3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class UG0 extends n0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new lb4}}class lb4 extends i0{spinner=new Z3;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=Wj3(F),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),D=u0.of(J),H=new l0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new _("",new g({color:D.colors.foreground,dim:!0}),[new _("Alt+W/Ctrl+T",new g({color:D.colors.primary,dim:!0})),new _(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:D.colors.foreground,dim:!0}))])})})}),U="",B=null,w=(L)=>{if(L!==U)U=L,B=j7(L);return B};return new n9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=w(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>w(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!Hj3(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:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:H,renderItem:(L,O,E,M)=>{let A=u0.of(M),{app:j,colors:I}=A,S=O?j.selectionBackground:void 0,T=O?j.selectionForeground:I.foreground,b=I.mutedForeground,m=(o,H0)=>new I0({width:H0,child:N1.end([new J0({text:new _(o,new g({color:b}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new bn({connectorColor:I.mutedForeground});if(L.depth>0){let o=[],H0=L.ancestorsAreLast.slice(1);for(let L0 of H0)o.push(new _(d.getAncestorPrefix(L0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,D0=d.getConnectorText(r);o.push(new _(D0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new _("",void 0,o)}))}let p=[],h=z===L.id?new _("(current) ",new g({color:I.success})):G.has(L.id)?new _("(visited) ",new g({color:I.foreground,dim:!0})):null;if(h)p.push(new J0({text:h}));if(dM(x))p.push(new ne0),p.push(new I0({width:1}));let i=L.title;if(L.relationshipType==="fork"){let o=i.match(/^Forked\((\d+)\): /);if(o)i=i.slice(o[0].length);else while(i.startsWith("Forked: "))i=i.slice(8);p.push(new J0({text:new _("[fork] ",new g({color:I.primary}))}))}else if(f)p.push(new J0({text:new _("[handoff] ",new g({color:I.accent}))}));if(p.push(new p1({child:new J0({text:new _(i,new g({color:T})),overflow:"ellipsis",maxLines:1})})),p.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let o=O?{success:b,warning:b,destructive:b}:I;p.push(...Dj3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,o)),p.push(new I0({width:2}))}return p.push(m(L.description.timeAgo,W)),new o0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new N1({children:[...k,...p]})})}})}}d0();AX();cM();PX();lZ();d4();U4();PP();var re0=H4($D(),1);import{execSync as wR}from"node:child_process";import{writeFile as zy}from"node:fs/promises";import Uj3 from"node:os";import yq from"node:path";var ib4="c446b2e9b16cdc06df2ec285894d6421",Bj3="5ea19563777f4ade8707fc56f7e7a388",wj3="amp-thread-worker",nb4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function Nj3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function FL(J){if(!J||!Nj3(J.meta))return!1;return J.meta.usesDtw===!0}function se0(J){let Z=new URL(`https://dash.cloudflare.com/${ib4}/workers/durable-objects/view/${Bj3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function te0(J){let Z=new URL(`https://dash.cloudflare.com/${ib4}/workers/services/view/${wj3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function Lj3(J,Z){if(jW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function ee0(J,Z){let Q=Lj3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Ha(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Ua(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Ua(J){return J.path??k9(J.uri)}function ab4(J,Z,Q){let Y=Ha("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function ob4(J,Z){return ee0(J,Z).map(({label:Q,command:Y})=>`# ${Q}
7402
7402
  ${Y}`).join(`
7403
7403
 
@@ -7619,7 +7619,7 @@ ${t.content||""}`:t.content||"",T0=[],s0=t.baseDir.startsWith("file://")?sG0(t.b
7619
7619
  `),process.exit(1)}process.stdout.write(await $T3(z.result.displayText)+`
7620
7620
  `),process.exit(0)})}cM();import{stdout as JT3}from"node:process";function ZT3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${MF(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Cp4(J){JT3.write(`${ZT3(J)}
7621
7621
  `)}function Tp4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Cp4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Cp4(Z),process.exit(0)})}var Mv3=sH.join(jX,"logs","headless.log"),L61=sH.join(sk,"device-id.json"),sl4=`cli-tui-${Ki4(16).toString("hex")}`;async function Av3(){for(let J of FE)try{if((await J.listConfigs()).length>0)return J}catch(Z){C.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => H4(by(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){g$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
7622
- `)}function jv3(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 L7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")mJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")mJ("experimental.agentMode",Z.mode)}function Fi4(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 Rv3(J){try{return await Gi4(J,"utf-8")}catch{return J}}async function O61(J,Z,Q){let Y=Fi4(J,Z);if(!Y)return;let X=f6(Q)?Q.features:[],K=f6(Q)?Q.user.email:void 0;if(!j61(X,R2.HARNESS_SYSTEM_PROMPT)&&!qi4(K))throw new C1("You are not allowed to do this.",1);mJ("systemPrompt",await Rv3(Y))}function qi4(J){return!!(J&&m00(J))}function j61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function E61(J){return(J.userEmail?bJ(J.userEmail):!1)||j61(J.features,R2.DTW_TUI)}function tl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function M61(J,Z){if(typeof J==="boolean")return J;if(!f6(Z))return!1;return E61({userEmail:Z.user.email,features:Z.features})}function Iv3(J){return J!=="pending"}function hy(J){if(!f6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pv3(J){let Z=hy(J);if(Z)return Z.id;if(cz(J))throw Error(J.error.message);throw Error("unreachable")}function Cv3(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 mz0(J){let Y=Cv3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function el4(J){if(!s6.write(J))await Nv3(s6,"drain")}var $i4=[{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??kK,description:`Custom settings file path (overrides the default location ${kK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xn0})`},{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:l7(),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:xz.SMART.key,description:`Set the agent mode (${fz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fz().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}],Ji4=(J)=>("deprecated"in J)&&J.deprecated===!0,Tv3=(J)=>("hidden"in J)&&J.hidden===!0,_v3=(J)=>("default"in J),Sv3=(J)=>("default"in J)?J.default:void 0,Wi4=[{name:"toggle-skills-count",entryPoint:Jo0}];function kv3(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 C1(E3.unknownCommand(Q),1,V)}}async function R61(J){return{...J,getThreadEnvironment:VZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:j80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iZ(J.configService),pluginService:J.pluginService}}function Di4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:VZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=z1.file(zi4.homedir()),A61=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(pz0,".config");function vv3(J){return AF4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MF4(Z);let Q=VX0(),Y=Ho0();if((!Q||Y||yC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(VX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function S9(J,Z,Q){let Y=Q?.deferAuth??!1;Rx1("0.0.1774971219-g0fd6a8");let X=V10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(z1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:pz0,userConfigDir:A61});vC4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(i),C.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:Y}),!i)if(Y)C.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
7622
+ `)}function jv3(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 L7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")mJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")mJ("experimental.agentMode",Z.mode)}function Fi4(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 Rv3(J){try{return await Gi4(J,"utf-8")}catch{return J}}async function O61(J,Z,Q){let Y=Fi4(J,Z);if(!Y)return;let X=f6(Q)?Q.features:[],K=f6(Q)?Q.user.email:void 0;if(!j61(X,R2.HARNESS_SYSTEM_PROMPT)&&!qi4(K))throw new C1("You are not allowed to do this.",1);mJ("systemPrompt",await Rv3(Y))}function qi4(J){return!!(J&&m00(J))}function j61(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function E61(J){return(J.userEmail?bJ(J.userEmail):!1)||j61(J.features,R2.DTW_TUI)}function tl4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new C1("This TUI mode is not enabled for your user;",1)}function M61(J,Z){if(typeof J==="boolean")return J;if(!f6(Z))return!1;return E61({userEmail:Z.user.email,features:Z.features})}function Iv3(J){return J!=="pending"}function hy(J){if(!f6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pv3(J){let Z=hy(J);if(Z)return Z.id;if(cz(J))throw Error(J.error.message);throw Error("unreachable")}function Cv3(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 mz0(J){let Y=Cv3(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 C1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function el4(J){if(!s6.write(J))await Nv3(s6,"drain")}var $i4=[{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??kK,description:`Custom settings file path (overrides the default location ${kK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(C).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xn0})`},{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:l7(),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:xz.SMART.key,description:`Set the agent mode (${fz().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:fz().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}],Ji4=(J)=>("deprecated"in J)&&J.deprecated===!0,Tv3=(J)=>("hidden"in J)&&J.hidden===!0,_v3=(J)=>("default"in J),Sv3=(J)=>("default"in J)?J.default:void 0,Wi4=[{name:"toggle-skills-count",entryPoint:Jo0}];function kv3(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 C1(E3.unknownCommand(Q),1,V)}}async function R61(J){return{...J,getThreadEnvironment:VZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new bV(J.fileSystem),generateThreadTitle:j80,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>iZ(J.configService),pluginService:J.pluginService}}function Di4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:VZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=z1.file(zi4.homedir()),A61=process.env.XDG_CONFIG_HOME?z1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(pz0,".config");function vv3(J){return AF4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){MF4(Z);let Q=VX0(),Y=Ho0();if((!Q||Y||yC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(LH("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(LH("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(VX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function S9(J,Z,Q){let Y=Q?.deferAuth??!1;Rx1("0.0.1774987755-gb72e09");let X=V10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(z1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:pz0,userConfigDir:A61});vC4(X);let K=await X.getLatest();C.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let i=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(i),C.info("API key lookup before login",{found:Boolean(i),ampURL:J.ampURL,deferAuth:Y}),!i)if(Y)C.info("No API key found, continuing startup with deferred auth");else{s6.write(`No API key found. Starting login flow...
7623
7623
  `);let c=await yv3(J),o=await J.secrets.get("apiKey",J.ampURL);if(C.info("Login flow completed",{success:c,storedKeyPresent:Boolean(o),ampURL:J.ampURL}),!c)await zH(),process.exit(1);V=!0}}{let i=await X.getLatest(),c=i.settings.url,o=i.secrets.isSet?.[c];C.info("Config secrets state after login",{configURL:c,apiKeySet:o?.apiKey??!1})}let G=R1(iZ(X).pipe(y5(Iv3))),z=Y?"pending":await G;if(!Y)C.info("Server status resolved",{status:"ready",isAuthenticated:f6(z),isError:cz(z),errorMessage:cz(z)?z.error.message:void 0});let F=G.then((i)=>Pv3(i)),{toolService:q,dispose:W}=wF4({configService:X}),D=new Map,H=()=>D.clear(),U=new DT0(X,J.settings.getWorkspaceRootPath()),B=Cs1({configService:X,filesystem:n8}),w=Mn1({configService:X,trustStore:U,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(i,c,o)=>{let H0=`${i}:${c}`,r=D.get(H0);if(r)return C.debug("Reusing existing OAuth provider for server",{serverName:i,serverUrl:c}),r;C.debug("Creating OAuth provider for server",{serverName:i,serverUrl:c});let D0=(async()=>{let L0=new NE(J.secrets),G0=await L0.getClientInfo(i,c),$0=o?.scopes??G0?.scopes,F0=HR4();C.info("OAuth headless mode check",{useHeadless:F0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:s6.isTTY});let n;if(F0)n=J.executeMode?DR4():WR4(i);let a=new nj0({storage:L0,serverName:i,serverUrl:c,clientId:o?.clientId??G0?.clientId,clientSecret:o?.clientSecret??G0?.clientSecret,authUrl:o?.authUrl??G0?.authUrl,tokenUrl:o?.tokenUrl??G0?.tokenUrl,scopes:$0,headlessAuthHandler:n});return C.debug("OAuth provider created",{serverName:i,serverUrl:c,hasManualClientId:!!(o?.clientId??G0?.clientId),willUseDCR:!(o?.clientId??G0?.clientId),scopes:$0,headlessMode:F0,executeMode:J.executeMode}),a})();return D.set(H0,D0),D0}}),N=Ug0({configService:X,filesystem:n8,spawn:q$0}),L;if(J.executeMode){let i=await EV4({toolService:q,providers:[w,N],initialTimeout:15000});L=i.registrations;for(let[c,o]of i.initErrors)C.warn(`${c} provider initialization slow or failed:`,o)}else L=Bg0({toolService:q,providers:[w,N]});if(Z.jetbrains)XE("JetBrains");else if(Z.ide&&tR4())XE("VS Code");else if(Z.ide&&eR4())XE("Neovim");else if(Z.ide){let i=await Av3();if(i){let c=w10(i.ideName);if(c)XE(c)}}if(J.executeMode)Ix1(!0);let O,E=q$.status.pipe(w1((i)=>Boolean(i.connected&&i.authenticated&&i.ideName&&Df1(i.ideName))),u4()).subscribe((i)=>{if(i){if(!O)O=q.registerTool(OV4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let i=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new tQ0(process.cwd(),{alwaysIncludePaths:i},!0)}else M=new class extends tQ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new US0(ds1(X),{maxThreads:200});C.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=M61(j,z),S;q$.status.subscribe((i)=>{S=i});let T=new MA0({workspaceRoots:[z1.file(process.cwd())],fileSystem:n8,getCurrentFile:()=>{if(!S?.openFile)return;try{return z1.parse(S.openFile)}catch(i){C.warn("Failed to parse current file URI",{uri:S.openFile,error:i});return}},getOpenFiles:()=>{if(!S?.visibleFiles?.length)return[];let i=S.openFile;return S.visibleFiles.filter((c)=>c!==i).map((c)=>{try{return z1.parse(c)}catch(o){return C.warn("Failed to parse visible file URI",{uri:c,error:o}),null}}).filter((c)=>c!==null)}}),b=new wo0,m=process.env.PLUGINS??"off",x=Z.headless?BC4():void 0,k=x??new ZX0({configService:X}),f=k instanceof ZX0?k:void 0;if(f)f.pluginExecutorKind=I?"local":"unknown";let d=TT0({configService:X,fileSystem:n8,platform:k,internalPlugins:Wi4,pluginFilter:m}),p=wa1({pluginService:d,toolService:q}),h={codebaseContextService:T,configService:X,toolService:q,mcpService:w,skillService:B,toolboxService:N,trustStore:U,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:n8,terminal:b,pluginService:d,pluginPlatform:f,headlessPluginPlatform:x,serverStatus:z,serverStatusPromise:G,viewerUserIDPromise:F,hasAPIKeyAtStartup:V};return{...h,async asyncDispose(){if(h.mcpService.hasAuthenticatingClients())C.info("Waiting for OAuth authentication to complete before exit..."),await h.mcpService.waitForAuthentication();for(let i of L.values())i.dispose();await h.mcpService.dispose(),H(),await h.threadService.asyncDispose(),h.configService.unsubscribe(),W(),h.fuzzyServer.dispose(),h.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),p.dispose(),await h.pluginService.dispose()}}}async function yv3(J){if(!J.executeMode){if(!await eY0("Would you like to log in to Amp? [(y)es, (n)o]: "))return s6.write(`Login cancelled. Run the command again to retry.
7624
7624
  `),!1}return await Hi4(J)}async function Hi4(J){let Z=Ki4(32).toString("hex"),Q=await Xv(J.ampURL,Z),Y=new AbortController;try{await NV(Q,Y.signal)}catch(K){C.error("Error opening browser",{error:K})}let X=await Xv(J.ampURL,Z,!1);s6.write(`If your browser does not open automatically, visit:
7625
7625
 
@@ -7627,7 +7627,7 @@ ${p0.blue.bold(X)}
7627
7627
 
7628
7628
  `);try{return await oP4(J.ampURL,Z,J.secrets,Y),s6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return C.error("Login failed",{error:K}),g$.write(`
7629
7629
  Login failed: ${K instanceof Error?K.message:String(K)}
7630
- `),!1}}function Zi4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xv3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!R7(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function uv3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fv3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bv3(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 hv3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gv3(J){let Z=new hw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Nj(),process.exit(0);let w=B.originalError??B;Hj4(w)}),Tp4(Z,{version:"0.0.1774971219-g0fd6a8",buildTimestamp:"2026-03-31T15:37:53.749Z",buildType:"'release'"}),Z.addHelpText("after",oR4()),Z.configureHelp({formatHelp:rR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await av3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await nv3(L,await $a0(N,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,w,N)=>{let L=N.optsWithGlobals(),O=await T3(L);await pj4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await dj4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7630
+ `),!1}}function Zi4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xv3(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 C1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!R7(Y.threadId))throw new C1("Create response did not include a valid thread ID",1);return Y.threadId}function fv3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function uv3(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 C1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fv3(Q))throw new C1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bv3(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 hv3(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 C1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gv3(J){let Z=new hw().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)Nj(),process.exit(0);let w=B.originalError??B;Hj4(w)}),Tp4(Z,{version:"0.0.1774987755-gb72e09",buildTimestamp:"2026-03-31T20:13:01.309Z",buildType:"'release'"}),Z.addHelpText("after",oR4()),Z.configureHelp({formatHelp:rR4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await av3(L)}),Z.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await nv3(L,await $a0(N,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,w,N)=>{let L=N.optsWithGlobals(),O=await T3(L);await pj4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,w)=>{let N=w.optsWithGlobals(),L=await T3(N);await dj4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
7631
7631
  Actions:
7632
7632
  create Create a new DTW thread and print its ID
7633
7633
  add-message <message> Send a user message and wait for message_added
@@ -7691,8 +7691,8 @@ ${M}
7691
7691
 
7692
7692
  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 mv3(J){C.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new hn({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:VZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new bV(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 C.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function pv3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await qv()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await qv()).trimEnd(),stdinInput:null}}function dv3(J,Z,Q){if(J.remote&&!Z)throw new C1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new C1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new C1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new C1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new C1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new C1("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 C1("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 C1("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"
7693
7693
  Or pipe via stdin: echo "your message" | amp --execute`)}async function dz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(G0,$0)=>{let F0=Number(process.hrtime.bigint()-$0)/1e6,n=BL4();C.info("Startup phase",{phase:G0,phaseMs:Math.round(F0),sinceMainMs:n===null?void 0:Math.round(n)})},{userInput:V,stdinInput:G}=await pv3(Z),z=!!Z.streamJson||!!Z.streamJsonThinking;dv3({...Z,streamJson:z},J.executeMode,V),L7(Q,Z);let F=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;C.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let D=await S9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let H=await R61(D);K("runMainThread:createWorkerDeps",F);let{serverStatus:U}=D;if(!W&&cz(U)){let G0=pk(Error(U.error.message));if(G0.message===E3.networkOffline||G0.message===E3.networkTimeout)throw mz0(J.ampURL);throw new C1(E3.invalidAPIKey,1)}let B=f6(U)?U:null,w=B?.user.email,N=qi4(w),L=E61({userEmail:w,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&M61(O,B);if(!W)await O61(Q,Z,U);let M=hy(U),A=M?.features??[],j=M?.team??null,I=$X0(Z,M);if(I instanceof Error)_3(I.message);if((J.executeMode||z)&&W8(Z.mode)&&!N)throw new C1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!VE(Z.mode,w))throw new C1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await LC4(V,G,D.configService),await D.asyncDispose(),process.exit(0);if(Z.headless){if(!w||!bJ(w))throw new C1("Headless DTW mode is only available for Amp employees",1);let G0=await D.secretStorage.get("apiKey",J.ampURL);if(!G0)throw new C1("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&&!R7($0))throw new C1(`Invalid thread ID: ${$0}`,1);let F0=$0?void 0:await Qy3({dependencies:D,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),n=$0??F0?.threadId;if(!n)throw new C1("Failed to resolve headless thread ID",1);let a=await NR4(n);if(a.status==="already-running")await D.asyncDispose(),await zH(),process.exit(0);try{await qR4({ampURL:J.ampURL,apiKey:G0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:n,ownerUserId:F0?.ownerUserId,threadVersion:F0?.threadVersion,agentMode:F0?.agentMode,initialToolDiscovery:Promise.all([D.mcpService.initialized,D.toolboxService.initialized]).then(()=>{return}),configService:D.configService,mcpService:D.mcpService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,pluginService:D.pluginService,pluginPlatform:D.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await a.release(),await D.asyncDispose()}await zH(),process.exit(0)}let S=J.executeMode?void 0:async(G0)=>Yo(G0,"interactive"),T={threadService:D.threadService,workerDeps:H,createThread:async()=>{let G0=W?await D.serverStatusPromise:U,$0=await uQ0(J.settings,process.cwd(),hy(G0),I);if($0 instanceof Error)_3($0.message);return vt0(H,{threadMeta:$0?vG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:S})},validateThreadOwnership:async(G0,$0)=>{if($0?.nonBlockingOwnershipCheck){Qi4(G0,D.configService,D.viewerUserIDPromise).catch((F0)=>{if(F0 instanceof C1){if($0.onOwnershipError){$0.onOwnershipError(F0,G0);return}FH(F0,G0);return}C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})});return}try{await Qi4(G0,D.configService,D.viewerUserIDPromise)}catch(F0){if(F0 instanceof C1)throw F0;C.warn("Failed to validate thread ownership in CLI, allowing to open",{error:F0})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:S,handleError:FH},b=async(G0)=>{try{if(G0==="dtw")return mv3({ampURL:J.ampURL,configService:D.configService,threadService:D.threadService,mcpService:D.mcpService,clientID:sl4,toolboxService:D.toolboxService,toolService:D.toolService,skillService:D.skillService,fileSystem:D.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Rx4(T,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof C1)throw $0;throw await FH($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")g$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
7694
- `),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await D.configService.getLatest(),$0=bu(G0),F0=await p5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new Tt0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await D.serverStatusPromise:D.serverStatus;await O61(Q,Z,G0);let $0=process.hrtime.bigint(),F0=M61(O,G0),n=f6(G0)?E61({userEmail:G0.user.email,features:G0.features}):!1;tl4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await b(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await R1(a.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));k.setInitError($0),await FH(G0,Z.threadId)});else F=process.hrtime.bigint(),tl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),vv3({configService:D.configService,threadService:D.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(I4((G0)=>{if(!G0)return k0.of({});return F5(G0.thread$,G0.threadViewState$).pipe(w1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){VC4(D.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await Rj4({threadPool:f,...G0});if(await Yo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Xo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Lf1();let G0=await qE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)q$.selectConfig($0)}else c=!0}F=process.hrtime.bigint();let o=La0("0.0.1774971219-g0fd6a8",D.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let H0=new $o0(D.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await R1(f.threadHandles$);if(!G0)throw new C1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await QX0();K("runMainThread:loadSessionState",F),C.info("Loaded session state:",r);let D0={...r,launchCount:r.launchCount+1};zv((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&R7(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Hf4({codebaseContextService:D.codebaseContextService,history:new fn0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:p5,threadPool:f,createSystemPromptDeps:async()=>Di4(D),ideClient:q$,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:H0,updateService:o,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:i,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:sl4,logFile:{path:Y},sessionState:D0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-31T15:37:53.749Z"},(G0)=>new it0({...G0,threadPool:G0.threadPool},($0)=>new l11({...$0,threadState:$0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await D.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function T3(J){if(C.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)g$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7695
- `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Pn1({get:async(G)=>{if(G!==bh)return;try{let z=await Gi4(L61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==bh)return;await Vi4(sH.dirname(L61),{recursive:!0}),await Lv3(L61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Px1(Y);let X=await SR4({...J,workspaceTrust:{current:!0,changes:kA0},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 XC4(J.mcpConfig);X=KC4(X,G)}let K=sH.dirname(X.getSettingsFilePath());EF4(sk,K);let V=await X.get("url","global");if(!V)V=o7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=wx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:jC4(await $a0(J,X))}}function cv3(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}function lv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=sH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Mv3:Xn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function iv3(){UL4();let J=cv3(process.argv),Z=lv3(process.argv,J),Q=RA4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(jv3(C),C.info("Starting Amp CLI.",{version:"0.0.1774971219-g0fd6a8",buildTimestamp:"2026-03-31T15:37:53.749Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new C1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gv3(Q).parseAsync(process.argv)}LF4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await iv3().catch(FH)});async function nv3(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"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7694
+ `),await zH(),process.exit(1);let m=(async()=>{if(W){C.info("Skipping initial free tier status fetch until auth is complete");return}try{let G0=await D.configService.getLatest(),$0=bu(G0),F0=await p5.getUserFreeTierStatus({},{config:D.configService,signal:AbortSignal.timeout($0)});if(F0.ok)return C.info("User free tier status:",F0),F0.result;return}catch(G0){C.error("Failed to fetch free tier status:",G0);return}})(),k=!J.executeMode?new Tt0:null,f,d=null;if(k)f=k,d=(async()=>{let G0=W?await D.serverStatusPromise:D.serverStatus;await O61(Q,Z,G0);let $0=process.hrtime.bigint(),F0=M61(O,G0),n=f6(G0)?E61({userEmail:G0.user.email,features:G0.features}):!1;tl4({dtwEnabled:F0,hasV2TUIAccess:n});let a=await b(F0?"dtw":"worker");if(K("runMainThread:createThreadPool",$0),k.attach(a),V){let t=await R1(a.threadHandles$);if(!t)throw new C1("No active thread is available yet.",1);await t.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(G0)=>{let $0=G0 instanceof Error?G0:Error(String(G0));k.setInitError($0),await FH(G0,Z.threadId)});else F=process.hrtime.bigint(),tl4({dtwEnabled:E,hasV2TUIAccess:L}),f=await b(E?"dtw":"worker"),K("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let h=await D.configService.getLatest();if(K("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),vv3({configService:D.configService,threadService:D.threadService,config:h,useNotificationsForService:p,threadViewStates$:()=>f.threadHandles$.pipe(I4((G0)=>{if(!G0)return k0.of({});return F5(G0.thread$,G0.threadViewState$).pipe(w1(([$0,F0])=>({[$0.id]:F0})))}))}),K("runMainThread:createCliNotificationService",F),J.executeMode){VC4(D.mcpService,J.settings);let G0={userInput:V,stdinInput:G,dependencies:D,streamJson:z,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await Rj4({threadPool:f,...G0});if(await Yo($0,"execute"),Z.archive)await D.threadService.archive($0,!0),await Xo(D.threadService,$0);await D.asyncDispose(),process.exit(0)}let i=!1,c=!1;if(Z.jetbrains||Z.ide){await Lf1();let G0=await qE({jetbrainsOnly:Z.jetbrains});if(G0.length===0){if(Z.jetbrains)i=!await D.configService.get("jetbrains.skipInstall")}else if(G0.length===1){let $0=G0[0];if($0)q$.selectConfig($0)}else c=!0}F=process.hrtime.bigint();let o=La0("0.0.1774987755-gb72e09",D.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let H0=new $o0(D.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",F),V&&J.executeMode){let G0=await R1(f.threadHandles$);if(!G0)throw new C1("No active thread is available yet.",1);await G0.sendMessage({content:[{type:"text",text:V}]})}F=process.hrtime.bigint();let r=await QX0();K("runMainThread:loadSessionState",F),C.info("Loaded session state:",r);let D0={...r,launchCount:r.launchCount+1};zv((G0)=>({...G0,launchCount:G0.launchCount+1}));let L0=Z.threadId&&R7(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Hf4({codebaseContextService:D.codebaseContextService,history:new fn0,fuzzyServer:D.fuzzyServer,settingsStorage:D.settingsStorage,threadService:D.threadService,skillService:D.skillService,configService:D.configService,secretStorage:D.secretStorage,internalAPIClient:p5,threadPool:f,createSystemPromptDeps:async()=>Di4(D),ideClient:q$,mcpService:D.mcpService,toolboxService:D.toolboxService,mcpTrustHandler:H0,updateService:o,pluginPlatform:D.pluginPlatform,pluginService:D.pluginService},{initialServerStatus:D.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:D.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:i,showIdePickerHint:c,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:sl4,logFile:{path:Y},sessionState:D0,freeTierStatusPromise:m,workspace:j??null,features:A,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-31T20:13:01.309Z"},(G0)=>new it0({...G0,threadPool:G0.threadPool},($0)=>new l11({...$0,threadState:$0.threadState}))),K("runMainThread:mountApp-returned",F),d)await d}finally{}await D.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function T3(J){if(C.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)g$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7695
+ `);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;C.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Pn1({get:async(G)=>{if(G!==bh)return;try{let z=await Gi4(L61,"utf-8");return JSON.parse(z).installationID}catch{return}},set:async(G,z)=>{if(G!==bh)return;await Vi4(sH.dirname(L61),{recursive:!0}),await Lv3(L61,JSON.stringify({installationID:z},null,2),{mode:384})}},{clientType:"cli",platform:vz()});Px1(Y);let X=await SR4({...J,workspaceTrust:{current:!0,changes:kA0},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 XC4(J.mcpConfig);X=KC4(X,G)}let K=sH.dirname(X.getSettingsFilePath());EF4(sk,K);let V=await X.get("url","global");if(!V)V=o7;if(C.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!jW(V))C.info("Targeting custom Amp server",{ampURL:V});return X=wx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:jC4(await $a0(J,X))}}function cv3(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}function lv3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=sH.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?Mv3:Xn0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function iv3(){UL4();let J=cv3(process.argv),Z=lv3(process.argv,J),Q=RA4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)p0.level=0;if(jv3(C),C.info("Starting Amp CLI.",{version:"0.0.1774987755-gb72e09",buildTimestamp:"2026-03-31T20:13:01.309Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new C1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gv3(Q).parseAsync(process.argv)}LF4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await iv3().catch(FH)});async function nv3(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"),s6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7696
7696
  `);else if(!jW(J.ampURL))s6.write(`Logging in to ${new URL(J.ampURL).hostname}
7697
7697
  `);let Y=process.env.AMP_API_KEY;if(Y)s6.write(`API key found in environment variable, storing...
7698
7698
  `),await Z.set("apiKey",Y,J.ampURL),s6.write(`API key successfully stored.