@sourcegraph/amp 0.0.1774354153-gdeebb8 → 0.0.1774369119-gbb3185
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4680,7 +4680,7 @@ ${U9(Ox5)}
|
|
|
4680
4680
|
`))}await q.asyncDispose(),process.exit(0)}catch(U){await q.asyncDispose();let W=`Failed to analyze thread context: ${U instanceof Error?U.message:String(U)}`;z(W)}}var MD4=process.hrtime.bigint(),wd0=null;function AD4(){wd0=process.hrtime.bigint()}function jD4(){if(wd0===null)return null;return Number(process.hrtime.bigint()-wd0)/1e6}fX();g0();var vw4=G4(L4(),1),aY=G4(kw4(),1),xw4=G4(Jj(),1);import eZ0 from"node:fs";import $Q0 from"node:path";var yw4=Object.keys(P),ed5=$Q0.join(ZQ,"logs"),Xj=$Q0.join(ed5,"cli.log"),$c5=10485760;function Jc5(J){try{if(eZ0.statSync(J).size>$c5)eZ0.truncateSync(J,0)}catch{}}var gl,Yl0=!1,hl=null;function Zc5(J){return J instanceof Error&&J.message.includes("write after end")}function bl(J,Z,Q,Y){if(Yl0)return;try{J[Z](Q,...Y)}catch(X){if(!Zc5(X))throw X}}function fw4(J){Yl0=!1,hl=null;let Z=$Q0.resolve(J?.logFile||Xj),Q=J?.logLevel||"info";if(!yw4.includes(Q))console.warn(`Invalid log level: ${Q}. Using 'info' instead.`);try{eZ0.mkdirSync($Q0.dirname(Z),{recursive:!0})}catch(G){console.error(`Failed to create log directory: ${G}`)}Jc5(Z);let Y=aY.default.format((G)=>{for(let F of Object.keys(G)){let z=G[F];if(z instanceof Error)G[F]={name:z.name,message:z.message,stack:z.stack}}return G}),X=aY.default.format((G)=>{return G.pid=process.pid,G}),K=[new aY.default.transports.File({filename:Z}),new uw4];if(process.env.AMP_CLI_STDOUT_DEBUG==="true")K.push(new aY.default.transports.Console({level:"debug",format:aY.default.format.combine(aY.default.format.colorize(),aY.default.format.simple())}));gl=aY.default.createLogger({level:yw4.includes(Q)?Q:"info",format:aY.default.format.combine(aY.default.format.timestamp(),X(),Y(),aY.default.format.json(),aY.default.format.errors({stack:!0})),transports:K});let V=gl;ax1({error:(G,...F)=>{bl(V,"error",G,F)},warn:(G,...F)=>{bl(V,"warn",G,F)},info:(G,...F)=>{bl(V,"info",G,F)},debug:(G,...F)=>{bl(V,"debug",G,F)},audit:(G,...F)=>{let z=typeof F[0]==="object"&&F[0]!==null?{audit:!0,...F[0]}:{audit:!0};bl(V,"info",G,[z])}})}class uw4 extends xw4.default{log({message:J,...Z},Q){vw4.trace.getActiveSpan()?.addEvent(J,Z),Q()}}function XD(){if(hl)return hl;let J=gl;if(!J)return Promise.resolve();return Yl0=!0,hl=new Promise((Z)=>{let Q=!1,Y=()=>{if(!Q){if(Q=!0,gl===J)gl=void 0;Z()}};setImmediate(()=>{try{J.once("finish",Y).once("error",Y).end()}catch{Y()}}),setTimeout(Y,500)}),hl}g0();import{execFile as Qc5}from"node:child_process";import{promisify as Yc5}from"node:util";var Xc5=Yc5(Qc5),Kc5=["private","public","workspace"];function Xl0(J){return J.endsWith("/")?J.slice(0,-1):J}function Vc5(J){let Z=MZ0(J);try{let X=new URL(Z);return Xl0(`${X.host}${X.pathname}`).replace(/^\//,"")}catch{}let Q=Z.match(/^[^@]+@([^:/]+)[:/](.+)$/);if(Q?.[1]&&Q[2])return Xl0(`${Q[1]}/${Q[2]}`).replace(/\.git$/,"");let Y=Z.match(/^([^:]+):(.+)$/);if(Y?.[1]&&Y[2])return Xl0(`${Y[1]}/${Y[2]}`).replace(/\.git$/,"");return null}async function gw4(J){try{let{stdout:Z}=await Xc5("git",["remote","get-url","origin"],{cwd:J}),Q=Z.trim();if(!Q)return null;return Vc5(Q)}catch{return null}}function Gc5(J){let Z=[...Kc5];if(J?.team?.disablePrivateThreads){let Q=Z.indexOf("private");if(Q!==-1)Z.splice(Q,1)}if(J?.team?.groups&&J.team.groups.length>0)Z.push("group");return Z}function bw4(J){let Z=J?.team?.disablePrivateThreads??!1,Q=J?.team?.defaultThreadVisibility;if(!Q||Q==="private")return Z?"workspace":"private";if(Q==="thread_workspace_shared")return"workspace";if(Q==="creator_groups_fallback_private"){if(J?.team?.groups?.length)return"group";return Z?"workspace":"private"}return Z?"workspace":"private"}function Fc5(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.
|
|
4681
4681
|
`].join(""));return Error(`Group visibility is not available.
|
|
4682
4682
|
`)}function hw4(J,Z){let Y=[`Invalid ${J?`visibility for amp.defaultVisibility.${J}`:"visibility"}. `,`Must be one of: ${Z.join(", ")}.
|
|
4683
|
-
`].join("");return Error(Y)}function zc5(J,Z){return Z.includes(J)}function qc5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function mw4(J,Z,Q){if(J===void 0||J===null)return;let Y=Gc5(Z);if(typeof J!=="string")return hw4(Q,Y);if(J==="group"&&!Y.includes("group"))return Fc5(Z);if(zc5(J,Y))return J;return hw4(Q,Y)}async function Uc5(J,Z,Q){let Y=await gw4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return mw4(K,Q,Y)}async function JQ0(J,Z,Q,Y){if(Y)return Y;if(!qc5(Q))return bw4(Q);let X=await Uc5(J,Z,Q);if(X instanceof Error)return X;return X??bw4(Q)}function pw4(J,Z){return mw4(J,Z)}async function dw4(J,Z,Q){let Y=await gw4(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}}ZJ();function ZQ0(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")}b3();D4();BR0();ZJ();var z8=y.string().min(1),Vl0=y.string().regex(/^[0-9A-Za-z]{22}$/),Wc5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),ml=y.templateLiteral(["T-",Wc5]),Dc5=y.enum(["fork","handoff","mention"]),Hc5=y.enum(["parent","child"]),cw4=y.object({threadID:ml,type:Dc5,role:Hc5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),W5=y.templateLiteral(["M-",Vl0]);function ez(){return`M-${ZQ0(DE())}`}var j8=y.templateLiteral(["TU-",Vl0]);function lw4(){return`TU-${ZQ0(DE())}`}var pl=y.templateLiteral(["E-",Vl0]);function Gl0(){return`E-${ZQ0(DE())}`}var Bc5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),Nc5=y.union([y.literal("builtin"),y.object({toolbox:z8}).strict(),y.object({mcp:z8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:z8}).strict(),y.object({remote:z8}).strict()]),wc5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(z8).optional()}),iw4=y.looseObject({name:z8,description:y.string(),inputSchema:Bc5,source:Nc5,meta:wc5.optional()}),V49=y.object({id:z8,category:z8,title:z8,description:y.string().optional(),pluginName:z8}),Fl0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.openai.websocket.enabled":y.boolean().optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),nw4=y.object({settings:Fl0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),aw4=y.enum(["sandbox","local-client"]),dl=y.any().and(y.object({status:y.string()})),ow4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),$q=z8,rw4=30000,Tk=fF,Lc5=y.enum(["file","directory"]),Oc5=y.object({mtimeMs:y.number().nonnegative().optional()}),cl=y.tuple([y.string(),Lc5,Oc5.optional()]),Ec5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Vw=y.object({code:Ec5,message:y.string()}),Mc5=y.object({ok:y.literal(!0),entries:y.array(cl)}),Ac5=y.object({ok:y.literal(!1),error:Vw}),G49=y.discriminatedUnion("ok",[Mc5,Ac5]),jc5=y.object({ok:y.literal(!0),contentBase64:y.string()}),Rc5=y.object({ok:y.literal(!1),error:Vw}),F49=y.discriminatedUnion("ok",[jc5,Rc5]),Ic5=z8,zl0=y.object({key:z8,dataType:Ic5,contentBase64:y.string()}),ql0=zl0.extend({toolCallId:j8.optional(),updatedAt:y.string()}),Sk=y.looseObject({uri:fF,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),sw4=y.object({name:z8,description:y.string(),baseDir:fF,frontmatter:y.object({name:z8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),Ul0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),tw4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),kk=y.array(y.discriminatedUnion("type",[Ul0,tw4])),_k=y.record(y.string(),y.unknown()),ew4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Pc5=ew4.extend({complete:y.literal(!0),input:_k,normalizedInput:_k.optional()}),Cc5=ew4.extend({complete:y.literal(!1),input:_k,inputIncomplete:_k,inputPartialJSON:y.object({json:y.string()}),normalizedInput:_k.optional()}),_c5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Tc5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:dl,userInput:_c5.optional()}),Sc5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),kc5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),yc5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:_k}),vc5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:dl,hidden:y.boolean().optional()}),xc5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:ml.optional()}),fc5=y.object({uri:fF,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),uc5=y.union([Ul0,tw4,Tc5]),bc5=y.union([Ul0,Sc5,kc5,Pc5,Cc5,yc5]),Wl0=y.array(uc5),Dl0=y.array(bc5),hc5=y.array(vc5),Kl0=y.looseObject({line:y.number().int(),column:y.number().int()}),gc5=y.looseObject({start:Kl0,end:Kl0}),mc5=y.looseObject({name:y.string(),repositoryURL:y.string()}),pc5=y.looseObject({currentURL:y.string(),availableProjects:y.array(mc5).optional()}),dc5=y.object({treeOID:y.string(),repoRoot:y.string()}),Hl0=y.looseObject({currentlyVisibleFiles:y.array(fF),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:Kl0.optional(),cursorLocationLine:y.string().optional(),selectionRange:gc5.optional(),snapshotOIDs:y.array(dc5).optional(),aggmanContext:pc5.optional()}),Bl0=y.custom((J)=>typeof J==="string"&&E$(J)!==void 0),cc5=y.object({threadId:ml,role:y.literal("user"),content:Wl0,agentMode:Bl0.optional(),discoveredGuidanceFiles:y.array(fc5).optional(),meta:xc5.optional(),userState:Hl0.optional(),readAt:y.string().nullable().optional(),messageId:W5,createdAt:y.string().optional()}),Nl0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),lc5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),ic5=y.object({threadId:ml,role:y.literal("assistant"),content:Dl0,state:lc5.optional(),usage:Nl0.optional(),readAt:y.string().nullable().optional(),messageId:W5,createdAt:y.string().optional()}),nc5=y.object({threadId:ml,role:y.literal("info"),content:hc5,messageId:W5,createdAt:y.string().optional()}),$L4=y.discriminatedUnion("role",[cc5,ic5,nc5]),ll=y.object({workspaceRoot:fF.optional(),workingDirectory:fF.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),ac5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),oc5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),diffStat:ac5}),rc5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),QQ0=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(rc5).optional(),files:y.array(oc5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),YQ0=y.object({id:y.string(),toolCallId:j8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:j8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),sc5=y.object({type:y.literal("request"),id:z8,method:z8,params:y.unknown()}),tc5=y.object({type:y.literal("response"),id:z8,result:y.unknown().optional(),error:y.string().optional()}),ec5=y.object({type:y.literal("event"),event:z8,data:y.unknown(),span:y.string().optional()}),XQ0=y.discriminatedUnion("type",[sc5,tc5,ec5]);var $l5=y.object({type:y.literal("executor_connect"),clientId:z8,capabilities:nw4,executorType:aw4.optional()}),Jl5=y.object({type:y.literal("executor_settings_update"),settings:Fl0}),Zl5=y.object({type:y.literal("executor_tools_register"),tools:y.array(iw4)}),Ql5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(z8)}),Yl5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),Xl5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:j8}),wl0=y.object({type:y.literal("tool_progress"),toolCallId:j8,progress:y.union([ow4,y.unknown()]).optional(),parentToolCallId:j8.optional()}),Kl5=y.object({type:y.literal("executor_tool_result"),toolCallId:j8,run:dl}),Vl5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:z8,files:y.array(Sk),isLast:y.boolean(),userConfigDir:y.any().optional()}),Gl5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:j8,files:y.array(Sk),isLast:y.boolean()}),Fl5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:z8,skills:y.array(sw4),isLast:y.boolean()}),zl5=y.object({type:y.literal("executor_rollback_ack"),editId:pl,ok:y.boolean(),error:y.string().optional()}),ql5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:j8}),Ul5=y.object({type:y.literal("executor_environment_snapshot"),environment:ll}),Wl5=y.object({type:y.literal("executor_environment_update"),environment:ll}),Dl5=y.object({type:y.literal("executor_artifact_upsert"),artifact:zl0,toolCallId:j8.optional()}),Hl5=y.object({type:y.literal("executor_artifact_delete"),key:z8}),Bl5=y.object({type:y.literal("executor_git_status"),status:QQ0,toolCallId:j8.optional()}),Nl5=y.object({type:y.literal("executor_tool_approval_request"),approval:YQ0}),wl5=y.object({type:y.literal("executor_plugin_message"),message:XQ0}),Ll5=y.object({type:y.literal("client_append_user_msg"),content:kk,userState:Hl0.optional(),discoveredGuidanceFiles:y.array(Sk).optional(),agentMode:y.string().optional(),messageId:W5}),Ol5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:W5}),El5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:W5}),Ml5=y.object({type:y.literal("client_edit_message"),messageId:W5,editId:pl,content:kk,agentMode:y.string().optional()}),Al5=y.object({type:y.literal("client_mark_message_read"),messageId:W5}),jl5=y.object({type:y.literal("client_mark_message_unread"),messageId:W5}),Rl5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Il5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Pl5=y.object({endpoint:y.string().url(),keys:Il5}),Cl5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Pl5,threadURL:y.string().min(1)}),_l5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:$q,uri:Tk}),Tl5=y.object({type:y.literal("client_filesystem_read_file"),requestId:$q,uri:Tk}),Sl5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:$q,ok:y.boolean(),entries:y.array(cl).optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),kl5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:$q,ok:y.boolean(),contentBase64:y.string().optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),yl5=y.object({type:y.literal("client_resume"),version:y.number()}),vl5=y.object({type:y.literal("client_retry")}),xl5=y.object({type:y.literal("client_cancel")}),fl5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:dl,hidden:y.boolean().optional()}),ul5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),bl5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),W49=y.enum(["agg-man"]),JL4=y.discriminatedUnion("type",[$l5,Jl5,Zl5,Ql5,Yl5,Xl5,wl0,Kl5,Vl5,Gl5,Fl5,zl5,ql5,Ul5,Wl5,Dl5,Hl5,Bl5,Nl5,wl5,Ll5,Ol5,El5,Ml5,Al5,jl5,Rl5,Cl5,_l5,Tl5,Sl5,kl5,yl5,vl5,xl5,fl5,ul5,bl5]);ZJ();ZJ();var hl5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),gl5=y.enum(["start","generating","tool_use","complete","error"]),ml5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),pl5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),dl5=y.enum(["starting","running","failed"]),cl5=y.object({cutMessageId:W5,createdAt:y.string()}),ZL4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:W5,content:kk,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Sk).optional(),createdAt:y.string().optional()})}),ll5=y.object({type:y.literal("agent_state"),state:hl5,messageId:W5.optional()}),il5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),nl5=y.object({type:y.literal("error_set"),seq:y.number(),error:ml5}),al5=y.object({type:y.literal("error_cleared"),seq:y.number()}),ol5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:W5.optional()}),rl5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),sl5=y.object({type:y.literal("retry_started")}),tl5=y.object({type:y.literal("retry_cancelled")}),el5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),$i5=y.object({type:y.literal("tool_lease"),toolCallId:j8,toolName:y.string(),args:y.unknown(),messageId:W5,parentToolCallId:j8.optional()}),Ji5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:$q,uri:Tk}),Zi5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:$q,uri:Tk}),Qi5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:$q,ok:y.boolean(),entries:y.array(cl).optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),Yi5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:$q,ok:y.boolean(),contentBase64:y.string().optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Xi5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(YQ0)}),Ki5=y.object({type:y.literal("executor_rollback_request"),editId:pl,messageId:W5,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(j8)}),Vi5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:j8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),Gi5=y.object({type:y.literal("plugin_message"),message:XQ0}),Fi5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional()}).optional()}),zi5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),qi5=y.object({type:y.literal("delta"),messageId:W5,role:y.literal("assistant"),blocks:Dl0.optional(),state:gl5,usage:Nl0.optional(),parentToolCallId:j8.optional()}),Ui5=y.object({type:y.literal("delta"),messageId:W5,role:y.literal("user"),blocks:Wl0.optional(),state:y.literal("complete"),parentToolCallId:j8.optional()}),Wi5=y.discriminatedUnion("role",[qi5,Ui5]),Di5=y.object({type:y.literal("queued_messages"),messages:y.array(ZL4)}),Hi5=y.object({type:y.literal("queued_message_added"),message:ZL4,seq:y.number()}),Bi5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:W5,seq:y.number()}),Ni5=y.object({type:y.literal("message_added"),message:$L4,seq:y.number(),parentToolUseId:z8.optional()}),wi5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),Li5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:W5,content:kk,truncateToMessageId:W5,reason:y.literal("message_edit"),agentMode:Bl0.optional()}),Oi5=y.looseObject({type:y.literal("cf_agent_state")}),Ei5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),Mi5=y.looseObject({type:y.literal("cf_agent_identity")}),Ai5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(pl5),hasExecutor:y.boolean().optional()}),ji5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:dl5,message:y.string().optional(),executorId:y.string().optional()}),Ri5=y.object({type:y.literal("environment_update"),environment:ll}),Ii5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(ql0)}),Pi5=y.object({type:y.literal("artifact_upserted"),artifact:ql0}),Ci5=y.object({type:y.literal("artifact_deleted"),key:z8}),_i5=y.object({type:y.literal("git_status"),status:QQ0,toolCallId:j8.optional()}),Ti5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),Si5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),ki5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(cw4)}),yi5=y.object({type:y.literal("compaction_started")}),vi5=y.object({type:y.literal("compaction_complete"),cutMessageId:W5}),xi5=y.object({type:y.literal("compaction_records"),records:y.array(cl5)}),KQ0=y.discriminatedUnion("type",[ll5,il5,nl5,al5,ol5,rl5,sl5,tl5,el5,$i5,Ji5,Zi5,Qi5,Yi5,Xi5,Ki5,Vi5,Gi5,Fi5,wl0,zi5,Wi5,Di5,Hi5,Bi5,Ni5,wi5,Li5,Oi5,Ei5,Mi5,Ai5,ji5,Ri5,Ii5,Pi5,Ci5,_i5,Ti5,Si5,ki5,yi5,vi5,xi5]);var Ll0=(J)=>y.codec(y.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),QL4=Ll0(JL4),fi5=y.union([KQ0,y.array(KQ0)]),YL4=Ll0(KQ0),XL4=Ll0(fi5);D4();function KL4(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=c1(Y1.parse(V.uri))}catch{if(Y)return null;continue}let F={uri:G};if(typeof V.content==="string")F.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))F.lineCount=V.lineCount;if(typeof V.hash==="string")F.hash=V.hash;X.push(F)}return X}var VL4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Ol0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function ui5(J){return J.replace(/\s+/g," ").trim()}function bi5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function hi5(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 Ol0(JSON.stringify(J),120)}catch{return Ol0(String(J),120)}}function GL4(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 gi5(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=GL4(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 FL4(J){for(let Z of J){let Q=gi5(Z);if(Q)return Q}return null}function mi5(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"||GL4(Q.path)==="type")})}function pi5(J,Z){let Q=FL4(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 zL4(J,Z,Q){let Y=bi5(Z),X=(()=>{let z=ui5(J);if(z.length===0)return null;return Ol0(z,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let z=FL4(Y);return{failureType:"invalid_json",summary:z?`malformed JSON: ${z}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let G=V.type,F=hi5(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:X,issues:Y};if(mi5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:F,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:pi5(G,Y),messageType:G,typePreview:F,payloadPreview:X,issues:Y}}function il(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 qL4(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}}ZJ();var UL4="[dtw-parse-error]",Ml0="dtw-parse-error",di5=y.object({kind:y.literal(Ml0),failureType:y.enum(VL4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),ci5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function El0(J){return{kind:Ml0,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 WL4(J){let Z=El0(J);return JSON.stringify(Z)}function DL4(J,Z){let Q=zL4(J,Z);return WL4({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 Al0(J){let Z=J.startsWith(UL4)?J.slice(UL4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=di5.safeParse(Q);if(Y.success)return El0(Y.data);let X=ci5.safeParse(Q);if(X.success)return El0(X.data);return null}w1();class jl0 extends Error{constructor(J){super(J);this.name="DTWError"}}class S9 extends jl0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}w1();var li5=1000,ii5=30000,ni5=5,ai5=30000,oi5=200,ri5=30000,HL4=["online","focus","pageshow","keydown","pointerdown"],BL4=["visibilitychange"];function Il0(){return globalThis}function wL4(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 NL4(){return wL4(Il0().window)}function Rl0(){let J=Il0().document;if(!wL4(J))return null;return J}function si5(){let J=Il0().navigator;if(!J||typeof J!=="object")return null;return J}function ti5(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 VQ0(J){return!!(J.apiKey&&J.WebSocketClass)}function Pl0(J){if(VQ0(J))return"one-step";return"two-step"}class Cl0{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 X4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new X4([]);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??li5,maxReconnectDelayMs:J.maxReconnectDelayMs??ii5,maxReconnectAttempts:J.maxReconnectAttempts??ni5,pingIntervalMs:J.pingIntervalMs??ai5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${Pl0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=oi5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new S9("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(VQ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new S9("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 S9("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=${ti5(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 S9(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new S9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let G="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new S9(`WebSocket connection failed: ${G}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new S9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K)})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=NL4(),Z=Rl0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=si5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Rl0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=NL4(),Z=Rl0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of HL4)J?.addEventListener(Y,Q);for(let Y of BL4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of HL4)J?.removeEventListener(Y,Q);for(let Y of BL4)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},ri5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function ei5(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 Jq extends Cl0{deltaSubject=new e1;errorSubject=new e1;errorEventSubject=new e1;cancelledSubject=new e1;agentStateSubject=new e1;messageAddedSubject=new e1;editRejectedSubject=new e1;messageEditedSubject=new e1;queuedMessagesSubject=new e1;retrySubject=new e1;toolLeaseSubject=new e1;toolLeaseRevokedSubject=new e1;toolApprovalQueueSubject=new e1;executorToolApprovalResponseSubject=new e1;toolProgressSubject=new e1;executorErrorSubject=new e1;executorConnectedSubject=new e1;executorRollbackRequestSubject=new e1;observersSubject=new e1;executorStatusSubject=new e1;environmentUpdateSubject=new e1;artifactsSubject=new e1;gitStatusSubject=new e1;threadTitleSubject=new e1;threadStatusSubject=new e1;threadRelationshipsSubject=new e1;compactionSubject=new e1;compactionRecordsSubject=new e1;pluginMessageSubject=new e1;fileSystemReadDirectoryRequestSubject=new e1;fileSystemReadFileRequestSubject=new e1;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}gitStatuses(){return this.gitStatusSubject}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.gitStatusSubject.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??ez();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 S9("Transport is disposed");if(!this.hasOpenSocket())throw new S9("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;F.unsubscribe(),z.unsubscribe(),q()},F=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))}}),z=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=il(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})}sendExecutorGitStatus(J,Z){this.send({type:"executor_git_status",status:J,toolCallId:Z})}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 S9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new S9(`Filesystem request timed out: ${Z}`))},rw4);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(ei5(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 S9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new S9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=XL4.safeDecode(J);if(!Z.success){let Y=YL4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:DL4(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"git_status":this.gitStatusSubject.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(QL4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new S9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function $n5(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 Jn5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function Zn5(J){if($n5(J))return J.queuedMessage.messageId;if(Jn5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function _l0(J,Z,Q={}){let Y=Q.getQueuedMessageId??Zn5;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 Qn5=15000;function Yn5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let F of K)F.unsubscribe()};return{promise:new Promise((F,z)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),F(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),z(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),z(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),z(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),z(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function Tl0(J){let Z=J.workerUrl??p7(J.ampURL),Q=new Jq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??Qn5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=Yn5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as Xn5}from"node:fs";import{mkdir as Kn5,readdir as Vn5,readFile as Gn5}from"node:fs/promises";import{createServer as Fn5}from"node:http";import Sl0 from"node:path";function LL4(J){return J instanceof Error?J.message:String(J)}function Kj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function zn5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function OL4(J,Z){let Q=Sl0.basename(Z),Y=Q.endsWith(".json")?Sl0.join(J,Q):Sl0.join(J,`${Q}.json`),X=await Gn5(Y,"utf-8");return JSON.parse(X)}async function qn5(J){let Z=await Vn5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await OL4(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 Un5(){return`<!doctype html>
|
|
4683
|
+
`].join("");return Error(Y)}function zc5(J,Z){return Z.includes(J)}function qc5(J){return J?.team?.billingMode==="enterprise"||J?.team?.billingMode==="enterprise.selfserve"}function mw4(J,Z,Q){if(J===void 0||J===null)return;let Y=Gc5(Z);if(typeof J!=="string")return hw4(Q,Y);if(J==="group"&&!Y.includes("group"))return Fc5(Z);if(zc5(J,Y))return J;return hw4(Q,Y)}async function Uc5(J,Z,Q){let Y=await gw4(Z);if(!Y)return;let X;try{X=await J.get("defaultVisibility")}catch(V){P.warn("Failed to read defaultVisibility setting",{error:V});return}let K=X?.[Y];return mw4(K,Q,Y)}async function JQ0(J,Z,Q,Y){if(Y)return Y;if(!qc5(Q))return bw4(Q);let X=await Uc5(J,Z,Q);if(X instanceof Error)return X;return X??bw4(Q)}function pw4(J,Z){return mw4(J,Z)}async function dw4(J,Z,Q){let Y=await gw4(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}}ZJ();function ZQ0(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")}b3();D4();BR0();ZJ();var z8=y.string().min(1),Vl0=y.string().regex(/^[0-9A-Za-z]{22}$/),Wc5=y.templateLiteral([y.string().regex(/^[0-9a-f]{8}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{4}$/),"-",y.string().regex(/^[0-9a-f]{12}$/)]),ml=y.templateLiteral(["T-",Wc5]),Dc5=y.enum(["fork","handoff","mention"]),Hc5=y.enum(["parent","child"]),cw4=y.object({threadID:ml,type:Dc5,role:Hc5,messageIndex:y.number().int().nonnegative().optional(),blockIndex:y.number().int().nonnegative().optional(),createdAt:y.number().int().nonnegative(),comment:y.string().optional()}),W5=y.templateLiteral(["M-",Vl0]);function ez(){return`M-${ZQ0(DE())}`}var j8=y.templateLiteral(["TU-",Vl0]);function lw4(){return`TU-${ZQ0(DE())}`}var pl=y.templateLiteral(["E-",Vl0]);function Gl0(){return`E-${ZQ0(DE())}`}var Bc5=y.looseObject({type:y.literal("object"),properties:y.record(y.string(),y.unknown()),required:y.array(y.string()).optional(),additionalProperties:y.boolean().optional()}),Nc5=y.union([y.literal("builtin"),y.object({toolbox:z8}).strict(),y.object({mcp:z8,target:y.enum(["global","workspace","flag","default"]).optional()}).strict(),y.object({plugin:z8}).strict(),y.object({remote:z8}).strict()]),wc5=y.object({serial:y.boolean().optional(),deferred:y.boolean().optional(),skillNames:y.array(z8).optional()}),iw4=y.looseObject({name:z8,description:y.string(),inputSchema:Bc5,source:Nc5,meta:wc5.optional()}),V49=y.object({id:z8,category:z8,title:z8,description:y.string().optional(),pluginName:z8}),Fl0=y.strictObject({"agent.deepReasoningEffort":y.enum(["medium","high","xhigh"]).optional(),"agent.skipTitleGenerationIfMessageContains":y.array(y.string()).optional(),"anthropic.thinking.enabled":y.boolean().optional(),"anthropic.interleavedThinking.enabled":y.boolean().optional(),"anthropic.temperature":y.number().optional(),"anthropic.effort":y.enum(["low","medium","high","max"]).optional(),"anthropic.speed":y.enum(["standard","fast"]).optional(),"anthropic.provider":y.enum(["anthropic","vertex"]).optional(),"openai.speed":y.enum(["standard","fast"]).optional(),"internal.compactionThresholdPercent":y.number().min(0).max(100).optional(),"internal.model":y.union([y.string(),y.record(y.string(),y.string())]).optional(),"internal.openai.websocket.enabled":y.boolean().optional(),"internal.oracleReasoningEffort":y.enum(["none","minimal","low","medium","high","xhigh"]).optional(),"gemini.thinkingLevel":y.enum(["minimal","low","medium","high"]).optional(),"tools.disable":y.array(y.string()).optional(),"tools.enable":y.array(y.string()).optional()}),nw4=y.object({settings:Fl0,workspaceId:y.string(),workingDirectory:y.string(),environment:y.object({os:y.enum(["darwin","linux","windows"]),hasDocker:y.boolean().optional(),hasBrowser:y.boolean().optional()}).strict(),tags:y.array(y.string())}).strict(),aw4=y.enum(["sandbox","local-client"]),dl=y.any().and(y.object({status:y.string()})),ow4=y.discriminatedUnion("type",[y.object({type:y.literal("delta"),blocks:y.array(y.unknown()).optional(),state:y.enum(["start","generating","tool_use","complete","error"])}),y.object({type:y.literal("snapshot"),value:y.unknown()})]),$q=z8,rw4=30000,Tk=fF,Lc5=y.enum(["file","directory"]),Oc5=y.object({mtimeMs:y.number().nonnegative().optional()}),cl=y.tuple([y.string(),Lc5,Oc5.optional()]),Ec5=y.enum(["INVALID_URI","EXECUTOR_NOT_CONNECTED","NOT_FOUND","NOT_DIRECTORY","IS_DIRECTORY","ACCESS_DENIED","INTERNAL_ERROR"]),Vw=y.object({code:Ec5,message:y.string()}),Mc5=y.object({ok:y.literal(!0),entries:y.array(cl)}),Ac5=y.object({ok:y.literal(!1),error:Vw}),G49=y.discriminatedUnion("ok",[Mc5,Ac5]),jc5=y.object({ok:y.literal(!0),contentBase64:y.string()}),Rc5=y.object({ok:y.literal(!1),error:Vw}),F49=y.discriminatedUnion("ok",[jc5,Rc5]),Ic5=z8,zl0=y.object({key:z8,dataType:Ic5,contentBase64:y.string()}),ql0=zl0.extend({toolCallId:j8.optional(),updatedAt:y.string()}),Sk=y.looseObject({uri:fF,content:y.string().optional(),lineCount:y.int().optional(),hash:y.string().optional()}),sw4=y.object({name:z8,description:y.string(),baseDir:fF,frontmatter:y.object({name:z8,description:y.string()}).catchall(y.unknown()),files:y.array(y.string()).optional()}),Ul0=y.object({type:y.literal("text"),text:y.string(),hidden:y.boolean().optional()}),tw4=y.looseObject({type:y.literal("image"),source:y.discriminatedUnion("type",[y.object({type:y.literal("base64"),mediaType:y.literal(["image/jpeg","image/png","image/gif","image/webp"]),data:y.string()}),y.object({type:y.literal("url"),url:y.string()})]),sourcePath:y.string()}),kk=y.array(y.discriminatedUnion("type",[Ul0,tw4])),_k=y.record(y.string(),y.unknown()),ew4=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),normalizedName:y.string().optional(),metadata:y.record(y.string(),y.unknown()).optional()}),Pc5=ew4.extend({complete:y.literal(!0),input:_k,normalizedInput:_k.optional()}),Cc5=ew4.extend({complete:y.literal(!1),input:_k,inputIncomplete:_k,inputPartialJSON:y.object({json:y.string()}),normalizedInput:_k.optional()}),_c5=y.object({accepted:y.boolean(),askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}),Tc5=y.object({type:y.literal("tool_result"),toolUseID:y.string().min(1),run:dl,userInput:_c5.optional()}),Sc5=y.object({type:y.literal("thinking"),thinking:y.string(),signature:y.string()}),kc5=y.object({type:y.literal("redacted_thinking"),data:y.string()}),yc5=y.object({type:y.literal("server_tool_use"),id:y.string().min(1),name:y.string().min(1),input:_k}),vc5=y.object({type:y.literal("manual_bash_invocation"),args:y.object({cmd:y.string(),args:y.array(y.string()).readonly().optional(),cwd:y.string().optional()}),toolRun:dl,hidden:y.boolean().optional()}),xc5=y.object({sentAt:y.number().int().nonnegative().optional(),fromAggman:y.boolean().optional(),fromExecutorThreadID:ml.optional()}),fc5=y.object({uri:fF,lineCount:y.number().int().nonnegative(),content:y.string().optional()}),uc5=y.union([Ul0,tw4,Tc5]),bc5=y.union([Ul0,Sc5,kc5,Pc5,Cc5,yc5]),Wl0=y.array(uc5),Dl0=y.array(bc5),hc5=y.array(vc5),Kl0=y.looseObject({line:y.number().int(),column:y.number().int()}),gc5=y.looseObject({start:Kl0,end:Kl0}),mc5=y.looseObject({name:y.string(),repositoryURL:y.string()}),pc5=y.looseObject({currentURL:y.string(),availableProjects:y.array(mc5).optional()}),dc5=y.object({treeOID:y.string(),repoRoot:y.string()}),Hl0=y.looseObject({currentlyVisibleFiles:y.array(fF),runningTerminalCommands:y.array(y.string()).optional(),activeEditor:y.any().optional(),cursorLocation:Kl0.optional(),cursorLocationLine:y.string().optional(),selectionRange:gc5.optional(),snapshotOIDs:y.array(dc5).optional(),aggmanContext:pc5.optional()}),Bl0=y.custom((J)=>typeof J==="string"&&E$(J)!==void 0),cc5=y.object({threadId:ml,role:y.literal("user"),content:Wl0,agentMode:Bl0.optional(),discoveredGuidanceFiles:y.array(fc5).optional(),meta:xc5.optional(),userState:Hl0.optional(),readAt:y.string().nullable().optional(),messageId:W5,createdAt:y.string().optional()}),Nl0=y.object({model:y.string().optional(),maxInputTokens:y.number(),inputTokens:y.number(),outputTokens:y.number(),cacheCreationInputTokens:y.number().nullable(),cacheReadInputTokens:y.number().nullable(),totalInputTokens:y.number(),thinkingBudget:y.number().optional(),timestamp:y.string().optional()}),lc5=y.union([y.object({type:y.literal("complete")}),y.object({type:y.literal("cancelled")})]),ic5=y.object({threadId:ml,role:y.literal("assistant"),content:Dl0,state:lc5.optional(),usage:Nl0.optional(),readAt:y.string().nullable().optional(),messageId:W5,createdAt:y.string().optional()}),nc5=y.object({threadId:ml,role:y.literal("info"),content:hc5,messageId:W5,createdAt:y.string().optional()}),$L4=y.discriminatedUnion("role",[cc5,ic5,nc5]),ll=y.object({workspaceRoot:fF.optional(),workingDirectory:fF.optional(),rootDirectoryListing:y.string().nullable().optional(),trees:y.array(y.any()).optional(),platform:y.any().optional(),tags:y.array(y.string()).optional(),updatedAt:y.string().optional()}),ac5=y.object({added:y.number().int().nonnegative(),deleted:y.number().int().nonnegative(),changed:y.number().int().nonnegative()}),oc5=y.object({path:y.string(),previousPath:y.string().optional(),changeType:y.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","untracked"]),created:y.boolean(),diff:y.string(),fullFileDiff:y.string().optional(),diffStat:ac5}),rc5=y.object({hash:y.string(),shortHash:y.string(),subject:y.string()}),QQ0=y.object({provider:y.literal("git"),capturedAt:y.number(),available:y.boolean(),repositoryRoot:y.string().nullable(),repositoryName:y.string().nullable(),branch:y.string().nullable(),head:y.string().nullable(),baseRef:y.string().nullable().optional(),baseRefHead:y.string().nullable().optional(),aheadCount:y.number().int().nonnegative().optional(),behindCount:y.number().int().nonnegative().optional(),aheadCommits:y.array(rc5).optional(),files:y.array(oc5),unavailableReason:y.string().optional(),unchanged:y.boolean().optional()}),YQ0=y.object({id:y.string(),toolCallId:j8,toolName:y.string(),args:y.record(y.string(),y.unknown()),reason:y.string().optional(),toAllow:y.array(y.string()).optional(),context:y.enum(["thread","subagent"]),subagentToolName:y.string().optional(),parentToolCallId:j8.optional(),timestamp:y.number(),matchedRule:y.object({tool:y.string(),action:y.string(),matches:y.record(y.string(),y.unknown()).optional()}).optional(),ruleSource:y.enum(["user","built-in"]).optional()}),sc5=y.object({type:y.literal("request"),id:z8,method:z8,params:y.unknown()}),tc5=y.object({type:y.literal("response"),id:z8,result:y.unknown().optional(),error:y.string().optional()}),ec5=y.object({type:y.literal("event"),event:z8,data:y.unknown(),span:y.string().optional()}),XQ0=y.discriminatedUnion("type",[sc5,tc5,ec5]);var $l5=y.object({type:y.literal("executor_connect"),clientId:z8,capabilities:nw4,executorType:aw4.optional()}),Jl5=y.object({type:y.literal("executor_settings_update"),settings:Fl0}),Zl5=y.object({type:y.literal("executor_tools_register"),tools:y.array(iw4)}),Ql5=y.object({type:y.literal("executor_tools_unregister"),toolNames:y.array(z8)}),Yl5=y.object({type:y.literal("executor_tools_bootstrap_complete"),ok:y.boolean(),error:y.string().optional()}),Xl5=y.object({type:y.literal("executor_tool_lease_ack"),toolCallId:j8}),wl0=y.object({type:y.literal("tool_progress"),toolCallId:j8,progress:y.union([ow4,y.unknown()]).optional(),parentToolCallId:j8.optional()}),Kl5=y.object({type:y.literal("executor_tool_result"),toolCallId:j8,run:dl}),Vl5=y.object({type:y.literal("executor_guidance_snapshot"),snapshotId:z8,files:y.array(Sk),isLast:y.boolean(),userConfigDir:y.any().optional()}),Gl5=y.object({type:y.literal("executor_guidance_discovery"),toolCallId:j8,files:y.array(Sk),isLast:y.boolean()}),Fl5=y.object({type:y.literal("executor_skill_snapshot"),snapshotId:z8,skills:y.array(sw4),isLast:y.boolean()}),zl5=y.object({type:y.literal("executor_rollback_ack"),editId:pl,ok:y.boolean(),error:y.string().optional()}),ql5=y.object({type:y.literal("executor_revocation_ack"),toolCallId:j8}),Ul5=y.object({type:y.literal("executor_environment_snapshot"),environment:ll}),Wl5=y.object({type:y.literal("executor_environment_update"),environment:ll}),Dl5=y.object({type:y.literal("executor_artifact_upsert"),artifact:zl0,toolCallId:j8.optional()}),Hl5=y.object({type:y.literal("executor_artifact_delete"),key:z8}),Bl5=y.object({type:y.literal("executor_git_status"),status:QQ0,toolCallId:j8.optional()}),Nl5=y.object({type:y.literal("executor_tool_approval_request"),approval:YQ0}),wl5=y.object({type:y.literal("executor_plugin_message"),message:XQ0}),Ll5=y.object({type:y.literal("client_append_user_msg"),content:kk,userState:Hl0.optional(),discoveredGuidanceFiles:y.array(Sk).optional(),agentMode:y.string().optional(),messageId:W5}),Ol5=y.object({type:y.literal("client_remove_queued_msg"),queuedMessageId:W5}),El5=y.object({type:y.literal("client_interrupt_queued_msg"),queuedMessageId:W5}),Ml5=y.object({type:y.literal("client_edit_message"),messageId:W5,editId:pl,content:kk,agentMode:y.string().optional()}),Al5=y.object({type:y.literal("client_mark_message_read"),messageId:W5}),jl5=y.object({type:y.literal("client_mark_message_unread"),messageId:W5}),Rl5=y.object({type:y.literal("client_set_thread_title"),title:y.string().trim().min(1).max(256)}),Il5=y.object({auth:y.string().min(1),p256dh:y.string().min(1)}),Pl5=y.object({endpoint:y.string().url(),keys:Il5}),Cl5=y.object({type:y.literal("client_upsert_notification_subscription"),subscription:Pl5,threadURL:y.string().min(1)}),_l5=y.object({type:y.literal("client_filesystem_read_directory"),requestId:$q,uri:Tk}),Tl5=y.object({type:y.literal("client_filesystem_read_file"),requestId:$q,uri:Tk}),Sl5=y.object({type:y.literal("executor_filesystem_read_directory_result"),requestId:$q,ok:y.boolean(),entries:y.array(cl).optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),kl5=y.object({type:y.literal("executor_filesystem_read_file_result"),requestId:$q,ok:y.boolean(),contentBase64:y.string().optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),yl5=y.object({type:y.literal("client_resume"),version:y.number()}),vl5=y.object({type:y.literal("client_retry")}),xl5=y.object({type:y.literal("client_cancel")}),fl5=y.object({type:y.literal("client_append_manual_bash_invocation"),args:y.object({cmd:y.string().trim().min(1,"cmd must contain at least one non-whitespace character"),args:y.array(y.string()).optional(),cwd:y.string().optional()}),run:dl,hidden:y.boolean().optional()}),ul5=y.object({type:y.literal("client_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),bl5=y.object({type:y.literal("client_spawn_executor"),requestId:y.string().optional(),repositoryURL:y.string().optional(),projectID:y.uuid().optional(),additionalRepositories:y.array(y.object({name:y.string(),url:y.string()})).optional()}),W49=y.enum(["agg-man"]),JL4=y.discriminatedUnion("type",[$l5,Jl5,Zl5,Ql5,Yl5,Xl5,wl0,Kl5,Vl5,Gl5,Fl5,zl5,ql5,Ul5,Wl5,Dl5,Hl5,Bl5,Nl5,wl5,Ll5,Ol5,El5,Ml5,Al5,jl5,Rl5,Cl5,_l5,Tl5,Sl5,kl5,yl5,vl5,xl5,fl5,ul5,bl5]);ZJ();ZJ();var hl5=y.enum(["idle","working","streaming","tool_use","running_tools","awaiting_approval","error"]),gl5=y.enum(["start","generating","tool_use","complete","error"]),ml5=y.object({message:y.string(),code:y.string().optional(),stack:y.string().optional(),retryAt:y.number().optional(),attempt:y.number().optional()}),pl5=y.object({userId:y.string(),name:y.string(),avatarURL:y.string().optional()}),dl5=y.enum(["starting","running","failed"]),cl5=y.object({cutMessageId:W5,createdAt:y.string()}),ZL4=y.object({interrupt:y.boolean(),queuedMessage:y.object({role:y.literal("user"),messageId:W5,content:kk,userState:y.any().optional(),discoveredGuidanceFiles:y.array(Sk).optional(),createdAt:y.string().optional()})}),ll5=y.object({type:y.literal("agent_state"),state:hl5,messageId:W5.optional()}),il5=y.object({type:y.literal("error"),message:y.string(),code:y.enum(["ACCESS_DENIED","CONNECTION_ERROR","MAX_RECONNECT_EXCEEDED","MESSAGE_ERROR","LOOP_RUNNING","NO_THREAD_ID","NO_ERROR","INVALID_MESSAGE","PARSE_ERROR","UNKNOWN_TYPE","INTERNAL_ERROR"]).optional()}),nl5=y.object({type:y.literal("error_set"),seq:y.number(),error:ml5}),al5=y.object({type:y.literal("error_cleared"),seq:y.number()}),ol5=y.object({type:y.literal("cancelled"),seq:y.number(),messageId:W5.optional()}),rl5=y.object({type:y.literal("retry_scheduled"),retryAt:y.number(),attempt:y.number(),maxAttempts:y.number(),reason:y.string()}),sl5=y.object({type:y.literal("retry_started")}),tl5=y.object({type:y.literal("retry_cancelled")}),el5=y.object({type:y.literal("executor_connected"),executorId:y.string(),registeredToolCount:y.number(),rejectedTools:y.array(y.object({name:y.string(),reason:y.string()})).optional()}),$i5=y.object({type:y.literal("tool_lease"),toolCallId:j8,toolName:y.string(),args:y.unknown(),messageId:W5,parentToolCallId:j8.optional()}),Ji5=y.object({type:y.literal("executor_filesystem_read_directory"),requestId:$q,uri:Tk}),Zi5=y.object({type:y.literal("executor_filesystem_read_file"),requestId:$q,uri:Tk}),Qi5=y.object({type:y.literal("client_filesystem_read_directory_result"),requestId:$q,ok:y.boolean(),entries:y.array(cl).optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(!J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.entries)Z.addIssue({code:y.ZodIssueCode.custom,message:"entries must not be present when ok is false"})}),Yi5=y.object({type:y.literal("client_filesystem_read_file_result"),requestId:$q,ok:y.boolean(),contentBase64:y.string().optional(),error:Vw.optional()}).superRefine((J,Z)=>{if(J.ok){if(J.contentBase64===void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 is required when ok is true"});if(J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error must not be present when ok is true"});return}if(!J.error)Z.addIssue({code:y.ZodIssueCode.custom,message:"error is required when ok is false"});if(J.contentBase64!==void 0)Z.addIssue({code:y.ZodIssueCode.custom,message:"contentBase64 must not be present when ok is false"})}),Xi5=y.object({type:y.literal("tool_approval_queue"),approvals:y.array(YQ0)}),Ki5=y.object({type:y.literal("executor_rollback_request"),editId:pl,messageId:W5,reason:y.literal("message_edit"),toolUseIdsToRevert:y.array(j8)}),Vi5=y.object({type:y.literal("executor_tool_lease_revoked"),toolCallId:j8,reason:y.enum(["executor_disconnected","reassigned","user_canceled"])}),Gi5=y.object({type:y.literal("plugin_message"),message:XQ0}),Fi5=y.object({type:y.literal("executor_tool_approval_response"),toolCallId:j8,accepted:y.boolean(),input:y.object({askAnswers:y.record(y.string(),y.string()).optional(),denyFeedback:y.string().optional()}).optional()}),zi5=y.object({type:y.literal("executor_error"),message:y.string(),code:y.enum(["NOT_CONNECTED","ACCESS_DENIED","INVALID_MESSAGE","TOOL_NOT_FOUND","LEASE_NOT_FOUND","DUPLICATE_TOOL","INTERNAL_ERROR"])}),qi5=y.object({type:y.literal("delta"),messageId:W5,role:y.literal("assistant"),blocks:Dl0.optional(),state:gl5,usage:Nl0.optional(),parentToolCallId:j8.optional()}),Ui5=y.object({type:y.literal("delta"),messageId:W5,role:y.literal("user"),blocks:Wl0.optional(),state:y.literal("complete"),parentToolCallId:j8.optional()}),Wi5=y.discriminatedUnion("role",[qi5,Ui5]),Di5=y.object({type:y.literal("queued_messages"),messages:y.array(ZL4)}),Hi5=y.object({type:y.literal("queued_message_added"),message:ZL4,seq:y.number()}),Bi5=y.object({type:y.literal("queued_message_removed"),queuedMessageId:W5,seq:y.number()}),Ni5=y.object({type:y.literal("message_added"),message:$L4,seq:y.number(),parentToolUseId:z8.optional()}),wi5=y.object({type:y.literal("edit_rejected"),editId:y.string(),message:y.string()}),Li5=y.object({type:y.literal("message_edited"),seq:y.number(),editId:y.string(),messageId:W5,content:kk,truncateToMessageId:W5,reason:y.literal("message_edit"),agentMode:Bl0.optional()}),Oi5=y.looseObject({type:y.literal("cf_agent_state")}),Ei5=y.looseObject({type:y.literal("cf_agent_mcp_servers")}),Mi5=y.looseObject({type:y.literal("cf_agent_identity")}),Ai5=y.object({type:y.literal("observers"),count:y.number(),observers:y.array(pl5),hasExecutor:y.boolean().optional()}),ji5=y.object({type:y.literal("executor_status"),spawnId:y.string(),status:dl5,message:y.string().optional(),executorId:y.string().optional()}),Ri5=y.object({type:y.literal("environment_update"),environment:ll}),Ii5=y.object({type:y.literal("artifacts_snapshot"),artifacts:y.array(ql0)}),Pi5=y.object({type:y.literal("artifact_upserted"),artifact:ql0}),Ci5=y.object({type:y.literal("artifact_deleted"),key:z8}),_i5=y.object({type:y.literal("git_status"),status:QQ0,toolCallId:j8.optional()}),Ti5=y.object({type:y.literal("thread_title"),title:y.string().nullable()}),Si5=y.object({type:y.literal("thread_status"),status:y.union([y.literal("merging"),y.literal("merged"),y.null()])}),ki5=y.object({type:y.literal("thread_relationships"),seq:y.number(),relationships:y.array(cw4)}),yi5=y.object({type:y.literal("compaction_started")}),vi5=y.object({type:y.literal("compaction_complete"),cutMessageId:W5}),xi5=y.object({type:y.literal("compaction_records"),records:y.array(cl5)}),KQ0=y.discriminatedUnion("type",[ll5,il5,nl5,al5,ol5,rl5,sl5,tl5,el5,$i5,Ji5,Zi5,Qi5,Yi5,Xi5,Ki5,Vi5,Gi5,Fi5,wl0,zi5,Wi5,Di5,Hi5,Bi5,Ni5,wi5,Li5,Oi5,Ei5,Mi5,Ai5,ji5,Ri5,Ii5,Pi5,Ci5,_i5,Ti5,Si5,ki5,yi5,vi5,xi5]);var Ll0=(J)=>y.codec(y.string(),J,{decode:(Z,Q)=>{try{return JSON.parse(Z)}catch(Y){return Q.issues.push({code:"invalid_format",format:"json",input:Z,message:Y.message}),y.NEVER}},encode:(Z)=>JSON.stringify(Z)}),QL4=Ll0(JL4),fi5=y.union([KQ0,y.array(KQ0)]),YL4=Ll0(KQ0),XL4=Ll0(fi5);D4();function KL4(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=c1(Y1.parse(V.uri))}catch{if(Y)return null;continue}let F={uri:G};if(typeof V.content==="string")F.content=V.content;if(typeof V.lineCount==="number"&&Number.isFinite(V.lineCount))F.lineCount=V.lineCount;if(typeof V.hash==="string")F.hash=V.hash;X.push(F)}return X}var VL4=["invalid_json","missing_type","invalid_type","unknown_type","invalid_shape"];function Ol0(J,Z){if(J.length<=Z)return J;return`${J.slice(0,Z)}...<truncated>`}function ui5(J){return J.replace(/\s+/g," ").trim()}function bi5(J){if(!J||typeof J!=="object")return[];let Z=J.issues;return Array.isArray(Z)?Z.slice(0,5):[]}function hi5(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 Ol0(JSON.stringify(J),120)}catch{return Ol0(String(J),120)}}function GL4(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 gi5(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=GL4(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 FL4(J){for(let Z of J){let Q=gi5(Z);if(Q)return Q}return null}function mi5(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"||GL4(Q.path)==="type")})}function pi5(J,Z){let Q=FL4(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 zL4(J,Z,Q){let Y=bi5(Z),X=(()=>{let z=ui5(J);if(z.length===0)return null;return Ol0(z,Q?.payloadPreviewMaxChars??1200)})(),K;try{K=JSON.parse(J)}catch{let z=FL4(Y);return{failureType:"invalid_json",summary:z?`malformed JSON: ${z}`:"malformed JSON",messageType:null,typePreview:null,payloadPreview:X,issues:Y}}if(!K||typeof K!=="object"||Array.isArray(K))return{failureType:"invalid_shape",summary:"expected a JSON object payload",messageType:null,typePreview:null,payloadPreview:X,issues:Y};let V=K;if(!Object.hasOwn(V,"type"))return{failureType:"missing_type",summary:'missing string "type"',messageType:null,typePreview:null,payloadPreview:X,issues:Y};let G=V.type,F=hi5(G);if(typeof G!=="string")return{failureType:"invalid_type",summary:`expected string "type", got ${F??"unknown value"}`,messageType:null,typePreview:F,payloadPreview:X,issues:Y};if(mi5(Y))return{failureType:"unknown_type",summary:`unsupported type ${JSON.stringify(G)} (likely protocol version mismatch)`,messageType:G,typePreview:F,payloadPreview:X,issues:Y};return{failureType:"invalid_shape",summary:pi5(G,Y),messageType:G,typePreview:F,payloadPreview:X,issues:Y}}function il(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 qL4(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}}ZJ();var UL4="[dtw-parse-error]",Ml0="dtw-parse-error",di5=y.object({kind:y.literal(Ml0),failureType:y.enum(VL4).nullable().optional(),source:y.string().nullable().optional(),direction:y.string().nullable().optional(),stage:y.string().nullable().optional(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),typePreview:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough(),ci5=y.object({source:y.string(),direction:y.string(),stage:y.string(),summary:y.string().nullable().optional(),messageType:y.string().nullable().optional(),payloadPreview:y.string().nullable().optional(),issues:y.array(y.unknown()).optional()}).passthrough();function El0(J){return{kind:Ml0,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 WL4(J){let Z=El0(J);return JSON.stringify(Z)}function DL4(J,Z){let Q=zL4(J,Z);return WL4({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 Al0(J){let Z=J.startsWith(UL4)?J.slice(UL4.length):J,Q;try{Q=JSON.parse(Z)}catch{return null}let Y=di5.safeParse(Q);if(Y.success)return El0(Y.data);let X=ci5.safeParse(Q);if(X.success)return El0(X.data);return null}w1();class jl0 extends Error{constructor(J){super(J);this.name="DTWError"}}class S9 extends jl0{cause;constructor(J,Z){super(J);this.cause=Z;this.name="NetworkError"}}w1();var li5=1000,ii5=30000,ni5=5,ai5=30000,oi5=200,ri5=30000,HL4=["online","focus","pageshow","keydown","pointerdown"],BL4=["visibilitychange"];function Il0(){return globalThis}function wL4(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 NL4(){return wL4(Il0().window)}function Rl0(){let J=Il0().document;if(!wL4(J))return null;return J}function si5(){let J=Il0().navigator;if(!J||typeof J!=="object")return null;return J}function ti5(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 VQ0(J){return!!(J.apiKey&&J.WebSocketClass)}function Pl0(J){if(VQ0(J))return"one-step";return"two-step"}class Cl0{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 X4({state:"disconnected",role:null,clientId:null,threadId:null});lifecycleEventSubject=new X4([]);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??li5,maxReconnectDelayMs:J.maxReconnectDelayMs??ii5,maxReconnectAttempts:J.maxReconnectAttempts??ni5,pingIntervalMs:J.pingIntervalMs??ai5,WebSocketClass:J.WebSocketClass},this.currentThreadID=J.threadId??null,this.currentWsToken=J.wsToken??null,this.recordLifecycleEvent("transport_initialized",`flow=${Pl0(this.config)} threadId=${this.currentThreadID??"none"}`)}getThreadId(){return this.currentThreadID}connectionChanges(){return this.connectionSubject}getConnectionInfo(){return{...this.connectionInfo}}connectionLifecycleChanges(){return this.lifecycleEventSubject}getConnectionLifecycleEvents(){return[...this.lifecycleEvents]}async connect(){return this.connectInternal({fromReconnect:!1})}recordLifecycleEvent(J,Z){let Q={id:++this.lifecycleEventID,at:Date.now(),type:J,...Z?{details:Z}:{}},Y=oi5,X=this.lifecycleEvents.slice(-(Y-1));this.lifecycleEvents=[...X,Q],this.lifecycleEventSubject.next([...this.lifecycleEvents])}async connectInternal(J){if(this.disposed)throw new S9("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(VQ0(this.config)){let Y=this.config.baseURL.replace(/^http:/,"ws:").replace(/^https:/,"wss:"),X=this.config.apiKey;if(!X)throw new S9("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 S9("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=${ti5(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 S9(`Failed to get wsToken: ${K.status} ${G}`)}let V=await K.json();if(!V.threadId||!V.wsToken)throw new S9("Invalid response from /threads: missing threadId or wsToken");return this.currentThreadID=V.threadId,this.currentWsToken=V.wsToken,{threadId:V.threadId,wsToken:V.wsToken}}async waitForOpen(J){if(J.readyState===WebSocket.OPEN)return;return new Promise((Z,Q)=>{let Y=()=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),Z()},X=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected");let G="message"in V?V.message:("error"in V)&&V.error instanceof Error?V.error.message:V.type;Q(new S9(`WebSocket connection failed: ${G}`))},K=(V)=>{J.removeEventListener("open",Y),J.removeEventListener("error",X),J.removeEventListener("close",K),this.updateConnectionState("disconnected"),Q(new S9(`WebSocket closed during connect: code=${V.code} reason=${V.reason||"none"}`))};J.addEventListener("open",Y),J.addEventListener("error",X),J.addEventListener("close",K)})}setupWebSocketHandlers(J){J.addEventListener("message",(Z)=>{let Q=Z.data;if(typeof Q==="string"){if(Q==="pong"){this.lastPongAt=Date.now();return}this.onRawMessage(Q)}else if(Q instanceof ArrayBuffer)this.onRawMessage(new TextDecoder().decode(Q))}),J.addEventListener("close",(Z)=>{this.handleClose(J,Z.code,Z.reason)}),J.addEventListener("error",()=>{this.handleError(J)}),this.startPingInterval()}handleClose(J,Z,Q){let Y=this.intentionallyClosedSockets.has(J);if(Y)this.intentionallyClosedSockets.delete(J);if(this.recordLifecycleEvent("socket_closed",`code=${Z} reason=${Q||"none"} intentional=${Y}`),J!==this.ws)return;if(this.ws=null,this.stopPingInterval(),this.cancelReconnectAttemptsReset(),!this.disposed&&!Y){let X=this.reconnectCause,K=X?.type==="ping_timeout"&&Z===4000&&!Q?{...X,at:Date.now(),code:Z}:{type:"close",at:Date.now(),code:Z,...Q?{reason:Q}:{}};if(this.reconnectCause=K,Z===4001||Q.includes("Token expired"))this.handleAuthExpired().catch(()=>{return}).finally(()=>{if(!this.disposed)this.scheduleReconnect()});else this.scheduleReconnect()}else this.reconnectCause=null,this.updateConnectionState("disconnected")}handleError(J){if(J!==this.ws)return;if(this.recordLifecycleEvent("socket_error","error=WebSocket error event"),this.reconnectCause={type:"error",at:Date.now(),error:"WebSocket error event"},this.ws)this.ws.close()}scheduleReconnect(J){if(this.disposed||this.reconnectTimeoutID)return;if(this.reconnectAttempts>=this.config.maxReconnectAttempts){this.stopWaitingForReconnectActivity(),this.recordLifecycleEvent("reconnect_exhausted",`attempts=${this.reconnectAttempts} max=${this.config.maxReconnectAttempts}`),this.updateConnectionState("disconnected"),this.onMaxReconnectExceeded(this.config.maxReconnectAttempts);return}if(!J?.bypassActivityGate&&this.shouldWaitForReconnectActivity()){this.recordLifecycleEvent("reconnect_waiting_for_activity",`offline=${this.isBrowserOffline()} hidden=${this.isDocumentHidden()}`),this.updateConnectionState("reconnecting"),this.waitForReconnectActivity();return}this.stopWaitingForReconnectActivity(),this.updateConnectionState("reconnecting"),this.reconnectAttempts++;let Z=J?.immediate?0:this.getReconnectDelayMs();this.recordLifecycleEvent("reconnect_scheduled",`attempt=${this.reconnectAttempts} delayMs=${Math.round(Z)}`),this.reconnectTimeoutID=setTimeout(()=>{this.reconnectTimeoutID=null,this.connectInternal({fromReconnect:!0}).catch((Q)=>{if(this.reconnectCause={type:"connect_failed",at:Date.now(),error:Q instanceof Error?Q.message:String(Q)},!this.disposed)this.scheduleReconnect()})},Z)}cancelReconnect(){if(this.reconnectTimeoutID)clearTimeout(this.reconnectTimeoutID),this.reconnectTimeoutID=null;this.stopWaitingForReconnectActivity(),this.cancelReconnectAttemptsReset(),this.reconnectAttempts=0}getReconnectDelayMs(){let J=this.config.reconnectDelayMs*2**(this.reconnectAttempts-1),Z=0.8+Math.random()*0.4;return Math.min(J*Z,this.config.maxReconnectDelayMs)}shouldWaitForReconnectActivity(){let J=NL4(),Z=Rl0();if(!J&&!Z)return!1;return this.isBrowserOffline()||this.isDocumentHidden()}isBrowserOffline(){let J=si5();if(typeof J?.onLine!=="boolean")return!1;return J.onLine===!1}isDocumentHidden(){let J=Rl0();if(!J)return!1;return J.visibilityState==="hidden"}waitForReconnectActivity(){if(this.reconnectActivityCleanup)return;let J=NL4(),Z=Rl0();if(!J&&!Z)return;let Q=()=>{this.handleReconnectActivity()};for(let Y of HL4)J?.addEventListener(Y,Q);for(let Y of BL4)Z?.addEventListener(Y,Q);this.reconnectActivityCleanup=()=>{for(let Y of HL4)J?.removeEventListener(Y,Q);for(let Y of BL4)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},ri5)}cancelReconnectAttemptsReset(){if(this.reconnectResetTimeoutID)clearTimeout(this.reconnectResetTimeoutID),this.reconnectResetTimeoutID=null}startPingInterval(){this.stopPingInterval();let J=Date.now();this.pingIntervalID=setInterval(()=>{let Z=Date.now(),Q=Z-J;if(J=Z,Q>this.config.pingIntervalMs*3){this.lastPongAt=Z;return}if(this.hasOpenSocket()){let Y=Z-this.lastPongAt,X=this.config.pingIntervalMs*2;if(Y>X){this.recordLifecycleEvent("ping_timeout",`elapsedMs=${Y} thresholdMs=${X}`),this.reconnectCause={type:"ping_timeout",at:Z,code:4000,reason:"Pong timeout",error:`No pong received for ${Y}ms (threshold ${X}ms)`},this.ws?.close(4000,"Pong timeout");return}try{this.ws?.send("ping")}catch{}}},this.config.pingIntervalMs)}stopPingInterval(){if(this.pingIntervalID)clearInterval(this.pingIntervalID),this.pingIntervalID=null}}function ei5(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 Jq extends Cl0{deltaSubject=new e1;errorSubject=new e1;errorEventSubject=new e1;cancelledSubject=new e1;agentStateSubject=new e1;messageAddedSubject=new e1;editRejectedSubject=new e1;messageEditedSubject=new e1;queuedMessagesSubject=new e1;retrySubject=new e1;toolLeaseSubject=new e1;toolLeaseRevokedSubject=new e1;toolApprovalQueueSubject=new e1;executorToolApprovalResponseSubject=new e1;toolProgressSubject=new e1;executorErrorSubject=new e1;executorConnectedSubject=new e1;executorRollbackRequestSubject=new e1;observersSubject=new e1;executorStatusSubject=new e1;environmentUpdateSubject=new e1;artifactsSubject=new e1;gitStatusSubject=new e1;threadTitleSubject=new e1;threadStatusSubject=new e1;threadRelationshipsSubject=new e1;compactionSubject=new e1;compactionRecordsSubject=new e1;pluginMessageSubject=new e1;fileSystemReadDirectoryRequestSubject=new e1;fileSystemReadFileRequestSubject=new e1;pendingReadDirectoryRequests=new Map;pendingReadFileRequests=new Map;fileSystemRequestCounter=0;constructor(J){super(J)}deltas(){return this.deltaSubject}agentStates(){return this.agentStateSubject}messageEvents(){return this.messageAddedSubject}editRejected(){return this.editRejectedSubject}messageEdited(){return this.messageEditedSubject}queuedMessages(){return this.queuedMessagesSubject}retryEvents(){return this.retrySubject}errors(){return this.errorSubject}errorEvents(){return this.errorEventSubject}cancelledEvents(){return this.cancelledSubject}toolLeases(){return this.toolLeaseSubject}toolLeaseRevoked(){return this.toolLeaseRevokedSubject}toolApprovalQueue(){return this.toolApprovalQueueSubject}executorToolApprovalResponses(){return this.executorToolApprovalResponseSubject}toolProgress(){return this.toolProgressSubject}executorErrors(){return this.executorErrorSubject}executorConnected(){return this.executorConnectedSubject}executorRollbackRequests(){return this.executorRollbackRequestSubject}observers(){return this.observersSubject}executorStatuses(){return this.executorStatusSubject}environmentUpdates(){return this.environmentUpdateSubject}artifacts(){return this.artifactsSubject}gitStatuses(){return this.gitStatusSubject}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.gitStatusSubject.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??ez();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 S9("Transport is disposed");if(!this.hasOpenSocket())throw new S9("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;F.unsubscribe(),z.unsubscribe(),q()},F=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))}}),z=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=il(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})}sendExecutorGitStatus(J,Z){this.send({type:"executor_git_status",status:J,toolCallId:Z})}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 S9("WebSocket is not connected"));return new Promise((Y,X)=>{let K=setTimeout(()=>{J.delete(Z),X(new S9(`Filesystem request timed out: ${Z}`))},rw4);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(ei5(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 S9(J)),this.pendingReadDirectoryRequests.delete(Z);for(let[Z,Q]of this.pendingReadFileRequests)clearTimeout(Q.timeoutID),Q.reject(new S9(J)),this.pendingReadFileRequests.delete(Z)}onRawMessage(J){let Z=XL4.safeDecode(J);if(!Z.success){let Y=YL4.safeDecode(J),X=Y.success?Z.error:Y.error;this.errorSubject.next({type:"error",message:DL4(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"git_status":this.gitStatusSubject.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(QL4.encode(J))}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw new S9(`Failed to encode DTW client message "${J.type}": ${Q}`,Z)}}}function $n5(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 Jn5(J){if(!J||typeof J!=="object")return!1;return typeof J.id==="string"}function Zn5(J){if($n5(J))return J.queuedMessage.messageId;if(Jn5(J))return J.id;throw Error("reduceQueuedMessages requires getQueuedMessageId for this message shape")}function _l0(J,Z,Q={}){let Y=Q.getQueuedMessageId??Zn5;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 Qn5=15000;function Yn5(J,Z,Q){let Y=!1,X=null,K=[],V=()=>{if(Y)return;if(Y=!0,X)clearTimeout(X),X=null;for(let F of K)F.unsubscribe()};return{promise:new Promise((F,z)=>{K.push(J.messageEvents().subscribe({next:(q)=>{if(q.message.messageId===Z)V(),F(q)}})),K.push(J.errors().subscribe({next:(q)=>{V(),z(Error(q.message))}})),K.push(J.executorErrors().subscribe({next:(q)=>{V(),z(Error(q.message))}})),K.push(J.connectionChanges().subscribe({next:(q)=>{if(q.state==="disconnected")V(),z(Error("Disconnected before message was acknowledged"))}})),X=setTimeout(()=>{V(),z(Error(`Timed out waiting for message_added after ${Q}ms`))},Q)}),dispose:V}}async function Tl0(J){let Z=J.workerUrl??p7(J.ampURL),Q=new Jq({baseURL:Z,apiKey:J.apiKey,threadId:J.threadId,WebSocketClass:WebSocket,maxReconnectAttempts:1,pingIntervalMs:5000}),Y=J.timeoutMs??Qn5;await Q.connect(),Q.resumeFromVersion(0);let X=Q.sendUserMessage([{type:"text",text:J.message}],J.agentMode),K=Yn5(Q,X,Y);try{return{messageId:(await K.promise).message.messageId}}finally{K.dispose(),Q.dispose()}}import{watch as Xn5}from"node:fs";import{mkdir as Kn5,readdir as Vn5,readFile as Gn5}from"node:fs/promises";import{createServer as Fn5}from"node:http";import Sl0 from"node:path";function LL4(J){return J instanceof Error?J.message:String(J)}function Kj(J,Z,Q){J.writeHead(Z,{"Content-Type":"application/json; charset=utf-8"}),J.end(JSON.stringify(Q))}function zn5(J,Z){J.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),J.end(Z)}async function OL4(J,Z){let Q=Sl0.basename(Z),Y=Q.endsWith(".json")?Sl0.join(J,Q):Sl0.join(J,`${Q}.json`),X=await Gn5(Y,"utf-8");return JSON.parse(X)}async function qn5(J){let Z=await Vn5(J,{withFileTypes:!0}).catch(()=>[]),Q=[];for(let Y of Z){if(!Y.isFile()||!Y.name.endsWith(".json"))continue;try{let X=await OL4(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 Un5(){return`<!doctype html>
|
|
4684
4684
|
<html lang="en">
|
|
4685
4685
|
<head>
|
|
4686
4686
|
<meta charset="utf-8" />
|
|
@@ -6086,7 +6086,7 @@ ${z}`)}}if(J.skipParseResponse)return;try{let X=new Uint8Array(await Y.arrayBuff
|
|
|
6086
6086
|
`).length})),G=crypto.randomUUID(),F=Q.userConfigDir?c1(Q.userConfigDir):void 0;if(V.length===0){X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:0,isLast:!0}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:[],isLast:!0,userConfigDir:F});return}let z=nC4(V,G,F);for(let q=0;q<z.length;q++){let U=z[q];if(!U)continue;let W=q===z.length-1;X?.("SEND",{type:"executor_guidance_snapshot",snapshotId:G,fileCount:U.length,isLast:W}),J.sendExecutorGuidanceSnapshot({snapshotId:G,files:U,isLast:W,userConfigDir:F})}}async function tQ3(J,Z,Q){let Y=await Z.getSkills(),X=crypto.randomUUID(),K=20,V=Y.map((G)=>({name:G.name,description:G.description,baseDir:G.baseDir,frontmatter:G.frontmatter,files:G.files}));if(V.length===0){Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:0,isLast:!0}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:[],isLast:!0});return}for(let G=0;G<V.length;G+=20){let F=V.slice(G,G+20),z=G+20>=V.length;Q?.("SEND",{type:"executor_skill_snapshot",snapshotId:X,skillCount:F.length,isLast:z}),J.sendExecutorSkillSnapshot({snapshotId:X,skills:F,isLast:z})}}zJ();D4();import Bn from"node:path";class pj extends Error{code;constructor(J,Z){super(Z);this.code=J;this.name="ExecutorFileSystemPathError"}}function oC4(J,Z){let Q=Y1.parse(J);if(Q.scheme!=="file")throw new pj("INVALID_URI","Only file:// URIs are supported");if(!Q.path.startsWith("/"))throw new pj("INVALID_URI","File URI path must be absolute");if(Q.path.split("/").some((F)=>F===".."))throw new pj("ACCESS_DENIED","File URI resolves outside workspace root");let X=Bn.posix.normalize(Q.path).replace(/^\/+/u,"");if(X===".."||X.startsWith("../"))throw new pj("ACCESS_DENIED","File URI resolves outside workspace root");let K=Bn.resolve(Z),V=X.length>0?Bn.resolve(K,X):K,G=Bn.relative(K,V);if(G.startsWith("..")||Bn.isAbsolute(G))throw new pj("ACCESS_DENIED","File URI resolves outside workspace root");return V}async function bX0(J,Z){try{let Q=oC4(Z,J.workspaceRoot),Y=await J.fileSystem.readdir(Y1.file(Q));return{ok:!0,entries:await Promise.all(Y.map(async(K)=>{let V=K.isDirectory?"directory":"file",G=V==="file"?await eQ3(J.fileSystem,K.uri):void 0;return[X1.basename(K.uri),V,G]}))}}catch(Q){return{ok:!1,error:rC4(Q,"read_directory")}}}async function eQ3(J,Z){try{let Q=await J.getMtime(Z);if(!Number.isFinite(Q)||Q<0)return;return{mtimeMs:Q}}catch{return}}async function hX0(J,Z){try{let Q=oC4(Z,J.workspaceRoot),Y=await J.fileSystem.readBinaryFile(Y1.file(Q));return{ok:!0,contentBase64:Buffer.from(Y).toString("base64")}}catch(Q){return{ok:!1,error:rC4(Q,"read_file")}}}function rC4(J,Z){if(J instanceof pj)return{code:J.code,message:J.message};if(h8(J))return{code:"NOT_FOUND",message:"File or directory not found"};if(uX0(J,"EISDIR"))return{code:"IS_DIRECTORY",message:"Expected a file but found a directory"};if(uX0(J,"ENOTDIR"))return{code:Z==="read_directory"?"NOT_DIRECTORY":"INTERNAL_ERROR",message:Z==="read_directory"?"Expected a directory":aC4(J)};if(uX0(J,"EACCES")||uX0(J,"EPERM"))return{code:"ACCESS_DENIED",message:"Permission denied"};return{code:"INTERNAL_ERROR",message:aC4(J)}}function uX0(J,Z){if(!(J instanceof Error))return!1;return"code"in J&&J.code===Z}function aC4(J){if(J instanceof Error)return J.message;return String(J)}var Ty={baseDelayMs:1000,maxDelayMs:30000,maxAttempts:5};function gX0(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 $Y3(){let J=()=>{return},Z=()=>{return};return{promise:new Promise((Y,X)=>{J=Y,Z=X}),resolve:J,reject:Z}}class Nn{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??Ty.baseDelayMs,this.maxDelayMs=J.maxDelayMs??Ty.maxDelayMs,this.maxAttempts=J.maxAttempts??Ty.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=$Y3();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=gX0(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)}}f4();import{createHash as JY3}from"node:crypto";class wn{options;clientID;transport;sentApprovalRequests=new Set;discoveredGuidanceFileURIs=new Set;activeTools=new Map;lastGitStatusCapturedAt=0;lastGitStatusSignature=null;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,args:Y}=J,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=this.options.executeBuiltinTool(Q,Y);if(K){let z=K.ok?{status:"done",result:K.content}:{status:"error",error:{message:K.content}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:z}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,z),{toolCallId:Z}),this.queueGitStatusSnapshot(Z);return}let V=new AbortController,G={subscription:{unsubscribe:()=>{}},abortController:V};this.activeTools.set(Z,G);let F=()=>{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 q=!1,U=z.subscribe({next:(W)=>{if(V.signal.aborted)return;if(!q)q=!0,this.options.log.info(`${this.clientID} tool emitted first update`,{toolCallId:Z,toolName:Q,status:W.status,elapsedMs:Date.now()-X});let D=W.status==="in-progress"?W.progress??W.result:void 0;if(D!==void 0)this.options.log.wsMessage("SEND",this.clientID,{type:"tool_progress",toolCallId:Z,progress:D}),this.sendTransportMessage("tool_progress",()=>this.transport.sendToolProgress(Z,D),{toolCallId:Z});if(j9(W.status))this.sendToolResult(Z,W),F(),U.unsubscribe();if(W.status==="blocked-on-user")this.options.log.info(`${this.clientID} awaiting tool approval`,{toolCallId:Z,toolName:Q})},error:(W)=>{if(V.signal.aborted){F();return}this.options.log.error(`${this.clientID} tool execution failed: ${Q}`,W);let D={status:"error",error:{message:W instanceof Error?W.message:"Unknown error"}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:D}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,D),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),F()}});G.subscription=U}catch(z){this.options.log.error(`${this.clientID} tool execution setup failed: ${Q}`,z);let q={status:"error",error:{message:z instanceof Error?z.message:String(z)}};this.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:Z,run:q}),this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(Z,q),{toolCallId:Z}),this.queueGitStatusSnapshot(Z),F()}}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()}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.options.log.wsMessage("SEND",this.clientID,{type:"executor_tool_result",toolCallId:J,run:X});let V=this.sendTransportMessage("executor_tool_result",()=>this.transport.sendExecutorToolResult(J,X),{toolCallId:J});this.options.log.info(`${this.clientID} executor_tool_result send attempted`,{toolCallId:J,status:X.status,sent:V,guidanceFileCount:K.length,elapsedMs:Date.now()-Q}),this.sentApprovalRequests.delete(J),this.queueGitStatusSnapshot(J)}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(),Q=Math.max(Z.capturedAt,this.lastGitStatusCapturedAt+1),Y=Q===Z.capturedAt?Z:{...Z,capturedAt:Q},X=this.buildGitStatusSignature(Y),K=X!==null&&X===this.lastGitStatusSignature&&Y.available;if(this.lastGitStatusCapturedAt=Y.capturedAt,K){this.transport.sendExecutorArtifactUpsert(Dn(Y),J),this.options.log.wsMessage("SEND",this.clientID,{type:"executor_git_status",available:Y.available,fileCount:Y.files.length,toolCallId:J,branch:Y.branch,head:Y.head,note:"unchanged"}),this.transport.sendExecutorGitStatus({...Y,unchanged:!0,files:Y.files.map((V)=>({...V,diff:"",fullFileDiff:""}))},J);return}this.lastGitStatusSignature=X,this.options.log.wsMessage("SEND",this.clientID,{type:"executor_git_status",available:Y.available,fileCount:Y.files.length,toolCallId:J,branch:Y.branch,head:Y.head}),this.transport.sendExecutorGitStatus(Y,J),this.transport.sendExecutorArtifactUpsert(Dn(Y),J)}catch(Z){this.options.log.error("Failed to send git status snapshot",Z)}}buildGitStatusSignature(J){if(!J.available)return`unavailable:${J.unavailableReason??"unknown"}`;let Z=J.files.map((Y)=>[Y.path,Y.changeType,Y.previousPath??"",Y.diff.length,Y.fullFileDiff?.length??0]),Q=JSON.stringify({repositoryRoot:J.repositoryRoot,branch:J.branch,head:J.head,baseRef:J.baseRef??null,baseRefHead:J.baseRefHead??null,aheadCount:J.aheadCount??0,behindCount:J.behindCount??0,aheadCommitHashes:(J.aheadCommits??[]).map((Y)=>Y.hash),files:Z});return JY3("sha256").update(Q).digest("hex")}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=KL4(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 S9)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}}}g0();function mX0(J){return{async createHandoffDraft(Z){let Q=await tC4(J,Z.signal);return sC4(Q,Z.parentThread.id,Z.goal,Z.images)},createHandoffThread:async(Z)=>{let Q=await tC4(J,Z.signal),Y=await sC4(Q,Z.parentThread.id,Z.goal,Z.images),X=await XY3(Q,Z,Y);if(await YY3(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){P.error("Failed to follow handoff thread",{error:K,sourceThreadID:Z.parentThread.id,targetThreadID:X.threadID})}return X.threadID}}}function ZY3(J){let Z=new Headers({"Content-Type":"application/json"});if(J)Z.set("Authorization",`Bearer ${J}`);return Z}async function io0(J,Z,Q){return fetch(`${J.workerURL}${Z}`,{method:"POST",headers:ZY3(J.apiKey),body:JSON.stringify(Q),signal:J.signal})}async function sC4(J,Z,Q,Y){let X=await io0(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 QY3(J,Z,Q,Y){let X=await io0(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 YY3(J,Z,Q,Y){let X=await io0(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 tC4(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??p7(Q.settings.url);return{apiKey:Y,workerURL:X,signal:Z}}async function XY3(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,F=await QY3(J,G,Y??void 0,V);return{http:J,threadID:F,prompt:Q.content,agentMode:Y??void 0}}xV();$l();r_();lm0();f4();D4();w1();async function AD(J){let{toolName:Z,threadSnapshot:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,configService:K,toolService:V,mcpService:G,skillService:F,fsTracker:z,toolUseID:q,discoveredGuidanceFileURIs:U}=J,W=Y1.file(process.cwd()),D=q??mF(),H=await K.getLatest(),B,N;if(z)B=z.trackedFileSystem(D),N=z.tracker;else N=CJ0(ok0,Q.id,async()=>{}),B=im0(M8,N,D);return{dir:W,tool:Z,thread:Q,dtwHandoffService:Y,dtwArtifactSyncService:X,trackedFiles:new GQ,toolUseID:D,todos:void 0,configService:K,toolService:V,mcpService:G,config:H,filesystem:B,fileChangeTracker:N,getAllTrackedChanges:async()=>N.getAllRecords(),threadEnvironment:{trees:[],platform:"cli"},handleThreadDelta:()=>Promise.resolve(),threadService:{observe:()=>k0.of(Q),get:()=>Promise.resolve(Q)},threadSyncService:void 0,getThreadEnvironment:()=>Promise.resolve({trees:[],platform:"cli"}),threadSummaryService:{summarizeThread:()=>Promise.resolve({summary:"CLI execution",prompt:"CLI execution",title:"CLI Tool"})},osFileSystem:M8,deleteThread:()=>Promise.resolve(),generateThreadTitle:()=>Promise.resolve({title:"CLI Tool Execution"}),fileChangeTrackerStorage:ok0,discoveredGuidanceFileURIs:U??new Set,skillService:F??{getSkills:()=>Promise.resolve([]),getTargetDir:()=>Promise.resolve("/tmp/skills"),listInstalled:()=>[],reload:()=>{}}}}function no0(){return new Date().toISOString()}var ao0=process.stderr.isTTY;function KY3(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 oo0(J){if(J instanceof Error)return J.stack??J.message;if(typeof J==="string"){let Z=KY3(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(P.info("[headless-dtw] websocket message",{direction:J,clientId:Z,...typeof Q==="object"&&Q!==null?Q:{message:Q}}),!ao0)return;let Y=c0.dim(`[${no0()}]`),X=c0.magenta(`[${Z}]`),K=J==="SEND"?c0.green(">>>"):c0.yellow("<<<"),V=oo0(Q);process.stderr.write(`${Y} ${X} ${K} ${V}
|
|
6087
6087
|
`)}function e7(J,Z){if(Z)P.info(`[headless-dtw] ${J}`,Z);else P.info(`[headless-dtw] ${J}`);if(!ao0)return;let Q=c0.dim(`[${no0()}]`),Y=c0.cyan("[INFO]"),X=Z?` ${oo0(Z)}`:"";process.stderr.write(`${Q} ${Y} ${J}${X}
|
|
6088
6088
|
`)}function bG(J,Z){if(Z!==void 0)P.error(`[headless-dtw] ${J}`,{error:Z});else P.error(`[headless-dtw] ${J}`);if(!ao0)return;let Q=c0.dim(`[${no0()}]`),Y=c0.red("[ERROR]"),X=oo0(Z);process.stderr.write(`${Q} ${Y} ${J} ${X}
|
|
6089
|
-
`)}function VY3(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 GY3(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class eC4{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??M8,X=new nV(Y);J.fsTracker=Qk({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){try{await J.connect()}catch(Y){let X=J.getConnectionInfo();if(X.state!=="reconnecting")throw Y;e7(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason})}}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,e7(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{X.transport.disconnect(),await this.connectTransport(X.transport,J,"recovery");let K=X.transport.getConnectionInfo(),V=X.transport.getThreadId();if(V)this.bindClientThread(X,V);if(K.state!=="connected"){e7(`${J} waiting for reconnect after transport recovery`,{connectionState:K.state});return}X.handshakeManager.ensureHandshake("retry")}catch(K){bG(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){e7("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??p7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=_y(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);e7("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 bG("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=GY3(this.options.ampURL,J);e7(`Thread URL: ${c0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)e7(Z);else bG(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:F}=Z,z=typeof F==="object"&&F!==null?F:{},q=mX0({configService:Y,apiKey:this.options.apiKey}),U={upsertArtifact:(D,H)=>{let B=j8.safeParse(H);J.transport.sendExecutorArtifactUpsert(D,B.success?B.data:void 0)},deleteArtifact:(D)=>{J.transport.sendExecutorArtifactDelete(D)}},W=await AD({toolName:V,threadSnapshot:{id:J.threadId??C3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:U,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:G,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:z},W)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??p7(this.options.ampURL),X=this.options.useThreadActors?AZ0(this.options.ampURL):void 0;e7(`Creating client ${Z}`,{threadId:J??"new",workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)"});let K;if(this.options.useThreadActors&&X){let W=yi({endpoint:`${X}/api/rivet`});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await W.threadWorker.getOrCreate([J??`new-${Date.now()}`],{params:{apiKey:this.options.apiKey,threadId:J}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new Jq(K),G,F=new wn({clientID:Z,transport:V,executeBuiltinTool:()=>null,invokeTool:(W)=>this.invokeToolForClient(G,W),captureGitStatus:()=>yX0(this.options.workspaceRoot),batchGuidanceFiles:vX0,renderToolRunError:Wp,onTransportSendFailure:(W,D,H,B)=>{this.recoverTransport(W,D,H,B)},log:{info:e7,error:bG,wsMessage:q8}}),z=this.createHandshakeManager(()=>G,Z);G={id:Z,transport:V,threadId:J??null,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:z,toolRunner:F,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,G),this.subscribeToTransportEvents(G),e7(`Connecting ${Z}...`),await this.connectTransport(V,Z,"startup");let q=V.getConnectionInfo(),U=V.getThreadId();if(U)this.bindClientThread(G,U);if(q.state==="connected")e7(`Connected ${Z}`,{threadId:U});else e7(`${Z} waiting for transport reconnect`,{connectionState:q.state});if(q.state==="connected")G.handshakeManager.ensureHandshake("connect");return G}async connectAsExecutor(J,Z){e7(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await xX0({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.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw bG(`${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){bG(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,e7(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Nn({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{bG(`${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=fX0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Hn({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(mj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=mj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=_X0(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){bG(`${J.id} received approval response without tool service`);return}e7(`${J.id} approval resolved`,{toolCallId:Z.toolCallId,accepted:Z.accepted}),Q.resolveApproval(Z.toolCallId,Z.accepted)}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,VY3(X.reconnectCause));e7(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{q8("RECV",Q,X),bG(`${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),bG(`${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){bG(`${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 bX0({fileSystem:this.options.fileSystem??M8,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 hX0({fileSystem:this.options.fileSystem??M8,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(e7("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){e7(`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 $_4(J){await new eC4(J).start()}import{stderr as hG,stdin as qY3}from"node:process";import{createInterface as UY3}from"node:readline";import{stdout as FY3}from"node:process";function zY3(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function pX0(){if(!FY3.isTTY)return!0;if(zY3())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var dX0=[],ro0=null;function so0(J){if(ro0=J,J&&dX0.length>0){for(let Z of dX0)J(Z);dX0=[]}}function J_4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(ro0)ro0(K);else dX0.push(K)})}}function Z_4(){return async(J,Z)=>{return hG.write(`
|
|
6089
|
+
`)}function VY3(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 GY3(J,Z){let Q=new URL(J);if(!Q.pathname.endsWith("/"))Q.pathname+="/";return new URL(`threads/${Z}`,Q).toString()}class eC4{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??M8,X=new nV(Y);J.fsTracker=Qk({fileChangeTrackerStorage:X},Y,Z)}async connectTransport(J,Z,Q){try{await J.connect()}catch(Y){let X=J.getConnectionInfo();if(X.state!=="reconnecting")throw Y;e7(`${Z} waiting for reconnect during ${Q}`,{connectionState:X.state,reconnectCauseType:X.reconnectCause?.type,reconnectCauseCode:X.reconnectCause?.code,reconnectCauseReason:X.reconnectCause?.reason})}}async recoverTransport(J,Z,Q,Y){let X=this.clients.get(J);if(!X||X.recoveringTransport||this.disposed)return;X.recoveringTransport=!0,e7(`${J} recovering transport after send failure`,{messageType:Z,error:Q.message,...Y});try{X.transport.disconnect(),await this.connectTransport(X.transport,J,"recovery");let K=X.transport.getConnectionInfo(),V=X.transport.getThreadId();if(V)this.bindClientThread(X,V);if(K.state!=="connected"){e7(`${J} waiting for reconnect after transport recovery`,{connectionState:K.state});return}X.handshakeManager.ensureHandshake("retry")}catch(K){bG(`${J} transport recovery failed`,K)}finally{X.recoveringTransport=!1}}async start(){e7("Starting Headless DTW Harness",{ampURL:this.options.ampURL,workerUrl:this.options.workerUrl??p7(this.options.ampURL),workspaceRoot:this.options.workspaceRoot,threadId:this.options.threadId??null}),this.toolSyncSubscription??=this.options.toolService.tools.subscribe({next:(J)=>{let Z=_y(J);for(let Q of this.clients.values())this.syncExecutorTools(Q,Z)}});try{let J=await this.createClient(this.options.threadId);e7("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 bG("Failed to start harness",J),J}}logThreadURL(J){if(!J)return;let Z=GY3(this.options.ampURL,J);e7(`Thread URL: ${c0.blue.underline(Z)}`)}shutdown(J,Z){if(!this.disposed){if(J===0)e7(Z);else bG(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:F}=Z,z=typeof F==="object"&&F!==null?F:{},q=mX0({configService:Y,apiKey:this.options.apiKey}),U={upsertArtifact:(D,H)=>{let B=j8.safeParse(H);J.transport.sendExecutorArtifactUpsert(D,B.success?B.data:void 0)},deleteArtifact:(D)=>{J.transport.sendExecutorArtifactDelete(D)}},W=await AD({toolName:V,threadSnapshot:{id:J.threadId??C3(),created:Date.now(),v:0,messages:[]},dtwHandoffService:q,dtwArtifactSyncService:U,configService:Y,toolService:Q,mcpService:X,skillService:K,fsTracker:J.fsTracker??void 0,toolUseID:G,discoveredGuidanceFileURIs:J.toolRunner.discoveredGuidanceFileURIs});return Q.invokeTool(V,{args:z},W)}async createClient(J){let Z=`client-${++this.clientCounter}`,Q=`cli-headless-${crypto.randomUUID()}`,Y=this.options.workerUrl??p7(this.options.ampURL),X=this.options.useThreadActors?AZ0(this.options.ampURL):void 0;e7(`Creating client ${Z}`,{threadId:J??"new",workerUrl:Y,useThreadActors:this.options.useThreadActors??!1,threadActorsUrl:X??"(not used)"});let K;if(this.options.useThreadActors&&X){let W=yi({endpoint:`${X}/api/rivet`});K={baseURL:X,threadId:J,webSocketProvider:async()=>{return await W.threadWorker.getOrCreate([J??`new-${Date.now()}`],{params:{apiKey:this.options.apiKey,threadId:J}}).webSocket("/")},WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000}}else K={baseURL:Y,apiKey:this.options.apiKey,threadId:J,WebSocketClass:WebSocket,maxReconnectAttempts:Number.POSITIVE_INFINITY,pingIntervalMs:5000};let V=new Jq(K),G,F=new wn({clientID:Z,transport:V,executeBuiltinTool:()=>null,invokeTool:(W)=>this.invokeToolForClient(G,W),captureGitStatus:()=>yX0(this.options.workspaceRoot),batchGuidanceFiles:vX0,renderToolRunError:Wp,onTransportSendFailure:(W,D,H,B)=>{this.recoverTransport(W,D,H,B)},log:{info:e7,error:bG,wsMessage:q8}}),z=this.createHandshakeManager(()=>G,Z);G={id:Z,transport:V,threadId:J??null,hasLoggedPostBootstrapThreadURL:!1,executorClientId:Q,handshakeManager:z,toolRunner:F,fsTracker:null,settingsSubscription:null,lastSentSettingsJSON:"",recoveringTransport:!1,advertisedExecutorTools:[]},this.clients.set(Z,G),this.subscribeToTransportEvents(G),e7(`Connecting ${Z}...`),await this.connectTransport(V,Z,"startup");let q=V.getConnectionInfo(),U=V.getThreadId();if(U)this.bindClientThread(G,U);if(q.state==="connected")e7(`Connected ${Z}`,{threadId:U});else e7(`${Z} waiting for transport reconnect`,{connectionState:q.state});if(q.state==="connected")G.handshakeManager.ensureHandshake("connect");return G}async connectAsExecutor(J,Z){e7(`Connecting ${J.id} as executor...`,{trigger:Z});try{J.settingsSubscription?.unsubscribe(),J.settingsSubscription=null;let{advertisedTools:Q}=await xX0({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.hasLoggedPostBootstrapThreadURL&&J.threadId)this.logThreadURL(J.threadId),J.hasLoggedPostBootstrapThreadURL=!0;this.setNotifyForwarder(J),this.bootstrapPluginsAfterExecutorConnect(J),this.startSettingsSync(J)}catch(Q){throw bG(`${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){bG(`${J.id} failed to forward plugin notification`,X)}})}bootstrapPluginsAfterExecutorConnect(J){let Z=this.options.pluginService;if(!Z||this.pluginsBootstrapped)return;this.pluginsBootstrapped=!0,e7(`${J.id} reloading plugins after executor bootstrap`),Z.reload()}createHandshakeManager(J,Z){return new Nn({handshake:(Q)=>this.connectAsExecutor(J(),Q),onError:({error:Q,attempt:Y,delayMs:X})=>{bG(`${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=fX0(J.transport,Z,J.lastSentSettingsJSON)}})}syncExecutorTools(J,Z){let Q=J.transport.getConnectionInfo();if(Q.state!=="connected"||Q.role!=="executor")return;J.advertisedExecutorTools=Hn({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(mj));for(let X of[...J.toolRunner.sentApprovalRequests])if(!Y.has(X))J.toolRunner.sentApprovalRequests.delete(X);for(let X of Q){let K=mj(X);if(J.toolRunner.sentApprovalRequests.has(K))continue;let V=_X0(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){bG(`${J.id} received approval response without tool service`);return}e7(`${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,VY3(X.reconnectCause));e7(`${Q} connection: ${X.state}`,V),J.handshakeManager.handleConnectionChange(X)}}),Z.errors().subscribe({next:(X)=>{q8("RECV",Q,X),bG(`${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),bG(`${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){bG(`${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 bX0({fileSystem:this.options.fileSystem??M8,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 hX0({fileSystem:this.options.fileSystem??M8,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(e7("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){e7(`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 $_4(J){await new eC4(J).start()}import{stderr as hG,stdin as qY3}from"node:process";import{createInterface as UY3}from"node:readline";import{stdout as FY3}from"node:process";function zY3(){return!!(process.env.SSH_CLIENT||process.env.SSH_TTY||process.env.SSH_CONNECTION)}function pX0(){if(!FY3.isTTY)return!0;if(zY3())return!0;if(process.platform!=="darwin"&&process.platform!=="win32"&&!process.env.DISPLAY)return!0;return!1}var dX0=[],ro0=null;function so0(J){if(ro0=J,J&&dX0.length>0){for(let Z of dX0)J(Z);dX0=[]}}function J_4(J){return async(Z,Q)=>{return new Promise((Y,X)=>{let K={serverName:J,authorizationUrl:Z,redirectUrl:Q,resolve:Y,reject:X};if(ro0)ro0(K);else dX0.push(K)})}}function Z_4(){return async(J,Z)=>{return hG.write(`
|
|
6090
6090
|
`),hG.write(c0.yellow.bold(`OAuth Authorization Required
|
|
6091
6091
|
`)),hG.write(c0.dim("─".repeat(60)+`
|
|
6092
6092
|
`)),hG.write(`
|
|
@@ -6204,7 +6204,7 @@ Manually weave this spell into your shell configuration:`),$$.bold(` ${Y.comman
|
|
|
6204
6204
|
`+J.command+`
|
|
6205
6205
|
`,{flag:"a"}),$$.green(`✓ Added "~/.local/bin" to PATH in "${Q}"`),!0}catch(Y){$$.red(`[WARN] Failed to update ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}}return!1}async function zr0(J,Z,Q){let Y=LX3();if(Y.ripgrepTargetDir){if(await OX3(Y.ripgrepTargetDir,J,Z),jD())await EX3(Y.ripgrepTargetDir,J,Z)}if(Y.installLocalBin)await MX3();let X=!1;if(Y.checkVersion){let K=await vw(Q);if(Z)$$.blue(`[INFO] "amp --version" state is ${K.status}`);if(K.warning)$$.yellow(K.warning);X=K.status==="missing"}if(X&&Y.installLocalBin)await AX3()}g0();vV();import*as Lr0 from"node:os";g0();import{realpath as RX3,stat as IX3}from"node:fs/promises";import{dirname as YT4,join as PX3}from"node:path";async function CX3(J){switch(J){case"npm":{let Q=await RD("npm",["list","-g","-p"]);if(Q.reason!=="success")return P.debug("Failed to get npm global path",{result:Q}),["/usr/local/lib/node_modules/"];if(!Q.output)return["/usr/local/lib/node_modules/"];let Y=`/usr/local/lib/node_modules/
|
|
6206
6206
|
${Q.output}`.split(`
|
|
6207
|
-
`).map((K)=>K.trim()).filter((K)=>K).sort();return Y.filter((K,V)=>{let G=Y[V+1];return!G||!G.includes(K)})}case"pnpm":{let Z=await RD("pnpm",["list","-g","--json"]);if(Z.reason!=="success")return P.debug("Failed to get pnpm global path",{result:Z}),[];let Q=JSON.parse(Z.output);if(Array.isArray(Q)&&Q[0]?.path)return[Q[0].path];return[]}case"yarn":{let Z=await RD("yarn",["global","dir"]);if(Z.reason!=="success")return P.debug("Failed to get yarn global path",{result:Z}),[];return Z.output?[Z.output]:[]}case"bun":return["/.bun/install/global/"];case"brew":return[];case"bootstrap":return[];case"binary":return[]}}function qr0(){if(process.env.AMP_HOME)return!1;if(!process.versions.bun)return!1;let J=process.execPath;return J.includes("/.amp/bin/amp")||J.includes("\\.amp\\bin\\amp")}function XT4(J){return["/opt/homebrew/Cellar/ampcode/","/usr/local/Cellar/ampcode/","/home/linuxbrew/.linuxbrew/Cellar/ampcode/"].some((Q)=>J.includes(Q))}async function sX0(){if(XT4(process.execPath))return"brew";if(qr0())return"binary";if(process.env.AMP_HOME)return"bootstrap";try{let J=process.argv[1]||"";P.debug("Detecting package manager from script path",{currentScript:J});let Z=J;try{Z=await RX3(J),P.debug("Resolved path",{from:J,to:Z})}catch(K){P.debug("Error resolving path",{error:K})}if(P.debug("Resolved installation path",{actualPath:Z}),XT4(Z))return"brew";let Q=["pnpm","yarn","bun","npm"];for(let K of Q)try{let V=await CX3(K);if(V.length===0)continue;if(P.debug("package manager global paths found",{packageManager:K,globalPaths:V}),V.some((G)=>Z.includes(G)))return K}catch(V){P.debug("Failed to query package manager global path",{packageManager:K,error:V})}P.debug("Checking installation directory for lockfiles");let Y=YT4(YT4(Z));P.debug("Checking installation directory",{installDir:Y});let X=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:K,manager:V}of X)try{let G=PX3(Y,K);return P.debug("Checking for lockfile",{filePath:G}),await IX3(G),P.debug("Found package manager lockfile",{file:K,manager:V,filePath:G}),V}catch(G){P.debug("Lockfile not found",{file:K,error:G})}return P.debug("Could not determine package manager from node_modules path"),null}catch(J){return P.debug("Error detecting installed package manager",{error:J}),null}}async function KT4(){let J=process.env.npm_config_user_agent;if(J){if(J.includes("pnpm"))return"pnpm";if(J.includes("yarn"))return"yarn";if(J.includes("bun"))return"bun";if(J.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Z,Q,Y,X]=await Promise.allSettled([rX0("pnpm"),rX0("yarn"),rX0("bun"),rX0("npm")]);if(Z.status==="fulfilled"&&Z.value)return"pnpm";if(Q.status==="fulfilled"&&Q.value)return"yarn";if(Y.status==="fulfilled"&&Y.value)return"bun";if(X.status==="fulfilled"&&X.value)return"npm";return null}async function rX0(J){P.debug("Checking command existence",{command:J});let Z=await RD(J,["--version"]);if(Z.reason==="success")return P.debug("Command found",{command:J,version:Z.output}),!0;else return P.debug("Command not found or failed",{command:J,result:Z}),!1}function VT4(J,Z){let Y=Z?`@sourcegraph/amp@${Z}`:"@sourcegraph/amp";switch(J){case"npm":return["npm",["install","-g",Y]];case"pnpm":return["pnpm",["add","-g",Y]];case"yarn":return["yarn",["global","add",Y]];case"bun":return["bun",["add","-g",Y]];case"brew":return["brew",["upgrade","ampcode/tap/ampcode"]];case"bootstrap":throw Error("Bootstrap updates are handled separately");case"binary":throw Error("Binary updates are handled separately")}}g0();import{execSync as _X3}from"node:child_process";import{createHash as TX3}from"node:crypto";import{chmodSync as SX3,existsSync as kX3,mkdirSync as yX3,readFileSync as GT4,renameSync as vX3,unlinkSync as xX3,writeFileSync as fX3}from"node:fs";import{homedir as uX3}from"node:os";import{join as Pn}from"node:path";var Ur0="https://
|
|
6207
|
+
`).map((K)=>K.trim()).filter((K)=>K).sort();return Y.filter((K,V)=>{let G=Y[V+1];return!G||!G.includes(K)})}case"pnpm":{let Z=await RD("pnpm",["list","-g","--json"]);if(Z.reason!=="success")return P.debug("Failed to get pnpm global path",{result:Z}),[];let Q=JSON.parse(Z.output);if(Array.isArray(Q)&&Q[0]?.path)return[Q[0].path];return[]}case"yarn":{let Z=await RD("yarn",["global","dir"]);if(Z.reason!=="success")return P.debug("Failed to get yarn global path",{result:Z}),[];return Z.output?[Z.output]:[]}case"bun":return["/.bun/install/global/"];case"brew":return[];case"bootstrap":return[];case"binary":return[]}}function qr0(){if(process.env.AMP_HOME)return!1;if(!process.versions.bun)return!1;let J=process.execPath;return J.includes("/.amp/bin/amp")||J.includes("\\.amp\\bin\\amp")}function XT4(J){return["/opt/homebrew/Cellar/ampcode/","/usr/local/Cellar/ampcode/","/home/linuxbrew/.linuxbrew/Cellar/ampcode/"].some((Q)=>J.includes(Q))}async function sX0(){if(XT4(process.execPath))return"brew";if(qr0())return"binary";if(process.env.AMP_HOME)return"bootstrap";try{let J=process.argv[1]||"";P.debug("Detecting package manager from script path",{currentScript:J});let Z=J;try{Z=await RX3(J),P.debug("Resolved path",{from:J,to:Z})}catch(K){P.debug("Error resolving path",{error:K})}if(P.debug("Resolved installation path",{actualPath:Z}),XT4(Z))return"brew";let Q=["pnpm","yarn","bun","npm"];for(let K of Q)try{let V=await CX3(K);if(V.length===0)continue;if(P.debug("package manager global paths found",{packageManager:K,globalPaths:V}),V.some((G)=>Z.includes(G)))return K}catch(V){P.debug("Failed to query package manager global path",{packageManager:K,error:V})}P.debug("Checking installation directory for lockfiles");let Y=YT4(YT4(Z));P.debug("Checking installation directory",{installDir:Y});let X=[{file:"pnpm-lock.yaml",manager:"pnpm"},{file:"yarn.lock",manager:"yarn"},{file:"bun.lockb",manager:"bun"},{file:"package-lock.json",manager:"npm"}];for(let{file:K,manager:V}of X)try{let G=PX3(Y,K);return P.debug("Checking for lockfile",{filePath:G}),await IX3(G),P.debug("Found package manager lockfile",{file:K,manager:V,filePath:G}),V}catch(G){P.debug("Lockfile not found",{file:K,error:G})}return P.debug("Could not determine package manager from node_modules path"),null}catch(J){return P.debug("Error detecting installed package manager",{error:J}),null}}async function KT4(){let J=process.env.npm_config_user_agent;if(J){if(J.includes("pnpm"))return"pnpm";if(J.includes("yarn"))return"yarn";if(J.includes("bun"))return"bun";if(J.includes("npm"))return"npm"}if(process.env.PNPM_HOME||process.env.PNPM_SCRIPT_SRC_DIR)return"pnpm";if(process.env.YARN_WRAP_OUTPUT||process.env.YARNPKG_LOCKFILE_VERSION)return"yarn";if(process.env.BUN_INSTALL)return"bun";let[Z,Q,Y,X]=await Promise.allSettled([rX0("pnpm"),rX0("yarn"),rX0("bun"),rX0("npm")]);if(Z.status==="fulfilled"&&Z.value)return"pnpm";if(Q.status==="fulfilled"&&Q.value)return"yarn";if(Y.status==="fulfilled"&&Y.value)return"bun";if(X.status==="fulfilled"&&X.value)return"npm";return null}async function rX0(J){P.debug("Checking command existence",{command:J});let Z=await RD(J,["--version"]);if(Z.reason==="success")return P.debug("Command found",{command:J,version:Z.output}),!0;else return P.debug("Command not found or failed",{command:J,result:Z}),!1}function VT4(J,Z){let Y=Z?`@sourcegraph/amp@${Z}`:"@sourcegraph/amp";switch(J){case"npm":return["npm",["install","-g",Y]];case"pnpm":return["pnpm",["add","-g",Y]];case"yarn":return["yarn",["global","add",Y]];case"bun":return["bun",["add","-g",Y]];case"brew":return["brew",["upgrade","ampcode/tap/ampcode"]];case"bootstrap":throw Error("Bootstrap updates are handled separately");case"binary":throw Error("Binary updates are handled separately")}}g0();import{execSync as _X3}from"node:child_process";import{createHash as TX3}from"node:crypto";import{chmodSync as SX3,existsSync as kX3,mkdirSync as yX3,readFileSync as GT4,renameSync as vX3,unlinkSync as xX3,writeFileSync as fX3}from"node:fs";import{homedir as uX3}from"node:os";import{join as Pn}from"node:path";var Ur0="https://static.ampcode.com/cli";function FT4(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let J=uX3();if(!J)throw Error("Cannot determine home directory");return Pn(J,".amp")}function bX3(){try{if(process.platform==="linux")return GT4("/proc/cpuinfo","utf8").includes("avx2");if(process.platform==="darwin")return _X3("sysctl -a 2>/dev/null",{encoding:"utf8"}).includes("AVX2")}catch{}return!1}function hX3(){let{platform:J,arch:Z}=process;if(J==="darwin"){if(Z==="arm64")return"darwin-arm64";return"darwin-x64"}if(J==="win32")return"windows-x64";if(J==="linux"){if(Z==="arm64")return"linux-arm64";return bX3()?"linux-x64":"linux-x64-baseline"}return"linux-x64"}async function Wr0(J,Z=300000){let Q=new AbortController,Y=setTimeout(()=>Q.abort(),Z);try{let X=await fetch(J,{signal:Q.signal});return clearTimeout(Y),X}catch(X){if(clearTimeout(Y),X instanceof Error&&X.name==="AbortError")throw Error(`Network timeout after ${Z}ms while fetching: ${J}`);throw X}}function gX3(J,Z){let Q=GT4(J),Y=TX3("sha256");Y.update(Q);let X=Y.digest("hex");if(X!==Z)throw Error(`Checksum verification failed for ${J}
|
|
6208
6208
|
Expected: ${Z}
|
|
6209
6209
|
Actual: ${X}`)}function Dr0(){let J=FT4(),Z=Pn(J,"bin"),Q=process.platform==="win32";return Pn(Z,Q?"amp.exe":"amp")}async function mX3(){let J=`${Ur0}/cli-version.txt`,Z=await Wr0(J);if(!Z.ok)throw Error(`Failed to fetch latest version: ${Z.status}`);return(await Z.text()).trim()}async function zT4(J){let Z=hX3(),Q=FT4(),Y=Pn(Q,"bin");yX3(Y,{recursive:!0});let X=J||await mX3(),V=Z.startsWith("windows")?`amp-${Z}.exe`:`amp-${Z}`,G=`${Z}-amp.sha256`,F=`${Ur0}/${X}/${V}`,z=`${Ur0}/${X}/${G}`,q=Dr0(),U=Pn(Y,"amp.download.tmp");P.debug("Downloading binary update",{platform:Z,version:X,binaryUrl:F});try{let W=await Wr0(z);if(!W.ok)throw Error(`Failed to fetch checksum: ${W.status}`);let D=(await W.text()).trim();P.debug("Downloading binary",{binaryUrl:F});let H=await Wr0(F);if(!H.ok)throw Error(`Failed to download binary: ${H.status}`);let B=await H.arrayBuffer();if(fX3(U,new Uint8Array(B)),gX3(U,D),process.platform!=="win32")SX3(U,493);vX3(U,q),P.info("Binary updated successfully",{binaryPath:q})}catch(W){if(kX3(U))try{xX3(U)}catch{}if(process.platform==="win32"&&pX3(W))throw Error(`Cannot update: the amp binary is locked by a running process.
|
|
6210
6210
|
Please close all amp sessions and run "amp update" again.`);throw Error(`Binary update failed: ${W instanceof Error?W.message:String(W)}`)}}function pX3(J){let Z=J.code??"",Q=(J instanceof Error?J.message:"").toLowerCase();return Z==="EBUSY"||Z==="EPERM"||Z==="EACCES"||Q.includes("being used by another process")||Q.includes("locked")}g0();import{execSync as Br0}from"node:child_process";import{createHash as dX3}from"node:crypto";import{existsSync as xw,mkdirSync as cX3,readFileSync as WT4,renameSync as UT4,rmSync as Cn,writeFileSync as lX3}from"node:fs";import{homedir as iX3}from"node:os";import{join as jq}from"node:path";g0();import{execSync as qT4}from"node:child_process";function Hr0(J){if(J=J.replace(/\/$/,""),!J.startsWith("http://")&&!J.startsWith("https://"))J=`https://${J}`;try{return new URL(J),J}catch{return P.warn(`Invalid registry URL: ${J}, falling back to npmjs.org`),"https://registry.npmjs.org"}}var Aq=null;function ij(){if(Aq)return Aq;let J=process.env.NPM_CONFIG_REGISTRY;if(J)return Aq=Hr0(J),Aq;try{try{let Q=qT4("npm config get @sourcegraph:registry",{encoding:"utf8",timeout:5000,stdio:["pipe","pipe","pipe"]}).trim();if(Q&&Q!=="undefined")return Aq=Hr0(Q),Aq}catch{}let Z=qT4("npm config get registry",{encoding:"utf8",timeout:5000,stdio:["pipe","pipe","pipe"]}).trim();if(Z&&Z!=="undefined")return Aq=Hr0(Z),Aq}catch{}return Aq="https://registry.npmjs.org",Aq}function nX3(){if(process.env.AMP_HOME)return process.env.AMP_HOME;let J=iX3();if(!J)throw Error("Cannot determine home directory. Set AMP_HOME environment variable to ~/.amp and try again.");return jq(J,".amp")}async function Nr0(J,Z=300000){let Q=new AbortController,Y=setTimeout(()=>Q.abort(),Z);try{let X=await fetch(J,{signal:Q.signal});return clearTimeout(Y),X}catch(X){if(clearTimeout(Y),X instanceof Error&&X.name==="AbortError")throw Error(`Network timeout after ${Z}ms while fetching: ${J}`);throw X}}async function aX3(){let J=process.env.AMP_VERSION;if(J)return J;let Z=ij(),Q=await Nr0(`${Z}/@sourcegraph%2Famp`);if(!Q.ok)throw Error("Failed to fetch package metadata from npm registry");let X=(await Q.json())["dist-tags"]?.latest;if(!X)throw Error("Failed to find latest version in npm registry");return X}async function oX3(J){let Z=ij(),Q=await Nr0(`${Z}/@sourcegraph%2Famp/${J}`);if(!Q.ok)throw Error(`Failed to fetch metadata for version ${J}`);let Y=await Q.json(),X=Y.dist?.tarball,K=Y.dist?.integrity;if(!X)throw Error(`Failed to find tarball URL for version ${J}`);return{tarballUrl:X,integrity:K}}function rX3(J){if(!J)return null;let Z=J.match(/sha256-([A-Za-z0-9+/=]+)/);if(Z?.[1]){let Y=Z[1];return{algorithm:"sha256",hash:Buffer.from(Y,"base64").toString("hex")}}let Q=J.match(/sha512-([A-Za-z0-9+/=]+)/);if(Q?.[1]){let Y=Q[1];return{algorithm:"sha512",hash:Buffer.from(Y,"base64").toString("hex")}}return null}function sX3(J,Z){if(!Z)return;let Q=WT4(J),Y=dX3(Z.algorithm);Y.update(Q);let X=Y.digest("hex");if(X!==Z.hash)throw Error(`Checksum verification failed for ${J}
|
|
@@ -6214,11 +6214,11 @@ ${D}`))}},error:(W)=>{if(!U)U=!0,G(Error(`Failed to spawn brew: ${W.message}`))}
|
|
|
6214
6214
|
${D}`;if(X==="pnpm"&&D.includes("Unable to find the global bin directory"))H+=`
|
|
6215
6215
|
|
|
6216
6216
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6217
|
-
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(W)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();GA();async function tX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=LT4(J,z),U=q<0,W,D;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:U,currentVersionAge:W,latestVersionAge:D}),{hasUpdate:U,latestVersion:z,currentVersion:J,currentVersionAge:W,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var QK3="https://
|
|
6217
|
+
npm install -g @sourcegraph/amp`;G(Error(H))}},error:(W)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${W.message}`))},complete:()=>{if(!q)q=!0,V()}})})}g0();g0();GA();async function tX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=LT4(J,z),U=q<0,W,D;if(F.time){let H=F.time[J],B=F.time[z],N=Date.now();if(H)W=Math.floor((N-new Date(H).getTime())/3600000);if(B)D=Math.floor((N-new Date(B).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:U,currentVersionAge:W,latestVersionAge:D}),{hasUpdate:U,latestVersion:z,currentVersion:J,currentVersionAge:W,latestVersionAge:D,source:"npm"}}catch(G){return P.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var QK3="https://static.ampcode.com/cli/cli-version.txt";async function eX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${QK3}?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=LT4(J,X),V=K<0;return P.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return P.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var YK3=604800000;function wT4(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>YK3)return{ageMs:Q};return null}function LT4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function Or0(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?kz(Q):void 0;return{sha:Y,age:X}}catch{return null}}w1();function Er0(J,Z,Q={}){let Y=new e1,X=Y.pipe(c6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new uF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await zz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await zz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await sX0(),U=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:U});let W=U?await eX0(J):await tX0(J,ij());if(!(W.latestVersion&&W.hasUpdate)){K.debug("no update available");return}let D=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let H=W.currentVersionAge-W.latestVersionAge,B=0.5;if(Math.abs(H)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:H}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!D())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Dr0()){if(K.debug("non-standard binary path, showing warning"),!D())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!D())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!D())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"),!D())Y.next("update-available");return}try{await _n(W.latestVersion,q);let H=await vw(W.latestVersion),B={from:W.currentVersion,to:W.latestVersion,...H};if(H.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(H){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await zz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}GA();import{stderr as Rq}from"node:process";function OT4(J){let Z=new $w().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 zr0(Y.force||!1,Y.verbose||!1,"0.0.1774369119-gbb3185"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new $w("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 XK3(Y.targetVersion)});J.addCommand(Q)}async function XK3(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")Rq.write(c0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6218
6218
|
|
|
6219
6219
|
`));try{if(!J){Rq.write(c0.blue(`Checking for updates...
|
|
6220
|
-
`));let{hasUpdate:Y,latestVersion:X}=qr0()?await eX0("0.0.
|
|
6221
|
-
`));let G=await vw("0.0.
|
|
6220
|
+
`));let{hasUpdate:Y,latestVersion:X}=qr0()?await eX0("0.0.1774369119-gbb3185"):await tX0("0.0.1774369119-gbb3185",ij());if(!Y){let K=Or0("0.0.1774369119-gbb3185"),V=K?.age?`released ${K.age} ago`:`built ${kz(new Date("2026-03-24T16:22:07.349Z"))} ago`;Rq.write(c0.green(`✓ Amp is already up to date on version ${"0.0.1774369119-gbb3185"} (${V})
|
|
6221
|
+
`));let G=await vw("0.0.1774369119-gbb3185");if(G.warning)Rq.write(`
|
|
6222
6222
|
`+c0.yellow(G.warning)+`
|
|
6223
6223
|
`);process.exit(0)}if(!X)Rq.write(c0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}Rq.write(c0.blue(`Updating to version ${J}...
|
|
6224
6224
|
`)),await _n(J,void 0,(Y)=>{Rq.write(c0.dim(`Running: ${Y}
|
|
@@ -7043,7 +7043,7 @@ ${Y}`}async function RM3(J,Z){if(!Z?.forceExternal&&Z?.onShowImagePreview&&eb4(J
|
|
|
7043
7043
|
`).trim()});return Q}function sK(J){return J.replace(kM3,"").replace(yM3,"").replace(SM3,"").trim()}function EG0(J){let Z=J.split(`
|
|
7044
7044
|
`);for(let Q=0;Q<Z.length;Q++){let Y=Z[Q]?.trim();if(!Y)continue;let X=Y.match(Kh4);if(X?.[1]){let V=X[1].trim();if(V)return{header:V,lineIndex:Q}}let K=Y.match(Vh4);if(K?.[1]){let V=K[1].trim();if(V)return{header:V,lineIndex:Q}}break}return{}}function Gh4(J,Z){if(Z===void 0)return J;let Q=J.split(`
|
|
7045
7045
|
`);return Q.splice(Z,1),Q.join(`
|
|
7046
|
-
`).trim()}function Fh4(J){let Z=sK(J),Q=EG0(Z);return Gh4(Z,Q.lineIndex)}class SR extends l0{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 zh4}}class zh4 extends d0{_animationTimer;_spinner=new F3;_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=T1.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=sK(this.widget.thinkingBlock.thinking),G=EG0(V),F=Gh4(V,G.lineIndex),z=F.trim().length>0,q=z?new J0({text:new C(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,U=Y?Q.warning:Q.foreground,W=new g({color:Y?X:Q.foreground,dim:!Y}),D=[new C(K,W),new C(G.header??"Thinking",new g({color:U,dim:!Y}))];if(Y)D.push(new C(" (interrupted)",new g({color:Q.warning,italic:!0})));let H=[new J0({text:new C("",void 0,D)})];if(q)H.push(new I0({width:1}),q);let B=new q1({mainAxisSize:"min",children:H}),N={...Bv(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})},w=()=>{if(this.isComplete&&!this.expanded)return;let R=O.map((S)=>{let T=[];if(T.push(new J0({text:new C(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)T.push(new a0({padding:C0.vertical(1),child:new R3({markdown:S.content,styleScheme:N})}));return new x0({crossAxisAlignment:"start",children:T})});return new a0({padding:C0.only({left:2}),child:new rK({children:R})})},L=()=>{if(!this.expanded)return;return new a0({padding:C0.only({left:2}),child:new R3({markdown:F,styleScheme:N})})},O=vM3(F),M=O.length>0&&!!O[0]?.header?w():L(),j=[z?new J4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new x0({crossAxisAlignment:"start",children:[B]})}):new x0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function zL(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},toolProgressByToolUseID:new Map,items:[],todosList:[],mainThread:null}}function kR(J){let{thread:Z,viewState:Q,toolProgressByToolUseID:Y=new Map,resolvedTokenUsage:X}=J;if(!Z)return zL();let{items:K}=MG0(Z,{liveToolProgressByToolUseID:Y}),V=WC({messages:Z.messages}),G=Array.isArray(V)?V:[];return{viewState:Q,subagentContentByParentID:mM3(K,Z,Y),toolProgressByToolUseID:Y,items:K,todosList:G,mainThread:Z,resolvedTokenUsage:X??Z7(Z)}}function xM3(J){return J===b9||J===P3||J===J7||J===F2||J===GC}function fM3(J){return J.content.filter((Z)=>Z.type==="text")}function uM3(J){return J.type==="tool_use"||J.type==="server_tool_use"}function bM3(J){if(J.meta?.openAIResponsePhase==="commentary")return;let Z=fM3(J);if(n3(Z).trim().length===0)return;switch(J.state.type){case"streaming":case"error":return;case"cancelled":return{...J,content:Z};case"complete":if(J.state.stopReason==="tool_use")return;if(J.content.some(uM3))return;return{...J,content:Z}}}function hM3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=bM3(Q.message);if(!Y)continue;Z=Y}return Z}function gM3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function mM3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&xM3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,F)=>{let z=Y.get(G);if(!z||z.status!=="cancelled"||j9(F.status))return F;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,F]of K){let z=[],q;if(F.status==="in-progress"||F.status==="done"||F.status==="error"||F.status==="cancelled")q=F.progress;if(Array.isArray(q)){let U=0;for(let W of q)if(W.tool_uses)for(let D of W.tool_uses){let H=pM3(D,G,U);if(!D.id||D.id.length===0)U++;let B=dM3(D),N=D.normalized_name??D.tool_name,w=gM3(D.input),L=Q?.get(H);z.push({toolUse:zC(N,w,H),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:z}}if(Z){let G=new Map;for(let F of Z.messages){let z=F.parentToolUseId;if(!z)continue;let q=G.get(z)??[];q.push(F),G.set(z,q)}for(let[F,z]of G){let{items:q}=MG0({id:Z.id,messages:z},{includeSubagentMessages:!0,liveToolProgressByToolUseID:Q}),U=q.filter((H)=>H.type==="toolResult").map((H)=>({toolUse:H.toolUse,toolRun:X(F,H.toolResult.run),toolProgress:Q?.get(H.toolUse.id)})),W=hM3(q),D=V[F]??{tools:[]};V[F]={tools:U.length>0?U:D.tools,...W?{terminalAssistantMessage:W}:{}}}}return V}function pM3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function dM3(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 cM3(J){let Z=J.subagentProgressTurns;if(Z&&J.status==="in-progress")return{status:J.status,progress:Z};switch(J.status){case"done":return{status:"done",result:J.content};case"error":return{status:"error",error:{message:J.content||"Tool failed"}};case"cancelled":return{status:"cancelled",...J.content?{reason:J.content}:{}};case"rejected-by-user":return{status:"rejected-by-user",...J.content?{reason:J.content}:{}};case"queued":return{status:"queued"};case"blocked-on-user":return{status:"blocked-on-user"};case"cancellation-requested":return{status:"cancellation-requested"};case"in-progress":default:return{status:"in-progress",...J.content?{progress:{output:J.content}}:{}}}}function MG0(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 F=`${G.role}-${V}`;switch(G.role){case"assistant":{let z=G.state.type==="streaming";for(let U of G.content)if(U.type==="tool_use"){if(X.set(U.id,U),z)K.add(U.id)}if(G.content.some((U)=>U.type==="text"&&U.text.trim()||U.type==="thinking"&&sK(U.thinking).length>0))Q.push({type:"message",id:F,message:G});for(let U of G.content){if(U.type!=="tool_use")continue;let W=!1;for(let B=V+1;B<J.messages.length;B++){if(!Y.has(B))continue;let N=J.messages[B];if(!N)continue;for(let w of N.content)if(w.type==="tool_result"&&w.toolUseID===U.id){W=!0;break}if(W)break}if(W)continue;let D=Z?.liveToolProgressByToolUseID?.get(U.id),H=D?cM3(D):{status:"in-progress"};Q.push({type:"toolResult",id:U.id,toolUse:U,toolResult:{type:"tool_result",toolUseID:U.id,run:H}})}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:F,message:G});break}case"user":{let z=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 U=X.get(q.toolUseID)??$Z(J,q.toolUseID);if(!U)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:U,toolResult:q})}if(z)Q.push({type:"message",id:F,message:G});break}}}return{items:Q}}function Nv(J){let Z=J.toolProgressByToolUseID$.pipe(U1(sK0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,F=()=>{let D=Q();if(!D?.autoSubmitDraft)return!1;return f8({messages:D.messages})===0},z=()=>{let D=Q();if(!D)return;if(f8({messages:D.messages})>0)return;return X40(D,"handoff")?.threadID},q=()=>f8({messages:K()})===0,U=()=>{let D=K().at(-1);return D?.role==="assistant"&&D.state.type==="streaming"},W=F5(J.thread$,J.threadViewState$,Z).pipe(U1(([D,H,B])=>kR({thread:D,viewState:H,toolProgressByToolUseID:B,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return W},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 F()},getEmptyHandoffParentThreadID(){return z()},isThreadEmpty(){return q()},isStreaming(){return U()},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 qh4="Loading thread...";function lM3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class C01{placeholderThreadID;recentThreadIDsSubject=new X4([]);threadTitlesSubject=new X4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new X4({});legacyHandoffNavigationSubject=new e1;initializationStatusSubject=new X4({pending:!0,message:qh4});pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=C3()){this.placeholderThreadID=J;let Z=new X4(lM3(this.placeholderThreadID)),Q=new X4(new Map),Y=new X4(SS(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new X4(Nv({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}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:qh4}),{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 M1(J.threadHandles$.pipe(E5((Z)=>Z!==null)))}}g0();$l();f4();w1();g0();L3();b2();HB();YZ();p80();f4();LW();$p0();P4();D4();w1();f4();function iM3(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||!j9(G.status))K++}return{running:K,blocked:0}}function nM3(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 aM3(J){let Z=nM3(J);if(Z)return Z;return!1}function wv(J,Z,Q={files:[]},Y=void 0){let X=iM3(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:aM3(J),toolState:{running:X.running,blocked:K}}}f4();class _01{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||T01(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(KA3(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(HA3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=jR0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:QA3(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 rM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=ZA3(this.authoritativeThread);this.pendingMessageSubmits=VA3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=qA3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=UA3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=WA3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return oM3(this.authoritativeThread,(Z)=>sM3(Z,J),(Z)=>tM3(Z,this.pendingMessageSubmits),(Z)=>eM3(Z,this.pendingQueuedSubmits),(Z)=>$A3(Z,this.pendingQueuedInterruptMessageIDs))}}function oM3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function rM3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function sM3(J,Z){if(!Z)return J;let Q=Zu1(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:AR0({messages:K,nextMessageId:J.nextMessageId})}}function tM3(J,Z){if(Z.length===0)return J;let Q=AR0(J),Y=Z.map((X,K)=>Wh4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function eM3(J,Z){if(Z.length===0)return J;let Q=Z.map(JA3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function $A3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=jG0(X);if(!K||!Z.has(K)||T01(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Wh4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function JA3(J){return{id:J.clientMessageID,queuedMessage:Wh4(J,-1)}}function ZA3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=AG0(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=jG0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function QA3(J,Z){return J.messages.slice(Z+1).map((Q)=>AG0(Q)).filter((Q)=>Q!==void 0)}function YA3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&AG0(Q)===Z)}function XA3(J,Z){return(J.queuedMessages??[]).some((Q)=>jG0(Q)===Z)}function T01(J){return"interrupt"in J&&J.interrupt===!0}function KA3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||YA3(Q,Y)||XA3(Q,Y)}function VA3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=GA3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=FA3(J,Z);if(!V)return X;let G=zA3(V,K,X.length);return X.slice(G)}function GA3(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 FA3(J,Z){let Q=Uh4(J),Y=Uh4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function zA3(J,Z,Q){let Y=0;for(let X of J){let K=AG0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Uh4(J){return J.messages.filter((Z)=>Z.role==="user")}function qA3(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)=>RR0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function UA3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=jG0(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(T01(G))continue;K.add(V)}return K}function WA3(J,Z){if(!Z)return;return DA3(J,Z)?void 0:Z}function DA3(J,Z){let Q=W5.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!RR0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=W5.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function AG0(J){let Z=W5.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function jG0(J){let Z=W5.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=W5.safeParse(J.id);if(Q.success)return Q.data;return}function HA3(J){return BA3.has(J)}var BA3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var NA3=1e4;class S01{threadWriter;deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);inferenceErrorsSubject=new e1;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=mH("info"),X=mH("error");this.toolRunner=new wn({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(F)=>this.invokeToolForLease(F),batchGuidanceFiles:vX0,renderToolRunError:Wp,log:{info:(F,z)=>Y(F,z),error:(F,z)=>X(F,{error:z}),wsMessage:(F,z,q)=>{P.debug("DTW executor tool runner message",{direction:F,clientID:z,...typeof q==="object"&&q!==null?q:{message:q}})}}}),this.handshakeManager=this.createHandshakeManager();let K=J.getThread();this.optimisticThreadProjection=new _01(K,J.getAgentLoopState());let V=this.optimisticThreadProjection.resolve(K),G=wv(V,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new X4(V),this.thread$=this.threadSubject,this.threadStateSubject=new X4(kR({thread:V,viewState:G,resolvedTokenUsage:Z7(V)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new X4(G),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(U1(sK0)),this.transportSubscriptions.push(F5(this.threadSubject,this.threadViewStateSubject,this.toolProgressByToolUseID$).subscribe(([F,z,q])=>{this.threadStateSubject.next(kR({thread:F,viewState:z,toolProgressByToolUseID:q,resolvedTokenUsage:this.getResolvedTokenUsage()}))})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Q.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.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.threadWriter.write(J),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 f8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(f8(J)>0)return;return X40(J,"handoff")?.threadID}isThreadEmpty(){return f8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return Z7(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.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),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.transport.editUserMessage(V.dtwMessageID,J.content,Gl0(),J.agentMode);let z=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(z);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=ez(),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 F=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),z=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:F});this.writeThread(z)}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.transport.editUserMessage(Y.dtwMessageID,X,Gl0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=ez(),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(){if(this.provider.transport.getConnectionInfo().state==="reconnecting")P.info("Forcing transport reconnect before client write action"),this.provider.transport.disconnect();await this.provider.connect();let Z=this.provider.transport.getConnectionInfo().state;if(Z!=="connected")throw Error(Z==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}async ensureProviderReadyForExecutorActions(J){if(this.provider.transport.getConnectionInfo().state==="reconnecting")P.info("Forcing transport reconnect before executor action"),this.provider.transport.disconnect();await this.provider.connect();let Y=this.provider.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";await this.handshakeManager.ensureReady({timeoutMs:NA3,timeoutMessage:Y})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){let Z=await g6.setThreadMeta({thread:this.provider.threadId,meta:pG(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.transport.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=lw4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.transport.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(U){P.warn("Failed to append manual bash invocation to DTW thread",{error:U}),this.activeError={message:`Failed to sync bash result to thread: ${U instanceof Error?U.message:String(U)}`},this.updateThreadViewStateFromProvider()}},G=(q,U={emitRun:!0})=>{if(X)return;if(X=!0,V(q),U.emitRun)Y.next(q);Y.complete()},F=(q)=>q instanceof Error?q.message:String(q),z=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",z),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await AD({toolName:i6,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 U={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(i6,{args:J,userInput:{accepted:!0}},U).subscribe({next:(W)=>{if(X)return;if(Y.next(W),W.status!=="in-progress")G(W,{emitRun:!1})},error:(W)=>{G({status:"error",error:{message:F(W)}})}})}catch(q){G({status:"error",error:{message:F(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",z)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=j8.safeParse(J);if(!Y.success)return;this.provider.transport.resolveToolApproval(Y.data,Z)}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=qC(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 Gz({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 TJ0()??qp}catch(J){return P.warn("Failed to collect IDE user state for DTW message",{error:J}),qp}}resolveUserMessageGuidanceContext(){let J=Y1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?T6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=Y1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(FJ(J))return Y1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return X1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=n3(J);if(!Z.trim())return;let{paths:Q}=_J0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let F=this.resolveMentionedPathToURI(G,Y);if(!F||!X1.hasPrefix(F,Y.workspaceRoot))continue;let z=F.toString();if(K.has(z))continue;K.add(z);let q=await OQ({stat:(U,W)=>this.deps.filesystem.stat(U,W),readFile:(U,W)=>this.deps.filesystem.readFile(U,W)},F,Y.workspaceRoot,null,X);for(let U of q){if(V.some((W)=>W.uri===U.uri))continue;X.add(U.uri),V.push({uri:U.uri,content:U.content,lineCount:U.lineCount})}}return V.length>0?V:void 0}createHandshakeManager(){return new Nn({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{P.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){P.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((K)=>K.threadId===Z||K.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(mj));for(let K of[...this.toolRunner.sentApprovalRequests])if(!Y.has(K))this.toolRunner.sentApprovalRequests.delete(K);let X=this.provider.transport.getConnectionInfo();if(X.state!=="connected"||X.role!=="executor")return;for(let K of Q){let V=mj(K);if(this.toolRunner.sentApprovalRequests.has(V))continue;let G=_X0(K);this.provider.transport.sendExecutorToolApprovalRequest(G),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=Hn({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{if(this.handshakeManager.handleConnectionChange(J),J.state==="connected"&&J.role==="executor")this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.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.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(_y(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){P.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await xX0({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,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.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=fX0(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await AZ();this.provider.setEnvironment({initial:J})}catch(J){P.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=j8.safeParse(Z);this.provider.transport.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.transport.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await AD({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});P.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 P.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 bX0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await hX0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await m80(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(wv(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}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}}}f4();w1();function Dh4(J){let Z=new X4(J.thread),Q=new X4(wv(J.thread,"idle")),Y=new X4(new Map),X=new X4([]),K=new X4([]),V=(z)=>{let U={...Z.getValue()};if(!z||!z.text&&z.images.length===0)delete U.draft,delete U.autoSubmitDraft;else{let W=[];if(z.text)W.push({type:"text",text:z.text});if(z.images.length>0)W.push(...z.images);U.draft=W,U.autoSubmitDraft=!1}Z.next(U),Q.next(wv(U,"idle"))};return{handle:Nv({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(z)=>(await J.materialize()).sendMessage(z),restoreTo:async(z)=>(await J.materialize()).restoreTo(z),queueMessage:async(z)=>(await J.materialize()).queueMessage(z),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(z)=>(await J.materialize()).setTitle(z),setVisibility:async(z)=>(await J.materialize()).setVisibility(z),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(z)=>{K.next([...K.getValue(),z])},removePendingSkill:(z)=>{K.next(K.getValue().filter((q)=>q.name!==z))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>wA3(Z.getValue()),setDraft:async(z)=>V(z),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function wA3(J){if(!J.draft)return null;let Z=qC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var RG0="Loading thread...",LA3="Importing thread";class aa{deps;recentThreadIDsSubject=new X4([]);threadTitlesSubject=new X4({});activeThreadHandleSubject=new X4(null);allConnectedThreadActivityStatusesSubject=new X4({});initializationStatusSubject=new X4({pending:!1,message:RG0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=mX0({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}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionInfo()?.role??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},F=C3(),z=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:z,comment:Z.goal}],U={id:F,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},W=Dh4({thread:U,materialize:()=>this.materializePendingHandoffThread(F)});return this.pendingHandoffThreads.set(F,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:W,materializingPromise:null}),F}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){P.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(),P.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(),P.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:RG0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=await this.deps.threadService.exclusiveSyncReadWriter(X.threadId),V=Qk({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),G=new S01(X,K,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:V,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,G),G.startProviderSubscription((F)=>{this.applyProviderState(X.threadId,F)}),await this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(G),this.addToRecentThreads(X.threadId),P.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:RG0})}}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)}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y),await this.deps.threadService.flushVersion(J,Y.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[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 ZK0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:LA3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:RG0})},repositoryURL:Z,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 ID(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)}}Ns0();import{readFile as SA3}from"node:fs/promises";import kA3 from"node:readline";import{setTimeout as yA3}from"node:timers/promises";b3();GJ();r_();f4();$D();w1();import{mkdir as OA3,writeFile as EA3}from"node:fs/promises";import MA3 from"node:path";function AA3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function jA3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function RA3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${jA3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function k01(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class y01{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=AA3(J.traceName),Y=RA3(Z,Q);this.traceFilePath=MA3.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:k01(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:k01(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:k01(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 OA3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await EA3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function Hh4(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.gitStatuses().subscribe({next:(Y)=>Z("git_statuses",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()}}}L3();GJ();f4();$D();w1();var IA3=1e4;class v01 extends P1{constructor(J){super(`Thread ${J} was migrated to the DTW runtime and can't be opened in legacy mode. Run without --take-me-back to continue this thread.`);this.name="LegacyModeDTWThreadSwitchError"}}class Nh4{stateSubject;constructor(J){this.stateSubject=new X4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function Bh4(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 PA3(J){if(!J.draft)return null;let Z=qC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function CA3(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}function _A3(J){if(!J?.meta||typeof J.meta!=="object")return!1;return J.meta.usesDtw===!0}async function TA3(J,Z){try{let Q=await V8(`/api/durable-thread-workers/${Z}`,{method:"GET"},J);if(!Q.ok)return!1;return(await Q.json()).usesDtw===!0}catch{return!1}}async function x01(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??C3(),K=c9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let F=await J.threadService.exclusiveSyncReadWriter(X);F.write(Q),await F.asyncDispose(),V=Q}let G=K??await c9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||f8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadSyncService?.updateThreadMeta(X,Y);if(Y&&!Q){let F=J.threadService.observe(X).subscribe((z)=>{if(z.messages.length===0)return;F.unsubscribe(),J.threadSyncService?.uploadThread(X).then(()=>J.threadSyncService?.updateThreadMeta(X,Y)).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let F=J.threadService.observe(X).subscribe(async(z)=>{if(R9(z,"assistant"))await Z.onFirstAssistantMessage?.(X),F.unsubscribe()})}return await G.resume(),G}async function wh4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;if(_A3(Y)||await TA3(J.workerDeps.configService,Z))throw new v01(Z);return x01(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?pG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function Lh4(J,Z,Q){let Y=Z?await wh4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new IG0(J,Y)}class IG0{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 X4([]);pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);threadViewStatesSubject=new X4({});threadTitlesSubject=new X4({});legacyHandoffNavigationSubject=new e1;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Nh4(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 X4(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(U1((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 Nv({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(U1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(U1((X)=>X.state==="active"?X.ephemeralError:void 0),E5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(U1((X)=>Bh4(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>Z7(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.workerDeps.threadSyncService?.sync()},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadSyncService?.updateThreadMeta(J,pG(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,K=this.deps.workerDeps.threadSyncService;if(!K)return;await this.deps.threadService.flushVersion(J,X);let V=K.uploadThread(J),G=new Promise((F,z)=>{setTimeout(()=>z(Error("Thread sync timeout")),IA3)});await Promise.race([V,G])},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"),PA3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:CA3(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 Gz({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 F=!1,z=V.subscribe({next:(q)=>G.next(q),error:(q)=>{F=!0,G.error(q)},complete:()=>{F=!0,G.complete()}});return()=>{if(!F)K.abortController.abort();z.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"&&sK(V.thinking).length>0))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 F={...Z,messages:G};this.refreshDerivedState(F),this.updateInterruptedMessage(F,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.workerDeps.threadSyncService?.sync()};setVisibility=async(J)=>{await this.deps.workerDeps.threadSyncService?.updateThreadMeta(this.currentThreadID,pG(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 c9.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 c9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observePatches(J.thread.id).pipe(Y40()).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=c9.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=c9.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=SS(J,this.latestStatus),Y=Bh4(J);return{threadState:kR({thread:J,viewState:Q,toolProgressByToolUseID:Y,resolvedTokenUsage:Z7(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){try{let Q=this.workersByThreadID.get(J)??await wh4(this.deps,J);this.switchToWorker(Q,Z)}catch(Q){if(Q instanceof v01)throw await this.deps.handleError(Q,J),Q;throw Q}}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 u4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
|
|
7046
|
+
`).trim()}function Fh4(J){let Z=sK(J),Q=EG0(Z);return Gh4(Z,Q.lineIndex)}class SR extends l0{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 zh4}}class zh4 extends d0{_animationTimer;_spinner=new F3;_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=T1.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=sK(this.widget.thinkingBlock.thinking),G=EG0(V),F=Gh4(V,G.lineIndex),z=F.trim().length>0,q=z?new J0({text:new C(this.expanded?"▼":"▶",new g({color:Q.foreground,dim:!0}))}):null,U=Y?Q.warning:Q.foreground,W=new g({color:Y?X:Q.foreground,dim:!Y}),D=[new C(K,W),new C(G.header??"Thinking",new g({color:U,dim:!Y}))];if(Y)D.push(new C(" (interrupted)",new g({color:Q.warning,italic:!0})));let H=[new J0({text:new C("",void 0,D)})];if(q)H.push(new I0({width:1}),q);let B=new q1({mainAxisSize:"min",children:H}),N={...Bv(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})},w=()=>{if(this.isComplete&&!this.expanded)return;let R=O.map((S)=>{let T=[];if(T.push(new J0({text:new C(S.header,new g({color:Q.foreground,dim:!0,bold:!0}))})),this.expanded)T.push(new a0({padding:C0.vertical(1),child:new R3({markdown:S.content,styleScheme:N})}));return new x0({crossAxisAlignment:"start",children:T})});return new a0({padding:C0.only({left:2}),child:new rK({children:R})})},L=()=>{if(!this.expanded)return;return new a0({padding:C0.only({left:2}),child:new R3({markdown:F,styleScheme:N})})},O=vM3(F),M=O.length>0&&!!O[0]?.header?w():L(),j=[z?new J4({onClick:this._handleHeaderClick.bind(this),cursor:"pointer",child:new x0({crossAxisAlignment:"start",children:[B]})}):new x0({crossAxisAlignment:"start",children:[B]})];if(M)j.push(M);return new x0({mainAxisSize:"min",crossAxisAlignment:"start",children:j})}_handleHeaderClick(J){let Z=!this.expanded;this.setState(()=>{this._localExpanded=Z}),this.widget.onToggle?.(Z)}}function zL(){return{viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},subagentContentByParentID:{},toolProgressByToolUseID:new Map,items:[],todosList:[],mainThread:null}}function kR(J){let{thread:Z,viewState:Q,toolProgressByToolUseID:Y=new Map,resolvedTokenUsage:X}=J;if(!Z)return zL();let{items:K}=MG0(Z,{liveToolProgressByToolUseID:Y}),V=WC({messages:Z.messages}),G=Array.isArray(V)?V:[];return{viewState:Q,subagentContentByParentID:mM3(K,Z,Y),toolProgressByToolUseID:Y,items:K,todosList:G,mainThread:Z,resolvedTokenUsage:X??Z7(Z)}}function xM3(J){return J===b9||J===P3||J===J7||J===F2||J===GC}function fM3(J){return J.content.filter((Z)=>Z.type==="text")}function uM3(J){return J.type==="tool_use"||J.type==="server_tool_use"}function bM3(J){if(J.meta?.openAIResponsePhase==="commentary")return;let Z=fM3(J);if(n3(Z).trim().length===0)return;switch(J.state.type){case"streaming":case"error":return;case"cancelled":return{...J,content:Z};case"complete":if(J.state.stopReason==="tool_use")return;if(J.content.some(uM3))return;return{...J,content:Z}}}function hM3(J){let Z;for(let Q of J){if(Q.type!=="message"||Q.message.role!=="assistant")continue;let Y=bM3(Q.message);if(!Y)continue;Z=Y}return Z}function gM3(J){if(typeof J==="object"&&J!==null&&!Array.isArray(J))return J;return{}}function mM3(J,Z,Q){let Y=new Map;for(let G of J)if(G.type==="toolResult"&&xM3(G.toolUse.name))Y.set(G.toolUse.id,G.toolResult.run);let X=(G,F)=>{let z=Y.get(G);if(!z||z.status!=="cancelled"||j9(F.status))return F;return{status:"cancelled",reason:"Parent subagent was cancelled"}},K=Array.from(Y.entries()),V={};for(let[G,F]of K){let z=[],q;if(F.status==="in-progress"||F.status==="done"||F.status==="error"||F.status==="cancelled")q=F.progress;if(Array.isArray(q)){let U=0;for(let W of q)if(W.tool_uses)for(let D of W.tool_uses){let H=pM3(D,G,U);if(!D.id||D.id.length===0)U++;let B=dM3(D),N=D.normalized_name??D.tool_name,w=gM3(D.input),L=Q?.get(H);z.push({toolUse:zC(N,w,H),toolRun:X(G,B),toolProgress:L})}}V[G]={tools:z}}if(Z){let G=new Map;for(let F of Z.messages){let z=F.parentToolUseId;if(!z)continue;let q=G.get(z)??[];q.push(F),G.set(z,q)}for(let[F,z]of G){let{items:q}=MG0({id:Z.id,messages:z},{includeSubagentMessages:!0,liveToolProgressByToolUseID:Q}),U=q.filter((H)=>H.type==="toolResult").map((H)=>({toolUse:H.toolUse,toolRun:X(F,H.toolResult.run),toolProgress:Q?.get(H.toolUse.id)})),W=hM3(q),D=V[F]??{tools:[]};V[F]={tools:U.length>0?U:D.tools,...W?{terminalAssistantMessage:W}:{}}}}return V}function pM3(J,Z,Q){if(typeof J.id==="string"&&J.id.length>0)return J.id;return`${Z}:progress:${Q}`}function dM3(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 cM3(J){let Z=J.subagentProgressTurns;if(Z&&J.status==="in-progress")return{status:J.status,progress:Z};switch(J.status){case"done":return{status:"done",result:J.content};case"error":return{status:"error",error:{message:J.content||"Tool failed"}};case"cancelled":return{status:"cancelled",...J.content?{reason:J.content}:{}};case"rejected-by-user":return{status:"rejected-by-user",...J.content?{reason:J.content}:{}};case"queued":return{status:"queued"};case"blocked-on-user":return{status:"blocked-on-user"};case"cancellation-requested":return{status:"cancellation-requested"};case"in-progress":default:return{status:"in-progress",...J.content?{progress:{output:J.content}}:{}}}}function MG0(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 F=`${G.role}-${V}`;switch(G.role){case"assistant":{let z=G.state.type==="streaming";for(let U of G.content)if(U.type==="tool_use"){if(X.set(U.id,U),z)K.add(U.id)}if(G.content.some((U)=>U.type==="text"&&U.text.trim()||U.type==="thinking"&&sK(U.thinking).length>0))Q.push({type:"message",id:F,message:G});for(let U of G.content){if(U.type!=="tool_use")continue;let W=!1;for(let B=V+1;B<J.messages.length;B++){if(!Y.has(B))continue;let N=J.messages[B];if(!N)continue;for(let w of N.content)if(w.type==="tool_result"&&w.toolUseID===U.id){W=!0;break}if(W)break}if(W)continue;let D=Z?.liveToolProgressByToolUseID?.get(U.id),H=D?cM3(D):{status:"in-progress"};Q.push({type:"toolResult",id:U.id,toolUse:U,toolResult:{type:"tool_result",toolUseID:U.id,run:H}})}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:F,message:G});break}case"user":{let z=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 U=X.get(q.toolUseID)??$Z(J,q.toolUseID);if(!U)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:U,toolResult:q})}if(z)Q.push({type:"message",id:F,message:G});break}}}return{items:Q}}function Nv(J){let Z=J.toolProgressByToolUseID$.pipe(U1(sK0)),Q=()=>J.getCurrentThread?.(),Y=()=>Q()?.title,X=()=>Q()?.agentMode,K=()=>Q()?.messages??[],V=()=>Q()?.queuedMessages??[],G=()=>Q()?.env?.initial.trees?.[0]?.uri,F=()=>{let D=Q();if(!D?.autoSubmitDraft)return!1;return f8({messages:D.messages})===0},z=()=>{let D=Q();if(!D)return;if(f8({messages:D.messages})>0)return;return X40(D,"handoff")?.threadID},q=()=>f8({messages:K()})===0,U=()=>{let D=K().at(-1);return D?.role==="assistant"&&D.state.type==="streaming"},W=F5(J.thread$,J.threadViewState$,Z).pipe(U1(([D,H,B])=>kR({thread:D,viewState:H,toolProgressByToolUseID:B,resolvedTokenUsage:J.getResolvedTokenUsage?.()})));return{get thread$(){return J.thread$},get threadState$(){return W},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 F()},getEmptyHandoffParentThreadID(){return z()},isThreadEmpty(){return q()},isStreaming(){return U()},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 qh4="Loading thread...";function lM3(J){return{id:J,created:Date.now(),v:0,messages:[]}}class C01{placeholderThreadID;recentThreadIDsSubject=new X4([]);threadTitlesSubject=new X4({});threadHandlesSubject;allConnectedThreadActivityStatusesSubject=new X4({});legacyHandoffNavigationSubject=new e1;initializationStatusSubject=new X4({pending:!0,message:qh4});pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);attachedPool=null;attachedPoolSubscriptions=[];attached=!1;readyPromise;readyResolve=null;readyReject=null;constructor(J=C3()){this.placeholderThreadID=J;let Z=new X4(lM3(this.placeholderThreadID)),Q=new X4(new Map),Y=new X4(SS(Z.getValue(),{state:"active",inferenceState:"idle",fileChanges:{files:[]}}));this.threadHandlesSubject=new X4(Nv({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}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:qh4}),{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 M1(J.threadHandles$.pipe(E5((Z)=>Z!==null)))}}g0();$l();f4();w1();g0();L3();b2();HB();YZ();p80();f4();LW();$p0();P4();D4();w1();f4();function iM3(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||!j9(G.status))K++}return{running:K,blocked:0}}function nM3(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 aM3(J){let Z=nM3(J);if(Z)return Z;return!1}function wv(J,Z,Q={files:[]},Y=void 0){let X=iM3(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:aM3(J),toolState:{running:X.running,blocked:K}}}f4();class _01{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||T01(Q))return Z;if(this.pendingQueuedInterruptMessageIDs.has(J.queuedMessageID))return this.buildProjection();return this.pendingQueuedInterruptMessageIDs.add(J.queuedMessageID),this.buildProjection()}optimisticSubmit(J){if(KA3(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(HA3(this.currentAgentLoopState))this.pendingQueuedSubmits.push(Z);else this.pendingMessageSubmits.push(Z);return this.buildProjection()}optimisticEdit(J){let Z=this.buildProjection(),Q=jR0(Z,J.targetMessageID);if(Q<0)return Z;return this.pendingMessageSubmits=[],this.pendingQueuedSubmits=[],this.pendingEdit={targetMessageID:J.targetMessageID,content:J.content,truncatedMessageIDs:QA3(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 rM3(this.pendingMessageSubmits,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs,this.pendingEdit)}reconcilePending(J){let Z=ZA3(this.authoritativeThread);this.pendingMessageSubmits=VA3(J,this.authoritativeThread,Z,this.pendingMessageSubmits),this.pendingQueuedSubmits=qA3(this.authoritativeThread,Z,this.pendingQueuedSubmits),this.pendingQueuedInterruptMessageIDs=UA3(this.authoritativeThread,this.pendingQueuedSubmits,this.pendingQueuedInterruptMessageIDs),this.pendingEdit=WA3(Z,this.pendingEdit)}buildProjection(){if(!this.hasPendingOverlay())return this.authoritativeThread;let J=this.pendingEdit;return oM3(this.authoritativeThread,(Z)=>sM3(Z,J),(Z)=>tM3(Z,this.pendingMessageSubmits),(Z)=>eM3(Z,this.pendingQueuedSubmits),(Z)=>$A3(Z,this.pendingQueuedInterruptMessageIDs))}}function oM3(J,...Z){return Z.reduce((Q,Y)=>Y?Y(Q):Q,J)}function rM3(J,Z,Q,Y){return J.length>0||Z.length>0||Q.size>0||Y!==void 0}function sM3(J,Z){if(!Z)return J;let Q=Zu1(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:AR0({messages:K,nextMessageId:J.nextMessageId})}}function tM3(J,Z){if(Z.length===0)return J;let Q=AR0(J),Y=Z.map((X,K)=>Wh4(X,Q+K));return{...J,messages:[...J.messages,...Y],nextMessageId:Math.max(J.nextMessageId??0,Q+Y.length)}}function eM3(J,Z){if(Z.length===0)return J;let Q=Z.map(JA3);return{...J,queuedMessages:[...J.queuedMessages??[],...Q]}}function $A3(J,Z){if(Z.size===0||!J.queuedMessages?.length)return J;let Q=!1,Y=J.queuedMessages.map((X)=>{let K=jG0(X);if(!K||!Z.has(K)||T01(X))return X;return Q=!0,{...X,interrupt:!0}});if(!Q)return J;return{...J,queuedMessages:Y}}function Wh4(J,Z){return{role:"user",content:J.content,userState:J.userState,discoveredGuidanceFiles:J.discoveredGuidanceFiles,meta:{sentAt:J.sentAt},messageId:Z,dtwMessageID:J.clientMessageID}}function JA3(J){return{id:J.clientMessageID,queuedMessage:Wh4(J,-1)}}function ZA3(J){let Z=new Set,Q=new Set,Y=new Map,X=new Set;for(let K of J.messages){let V=AG0(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=jG0(K);if(V)Q.add(V)}return{userMessageIDs:Z,queuedMessageIDs:Q,userMessagesByID:Y,messageIDsInTimeline:X}}function QA3(J,Z){return J.messages.slice(Z+1).map((Q)=>AG0(Q)).filter((Q)=>Q!==void 0)}function YA3(J,Z){return J.messages.some((Q)=>Q.role==="user"&&AG0(Q)===Z)}function XA3(J,Z){return(J.queuedMessages??[]).some((Q)=>jG0(Q)===Z)}function T01(J){return"interrupt"in J&&J.interrupt===!0}function KA3(J,Z,Q,Y){return J.some((X)=>X.clientMessageID===Y)||Z.some((X)=>X.clientMessageID===Y)||YA3(Q,Y)||XA3(Q,Y)}function VA3(J,Z,Q,Y){if(Y.length===0)return[];let{unmatchedPendingSubmits:X,acknowledgedByID:K}=GA3(Y,Q.userMessageIDs);if(X.length===0)return[];let V=FA3(J,Z);if(!V)return X;let G=zA3(V,K,X.length);return X.slice(G)}function GA3(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 FA3(J,Z){let Q=Uh4(J),Y=Uh4(Z);if(!(Q.length<=Y.length&&Q.every((K,V)=>K.dtwMessageID===Y[V]?.dtwMessageID)))return;return Y.slice(Q.length)}function zA3(J,Z,Q){let Y=0;for(let X of J){let K=AG0(X);if(K&&Z.has(K))continue;if(Y++,Y===Q)return Y}return Y}function Uh4(J){return J.messages.filter((Z)=>Z.role==="user")}function qA3(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)=>RR0(X.content,V.queuedMessage.content));if(K>=0)return Y.splice(K,1),!1;return!0})}function UA3(J,Z,Q){if(Q.size===0)return new Set;let Y=new Map((J.queuedMessages??[]).map((V)=>{let G=jG0(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(T01(G))continue;K.add(V)}return K}function WA3(J,Z){if(!Z)return;return DA3(J,Z)?void 0:Z}function DA3(J,Z){let Q=W5.safeParse(Z.targetMessageID);if(!Q.success)return!1;let Y=J.userMessagesByID.get(Q.data);if(!Y)return!1;if(!RR0(Y.content,Z.content))return!1;return Z.truncatedMessageIDs.every((K)=>{let V=W5.safeParse(K);if(!V.success)return!0;return!J.messageIDsInTimeline.has(V.data)})}function AG0(J){let Z=W5.safeParse(J.dtwMessageID);if(!Z.success)return;return Z.data}function jG0(J){let Z=W5.safeParse(J.queuedMessage.dtwMessageID);if(Z.success)return Z.data;let Q=W5.safeParse(J.id);if(Q.success)return Q.data;return}function HA3(J){return BA3.has(J)}var BA3=new Set(["working","streaming","tool_use","running_tools","awaiting_approval"]);var NA3=1e4;class S01{threadWriter;deps;thread$;threadState$;threadViewState$;inferenceErrors$;toolProgressByToolUseID$;pendingApprovals$;provider;threadSubject;threadStateSubject;threadViewStateSubject;transportSubscriptions=[];clientID=`cli-tui-${crypto.randomUUID()}`;toolRunner;handshakeManager;optimisticThreadProjection;settingsSyncSubscription=null;lastSentSettingsJSON="";pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);inferenceErrorsSubject=new e1;pendingSkills$=this.pendingSkillsSubject;latestPendingApprovals=[];fileChanges={files:[]};activeError=null;retryCountdownTimer=null;advertisedExecutorTools=[];handoffService;providerSubscriptions=null;constructor(J,Z,Q){this.threadWriter=Z;this.deps=Q;this.provider=J;let Y=mH("info"),X=mH("error");this.toolRunner=new wn({clientID:this.clientID,transport:this.provider.transport,executeBuiltinTool:()=>null,invokeTool:(F)=>this.invokeToolForLease(F),batchGuidanceFiles:vX0,renderToolRunError:Wp,log:{info:(F,z)=>Y(F,z),error:(F,z)=>X(F,{error:z}),wsMessage:(F,z,q)=>{P.debug("DTW executor tool runner message",{direction:F,clientID:z,...typeof q==="object"&&q!==null?q:{message:q}})}}}),this.handshakeManager=this.createHandshakeManager();let K=J.getThread();this.optimisticThreadProjection=new _01(K,J.getAgentLoopState());let V=this.optimisticThreadProjection.resolve(K),G=wv(V,J.getAgentLoopState(),this.fileChanges,this.currentEphemeralError());this.threadSubject=new X4(V),this.thread$=this.threadSubject,this.threadStateSubject=new X4(kR({thread:V,viewState:G,resolvedTokenUsage:Z7(V)})),this.threadState$=this.threadStateSubject,this.threadViewStateSubject=new X4(G),this.threadViewState$=this.threadViewStateSubject,this.inferenceErrors$=this.inferenceErrorsSubject,this.toolProgressByToolUseID$=this.provider.toolProgressByToolUseIDChanges().pipe(U1(sK0)),this.transportSubscriptions.push(F5(this.threadSubject,this.threadViewStateSubject,this.toolProgressByToolUseID$).subscribe(([F,z,q])=>{this.threadStateSubject.next(kR({thread:F,viewState:z,toolProgressByToolUseID:q,resolvedTokenUsage:this.getResolvedTokenUsage()}))})),this.pendingApprovals$=this.pendingApprovalsSubject,this.refreshProviderFileChanges(),this.attachTransportHandlers(),this.handoffService=Q.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.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.threadWriter.write(J),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 f8(J)===0}getEmptyHandoffParentThreadID(){let J=this.getCurrentThread();if(f8(J)>0)return;return X40(J,"handoff")?.threadID}isThreadEmpty(){return f8(this.getCurrentThread())===0}isStreaming(){let J=this.getMessages().at(-1);return J?.role==="assistant"&&J.state.type==="streaming"}getResolvedTokenUsage(){return Z7(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.handshakeManager.dispose(),this.toolRunner.dispose(),this.provider.dispose(),await this.threadWriter.asyncDispose(),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.transport.editUserMessage(V.dtwMessageID,J.content,Gl0(),J.agentMode);let z=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:V.dtwMessageID,content:J.content});this.writeThread(z);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=ez(),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 F=V.map((q)=>({uri:q.uri,lineCount:q.lineCount??0,...typeof q.content==="string"?{content:q.content}:{}})),z=this.optimisticThreadProjection.optimisticUpdate({type:"update-submit-guidance",clientMessageID:Y,discoveredGuidanceFiles:F});this.writeThread(z)}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.transport.editUserMessage(Y.dtwMessageID,X,Gl0());let K=this.optimisticThreadProjection.optimisticUpdate({type:"edit",targetMessageID:Y.dtwMessageID,content:X});this.writeThread(K)}async queueMessage(J){let Z=ez(),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(){if(this.provider.transport.getConnectionInfo().state==="reconnecting")P.info("Forcing transport reconnect before client write action"),this.provider.transport.disconnect();await this.provider.connect();let Z=this.provider.transport.getConnectionInfo().state;if(Z!=="connected")throw Error(Z==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.")}async ensureProviderReadyForExecutorActions(J){if(this.provider.transport.getConnectionInfo().state==="reconnecting")P.info("Forcing transport reconnect before executor action"),this.provider.transport.disconnect();await this.provider.connect();let Y=this.provider.transport.getConnectionInfo().state==="reconnecting"?"Timed out while reconnecting. Please retry after reconnecting.":"Timed out waiting for connection. Please retry.";await this.handshakeManager.ensureReady({timeoutMs:NA3,timeoutMessage:Y})}rollbackOptimisticSubmit(J){let Z=this.optimisticThreadProjection.optimisticUpdate({type:"drop-submit",clientMessageID:J});this.writeThread(Z)}async setVisibility(J){let Z=await g6.setThreadMeta({thread:this.provider.threadId,meta:pG(J)},{config:this.deps.configService});if(!Z.ok)throw Error(Z.error.code)}async setTitle(J){let Z=J.trim();if(!Z)return;await this.ensureProviderReadyForExecutorActions(),this.provider.transport.setThreadTitle(Z),this.updateThread((Q)=>{Q.title=Z})}updateThread(J){let Z=this.threadWriter.update(J),Q=this.optimisticThreadProjection.resolve(Z);if(Q!==Z)this.threadWriter.write(Q);this.threadSubject.next(Q)}async cancelTurn(){this.provider.transport.cancelAgentLoop()}async cancelStreaming(){this.provider.transport.cancelAgentLoop()}async retryTurn(){this.provider.transport.retryAgentLoop()}invokeBashTool(J,Z){let Q=lw4();return new k0((Y)=>{let X=!1,K=null,V=(q)=>{try{this.provider.transport.appendManualBashInvocation({args:J,run:q,hidden:Z.hidden})}catch(U){P.warn("Failed to append manual bash invocation to DTW thread",{error:U}),this.activeError={message:`Failed to sync bash result to thread: ${U instanceof Error?U.message:String(U)}`},this.updateThreadViewStateFromProvider()}},G=(q,U={emitRun:!0})=>{if(X)return;if(X=!0,V(q),U.emitRun)Y.next(q);Y.complete()},F=(q)=>q instanceof Error?q.message:String(q),z=()=>{K?.unsubscribe(),G({status:"cancelled",reason:"User canceled"})};return Z.abortController.signal.addEventListener("abort",z),(async()=>{try{if(await this.ensureProviderReadyForExecutorActions(),X)return;let q=await AD({toolName:i6,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 U={...q,userInitiated:!0};Y.next({status:"in-progress"}),K=this.deps.toolService.invokeTool(i6,{args:J,userInput:{accepted:!0}},U).subscribe({next:(W)=>{if(X)return;if(Y.next(W),W.status!=="in-progress")G(W,{emitRun:!1})},error:(W)=>{G({status:"error",error:{message:F(W)}})}})}catch(q){G({status:"error",error:{message:F(q)}})}})(),()=>{K?.unsubscribe(),Z.abortController.signal.removeEventListener("abort",z)}})}dismissEphemeralError(){this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}async resolveApproval(J,Z,Q){let Y=j8.safeParse(J);if(!Y.success)return;this.provider.transport.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=qC(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 Gz({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 TJ0()??qp}catch(J){return P.warn("Failed to collect IDE user state for DTW message",{error:J}),qp}}resolveUserMessageGuidanceContext(){let J=Y1.file(process.cwd()),Q=this.thread$.getValue().env?.initial,Y=Q?.trees?.[0]?.uri?T6(Q.trees[0].uri):J;return{workspaceRoot:Y.scheme==="file"?Y:J,workingDirectory:J}}resolveMentionedPathToURI(J,Z){if(J.startsWith("file://"))try{let Y=Y1.parse(J);return Y.scheme==="file"?Y:null}catch{return null}if(FJ(J))return Y1.file(J);let Q=J.startsWith("./")||J.startsWith("../")?Z.workingDirectory:Z.workspaceRoot;return X1.resolvePath(Q,J)}async discoverGuidanceFilesForUserMessage(J){let Z=n3(J);if(!Z.trim())return;let{paths:Q}=_J0(Z);if(Q.length===0)return;let Y=this.resolveUserMessageGuidanceContext(),X=new Set,K=new Set,V=[];for(let G of Q){let F=this.resolveMentionedPathToURI(G,Y);if(!F||!X1.hasPrefix(F,Y.workspaceRoot))continue;let z=F.toString();if(K.has(z))continue;K.add(z);let q=await OQ({stat:(U,W)=>this.deps.filesystem.stat(U,W),readFile:(U,W)=>this.deps.filesystem.readFile(U,W)},F,Y.workspaceRoot,null,X);for(let U of q){if(V.some((W)=>W.uri===U.uri))continue;X.add(U.uri),V.push({uri:U.uri,content:U.content,lineCount:U.lineCount})}}return V.length>0?V:void 0}createHandshakeManager(){return new Nn({handshake:(J)=>this.sendExecutorHandshake(J),onError:({error:J,attempt:Z,delayMs:Q})=>{P.warn("DTW executor handshake failed",{error:J,attempt:Z,delayMs:Q})},onExhausted:(J)=>{this.handleHandshakeExhausted(J)}})}handleHandshakeExhausted(J){P.error("DTW executor handshake exhausted",J)}syncApprovalRequests(J){let Z=this.provider.threadId;if(!Z){this.pendingApprovalsSubject.next([]);return}let Q=J.filter((K)=>K.threadId===Z||K.mainThreadId===Z);this.pendingApprovalsSubject.next(Q);let Y=new Set(Q.map(mj));for(let K of[...this.toolRunner.sentApprovalRequests])if(!Y.has(K))this.toolRunner.sentApprovalRequests.delete(K);let X=this.provider.transport.getConnectionInfo();if(X.state!=="connected"||X.role!=="executor")return;for(let K of Q){let V=mj(K);if(this.toolRunner.sentApprovalRequests.has(V))continue;let G=_X0(K);this.provider.transport.sendExecutorToolApprovalRequest(G),this.toolRunner.sentApprovalRequests.add(V)}}handleExecutorToolApprovalResponse(J){this.deps.toolService.resolveApproval(J.toolCallId,J.accepted,J.input?.denyFeedback)}syncExecutorTools(J){let Z=this.provider.transport.getConnectionInfo();if(Z.state!=="connected"||Z.role!=="executor")return;this.advertisedExecutorTools=Hn({transport:this.provider.transport,nextTools:J,previouslyAdvertisedTools:this.advertisedExecutorTools})}attachTransportHandlers(){this.transportSubscriptions.push(this.provider.transport.connectionChanges().subscribe({next:(J)=>{if(this.handshakeManager.handleConnectionChange(J),J.state==="connected"&&J.role==="executor")this.syncApprovalRequests(this.latestPendingApprovals)}}),this.provider.compactionStateChanges().subscribe({next:()=>{this.updateThreadViewStateFromProvider()}}),this.provider.transport.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.transport.errors().subscribe({next:(J)=>{this.inferenceErrorsSubject.next(Error(J.message))}}),this.provider.transport.cancelledEvents().subscribe({next:()=>{this.activeError=null,this.clearRetryCountdownTimer(),this.updateThreadViewStateFromProvider()}}),this.provider.transport.toolLeases().subscribe({next:(J)=>{this.toolRunner.handleToolLease(J)}}),this.provider.transport.toolLeaseRevoked().subscribe({next:(J)=>{this.toolRunner.handleToolRevocation(J)}}),this.provider.transport.executorRollbackRequests().subscribe({next:(J)=>{this.handleRollbackRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadDirectoryRequests().subscribe({next:(J)=>{this.handleFileSystemReadDirectoryRequest(J).catch(()=>{return})}}),this.provider.transport.fileSystemReadFileRequests().subscribe({next:(J)=>{this.handleFileSystemReadFileRequest(J).catch(()=>{return})}}),this.provider.transport.executorToolApprovalResponses().subscribe({next:(J)=>{this.handleExecutorToolApprovalResponse(J)}}),this.deps.toolService.tools.subscribe({next:(J)=>{this.syncExecutorTools(_y(J))}}),this.deps.toolService.pendingApprovals$.subscribe((J)=>{this.latestPendingApprovals=J,this.syncApprovalRequests(J)}))}async sendExecutorHandshake(J){P.debug("DTW executor handshake",{trigger:J,threadID:this.provider.threadId}),this.settingsSyncSubscription?.unsubscribe(),this.settingsSyncSubscription=null;let{advertisedTools:Z}=await xX0({transport:this.provider.transport,executorClientID:this.clientID,workspaceRoot:process.cwd(),threadId:this.provider.threadId,resumeFromVersion:this.provider.getThread().v,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.applyLocalEnvironment(),this.settingsSyncSubscription=this.deps.configService.config.subscribe({next:(Q)=>{this.lastSentSettingsJSON=fX0(this.provider.transport,Q,this.lastSentSettingsJSON)}})}async applyLocalEnvironment(){try{let J=await AZ();this.provider.setEnvironment({initial:J})}catch(J){P.debug("Failed to apply local environment",{error:J})}}createDTWArtifactSyncService(){return{upsertArtifact:(J,Z)=>{let Q=j8.safeParse(Z);this.provider.transport.sendExecutorArtifactUpsert(J,Q.success?Q.data:void 0)},deleteArtifact:(J)=>{this.provider.transport.sendExecutorArtifactDelete(J)}}}async invokeToolForLease(J){let Z=typeof J.args==="object"&&J.args!==null?J.args:{},Q=Date.now(),Y=await AD({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});P.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 P.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 bX0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadDirectoryResult(J.requestId,Z)}async handleFileSystemReadFileRequest(J){let Z=await hX0({fileSystem:this.deps.filesystem,workspaceRoot:process.cwd()},J.uri);this.provider.transport.sendExecutorFileSystemReadFileResult(J.requestId,Z)}async refreshProviderFileChanges(){this.fileChanges={files:await m80(this.deps.fs.tracker)},this.updateThreadViewStateFromProvider()}updateThreadViewStateFromProvider(){this.threadViewStateSubject.next(wv(this.threadSubject.getValue(),this.provider.getAgentLoopState(),this.fileChanges,this.currentEphemeralError())),this.deps.onThreadViewStateChange()}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}}}f4();w1();function Dh4(J){let Z=new X4(J.thread),Q=new X4(wv(J.thread,"idle")),Y=new X4(new Map),X=new X4([]),K=new X4([]),V=(z)=>{let U={...Z.getValue()};if(!z||!z.text&&z.images.length===0)delete U.draft,delete U.autoSubmitDraft;else{let W=[];if(z.text)W.push({type:"text",text:z.text});if(z.images.length>0)W.push(...z.images);U.draft=W,U.autoSubmitDraft=!1}Z.next(U),Q.next(wv(U,"idle"))};return{handle:Nv({thread$:Z,threadViewState$:Q,toolProgressByToolUseID$:Y,pendingApprovals$:X,pendingSkills$:K,getCurrentThread:()=>Z.getValue(),sendMessage:async(z)=>(await J.materialize()).sendMessage(z),restoreTo:async(z)=>(await J.materialize()).restoreTo(z),queueMessage:async(z)=>(await J.materialize()).queueMessage(z),discardQueuedMessages:async()=>{},interruptQueuedMessage:async()=>{},setTitle:async(z)=>(await J.materialize()).setTitle(z),setVisibility:async(z)=>(await J.materialize()).setVisibility(z),cancelTurn:async()=>{},cancelStreaming:async()=>{},retryTurn:async()=>{},dismissEphemeralError:()=>{},resolveApproval:async()=>{},addPendingSkill:(z)=>{K.next([...K.getValue(),z])},removePendingSkill:(z)=>{K.next(K.getValue().filter((q)=>q.name!==z))},clearPendingSkills:()=>{K.next([])},getDraft:async()=>wA3(Z.getValue()),setDraft:async(z)=>V(z),getFilesAffectedByTruncation:async()=>[],clearPendingNavigation:async()=>{},getGuidanceFiles:async()=>[]}),getThreadViewState:()=>Q.getValue(),dispose:async()=>{Z.complete(),Q.complete(),Y.complete(),X.complete(),K.complete()}}}function wA3(J){if(!J.draft)return null;let Z=qC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}var RG0="Loading thread...",LA3="Importing thread";class aa{deps;recentThreadIDsSubject=new X4([]);threadTitlesSubject=new X4({});activeThreadHandleSubject=new X4(null);allConnectedThreadActivityStatusesSubject=new X4({});initializationStatusSubject=new X4({pending:!1,message:RG0});threadHandleMap=new Map;pendingHandoffThreads=new Map;threadBackStack=[];threadForwardStack=[];isThreadActivationInProgress=!1;activeThreadContextID=null;handoffService;queueOnSubmitByDefault=!0;constructor(J){this.deps=J;this.handoffService=mX0({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}getTransportConnectionState(){return this.activeProvider?.getConnectionInfo()?.state??"disconnected"}getTransportConnectionRole(){return this.activeProvider?.getConnectionInfo()?.role??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},F=C3(),z=Date.now(),q=[{threadID:J,type:"handoff",role:"child",...K.parentMessageIndex!==void 0?{messageIndex:K.parentMessageIndex}:{},createdAt:z,comment:Z.goal}],U={id:F,created:Date.now(),v:0,messages:[],relationships:q,...V?{agentMode:V}:{},...K.content.length>0?{draft:K.content,autoSubmitDraft:!1}:{}},W=Dh4({thread:U,materialize:()=>this.materializePendingHandoffThread(F)});return this.pendingHandoffThreads.set(F,{agentMode:V??void 0,relationship:G,repositoryURL:X,threadRelationships:q,optimisticHandle:W,materializingPromise:null}),F}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){P.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(),P.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(),P.info("[dtw-thread-pool] activateThread:optimistic",{activeThreadID:J,handleCount:this.threadHandleMap.size});return}this.isThreadActivationInProgress=!0,this.setInitializationStatus({pending:!0,message:RG0});try{let X=await this.createProvider(J);if(Z?.threadRelationships&&Z.threadRelationships.length>0)X.setRelationships(Z.threadRelationships);let K=await this.deps.threadService.exclusiveSyncReadWriter(X.threadId),V=Qk({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.osFileSystem,X.threadId),G=new S01(X,K,{configService:this.deps.configService,toolService:this.deps.toolService,skillService:this.deps.skillService,mcpService:this.deps.mcpService,initialToolDiscovery:this.deps.initialToolDiscovery,fs:V,filesystem:this.deps.osFileSystem,threadService:this.deps.threadService,onThreadViewStateChange:()=>{this.syncAllConnectedThreadActivityStatuses()},handoffService:this.handoffService});this.threadHandleMap.set(X.threadId,G),G.startProviderSubscription((F)=>{this.applyProviderState(X.threadId,F)}),await this.applyProviderState(X.threadId,X.getThread()),this.activeThreadContextID=X.threadId,this.activeThreadHandleSubject.next(G),this.addToRecentThreads(X.threadId),P.info("[dtw-thread-pool] activateThread:created",{activeThreadID:X.threadId,handleCount:this.threadHandleMap.size})}finally{this.isThreadActivationInProgress=!1,this.setInitializationStatus({pending:!1,message:RG0})}}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)}async applyProviderState(J,Z){let Q=this.threadHandleMap.get(J);if(!Q)return;let Y=Q.resolveAuthoritativeThread(Z);Q.writeThread(Y),await this.deps.threadService.flushVersion(J,Y.v).catch(()=>{return}),this.threadTitlesSubject.next({...this.threadTitlesSubject.getValue(),[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 ZK0.create({ampURL:this.deps.ampURL,configService:this.deps.configService,connectOnCreate:Boolean(J),executorType:Q,onLegacyImportStateChange:(Y)=>{if(Y==="importing"){this.setInitializationStatus({pending:!0,message:LA3});return}if(this.isThreadActivationInProgress)this.setInitializationStatus({pending:!0,message:RG0})},repositoryURL:Z,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 ID(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)}}Ns0();import{readFile as SA3}from"node:fs/promises";import kA3 from"node:readline";import{setTimeout as yA3}from"node:timers/promises";b3();GJ();r_();f4();$D();w1();import{mkdir as OA3,writeFile as EA3}from"node:fs/promises";import MA3 from"node:path";function AA3(J){let Z=J?.trim();return Z&&Z.length>0?Z:void 0}function jA3(J){let Z=J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);return Z.length>0?Z:"trace"}function RA3(J,Z){let Q=new Date(J).toISOString().replace(/[:.]/g,"-");return`${Z?`dtw-trace-${jA3(Z)}`:"dtw-trace"}-${Q}-${crypto.randomUUID().slice(0,8)}`}function k01(J){let Z=JSON.stringify(J);if(Z===void 0)return null;return JSON.parse(Z)}class y01{options;traceFilePath;session;constructor(J){this.options=J;let Z=Date.now(),Q=AA3(J.traceName),Y=RA3(Z,Q);this.traceFilePath=MA3.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:k01(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:k01(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:k01(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 OA3(this.options.traceDir,{recursive:!0});let J=JSON.stringify(this.session,null,2);return await EA3(this.traceFilePath,J,"utf-8"),this.traceFilePath}}function Hh4(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.gitStatuses().subscribe({next:(Y)=>Z("git_statuses",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()}}}L3();GJ();f4();$D();w1();var IA3=1e4;class v01 extends P1{constructor(J){super(`Thread ${J} was migrated to the DTW runtime and can't be opened in legacy mode. Run without --take-me-back to continue this thread.`);this.name="LegacyModeDTWThreadSwitchError"}}class Nh4{stateSubject;constructor(J){this.stateSubject=new X4(J)}get state$(){return this.stateSubject}get state(){return this.stateSubject.getValue()}update(J){this.stateSubject.next(J)}}function Bh4(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 PA3(J){if(!J.draft)return null;let Z=qC(J.draft);if(!Z.text&&Z.images.length===0)return null;return Z}function CA3(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}function _A3(J){if(!J?.meta||typeof J.meta!=="object")return!1;return J.meta.usesDtw===!0}async function TA3(J,Z){try{let Q=await V8(`/api/durable-thread-workers/${Z}`,{method:"GET"},J);if(!Q.ok)return!1;return(await Q.json()).usesDtw===!0}catch{return!1}}async function x01(J,Z){let{thread:Q,threadMeta:Y}=Z,X=Q?.id??Z.threadID??C3(),K=c9.get(X),V=K?.thread??await J.threadService.get(X);if(Q&&!V){let F=await J.threadService.exclusiveSyncReadWriter(X);F.write(Q),await F.asyncDispose(),V=Q}let G=K??await c9.getOrCreateForThread(J,X);if(Z.agentMode&&!V?.agentMode&&(!V||f8(V)===0))await G.handle({type:"agent-mode",mode:Z.agentMode});if(Y&&Q)await J.threadSyncService?.updateThreadMeta(X,Y);if(Y&&!Q){let F=J.threadService.observe(X).subscribe((z)=>{if(z.messages.length===0)return;F.unsubscribe(),J.threadSyncService?.uploadThread(X).then(()=>J.threadSyncService?.updateThreadMeta(X,Y)).catch(()=>{return})})}if(Z.onFirstAssistantMessage){let F=J.threadService.observe(X).subscribe(async(z)=>{if(R9(z,"assistant"))await Z.onFirstAssistantMessage?.(X),F.unsubscribe()})}return await G.resume(),G}async function wh4(J,Z,Q){await J.validateThreadOwnership?.(Z,Q);let Y=await J.threadService.get(Z)??void 0;if(_A3(Y)||await TA3(J.workerDeps.configService,Z))throw new v01(Z);return x01(J.workerDeps,{threadID:Z,threadMeta:J.switchThreadVisibility?pG(J.switchThreadVisibility):void 0,agentMode:Y?void 0:J.switchThreadAgentMode,thread:Y,onFirstAssistantMessage:J.onFirstAssistantMessage})}async function Lh4(J,Z,Q){let Y=Z?await wh4(J,Z,{nonBlockingOwnershipCheck:Q?.nonBlockingOwnershipCheck??!1}):await J.createThread();return new IG0(J,Y)}class IG0{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 X4([]);pendingApprovalsSubject=new X4([]);pendingSkillsSubject=new X4([]);threadViewStatesSubject=new X4({});threadTitlesSubject=new X4({});legacyHandoffNavigationSubject=new e1;pendingNavigationInFlightThreadID=null;threadBackStack=[];threadForwardStack=[];subscriptions=[];workerSubscription=null;disposing=!1;constructor(J,Z){this.deps=J;this.currentWorker=Z,this.stateTracker=new Nh4(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 X4(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(U1((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 Nv({thread$:this.deps.threadService.observe(J),threadViewState$:this.threadViewStatesSubject.pipe(U1((X)=>X[J]??{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}})),inferenceErrors$:Z.status.pipe(U1((X)=>X.state==="active"?X.ephemeralError:void 0),E5((X)=>X!==void 0)),toolProgressByToolUseID$:this.deps.threadService.observe(J).pipe(U1((X)=>Bh4(X))),pendingApprovals$:this.pendingApprovals$,pendingSkills$:this.pendingSkills$,getCurrentThread:()=>Z.thread,getResolvedTokenUsage:()=>Z7(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.workerDeps.threadSyncService?.sync()},setVisibility:async(X)=>{Q("setVisibility"),await this.deps.workerDeps.threadSyncService?.updateThreadMeta(J,pG(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,K=this.deps.workerDeps.threadSyncService;if(!K)return;await this.deps.threadService.flushVersion(J,X);let V=K.uploadThread(J),G=new Promise((F,z)=>{setTimeout(()=>z(Error("Thread sync timeout")),IA3)});await Promise.race([V,G])},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"),PA3(Z.thread)},setDraft:async(X)=>{Q("setDraft"),await Z.handle({type:"draft",content:CA3(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 Gz({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 F=!1,z=V.subscribe({next:(q)=>G.next(q),error:(q)=>{F=!0,G.error(q)},complete:()=>{F=!0,G.complete()}});return()=>{if(!F)K.abortController.abort();z.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"&&sK(V.thinking).length>0))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 F={...Z,messages:G};this.refreshDerivedState(F),this.updateInterruptedMessage(F,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.workerDeps.threadSyncService?.sync()};setVisibility=async(J)=>{await this.deps.workerDeps.threadSyncService?.updateThreadMeta(this.currentThreadID,pG(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 c9.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 c9.dispose(J),await this.deps.threadService.delete(J)}subscribeToWorker(J){this.threadSubscription?.unsubscribe(),this.statusSubscription?.unsubscribe(),this.pendingSkillsSubscription?.unsubscribe(),this.threadSubscription=this.deps.threadService.observePatches(J.thread.id).pipe(Y40()).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=c9.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=c9.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=SS(J,this.latestStatus),Y=Bh4(J);return{threadState:kR({thread:J,viewState:Q,toolProgressByToolUseID:Y,resolvedTokenUsage:Z7(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){try{let Q=this.workersByThreadID.get(J)??await wh4(this.deps,J);this.switchToWorker(Q,Z)}catch(Q){if(Q instanceof v01)throw await this.deps.handleError(Q,J),Q;throw Q}}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 u4(J,Z){let Q=Z?` ${JSON.stringify(Z)}`:"";process.stderr.write(`[thread-pool] ${J}${Q}
|
|
7047
7047
|
`)}function Eh4(J,Z){process.stdout.write(`${JSON.stringify({type:"state",reason:J,state:Z})}
|
|
7048
7048
|
`)}function PG0(J,Z){process.stdout.write(`${JSON.stringify({type:J,...Z})}
|
|
7049
7049
|
`)}function vA3(J){if(!J)return[];return xA3(J).map((Z)=>Z.trim()).filter((Z)=>Z.length>0)}function xA3(J){let Z=[],Q="";for(let Y of J){if(Y===";"||Y===`
|
|
@@ -7389,7 +7389,7 @@ Ctrl-X, Y, Z to unlock`;if(W){let u=z.text.replace(/`([^`]+)`/g,"$1")+`
|
|
|
7389
7389
|
`),K=[];for(let V=0;V<X.length;V++){let z=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
|
|
7390
7390
|
`))}return new i0({decoration:{color:Q.colorScheme.background,border:d1.all(new h1(Y.app.keybind,1,"rounded"))},child:new a0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class h11 extends h${chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=pF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new u11({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 wp4(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?x9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),U=Math.floor(z/q);return U>=0&&U<K?U:null}case"line":case"sparkline":case"stacked-area":{let G=V?x9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),U=Math.round(z/q);return Math.max(0,Math.min(K-1,U))}default:return null}}function cC3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?x9:0,q=Q-z,U=Y-(K?F:0);if(q<=0||U<=0)return null;let W=Math.max(1,Math.floor(q/X)),D=z+Z*W+Math.floor(W/2),H=G>0?V/G:0,B=Math.round((1-H)*(U-1));return{x:D,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?x9:0,q=Q-z,U=Y-(K?F:0);if(q<=0||U<=0)return null;let W=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),D=G>0?V/G:0,H=Math.round((1-D)*(U-1));return{x:W,y:H}}default:return null}}function lC3(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 iC3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function nC3(J,Z,Q,Y,X,K,V){let G;try{let H=T1.of(J),B=f0.of(J);G={foreground:H.colorScheme.foreground,background:H.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new g({color:G.foreground,bold:!0}),z=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),U=[],W=new g({color:G.foreground,underline:!0}),D=(H,B)=>new C(B,W,void 0,zK0(H),()=>{$8(J,H)});if(Y.length<=1){if(U.push(new C(`${Z.label}: `,F)),Z.link)U.push(D(Z.link,K(Z.value)));else U.push(new C(K(Z.value),z));if(Z.meta)U.push(new C(` (${Z.meta})`,q))}else{let H=V==="stacked-bar"||V==="stacked-area";U.push(new C(`${Z.label}
|
|
7391
7391
|
`,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(U.push(new C("● ",new g({color:O}))),U.push(new C(`${w.name}: `,q)),L.link)U.push(D(L.link,K(L.value)));else U.push(new C(K(L.value),z));if(N<Y.length-1||H)U.push(new C(`
|
|
7392
|
-
`))}if(H)U.push(new C(" ",q)),U.push(new C("Total: ",q)),U.push(new C(K(B),z))}return new i0({decoration:{color:G.background,border:d1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,U)})})}LE();g0();S2();import{execSync as E_3}from"node:child_process";RE();M$();b3();T7();Fc();GA();TV();GJ();YZ();NY();gA();f4();Om();Lb();w1();var wd4=G4(VW(),1);import{writeFile as Wd4}from"fs/promises";import Dd4 from"path";g0();GJ();class g11{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.1774354153-gdeebb8"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D60(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ML extends l0{props;constructor(J){super();this.props=J}createState(){return new Lp4}}class Lp4 extends d0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Op4 extends d0{controller=new K$;focusNode=new U6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=d1.all(new h1(Q.foreground,1,"solid")),F=new xZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),U=[];if(V)U.push(new C("Enter",new g({color:Y.keybind}))),U.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));U.push(new C("Esc",new g({color:Y.keybind}))),U.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let W=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,U)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),z,new g3,W]})})}}class Eo extends l0{props;constructor(J){super();this.props=J}createState(){return new Op4}}import{isDeepStrictEqual as m11}from"node:util";var aC3=/[\\/_ +.#"@[({&]/,oC3=/[\\/_ +.#"@[({&]/g,rC3=/[\s-]/,Ep4=/[\s-]/g;function lF0(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 F=Y.charAt(K),z=Q.indexOf(F,X),q=0,U,W,D,H;while(z>=0){if(U=lF0(J,Z,Q,Y,z+1,K+1,V),U>q){if(z===X)U*=1;else if(rC3.test(J.charAt(z-1))){if(U*=0.9,H=J.slice(X,z-1).match(Ep4),H&&X>0)U*=0.999**H.length}else if(aC3.test(J.charAt(z-1))){if(U*=0.8,D=J.slice(X,z-1).match(oC3),D&&X>0)U*=0.999**D.length}else if(U*=0.3,X>0)U*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(K))U*=0.9999}if(U<0.1&&(Q.charAt(z-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(z-1)!==Y.charAt(K))){if(W=lF0(J,Z,Q,Y,z+1,K+2,V),W*0.1>U)U=W*0.1}if(U>q)q=U;z=Q.indexOf(F,z+1)}return V[G]=q,q}function cF0(J){return J.toLowerCase().replace(Ep4," ")}function Mp4(J,Z){let Q=lF0(J,Z,cF0(J),cF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let F=lF0(J,G,cF0(J),cF0(G),0,0,{});if(F===0)return Q;X+=F,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class dv{}class cv{}class iF0{}class nF0{}class Ap4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new jp4}}class jp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function sC3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Mp4(Z,J);return{matches:Q>0.15,score:Q}}class s2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Rp4}}class Rp4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new K$(this.widget.props.controller?.query??""),this.focusNode=new U6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>m11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!m11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>m11(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 dv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof cv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof iF0){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 nF0)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,...sC3(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;uv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=d1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new xZ({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}),F=new l$({shortcuts:new Map([[new H4("ArrowDown"),new dv],[new H4("ArrowUp"),new cv],[new H4("Tab"),new dv],[new H4("Tab",{shift:!0}),new cv],[new H4("n",{ctrl:!0}),new dv],[new H4("p",{ctrl:!0}),new cv],[new H4("Enter"),new iF0],[new H4("Escape"),new nF0]]),focusNode:this.focusNode,child:G}),z=new A2({actions:new Map([[dv,new W6(this.invoke)],[cv,new W6(this.invoke)],[iF0,new W6(this.invoke)],[nF0,new W6(this.invoke)]]),child:F}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]});this.itemContexts=[];let U;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";U=new I0({height:10,child:new Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)U=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Ap4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});U=new x0({children:N,crossAxisAlignment:"start"})}let W=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:U})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:W}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:W}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Ip4(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 p11 extends $4{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)=>Ip4(X.pubDate).length));return new s2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,U=K?q.selectionBackground:void 0,W=K?q.selectionForeground:z.foreground,D=z.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:D}))})])});return new i0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Ip4(X.pubDate),Q)]})})}})}}class d11 extends l0{createState(){return new Pp4}}class Pp4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function tC3(J){return CY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function eC3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return OG0.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 c11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function $_3(J,Z,Q,Y){return[c11("+",J,Y.success),g3.horizontal(1),c11("~",Z,Y.warning),g3.horizontal(1),c11("-",Q,Y.destructive)]}function J_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class aF0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Cp4}}class Cp4 extends d0{spinner=new F3;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),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=eC3(z),U=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),W=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=tC3(L);return B};return new s2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!J_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,S=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,f=R.mutedForeground,m=(s,z0)=>new I0({width:z0,child:q1.end([new J0({text:new C(s,new g({color:f}))})])}),x=Z.threadViewStates[L.id],_=[],u=L.relationshipType==="handoff",p=new na({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],z0=L.ancestorsAreLast.slice(1);for(let w0 of z0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=F===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(kN(x))d.push(new d11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(u)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:f,warning:f,destructive:f}:R;d.push(...$_3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,U)),new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[..._,...d]})})}})}}function _p4(J){return 1-(1-J)**3}function Tp4(J,Z,Q){return J+(Z-J)*Q}function Mo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=_p4(Y),V=_p4(X);return{x:Tp4(J.startOffset.x,J.targetOffset.x,K),y:Tp4(J.startOffset.y,J.targetOffset.y,V)}}var Z_3={nodeWidth:3,horizontalSpacing:3};class lv{options;constructor(J={}){this.options={...Z_3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,F)=>{let z=Z.get(G.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(z.length===0){Y.push({node:q,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let U=[];for(let B of z)U.push(V(B,F+1));let W=Math.min(...U),D=Math.max(...U),H=Math.floor((W+D)/2);return Y.push({node:q,position:{x:H,y:F}}),H};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var Q_3={nodeWidth:3,nodeHeight:2};class iv{options;constructor(J={}){this.options={...Q_3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var Y_3={nodeWidth:3,nodeHeight:2},X_3={x:0,y:0};class rF0{options;constructor(J={}){this.options={...Y_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=X_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],T=0;for(let f of R){if(f.position.x>T)S.push(new I0({width:f.position.x-T}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,_=K?.activeFlashOn??!1,u=f.node.id===K?.copyFlashNodeId;S.push(this.renderNode(m,x,_,u,q,z)),T=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:T,child:this.renderInfoBox(j,f,z,q)}))}return new i0({padding:C0.horizontal(2),child:new lG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,z=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",G="┗━┛",z=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:F,bold:z}))}),new J0({text:new C(G,new g({color:F,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((W)=>W.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,U=[new J0({text:new C(G,new g({color:z}))})];for(let W of X){let D=" ".repeat(K-W.length);U.push(new J0({text:new C("│ ",new g({color:z}),[new C(W+D,new g({color:q??z})),new C(" │",new g({color:z}))])}))}return U.push(new J0({text:new C(F,new g({color:z}))})),new x0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let W of Z){let D=W.position.x+G;if(D>=0&&D<Y)z[D]="▲"}V.push(new J0({text:new C(z.join(""),new g({color:F}))}));let q=Array(Y).fill(" ");for(let W of J){let D=Z.filter((L)=>L.node.parentID===W.node.id);if(D.length===0)continue;let H=W.position.x+G,B=D.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===H)if(D.length===1&&B[0]===H)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:F}))}));let U=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+G;if(H>=0&&H<Y)U[H]="│"}return V.push(new J0({text:new C(U.join(""),new g({color:F}))})),V}}var K_3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},V_3={x:0,y:0};class l11{options;constructor(J={}){this.options={...K_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=V_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],T=0;for(let f of R){if(f.position.x>T)S.push(new I0({width:f.position.x-T}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,_=K?.activeFlashOn??!1;S.push(this.renderNode(m,x,_,q,z)),T=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:T,child:this.renderInfoBox(j,f,z)}))}return new i0({padding:C0.horizontal(2),child:new lG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let U=Z.filter((N)=>N.node.parentID===q.node.id);if(U.length===0)continue;let W=q.position.x+G,D=U.map((N)=>N.position.x+G),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,L=D.includes(N);if(w&&L)if(U.length===1)z[N]="│";else if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┼";else if(w)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┬";else if(L)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┴";else if(z[N]===" ")z[N]="─"}}return V.push(new J0({text:new C(z.join(""),new g({color:F}))})),V}}class Ao extends s3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Sp4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Sp4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class mR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vp4}}var kp4=400,yp4=300,G_3=16;class vp4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new lv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new iv;renderer=new l11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let z=this.widget.props.threads.find((q)=>q.id===K);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),G=this.widget.props.threads.some((F)=>F.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:kp4,durationY:yp4};let Z=Math.max(kp4,yp4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Mo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},G_3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,F=Math.floor(this.viewportHeight/2),q=Math.floor(F/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((U)=>U.node.id===this.selectedNodeId):null)??this.positionedNodes.find((U)=>!U.node.parentID);if(q){let U=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,U)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),F=new Ao({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class fp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new up4}}class up4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var xp4=30,F_3=30;class nv{}class av{}class sF0{}class tF0{}class i11 extends l0{props;constructor(J){super();this.props=J}createState(){return new bp4}}class bp4 extends d0{highlightedIndex=0;controller=new K$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new U6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;uv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof nv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof av){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof sF0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof tF0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=F_3+xp4,F=d1.all(new h1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),U=new xZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new l$({shortcuts:new Map([[new H4("ArrowDown"),new nv],[new H4("ArrowUp"),new av],[new H4("Tab"),new nv],[new H4("Tab",{shift:!0}),new av],[new H4("n",{ctrl:!0}),new nv],[new H4("p",{ctrl:!0}),new av],[new H4("Enter"),new sF0],[new H4("Escape"),new tF0]]),focusNode:this.focusNode,child:U}),D=new A2({actions:new Map([[nv,new W6(this.invoke)],[av,new W6(this.invoke)],[sF0,new W6(this.invoke)],[tF0,new W6(this.invoke)]]),child:W}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,S=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,f=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)f.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new fp4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,f)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=z?z.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=z?new i0({padding:C0.all(1),child:new mR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:xp4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class hJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!hJ._instance)hJ._instance=new hJ;return hJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}g0();class hp4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new s2({title:"Add Label",items:F,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(z,q,U,W)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(z.name,new g({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let W=q.trim().toLowerCase();return W.length===0||z.name.includes(W)},sortItems:(z,q,U)=>{let W="__isCreateMarker"in z.item&&z.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(W&&!D)return-1;if(!W&&D)return 1;return q.score-z.score}})}}class n11 extends l0{props;constructor(J){super();this.props=J}createState(){return new hp4}}class eG extends l0{props;constructor(J){super();this.props=J}createState(){return new gp4}}class gp4 extends d0{_spinner=new F3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=d1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),F=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let z=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}var jo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},eF0=["workspace","global","flag","default","external","skill","other"];function z_3(J){return Array.from(new Set(J))}function mp4(J){return z_3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function ov(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return mp4(J).length>0?"skill":"other"}function a11(J){return ov(J)==="skill"}function pp4(J){let Z=mp4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=ov(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${jo[Y].description}: ${Q}`}function dp4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var cp4=process.platform==="win32"?" ":"█",lp4=process.platform==="win32"?"░":"█";class E9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=cp4,thumbChar:K=lp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createState(){return new ip4}}class ip4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),z=X-G,q=Math.max(0,z*F),U=q+G;return J>=q&&J<=U}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),F=Math.max(1,K*G),z=K-F;if(z<=0)return;let q=Z-Q,U=z/q,W=V/U,D=Math.max(0,Math.min(q,this._dragStartOffset+W));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),F=Math.max(1,V*G),z=Q-Y,q=V-F,U=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,q*U),D=W+F;if(Z>=W&&Z<=D)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?d5.POINTER:d5.DEFAULT,child:new np4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class np4 extends yy{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=cp4,thumbChar:K=lp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createRenderObject(){return new ap4(this)}updateRenderObject(J){J.updateWidget(this)}}class ap4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,F=process.platform==="win32",z=Y,q=Y+X;if(!F){let U=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let D="█",H=!0;if(W===Math.floor(z)){let B=1-(z-W),N=Math.floor(B*8);D=U[N]||"█",H=!1}else if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);D=U[N]||"█"}else if(W>z&&W<q)H=!1;J.setChar(Z,Q+W,D,{fg:G,bg:V,reverse:H},1)}return}for(let U=0;U<this.size.height;U++){let W=U+0.5,D=W>=z&&W<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+U,H,{fg:D?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class pR extends l0{props;constructor(J){super();this.props=J}createState(){return new op4}}class op4 extends d0{scrollController=new j5;scrollAreaKey=new J$("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof r2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=PF0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=d1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),F=new k1({child:new i$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new E9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,U=this.scrollController.offset,W=this.getViewportHeight(),D=q+W;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(U,0)}}})]})})})}),z=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let U=new g({color:Z.app.keybind}),W=new g({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",U),new C(" to close • Use ",W),new C("↑↓",U),new C(" or ",W),new C("j/k",U),new C(" to scroll",W)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,z]})})})}}S2();class rp4 extends l0{props;constructor(J){super();this.props=J}createState(){return new sp4}}class sp4 extends d0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=y9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${p4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${p4(V,"command")}, ${G} ${p4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7392
|
+
`))}if(H)U.push(new C(" ",q)),U.push(new C("Total: ",q)),U.push(new C(K(B),z))}return new i0({decoration:{color:G.background,border:d1.all(new h1(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,U)})})}LE();g0();S2();import{execSync as E_3}from"node:child_process";RE();M$();b3();T7();Fc();GA();TV();GJ();YZ();NY();gA();f4();Om();Lb();w1();var wd4=G4(VW(),1);import{writeFile as Wd4}from"fs/promises";import Dd4 from"path";g0();GJ();class g11{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.1774369119-gbb3185"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await D60(Z,this.configService)}catch(Z){P.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ML extends l0{props;constructor(J){super();this.props=J}createState(){return new Lp4}}class Lp4 extends d0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class Op4 extends d0{controller=new K$;focusNode=new U6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=d1.all(new h1(Q.foreground,1,"solid")),F=new xZ({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(D)=>{let H=D.trim();if(X&&H.length===0)return;this.widget.props.onSubmit(H)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:F})]}),q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),U=[];if(V)U.push(new C("Enter",new g({color:Y.keybind}))),U.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));U.push(new C("Esc",new g({color:Y.keybind}))),U.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let W=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,U)})});return new i0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new x0({children:[q,new I0({height:1}),z,new g3,W]})})}}class Eo extends l0{props;constructor(J){super();this.props=J}createState(){return new Op4}}import{isDeepStrictEqual as m11}from"node:util";var aC3=/[\\/_ +.#"@[({&]/,oC3=/[\\/_ +.#"@[({&]/g,rC3=/[\s-]/,Ep4=/[\s-]/g;function lF0(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 F=Y.charAt(K),z=Q.indexOf(F,X),q=0,U,W,D,H;while(z>=0){if(U=lF0(J,Z,Q,Y,z+1,K+1,V),U>q){if(z===X)U*=1;else if(rC3.test(J.charAt(z-1))){if(U*=0.9,H=J.slice(X,z-1).match(Ep4),H&&X>0)U*=0.999**H.length}else if(aC3.test(J.charAt(z-1))){if(U*=0.8,D=J.slice(X,z-1).match(oC3),D&&X>0)U*=0.999**D.length}else if(U*=0.3,X>0)U*=0.999**(z-X);if(J.charAt(z)!==Z.charAt(K))U*=0.9999}if(U<0.1&&(Q.charAt(z-1)===Y.charAt(K+1)||Y.charAt(K+1)===Y.charAt(K)&&Q.charAt(z-1)!==Y.charAt(K))){if(W=lF0(J,Z,Q,Y,z+1,K+2,V),W*0.1>U)U=W*0.1}if(U>q)q=U;z=Q.indexOf(F,z+1)}return V[G]=q,q}function cF0(J){return J.toLowerCase().replace(Ep4," ")}function Mp4(J,Z){let Q=lF0(J,Z,cF0(J),cF0(Z),0,0,{}),Y=Z.trim().split(/\s+/);if(Y.length>1){let X=0,K=0;for(let G of Y){let F=lF0(J,G,cF0(J),cF0(G),0,0,{});if(F===0)return Q;X+=F,K+=G.length}let V=X/Y.length*0.95;return Math.max(Q,V)}return Q}class dv{}class cv{}class iF0{}class nF0{}class Ap4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new jp4}}class jp4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}function sC3(J,Z){if(J==="")return{matches:!0,score:1};let Q=Mp4(Z,J);return{matches:Q>0.15,score:Q}}class s2 extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new Rp4}}class Rp4 extends d0{textController;focusNode;scrollController=new j5;selectedIndex=0;itemContexts=[];hasUserInteracted=!1;cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){if(this.scrollController.disableFollowMode(),this.textController=new K$(this.widget.props.controller?.query??""),this.focusNode=new U6({debugLabel:this.widget.debugLabel}),this.textController.addListener(()=>{this.hasUserInteracted=!0,this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let J=this.widget.props.controller;if(J)J.query=this.textController.text;this.syncSelection()}),this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let J=this.cachedFiltered.findIndex((Z)=>m11(Z,this.widget.props.controller?.selectedItem));if(J>=0)this.selectedIndex=J}this.clampSelectedIndex(),this.syncSelection(),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!m11(J.props.items,this.widget.props.items)){if(this.recomputeFilteredItems(),this.widget.props.controller?.selectedItem){let Z=this.cachedFiltered.findIndex((Q)=>m11(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 dv){let Z=this.getFilteredItems();if(Z.length>0&&this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof cv){if(this.getFilteredItems().length>0&&this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection();return"handled"}if(J instanceof iF0){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 nF0)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,...sC3(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;uv(J,{top:Q,bottom:Y},{padding:1})}handleScroll=(J)=>{let Z=this.getFilteredItems();if(Z.length===0)return!1;let Q=this.selectedIndex;if(J.direction==="down")if(this.selectedIndex<Z.length-1)this.hasUserInteracted=!0,this.selectedIndex++;else return!1;else if(this.selectedIndex>0)this.hasUserInteracted=!0,this.selectedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.syncSelection(),this.selectedIndex!==Q};handleItemClick=(J,Z)=>{let Q=this.getFilteredItems();if(J>=0&&J<Q.length){let Y=Q[J],X=Y?this.widget.props.isItemDisabled?.(Y)??!1:!1;if(Z===1)this.hasUserInteracted=!0,this.selectedIndex=J,this.setState(),this.syncSelection();else if(Z===2&&!X){if(Y)this.hasUserInteracted=!0,this.widget.props.onAccept(Y,{hasUserInteracted:this.hasUserInteracted})}}};build(J){let Z=f0.of(J),{colors:Q}=Z,Y=this.getFilteredItems(),X=d1.all(new h1(Q.foreground,1,"solid")),K=this.widget.props.hidePromptWhenLoading&&this.widget.props.isLoading,V=this.widget.props.enabled??!0,G=new xZ({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}),F=new l$({shortcuts:new Map([[new H4("ArrowDown"),new dv],[new H4("ArrowUp"),new cv],[new H4("Tab"),new dv],[new H4("Tab",{shift:!0}),new cv],[new H4("n",{ctrl:!0}),new dv],[new H4("p",{ctrl:!0}),new cv],[new H4("Enter"),new iF0],[new H4("Escape"),new nF0]]),focusNode:this.focusNode,child:G}),z=new A2({actions:new Map([[dv,new W6(this.invoke)],[cv,new W6(this.invoke)],[iF0,new W6(this.invoke)],[nF0,new W6(this.invoke)]]),child:F}),q=new q1({children:[new i0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new k1({child:z})]});this.itemContexts=[];let U;if(this.widget.props.isLoading){let N=this.widget.props.loadingText??"Loading...";U=new I0({height:10,child:new Z4({child:new J0({text:new C(N,new g({color:Q.foreground}))})})})}else if(Y.length===0&&this.widget.props.emptyStateText)U=new k1({child:new Z4({child:new J0({text:new C(this.widget.props.emptyStateText,new g({color:Q.foreground,dim:!0}))})})});else{let N=Y.map((w,L)=>{let O=L===this.selectedIndex,E=this.widget.props.isItemDisabled?.(w)??!1,M;if(this.widget.props.renderItem)M=this.widget.props.renderItem(w,O,E,J);else{let A=O?Z.app.selectionBackground:void 0,j=O?Z.app.selectionForeground:Q.foreground;M=new i0({decoration:A?{color:A}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(this.widget.props.getLabel(w),new g({color:j,dim:E}))})})}return new Ap4(new J4({onClick:(A)=>this.handleItemClick(L,A.clickCount),child:M}),(A)=>{this.itemContexts[L]=A})});U=new x0({children:N,crossAxisAlignment:"start"})}let W=new J4({onScroll:this.handleScroll,opaque:!1,child:new _6({controller:this.scrollController,autofocus:!1,child:U})}),D=[];if(this.widget.props.title){let N=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(this.widget.props.title,new g({color:Z.app.command,bold:!0}))})});D.push(N)}if(!K)D.push(q,new I0({height:1}));if(this.textController.text!==""){let N=Y.length>0?Y[this.selectedIndex]:void 0,w=N&&this.widget.props.buildDisabledReasonWidget?.(N,J);D.push(new k1({child:new x0({mainAxisAlignment:"spaceBetween",children:[new k1({child:W}),new i0({padding:C0.only({top:1}),child:new Z4({child:w??new I0({height:1})})})]})}))}else D.push(new k1({child:W}));if(this.widget.props.footer)D.push(this.widget.props.footer);return new i0({decoration:{border:X,color:Q.background},padding:C0.symmetric(1,0),child:new x0({children:D})})}}function Ip4(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 p11 extends $4{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)=>Ip4(X.pubDate).length));return new s2({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,U=K?q.selectionBackground:void 0,W=K?q.selectionForeground:z.foreground,D=z.mutedForeground,H=(B,N)=>new I0({width:N,child:q1.end([new J0({text:new C(B,new g({color:D}))})])});return new i0({decoration:U?{color:U}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[new k1({child:new J0({text:new C(X.title,new g({color:W})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),H(Ip4(X.pubDate),Q)]})})}})}}class d11 extends l0{createState(){return new Pp4}}class Pp4 extends d0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function tC3(J){return CY(J,{acceptedHostnames:["ampcode.com","localhost"],allowThreadsPathExtraction:!0})}function eC3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return OG0.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 c11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function $_3(J,Z,Q,Y){return[c11("+",J,Y.success),g3.horizontal(1),c11("~",Z,Y.warning),g3.horizontal(1),c11("-",Q,Y.destructive)]}function J_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class aF0 extends l0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Cp4}}class Cp4 extends d0{spinner=new F3;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),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=eC3(z),U=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),W=f0.of(J),D=new a0({padding:C0.symmetric(0,1),child:new Z4({child:new J0({text:new C("",new g({color:W.colors.foreground,dim:!0}),[new C("Ctrl+T",new g({color:W.colors.primary,dim:!0})),new C(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:W.colors.foreground,dim:!0}))])})})}),H="",B=null,N=(L)=>{if(L!==H)H=L,B=tC3(L);return B};return new s2({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!J_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:"No threads match your filter",maxRenderItems:200,footer:Q?void 0:D,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:R}=A,S=O?j.selectionBackground:void 0,T=O?j.selectionForeground:R.foreground,f=R.mutedForeground,m=(s,z0)=>new I0({width:z0,child:q1.end([new J0({text:new C(s,new g({color:f}))})])}),x=Z.threadViewStates[L.id],_=[],u=L.relationshipType==="handoff",p=new na({connectorColor:R.mutedForeground});if(L.depth>0){let s=[],z0=L.ancestorsAreLast.slice(1);for(let w0 of z0)s.push(new C(p.getAncestorPrefix(w0),new g({color:p.connectorColor,dim:p.connectorDim})));let a=L.isLast?p.elbow:p.tee,q0=p.getConnectorText(a);s.push(new C(q0,new g({color:p.connectorColor,dim:p.connectorDim}))),_.push(new J0({text:new C("",void 0,s)}))}let d=[],h=F===L.id?new C("(current) ",new g({color:R.success})):G.has(L.id)?new C("(visited) ",new g({color:R.foreground,dim:!0})):null;if(h)d.push(new J0({text:h}));if(kN(x))d.push(new d11),d.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);d.push(new J0({text:new C("[fork] ",new g({color:R.primary}))}))}else if(u)d.push(new J0({text:new C("[handoff] ",new g({color:R.accent}))}));if(d.push(new k1({child:new J0({text:new C(n,new g({color:T})),overflow:"ellipsis",maxLines:1})})),d.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:f,warning:f,destructive:f}:R;d.push(...$_3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),d.push(new I0({width:2}))}return d.push(m(L.description.timeAgo,U)),new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new q1({children:[..._,...d]})})}})}}function _p4(J){return 1-(1-J)**3}function Tp4(J,Z,Q){return J+(Z-J)*Q}function Mo(J,Z){if(!J)return{x:0,y:0};let Q=Z-J.startTime,Y=Math.min(Q/J.durationX,1),X=Math.min(Q/J.durationY,1),K=_p4(Y),V=_p4(X);return{x:Tp4(J.startOffset.x,J.targetOffset.x,K),y:Tp4(J.startOffset.y,J.targetOffset.y,V)}}var Z_3={nodeWidth:3,horizontalSpacing:3};class lv{options;constructor(J={}){this.options={...Z_3,...J}}layout(J){let{childrenMap:Z,resolvedParent:Q}=this.buildTree(J),Y=[],X=Z.get(void 0)??[];if(this.options.comparator)X.sort(this.options.comparator);let K=0,V=(G,F)=>{let z=Z.get(G.id)??[];if(this.options.comparator)z.sort(this.options.comparator);let q={...G,parentID:Q.get(G.id)};if(z.length===0){Y.push({node:q,position:{x:K,y:F}});let B=K;return K+=this.options.nodeWidth+this.options.horizontalSpacing,B}let U=[];for(let B of z)U.push(V(B,F+1));let W=Math.min(...U),D=Math.max(...U),H=Math.floor((W+D)/2);return Y.push({node:q,position:{x:H,y:F}}),H};for(let G of X)V(G,0);return Y}buildTree(J){let Z=new Set(J.map((K)=>K.id)),Q=[...J].sort((K,V)=>K.id.localeCompare(V.id)),Y=new Map;for(let K of Q){if(!K.parentID||!Z.has(K.parentID)){Y.set(K.id,void 0);continue}let V=!1,G=K.parentID;while(G){if(G===K.id){V=!0;break}G=Y.get(G)}Y.set(K.id,V?void 0:K.parentID)}let X=new Map;for(let K of J){let V=Y.get(K.id);if(!X.has(V))X.set(V,[]);X.get(V).push(K)}return{childrenMap:X,resolvedParent:Y}}}var Q_3={nodeWidth:3,nodeHeight:2};class iv{options;constructor(J={}){this.options={...Q_3,...J}}calculate(J){let Z=[],Q=new Map;for(let Y of J)Q.set(Y.node.id,Y);for(let Y of J){if(!Y.node.parentID)continue;let X=Q.get(Y.node.parentID);if(!X)continue;let K=this.calculateConnectorLine(X.position,Y.position);Z.push({points:K,fromNodeID:X.node.id,toNodeID:Y.node.id})}return Z}calculateConnectorLine(J,Z){let Q=Math.floor(this.options.nodeWidth/2),Y=[],X=J.x+Q,K=Z.x+Q,V=J.y*(this.options.nodeHeight+3)+this.options.nodeHeight;Y.push({x:X,y:V});let G=V+1;if(Y.push({x:X,y:G}),X!==K)Y.push({x:K,y:G});let F=Z.y*(this.options.nodeHeight+3)-1;return Y.push({x:K,y:F}),Y}}var Y_3={nodeWidth:3,nodeHeight:2},X_3={x:0,y:0};class rF0{options;constructor(J={}){this.options={...Y_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=X_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+3,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],T=0;for(let f of R){if(f.position.x>T)S.push(new I0({width:f.position.x-T}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,_=K?.activeFlashOn??!1,u=f.node.id===K?.copyFlashNodeId;S.push(this.renderNode(m,x,_,u,q,z)),T=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,T=O+R*B+1,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:T,child:this.renderInfoBox(j,f,z,q)}))}return new i0({padding:C0.horizontal(2),child:new lG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X,K){let V="┌─┐",G="└─┘",F=J?X?.threadGraphNodeSelected??K?.primary??K?.foreground:X?.threadGraphNode??K?.primary??K?.foreground,z=!1;if(Y)F=X?.threadGraphNodeSelected??K?.primary??F,V="┏━┓",G="┗━┛",z=!0;else if(Z&&Q)F=X?.toolSuccess??K?.primary??F,V="┏━┓",G="┗━┛";return new x0({crossAxisAlignment:"start",children:[new J0({text:new C(V,new g({color:F,bold:z}))}),new J0({text:new C(G,new g({color:F,bold:z}))})]})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q,Y){let X=this.wrapText(J,Z),K=Math.min(Z,Math.max(1,...X.map((W)=>W.length))),V=K+2,G="┌"+"─".repeat(V)+"┐",F="└"+"─".repeat(V)+"┘",z=Q?.border??Y?.threadGraphConnector??Q?.foreground,q=Q?.foreground,U=[new J0({text:new C(G,new g({color:z}))})];for(let W of X){let D=" ".repeat(K-W.length);U.push(new J0({text:new C("│ ",new g({color:z}),[new C(W+D,new g({color:q??z})),new C(" │",new g({color:z}))])}))}return U.push(new J0({text:new C(F,new g({color:z}))})),new x0({crossAxisAlignment:"start",children:U})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let W of Z){let D=W.position.x+G;if(D>=0&&D<Y)z[D]="▲"}V.push(new J0({text:new C(z.join(""),new g({color:F}))}));let q=Array(Y).fill(" ");for(let W of J){let D=Z.filter((L)=>L.node.parentID===W.node.id);if(D.length===0)continue;let H=W.position.x+G,B=D.map((L)=>L.position.x+G),N=Math.min(...B),w=Math.max(...B);for(let L=N;L<=w;L++)if(L>=0&&L<Y){if(L===H)if(D.length===1&&B[0]===H)q[L]="│";else if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┬";else if(B.includes(L))if(L===N)q[L]="└";else if(L===w)q[L]="┘";else q[L]="┴";else if(q[L]===" ")q[L]="─"}}V.push(new J0({text:new C(q.join(""),new g({color:F}))}));let U=Array(Y).fill(" ");for(let W of J){if(Z.filter((B)=>B.node.parentID===W.node.id).length===0)continue;let H=W.position.x+G;if(H>=0&&H<Y)U[H]="│"}return V.push(new J0({text:new C(U.join(""),new g({color:F}))})),V}}var K_3={nodeWidth:1,nodeHeight:1,nodeIcon:"□",selectedIcon:"□"},V_3={x:0,y:0};class l11{options;constructor(J={}){this.options={...K_3,...J}}getNodeWidth(){return this.options.nodeWidth}render(J,Z,Q,Y=V_3,X,K,V,G){let F=G?f0.of(G):null,z=F?.colors,q=F?.app,U=z?.mutedForeground??z?.foreground;if(J.length===0)return new J0({text:new C("No nodes",new g({color:U}))});let W=Math.max(...J.map((j)=>j.position.y)),H=Math.max(...J.map((j)=>j.position.x))+this.options.nodeWidth+3,B=this.options.nodeHeight+1,N=[];for(let j=W;j>=0;j--){let R=J.filter((f)=>f.position.y===j);R.sort((f,m)=>f.position.x-m.position.x);let S=[],T=0;for(let f of R){if(f.position.x>T)S.push(new I0({width:f.position.x-T}));let m=f.node.id===Q,x=V?.(f.node.data)??!1,_=K?.activeFlashOn??!1;S.push(this.renderNode(m,x,_,q,z)),T=f.position.x+this.options.nodeWidth}if(N.push(new q1({crossAxisAlignment:"start",children:S})),j>0){let f=J.filter((_)=>_.position.y===j-1),m=R,x=this.renderConnectors(f,m,Z,H,z,q);N.push(...x)}}let w=new x0({crossAxisAlignment:"start",children:N}),L=Math.round(Y.x),O=Math.round(Y.y*B),E=(W+1)*B,M=[new I0({width:H,height:E}),new e6({left:L,top:O,child:w})],A=Q?J.find((j)=>j.node.id===Q):void 0;if(A&&X){let j=X(A.node.data),R=W-A.position.y,S=L+A.position.x+this.options.nodeWidth+1,T=O+R*B,f=30;if(K?.maxTitleWidthPercent&&K.viewportWidth)f=Math.floor(K.viewportWidth*K.maxTitleWidthPercent/100);M.push(new e6({left:S,top:T,child:this.renderInfoBox(j,f,z)}))}return new i0({padding:C0.horizontal(2),child:new lG(new q5({fit:"expand",children:M}))})}renderNode(J,Z,Q,Y,X){let K=J?this.options.selectedIcon:this.options.nodeIcon,V=J?Y?.threadGraphNodeSelected??X?.primary??X?.foreground:Y?.threadGraphNode??X?.primary??X?.foreground;if(Z&&Q)V=Y?.toolSuccess??X?.primary??V,K="■";return new J0({text:new C(K,new g({color:V}))})}wrapText(J,Z){let Q=J.split(" "),Y=[],X="";for(let K of Q){if(K.length>Z)K=K.slice(0,Z-1)+"…";if(X.length===0)X=K;else if(X.length+1+K.length<=Z)X+=" "+K;else Y.push(X),X=K}if(X.length>0)Y.push(X);return Y}renderInfoBox(J,Z=30,Q){let Y=this.wrapText(J,Z),X=Q?.foreground,K=[];for(let V of Y)K.push(new J0({text:new C(V,new g({color:X??Q?.primary??Q?.foreground}))}));return new x0({crossAxisAlignment:"start",children:K})}renderConnectors(J,Z,Q,Y,X,K){let V=[],G=Math.floor(this.options.nodeWidth/2),F=K?.threadGraphConnector??X?.primary??X?.foreground,z=Array(Y).fill(" ");for(let q of J){let U=Z.filter((N)=>N.node.parentID===q.node.id);if(U.length===0)continue;let W=q.position.x+G,D=U.map((N)=>N.position.x+G),H=Math.min(...D),B=Math.max(...D);for(let N=H;N<=B;N++)if(N>=0&&N<Y){let w=N===W,L=D.includes(N);if(w&&L)if(U.length===1)z[N]="│";else if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┼";else if(w)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┬";else if(L)if(N===H)z[N]="└";else if(N===B)z[N]="┘";else z[N]="┴";else if(z[N]===" ")z[N]="─"}}return V.push(new J0({text:new C(z.join(""),new g({color:F}))})),V}}class Ao extends s3{onWidth;onHeight;constructor(J){super(J.child);this.onWidth=J.onWidth,this.onHeight=J.onHeight}createRenderObject(){return new Sp4(this.onWidth,this.onHeight)}updateRenderObject(J){J.onWidth=this.onWidth,J.onHeight=this.onHeight}}class Sp4 extends v4{onWidth;onHeight;constructor(J,Z){super();this.onWidth=J,this.onHeight=Z}performLayout(){let J=this._lastConstraints,Z=Number.isFinite(J.maxWidth)?J.maxWidth:80,Q=Number.isFinite(J.maxHeight)?J.maxHeight:24;this.onWidth(Z),this.onHeight?.(Q);let Y=this.children[0];if(Y)Y.layout(J),this.setSize(Y.size.width,Y.size.height);else this.setSize(J.minWidth,J.minHeight)}paint(J,Z,Q){for(let Y of this.children)Y.paint(J,Z,Q)}}class mR extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new vp4}}var kp4=400,yp4=300,G_3=16;class vp4 extends d0{selectedNodeId=null;positionedNodes=[];dateComparator=(J,Z)=>{let Q=J.data.updatedAt??"",Y=Z.data.updatedAt??"";return Q.localeCompare(Y)};layoutEngine=new lv({nodeWidth:1,horizontalSpacing:1,comparator:this.dateComparator});lineCalculator=new iv;renderer=new l11;animation=null;currentOffset={x:0,y:0};animationTimer=null;viewportWidth=80;viewportHeight=24;activeFlashOn=!0;activeFlashTimer=null;initState(){let{initialSelectedThreadID:J}=this.widget.props;if(J){let Q=this.widget.props.threads.find((Y)=>Y.id===J);if(Q)this.selectedNodeId=Q.id}this.startActiveFlashTimer()}startActiveFlashTimer(){if(!this.widget.props.threads.some((Z)=>Z.isActive))return;this.activeFlashTimer=setInterval(()=>{this.activeFlashOn=!this.activeFlashOn,this.setState()},700)}stopActiveFlashTimer(){if(this.activeFlashTimer)clearInterval(this.activeFlashTimer),this.activeFlashTimer=null}didUpdateWidget(J){let Z=new Set(J.props.threads.map((F)=>F.id)),Q=new Set(this.widget.props.threads.map((F)=>F.id));if(Z.size!==Q.size||[...Z].some((F)=>!Q.has(F)))this.stopAnimation(),this.currentOffset={x:0,y:0};let X=J.props.initialSelectedThreadID,K=this.widget.props.initialSelectedThreadID;if(X!==K&&K){let z=this.widget.props.threads.find((q)=>q.id===K);if(z)this.selectedNodeId=z.id,this.stopAnimation(),this.currentOffset={x:0,y:0}}let V=J.props.threads.some((F)=>F.isActive),G=this.widget.props.threads.some((F)=>F.isActive);if(V!==G){if(this.stopActiveFlashTimer(),G)this.startActiveFlashTimer()}}dispose(){this.stopAnimation(),this.stopActiveFlashTimer()}startAnimation(J){this.stopAnimation(),this.animation={startOffset:{...this.currentOffset},targetOffset:J,startTime:Date.now(),durationX:kp4,durationY:yp4};let Z=Math.max(kp4,yp4);this.animationTimer=setInterval(()=>{let Q=Date.now();if(this.currentOffset=Mo(this.animation,Q),this.animation&&Q-this.animation.startTime>=Z)this.currentOffset={...this.animation.targetOffset},this.stopAnimation();this.setState()},G_3)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null;this.animation=null}calculateCenterOffset(J,Z,Q){let Y=Math.floor(this.renderer.getNodeWidth()/2),K=Math.floor(this.viewportWidth/2)-J-Y,V=Q-Z,G=2,F=Math.floor(this.viewportHeight/2),q=Math.floor(F/2)-V;return{x:K,y:q}}animateToNode(J){let Z=this.positionedNodes.find((Q)=>Q.node.id===J);if(Z){let Q=Math.max(...this.positionedNodes.map((X)=>X.position.y)),Y=this.calculateCenterOffset(Z.position.x,Z.position.y,Q);this.startAnimation(Y)}}toGraphNodes(){return this.widget.props.threads.map((J)=>({id:J.id,parentID:J.parentID,data:{title:J.title,updatedAt:J.updatedAt,isActive:J.isActive}}))}toThreadNode(J){return{id:J.node.id,parentID:J.node.parentID,title:J.node.data.title,updatedAt:J.node.data.updatedAt}}handleKeyEvent=(J)=>{if(!this.selectedNodeId)return"ignored";let Z=this.positionedNodes,Q=Z.find((X)=>X.node.id===this.selectedNodeId);if(!Q)return"ignored";let Y;switch(J.key){case"ArrowUp":{let X=Z.filter((K)=>K.node.parentID===Q.node.id);if(X.length>0){X.sort((V,G)=>V.position.x-G.position.x);let K=Math.floor(X.length/2);Y=X[K]}break}case"ArrowDown":{Y=Z.find((X)=>X.node.id===Q.node.parentID);break}case"ArrowLeft":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x<Q.position.x);if(X.length>0)X.sort((K,V)=>V.position.x-K.position.x),Y=X[0];break}case"ArrowRight":{let X=Z.filter((K)=>K.position.y===Q.position.y&&K.position.x>Q.position.x);if(X.length>0)X.sort((K,V)=>K.position.x-V.position.x),Y=X[0];break}case"Enter":{if(this.widget.props.onSelect)this.widget.props.onSelect(this.toThreadNode(Q));return"handled"}default:{if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"}}if(Y)return this.selectedNodeId=Y.node.id,this.widget.props.onSelectionChange?.(this.toThreadNode(Y)),this.animateToNode(Y.node.id),"handled";if(this.widget.props.onKey)return this.widget.props.onKey(J);return"ignored"};build(J){let Z=this.toGraphNodes();this.positionedNodes=this.layoutEngine.layout(Z);let Q=this.lineCalculator.calculate(this.positionedNodes);if(!this.animation&&this.currentOffset.x===0&&this.currentOffset.y===0){let q=(this.selectedNodeId?this.positionedNodes.find((U)=>U.node.id===this.selectedNodeId):null)??this.positionedNodes.find((U)=>!U.node.parentID);if(q){let U=Math.max(...this.positionedNodes.map((W)=>W.position.y));this.currentOffset=this.calculateCenterOffset(q.position.x,q.position.y,U)}}let X=this.widget.props.showTitle??!0,K=this.widget.props.offsetY??0,V={x:this.currentOffset.x,y:this.currentOffset.y+K},G=this.renderer.render(this.positionedNodes,Q,this.selectedNodeId??void 0,V,X?(z)=>z.title:void 0,{maxTitleWidthPercent:this.widget.props.maxTitleWidthPercent,viewportWidth:this.viewportWidth,activeFlashOn:this.activeFlashOn},(z)=>z.isActive??!1,J),F=new Ao({onWidth:(z)=>{if(this.viewportWidth!==z)this.viewportWidth=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},onHeight:(z)=>{if(this.viewportHeight!==z)this.viewportHeight=z,this.stopAnimation(),this.currentOffset={x:0,y:0},this.setState()},child:G});return new s4({autofocus:this.widget.props.autofocus??!0,onKey:this.handleKeyEvent,debugLabel:"MiniThreadGraph",child:F})}getSelectedNode(){let J=this.positionedNodes.find((Z)=>Z.node.id===this.selectedNodeId);return J?this.toThreadNode(J):null}}class fp4 extends l0{child;onContext;constructor(J,Z){super();this.child=J;this.onContext=Z}createState(){return new up4}}class up4 extends d0{build(J){return this.widget.onContext(J),this.widget.child}}var xp4=30,F_3=30;class nv{}class av{}class sF0{}class tF0{}class i11 extends l0{props;constructor(J){super();this.props=J}createState(){return new bp4}}class bp4 extends d0{highlightedIndex=0;controller=new K$;focusNode;scrollController=new j5;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new U6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Z=J.findRenderObject();if(!Z)return;let Q=0,Y=Z.size.height;uv(J,{top:Q,bottom:Y},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Z}=this.widget.props;if(!J)this.filteredClusters=[...Z];else this.filteredClusters=Z.filter((Q)=>Q.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof nv){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof av){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof sF0){let Z=this.filteredClusters[this.highlightedIndex];if(Z)this.widget.props.onAccept(Z);return"handled"}if(J instanceof tF0)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Z)=>{if(J>=0&&J<this.filteredClusters.length){if(Z===1)this.highlightedIndex=J,this.setState();else if(Z===2){let Q=this.filteredClusters[J];if(Q)this.widget.props.onAccept(Q)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return!1;let Z=this.highlightedIndex;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return!1;else if(this.highlightedIndex>0)this.highlightedIndex--;else return!1;return this.setState(),C6.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.highlightedIndex!==Z};build(J){let{currentThreadID:Z}=this.widget.props,Q=f0.of(J),{colors:Y,app:X}=Q,G=V4.of(J).size.width>=F_3+xp4,F=d1.all(new h1(Y.foreground,1,"solid")),z=this.filteredClusters[this.highlightedIndex]??null,q=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C("Select a cluster",new g({color:X.command,bold:!0}))})}),U=new xZ({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new l$({shortcuts:new Map([[new H4("ArrowDown"),new nv],[new H4("ArrowUp"),new av],[new H4("Tab"),new nv],[new H4("Tab",{shift:!0}),new av],[new H4("n",{ctrl:!0}),new nv],[new H4("p",{ctrl:!0}),new av],[new H4("Enter"),new sF0],[new H4("Escape"),new tF0]]),focusNode:this.focusNode,child:U}),D=new A2({actions:new Map([[nv,new W6(this.invoke)],[av,new W6(this.invoke)],[sF0,new W6(this.invoke)],[tF0,new W6(this.invoke)]]),child:W}),H=new q1({children:[new i0({decoration:{color:Y.background},child:new J0({text:new C(">",new g({color:Y.foreground}))})}),new k1({child:D})]});this.itemContexts=[];let B=this.filteredClusters.map((M,A)=>{let j=A===this.highlightedIndex,R=Z?M.threads.some((m)=>m.id===Z):!1,S=j?X.selectionBackground:void 0,T=j?X.selectionForeground:Y.foreground,f=[new C(M.label,new g({color:T})),new C(` (${M.threads.length})`,new g({color:T,dim:!0}))];if(R)f.push(new C(" (current)",new g({color:j?X.selectionForeground:Y.success})));return new fp4(new J4({onClick:(m)=>this.handleItemClick(A,m.clickCount),child:new i0({decoration:S?{color:S}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,f)})})}),(m)=>{this.itemContexts[A]=m})}),N=new x0({children:B,crossAxisAlignment:"start"}),w=new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})}),L=z?z.threads.map((M)=>({id:M.id,title:M.title,parentID:M.parentID,updatedAt:M.updatedAt})):[],O=z?new i0({padding:C0.all(1),child:new mR({threads:L,autofocus:!1,offsetY:2})}):null,E;if(G){let M=O?new k1({child:O}):new I0({width:xp4});E=new q1({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[w,M]})}else{let M=[new k1({child:new J4({onScroll:this.handleScroll,child:new _6({controller:this.scrollController,autofocus:!1,child:N})})})];if(O)M.push(new k1({child:O}));E=new x0({crossAxisAlignment:"stretch",children:M})}return new i0({decoration:{border:F,color:Y.background},padding:C0.symmetric(1,0),child:new x0({children:[q,H,new I0({height:1}),new k1({child:E})]})})}}class hJ{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!hJ._instance)hJ._instance=new hJ;return hJ._instance}get allExpanded(){return this._allExpanded}setAllExpanded(J){if(this._allExpanded===J)return;this._allExpanded=J,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(J){return this._listeners.add(J),()=>this.removeListener(J)}removeListener(J){this._listeners.delete(J)}_notifyListeners(){for(let J of this._listeners)J()}}g0();class hp4 extends d0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){P.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){P.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){let Z=J.trim().toLowerCase();if(Z.length===0)return null;if(Z.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Z))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Z)=>!J.includes(Z.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Z=J.trim().toLowerCase();if(!this.isValidLabelName(Z))return!1;let Q=this.widget.props.currentLabels||[],Y=this.labels.some((K)=>K.name===Z),X=Q.includes(Z);return!Y&&!X}build(J){let Z=f0.of(J),{app:Q,colors:Y}=Z,X=this.currentQuery.trim().toLowerCase(),K=X.length>0?this.getValidationError(X):null,V=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...V];return new s2({title:"Add Label",items:F,getLabel:(z)=>{if("__isCreateMarker"in z)return this.currentQuery.trim().toLowerCase();return z.name},onAccept:(z)=>{if("__isCreateMarker"in z)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(z.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:K||"Type to create a new label",renderItem:(z,q,U,W)=>{let D=q?Q.selectionBackground:void 0,H=q?Q.selectionForeground:Y.foreground;if("__isCreateMarker"in z&&z.__isCreateMarker){let N=this.currentQuery.trim().toLowerCase();return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C("",void 0,[new C("Create new label: ",new g({color:H})),new C(N,new g({color:H,bold:!0}))])})})}return new i0({decoration:D?{color:D}:void 0,padding:C0.symmetric(2,0),child:new J0({text:new C(z.name,new g({color:H}))})})},filterItem:(z,q)=>{if(this.currentQuery!==q)this.currentQuery=q,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in z&&z.__isCreateMarker)return this.shouldShowCreateMarker(q);let W=q.trim().toLowerCase();return W.length===0||z.name.includes(W)},sortItems:(z,q,U)=>{let W="__isCreateMarker"in z.item&&z.item.__isCreateMarker,D="__isCreateMarker"in q.item&&q.item.__isCreateMarker;if(W&&!D)return-1;if(!W&&D)return 1;return q.score-z.score}})}}class n11 extends l0{props;constructor(J){super();this.props=J}createState(){return new hp4}}class eG extends l0{props;constructor(J){super();this.props=J}createState(){return new gp4}}class gp4 extends d0{_spinner=new F3;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=d1.all(new h1(Q.foreground,1,"solid")),K=this._spinner.toBraille(),V=new J0({textAlign:"center",text:new C("",void 0,[new C(K,new g({color:Y.processing})),new C(" ",void 0),new C(this.widget.props.message,new g({color:Q.foreground}))])}),F=[new k1({child:new x0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[V]})})];if(this.widget.props.onAbort)F.push(new I0({height:2,child:new i0({padding:C0.symmetric(2,0),child:new J0({text:new C("",new g({dim:!0}),[new C("Press ",new g({color:Q.foreground})),new C("Esc",new g({color:Q.info})),new C(" to cancel",new g({color:Q.foreground}))])})})}));let z=new i0({decoration:new r4(Q.background,X),child:new I0({width:60,height:7,child:new x0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new s4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(q)=>{if(q.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:z});return z}}var jo={workspace:{label:"Workspace",pathHint:".amp/settings.json",description:"workspace config"},global:{label:"Global",pathHint:"~/.config/amp/settings.json",description:"global config"},flag:{label:"Flag",pathHint:"CLI flags",description:"flag config"},default:{label:"Default",pathHint:"built-in defaults",description:"default config"},external:{label:"External",pathHint:"extensions / external",description:"external source"},skill:{label:"Skills",pathHint:".agents/skills/",description:"skill source"},other:{label:"Other",pathHint:"",description:"other source"}},eF0=["workspace","global","flag","default","external","skill","other"];function z_3(J){return Array.from(new Set(J))}function mp4(J){return z_3([...J.skillNames??[],...J.skillName?[J.skillName]:[]])}function ov(J){if(J.isExternal)return"external";switch(J.spec._target){case"workspace":return"workspace";case"global":return"global";case"flag":return"flag";case"default":return"default"}return mp4(J).length>0?"skill":"other"}function a11(J){return ov(J)==="skill"}function pp4(J){let Z=mp4(J);if(Z.length===0)return;let Q=Z.join(", "),Y=ov(J);if(Y==="skill")return`skills: ${Q}`;return`${Z.length===1?"skill source":"skill sources"} overridden by ${jo[Y].description}: ${Q}`}function dp4(J){return J.spec.meta?.skillNames?Array.from(J.spec.meta.skillNames):[]}var cp4=process.platform==="win32"?" ":"█",lp4=process.platform==="win32"?"░":"█";class E9 extends l0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=cp4,thumbChar:K=lp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createState(){return new ip4}}class ip4 extends d0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(J){let{totalContentHeight:Z,viewportHeight:Q}=this.widget.getScrollInfo(),X=this.context.findRenderObject()?.size.height??0;if(X===0||Z<=Q)return!1;let K=this.widget.getScrollInfo(),V=Math.min(1,Q/Z),G=Math.max(1,X*V),F=Math.max(0,Math.min(1,K.scrollOffset/(Z-Q))),z=X-G,q=Math.max(0,z*F),U=q+G;return J>=q&&J<=U}_handleHover=(J)=>{let Z=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(J.localPosition.y),Z!==this._isOverThumb)this.setState()};_handleDrag=(J)=>{let{totalContentHeight:Z,viewportHeight:Q,scrollOffset:Y}=this.widget.getScrollInfo(),K=this.context.findRenderObject()?.size.height??0;if(K===0||Z<=Q)return;if(this._dragStartY===null)this._dragStartY=J.localPosition.y,this._dragStartOffset=Y;let V=J.localPosition.y-this._dragStartY,G=Math.min(1,Q/Z),F=Math.max(1,K*G),z=K-F;if(z<=0)return;let q=Z-Q,U=z/q,W=V/U,D=Math.max(0,Math.min(q,this._dragStartOffset+W));this.widget.controller.jumpTo(D)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(J)=>{if(J.button!=="left")return;let Z=J.localPosition.y,{totalContentHeight:Q,viewportHeight:Y,scrollOffset:X}=this.widget.getScrollInfo(),V=this.context.findRenderObject()?.size.height??0;if(V===0||Q<=Y)return;let G=Math.min(1,Y/Q),F=Math.max(1,V*G),z=Q-Y,q=V-F,U=Math.max(0,Math.min(1,X/(Q-Y))),W=Math.max(0,q*U),D=W+F;if(Z>=W&&Z<=D)return;if(Z<W)this.widget.controller.animateTo(Math.max(0,X-Y));else this.widget.controller.animateTo(Math.min(z,X+Y))};build(J){return new J4({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?d5.POINTER:d5.DEFAULT,child:new np4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class np4 extends yy{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:J,controller:Z,getScrollInfo:Q,thickness:Y=1,trackChar:X=cp4,thumbChar:K=lp4,showTrack:V=!0,thumbColor:G,trackColor:F}){super(J?{key:J}:{});this.controller=Z,this.getScrollInfo=Q,this.thickness=Y,this.trackChar=X,this.thumbChar=K,this.showTrack=V,this.thumbColor=G,this.trackColor=F}createRenderObject(){return new ap4(this)}updateRenderObject(J){J.updateWidget(this)}}class ap4 extends v4{_widget;constructor(J){super();this._widget=J}updateWidget(J){this._widget=J,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;J6(!!J,"performLayout called without constraints");let Z=Math.min(J.maxWidth,this._widget.thickness),Q=J.maxHeight;this.setSize(Z,Q),super.performLayout()}getMinIntrinsicWidth(J){return this._widget.thickness}getMaxIntrinsicWidth(J){return this._widget.thickness}getMinIntrinsicHeight(J){return 0}getMaxIntrinsicHeight(J){return 0}paint(J,Z,Q){let{thumbStartFloat:Y,thumbSizeFloat:X,showScrollbar:K}=this._calculateScrollbarMetrics();if(!K)return;let V=this._widget.trackColor,G=this._widget.thumbColor,F=process.platform==="win32",z=Y,q=Y+X;if(!F){let U=["▁","▂","▃","▄","▅","▆","▇","█"];for(let W=0;W<this.size.height;W++){let D="█",H=!0;if(W===Math.floor(z)){let B=1-(z-W),N=Math.floor(B*8);D=U[N]||"█",H=!1}else if(W===Math.floor(q)){let B=1-(q-W),N=Math.floor(B*8);D=U[N]||"█"}else if(W>z&&W<q)H=!1;J.setChar(Z,Q+W,D,{fg:G,bg:V,reverse:H},1)}return}for(let U=0;U<this.size.height;U++){let W=U+0.5,D=W>=z&&W<q,H=D?this._widget.thumbChar:this._widget.trackChar;J.setChar(Z,Q+U,H,{fg:D?G:V,bg:V,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:J,viewportHeight:Z,scrollOffset:Q}=this._widget.getScrollInfo(),Y=this.size.height;if(J<=Z||Y<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let X=Math.max(0,Math.min(1,Q/(J-Z))),K=Math.min(1,Z/J),V=Math.max(1,Y*K),G=Y-V;return{thumbStartFloat:Math.max(0,G*X),thumbSizeFloat:V,showScrollbar:!0}}}class pR extends l0{props;constructor(J){super();this.props=J}createState(){return new op4}}class op4 extends d0{scrollController=new j5;scrollAreaKey=new J$("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof r2}resolveFooterStyle(J){if(this.isWidgetMessage(J))return J.footerStyle;return"default"}getViewportHeight(){let Z=this.scrollAreaKey.currentElement?.renderObject;if(Z&&"size"in Z){let Q=Z.size;if(typeof Q.height==="number"&&Q.height>0)return this.viewportHeight=Q.height,Q.height}return this.viewportHeight}build(J){let Z=f0.of(J),Q=this.widget.props.message,Y=(()=>{if(this.isWidgetMessage(Q))return{title:Q.title,type:Q.type};if(Q instanceof Error&&Q.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Q.message};if(Q instanceof Error&&Q.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Q.message};let q=PF0(Q);return{title:q.title,type:q.type,description:q.description}})(),X=Y.type==="error"?Z.app.toolError:Z.app.command,K=d1.all(new h1(Z.colors.border,1,"solid")),V=new i0({padding:C0.symmetric(1,0),child:new J0({text:new C(Y.title,new g({color:X,bold:!0}))})}),G=this.isWidgetMessage(Q)?Q.widget:new J0({text:new C(Y.description,new g({color:Z.colors.foreground})),selectable:!0}),F=new k1({child:new i$({child:new i0({padding:C0.symmetric(1,0),child:new q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new _6({controller:this.scrollController,autofocus:!0,child:G})}),new E9({controller:this.scrollController,thumbColor:Z.app.scrollbarThumb,trackColor:Z.app.scrollbarTrack,getScrollInfo:()=>{let q=this.scrollController.maxScrollExtent,U=this.scrollController.offset,W=this.getViewportHeight(),D=q+W;return{totalContentHeight:Math.max(D,0),viewportHeight:Math.max(W,1),scrollOffset:Math.max(U,0)}}})]})})})}),z=new i0({padding:C0.symmetric(1,0),child:new J0({text:(()=>{if(this.widget.props.onRetry)return new C("",void 0,[new C("Press ",new g({color:Z.colors.foreground,dim:!0})),new C("R",new g({color:Z.app.keybind})),new C(" to retry, ",new g({color:Z.colors.foreground,dim:!0})),new C("Esc",new g({color:Z.app.keybind})),new C(" to cancel",new g({color:Z.colors.foreground,dim:!0}))]);let q=this.resolveFooterStyle(this.widget.props.message);if(q==="none")return new C("",new g({color:Z.colors.foreground,dim:!0}));if(q==="help"){let U=new g({color:Z.app.keybind}),W=new g({color:Z.colors.foreground,dim:!0});return new C("",W,[new C("Press ",W),new C("Escape",U),new C(" to close • Use ",W),new C("↑↓",U),new C(" or ",W),new C("j/k",U),new C(" to scroll",W)])}return new C("Press any key to close",new g({color:Z.colors.foreground,dim:!0,italic:!0}))})()})});return new s4({onKey:(q)=>{if(this.widget.props.onRetry&&q.key==="r")return this.widget.props.onRetry(),"handled";if(q.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new i0({decoration:{border:K,color:Z.colors.background},padding:C0.all(1),child:new x0({mainAxisAlignment:"center",children:[V,new I0({height:1}),F,z]})})})}}S2();class rp4 extends l0{props;constructor(J){super();this.props=J}createState(){return new sp4}}class sp4 extends d0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((J)=>{this.plugins=J,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(J){let Z=J.startsWith("file://")?J.slice(7):J,Q=this.widget.props.cwd;if(Z.startsWith(Q))return Z.slice(Q.length+1);return Z}statusIcon(J){let Z=y9.default(),{colors:Q,app:Y}=Z;switch(J){case"loading":return{icon:"◌",color:Q.warning};case"active":return{icon:"✓",color:Y.toolSuccess};case"error":return{icon:"✗",color:Y.toolError}}}build(J){let Z=f0.of(J),{app:Q}=Z;if(this.plugins.length===0)return new J0({text:new C("No plugins found.",new g({dim:!0}))});let Y=[],X=this.plugins.length,K=this.plugins.filter((F)=>F.status==="active").length,V=this.plugins.reduce((F,z)=>F+z.registeredCommands.length,0),G=this.plugins.reduce((F,z)=>F+z.registeredTools.length,0);if(Y.push(new C(`${K}/${X} ${p4(X,"plugin")} active`,new g({bold:!0}))),V>0||G>0)Y.push(new C(` (${V} ${p4(V,"command")}, ${G} ${p4(G,"tool")})`,new g({dim:!0})));Y.push(new C(`
|
|
7393
7393
|
|
|
7394
7394
|
`));for(let F of this.plugins){let{icon:z,color:q}=this.statusIcon(F.status),U=this.getRelativePath(F.uri.toString());if(Y.push(new C(`${z} `,new g({color:q}))),Y.push(new C(U,new g({bold:!0}))),Y.push(new C(` ${F.status}`,new g({dim:!0}))),Y.push(new C(`
|
|
7395
7395
|
`)),F.status==="active"&&F.registeredEvents.length>0)Y.push(new C(" Events: ",new g({dim:!0}))),Y.push(new C(F.registeredEvents.join(", "),new g({color:Q.link}))),Y.push(new C(`
|
|
@@ -7618,7 +7618,7 @@ ${Y0.content||""}`:Y0.content||"",$1=[],W1=Y0.baseDir.startsWith("file://")?uz0(
|
|
|
7618
7618
|
`),process.exit(1)}process.stdout.write(await $v3(F.result.displayText)+`
|
|
7619
7619
|
`),process.exit(0)})}GA();import{stdout as Jv3}from"node:process";function Zv3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${kz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function gi4(J){Jv3.write(`${Zv3(J)}
|
|
7620
7620
|
`)}function mi4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{gi4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{gi4(Z),process.exit(0)})}var Ab3=pL.join(ZQ,"logs","headless.log"),E31=pL.join(ky,"device-id.json");async function jb3(){for(let J of PE)try{if((await J.listConfigs()).length>0)return J}catch(Z){P.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => G4(jx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){R7.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
7621
|
-
`)}function Rb3(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 e2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZZ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")ZZ("experimental.agentMode",Z.mode)}function Lr4(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 Ib3(J){try{return await Nr4(J,"utf-8")}catch{return J}}async function M31(J,Z,Q){let Y=Lr4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!P31(X,S7.HARNESS_SYSTEM_PROMPT)&&!Or4(K))throw new P1("You are not allowed to do this.",1);ZZ("systemPrompt",await Ib3(Y))}function Or4(J){return!!(J&&G40(J))}function P31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function A31(J){return(J.userEmail?JZ(J.userEmail):!1)||P31(J.features,S7.DTW_TUI)}function Fr4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function j31(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return A31({userEmail:Z.user.email,features:Z.features})}function R31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pb3(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 Pq0(J){let Y=Pb3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function zr4(J){if(!V5.write(J))await Lb3(V5,"drain")}var qr4=[{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??gK,description:`Custom settings file path (overrides the default location ${gK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xj})`},{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:a2(),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:cF.SMART.key,description:`Set the agent mode (${lF().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:lF().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:"optional-option",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}],Ur4=(J)=>("deprecated"in J)&&J.deprecated===!0,Cb3=(J)=>("hidden"in J)&&J.hidden===!0,_b3=(J)=>("default"in J),Tb3=(J)=>("default"in J)?J.default:void 0,Er4=[{name:"toggle-skills-count",entryPoint:Js0}];function Sb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function C31(J){return{...J,getThreadEnvironment:AZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nV(J.fileSystem),generateThreadTitle:v90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>VQ(J.configService),pluginService:J.pluginService}}function Mr4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:AZ,filesystem:J.fileSystem,threadService:J.threadService}}var Cq0=Y1.file(wr4.homedir()),I31=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Cq0,".config");function kb3(J){return xW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){vW4(Z);let Q=gK0(),Y=Bs0();if((!Q||Y||Rk4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(SD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(SD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(gK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function yb3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Z2(J,Z,Q){let Y=Q?.deferAuth??!1;xu1("0.0.
|
|
7621
|
+
`)}function Rb3(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 e2(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")ZZ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")ZZ("experimental.agentMode",Z.mode)}function Lr4(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 Ib3(J){try{return await Nr4(J,"utf-8")}catch{return J}}async function M31(J,Z,Q){let Y=Lr4(J,Z);if(!Y)return;let X=m6(Q)?Q.features:[],K=m6(Q)?Q.user.email:void 0;if(!P31(X,S7.HARNESS_SYSTEM_PROMPT)&&!Or4(K))throw new P1("You are not allowed to do this.",1);ZZ("systemPrompt",await Ib3(Y))}function Or4(J){return!!(J&&G40(J))}function P31(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function A31(J){return(J.userEmail?JZ(J.userEmail):!1)||P31(J.features,S7.DTW_TUI)}function Fr4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new P1("This TUI mode is not enabled for your user;",1)}function j31(J,Z){if(typeof J==="boolean")return J;if(!m6(Z))return!1;return A31({userEmail:Z.user.email,features:Z.features})}function R31(J){if(!m6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Pb3(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 Pq0(J){let Y=Pb3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new P1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function zr4(J){if(!V5.write(J))await Lb3(V5,"drain")}var qr4=[{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??gK,description:`Custom settings file path (overrides the default location ${gK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(P).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Xj})`},{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:a2(),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:cF.SMART.key,description:`Set the agent mode (${lF().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:lF().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:"optional-option",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}],Ur4=(J)=>("deprecated"in J)&&J.deprecated===!0,Cb3=(J)=>("hidden"in J)&&J.hidden===!0,_b3=(J)=>("default"in J),Tb3=(J)=>("default"in J)?J.default:void 0,Er4=[{name:"toggle-skills-count",entryPoint:Js0}];function Sb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new P1(M3.unknownCommand(Q),1,V)}}async function C31(J){return{...J,getThreadEnvironment:AZ,threadSyncService:J.threadSyncService,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new nV(J.fileSystem),generateThreadTitle:v90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>VQ(J.configService),pluginService:J.pluginService}}function Mr4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:AZ,filesystem:J.fileSystem,threadService:J.threadService}}var Cq0=Y1.file(wr4.homedir()),I31=process.env.XDG_CONFIG_HOME?Y1.file(process.env.XDG_CONFIG_HOME):X1.joinPath(Cq0,".config");function kb3(J){return xW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){vW4(Z);let Q=gK0(),Y=Bs0();if((!Q||Y||Rk4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(SD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(SD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(gK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}function yb3(){return{sync:async()=>{},uploadThread:async()=>{},discoverThreads:async()=>[],initialSyncComplete:Promise.resolve(),updateThreadMeta:async()=>{},threadSyncInfo:()=>k0.of({}),flushPendingSyncs:async()=>{},dispose:()=>{}}}async function Z2(J,Z,Q){let Y=Q?.deferAuth??!1;xu1("0.0.1774369119-gbb3185");let X=M40({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(Y1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:Cq0,userConfigDir:I31});jk4(X);let K=await X.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let z0=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(z0),P.info("API key lookup before login",{found:Boolean(z0),ampURL:J.ampURL,deferAuth:Y}),!z0)if(Y)P.info("No API key found, continuing startup with deferred auth");else{V5.write(`No API key found. Starting login flow...
|
|
7622
7622
|
`);let a=await vb3(J),q0=await J.secrets.get("apiKey",J.ampURL);if(P.info("Login flow completed",{success:a,storedKeyPresent:Boolean(q0),ampURL:J.ampURL}),!a)await XD(),process.exit(1);V=!0}}{let z0=await X.getLatest(),a=z0.settings.url,q0=z0.secrets.isSet?.[a];P.info("Config secrets state after login",{configURL:a,apiKeySet:q0?.apiKey??!1})}let G=M1(VQ(X).pipe(E5((z0)=>z0!=="pending"))),F=Y?"pending":await G;if(!Y)P.info("Server status resolved",{status:"ready",isAuthenticated:m6(F),isError:iU(F),errorMessage:iU(F)?F.error.message:void 0});let{toolService:z,dispose:q}=_W4({configService:X}),U=new Map,W=()=>U.clear(),D=new KS0(X,J.settings.getWorkspaceRootPath()),H=ve1({configService:X,filesystem:M8}),B=_o1({configService:X,trustStore:D,skillMCPServers:H.skillMCPServers,createOAuthProvider:async(z0,a,q0)=>{let w0=`${z0}:${a}`,F0=U.get(w0);if(F0)return P.debug("Reusing existing OAuth provider for server",{serverName:z0,serverUrl:a}),F0;P.debug("Creating OAuth provider for server",{serverName:z0,serverUrl:a});let $0=(async()=>{let W0=new fE(J.secrets),i=await W0.getClientInfo(z0,a),o=q0?.scopes??i?.scopes,e=Q_4();P.info("OAuth headless mode check",{useHeadless:e,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:V5.isTTY});let Q0;if(e)Q0=J.executeMode?Z_4():J_4(z0);let Y0=new gI0({storage:W0,serverName:z0,serverUrl:a,clientId:q0?.clientId??i?.clientId,clientSecret:q0?.clientSecret??i?.clientSecret,authUrl:q0?.authUrl??i?.authUrl,tokenUrl:q0?.tokenUrl??i?.tokenUrl,scopes:o,headlessAuthHandler:Q0});return P.debug("OAuth provider created",{serverName:z0,serverUrl:a,hasManualClientId:!!(q0?.clientId??i?.clientId),willUseDCR:!(q0?.clientId??i?.clientId),scopes:o,headlessMode:e,executeMode:J.executeMode}),Y0})();return U.set(w0,$0),$0}}),N=Dp0({configService:X,filesystem:M8,spawn:vJ0}),w;if(J.executeMode){let z0=await yz4({toolService:z,providers:[B,N],initialTimeout:15000});w=z0.registrations;for(let[a,q0]of z0.initErrors)P.warn(`${a} provider initialization slow or failed:`,q0)}else w=Hp0({toolService:z,providers:[B,N]});if(Z.jetbrains)ME("JetBrains");else if(Z.ide&&m_4())ME("VS Code");else if(Z.ide&&p_4())ME("Neovim");else if(Z.ide){let z0=await jb3();if(z0){let a=S40(z0.ideName);if(a)ME(a)}}if(J.executeMode)fu1(!0);let L,O=A$.status.pipe(U1((z0)=>Boolean(z0.connected&&z0.authenticated&&z0.ideName&&Ob1(z0.ideName))),y4()).subscribe((z0)=>{if(z0){if(!L)L=z.registerTool(kz4)}else L?.dispose(),L=void 0}),E;if(!J.executeMode){let z0=await J.settings.get("fuzzy.alwaysIncludePaths")??[];E=new BQ0(process.cwd(),{alwaysIncludePaths:z0},!0)}else E=new class extends BQ0{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let M=await ge1({isDevelopment:!1}),A=new Vv0(M,X),j=new sk0(M,{lazy:!0,maxThreads:200});P.info("Starting Amp background services");let R=Z.takeMeBack?!1:void 0,S=j31(R,F),T=Boolean(S||Z.headless);if(T)P.info("DTW mode enabled: thread sync service disabled");let f=T?yb3():L14({threadService:A,threadHistoryService:j,configService:X,isExtensionDevelopment:!1}),m;A$.status.subscribe((z0)=>{m=z0});let x=new IR0({workspaceRoots:[Y1.file(process.cwd())],fileSystem:M8,getCurrentFile:()=>{if(!m?.openFile)return;try{return Y1.parse(m.openFile)}catch(z0){P.warn("Failed to parse current file URI",{uri:m.openFile,error:z0});return}},getOpenFiles:()=>{if(!m?.visibleFiles?.length)return[];let z0=m.openFile;return m.visibleFiles.filter((a)=>a!==z0).map((a)=>{try{return Y1.parse(a)}catch(q0){return P.warn("Failed to parse visible file URI",{uri:a,error:q0}),null}}).filter((a)=>a!==null)}}),_=new Ls0,u=process.env.PLUGINS??"off",p=Z.headless?Gk4():void 0,d=p??new vK0({configService:X}),h=d instanceof vK0?d:void 0;if(h)h.pluginExecutorKind=S?"local":"unknown";let n=MS0({configService:X,fileSystem:M8,platform:d,internalPlugins:Er4,pluginFilter:u}),c=Ar1({pluginService:n,toolService:z}),s={codebaseContextService:x,configService:X,toolService:z,mcpService:B,skillService:H,toolboxService:N,trustStore:D,threadService:A,threadHistoryService:j,threadSyncService:f,threadStorage:M,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:E,fileSystem:M8,terminal:_,pluginService:n,pluginPlatform:h,headlessPluginPlatform:p,serverStatus:F,serverStatusPromise:G,hasAPIKeyAtStartup:V};return{...s,async asyncDispose(){if(s.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await s.mcpService.waitForAuthentication();for(let z0 of w.values())z0.dispose();await s.mcpService.dispose(),W(),await s.threadService.asyncDispose(),s.configService.unsubscribe(),q(),s.fuzzyServer.dispose(),s.threadSyncService.dispose(),s.settingsStorage[Symbol.dispose](),O.unsubscribe(),L?.dispose(),c.dispose(),await s.pluginService.dispose()}}}async function vb3(J){if(!J.executeMode){if(!await SK0("Would you like to log in to Amp? [(y)es, (n)o]: "))return V5.write(`Login cancelled. Run the command again to retry.
|
|
7623
7623
|
`),!1}return await Ar4(J)}async function Ar4(J){let Z=wb3(32).toString("hex"),Q=await gy(J.ampURL,Z),Y=new AbortController;try{await CV(Q,Y.signal)}catch(K){P.error("Error opening browser",{error:K})}let X=await gy(J.ampURL,Z,!1);V5.write(`If your browser does not open automatically, visit:
|
|
7624
7624
|
|
|
@@ -7626,7 +7626,7 @@ ${c0.blue.bold(X)}
|
|
|
7626
7626
|
|
|
7627
7627
|
`);try{return await mS4(J.ampURL,Z,J.secrets,Y),V5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return P.error("Login failed",{error:K}),R7.write(`
|
|
7628
7628
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
7629
|
-
`),!1}}function Wr4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!h9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function fb3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ub3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fb3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bb3(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 hb3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gb3(){let J=new $w().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Vj(),process.exit(0);let B=H.originalError??H;jL4(B)}),mi4(J,{version:"0.0.
|
|
7629
|
+
`),!1}}function Wr4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function xb3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new P1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!h9(Y.threadId))throw new P1("Create response did not include a valid thread ID",1);return Y.threadId}function fb3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function ub3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new P1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!fb3(Q))throw new P1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function bb3(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 hb3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new P1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function gb3(){let J=new $w().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)Vj(),process.exit(0);let B=H.originalError??H;jL4(B)}),mi4(J,{version:"0.0.1774369119-gbb3185",buildTimestamp:"2026-03-24T16:22:07.349Z",buildType:"'release'"}),J.addHelpText("after",b_4()),J.configureHelp({formatHelp:h_4}),J.command("logout").description("Log out by removing stored API key").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await d3(N);await nb3(w)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,B)=>{let N=B.optsWithGlobals(),w=await d3(N);await ib3(w,await Jr0(N,w.settings))}),J.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,B,N)=>{let w=N.optsWithGlobals(),L=await d3(w);await rL4(H??"get",L.ampURL,L.secrets),process.exit(process.exitCode??0)}),J.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,B)=>{let N=B.optsWithGlobals(),w=await d3(N);await sL4(w.ampURL,w.secrets),process.exit(process.exitCode??0)}),J.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
7630
7630
|
Actions:
|
|
7631
7631
|
create Create a new DTW thread and print its ID
|
|
7632
7632
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -7690,8 +7690,8 @@ ${E}
|
|
|
7690
7690
|
|
|
7691
7691
|
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 mb3(J){P.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new aa({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:AZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new nV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw P.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function pb3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await ly()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await ly()).trimEnd(),stdinInput:null}}function db3(J,Z,Q){if(J.remote&&!Z)throw new P1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new P1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new P1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new P1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new P1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new P1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new P1("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new P1("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
7692
7692
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function _q0(J,Z,Q){let Y=process.hrtime.bigint(),X=(F0,$0)=>{let W0=Number(process.hrtime.bigint()-$0)/1e6,i=jD4();P.info("Startup phase",{phase:F0,phaseMs:Math.round(W0),sinceMainMs:i===null?void 0:Math.round(i)})},{userInput:K,stdinInput:V}=await pb3(Z),G=!!Z.streamJson||!!Z.streamJsonThinking;db3({...Z,streamJson:G},J.executeMode,K),e2(Q,Z);let F=process.hrtime.bigint(),z=Boolean(await J.secrets.get("apiKey",J.ampURL)),q=!J.executeMode&&!Z.headless&&!Z.threadActors&&z;P.info("Interactive auth startup mode",{deferInteractiveAuth:q,hasAPIKeyAtStartup:z,executeMode:J.executeMode,headless:Boolean(Z.headless)});let U=await Z2(J,Z,{deferAuth:q});X("runMainThread:createThreadDependencies",F),F=process.hrtime.bigint();let W=await C31(U);X("runMainThread:createWorkerDeps",F);let{serverStatus:D}=U;if(!q&&iU(D)){let F0=yk(Error(D.error.message));if(F0.message===M3.networkOffline||F0.message===M3.networkTimeout)throw Pq0(J.ampURL);throw new P1(M3.invalidAPIKey,1)}let H=m6(D)?D:null,B=H?.user.email,N=Or4(B),w=A31({userEmail:B,features:H?.features}),L=Z.takeMeBack?!1:void 0,O=H!==null&&j31(L,H);if(!q)await M31(Q,Z,D);let E=R31(D),M=E?.features??[],A=E?.team??null,j=kK0(Z,E);if(j instanceof Error)c3(j.message);if((J.executeMode||G)&&L8(Z.mode)&&!N)throw new P1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(H&&!jE(Z.mode,B))throw new P1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await qk4(K,V,U.configService),await U.asyncDispose(),process.exit(0);if(Z.headless){if(!B||!JZ(B))throw new P1("Headless DTW mode is only available for Amp employees",1);let F0=await U.secretStorage.get("apiKey",J.ampURL);if(!F0)throw new P1("API key required for headless mode. Please run `amp login` first.",1);let $0=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if($0&&!h9($0))throw new P1(`Invalid thread ID: ${$0}`,1);let W0=$0??await Jh3({dependencies:U,visibility:j??void 0,usesThreadActors:Z.threadActors?!0:void 0}),i=await V_4(W0);if(i.status==="already-running")await U.asyncDispose(),await XD(),process.exit(0);try{await $_4({ampURL:J.ampURL,apiKey:F0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:W0,initialToolDiscovery:Promise.all([U.mcpService.initialized,U.toolboxService.initialized]).then(()=>{return}),configService:U.configService,mcpService:U.mcpService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,pluginService:U.pluginService,pluginPlatform:U.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await i.release(),await U.asyncDispose()}await XD(),process.exit(0)}let R=J.executeMode?void 0:async(F0)=>Br(F0,"interactive"),S={threadService:U.threadService,workerDeps:W,createThread:async()=>{let F0=q?await U.serverStatusPromise:D,$0=await JQ0(J.settings,process.cwd(),R31(F0),j);if($0 instanceof Error)c3($0.message);return x01(W,{threadMeta:$0?pG($0):void 0,agentMode:Z.mode,onFirstAssistantMessage:R})},validateThreadOwnership:async(F0,$0)=>{if($0?.nonBlockingOwnershipCheck){Dr4(F0,U.configService).catch((W0)=>{if(W0 instanceof P1){if($0.onOwnershipError){$0.onOwnershipError(W0,F0);return}Gj(W0,F0);return}P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})});return}try{await Dr4(F0,U.configService)}catch(W0){if(W0 instanceof P1)throw W0;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:W0})}},switchThreadVisibility:j,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:R,handleError:Gj},T=async(F0)=>{try{if(F0==="dtw")return mb3({ampURL:J.ampURL,configService:U.configService,threadService:U.threadService,mcpService:U.mcpService,toolboxService:U.toolboxService,toolService:U.toolService,skillService:U.skillService,fileSystem:U.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return Lh4(S,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch($0){if($0 instanceof P1)throw $0;throw await Gj($0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")R7.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
7693
|
-
`),await XD(),process.exit(1);let f=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await U.configService.getLatest(),$0=hb(F0),W0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(F0){P.error("Failed to fetch free tier status:",F0);return}})(),x=!J.executeMode?new C01:null,_,u=null;if(x)_=x,u=(async()=>{let F0=q?await U.serverStatusPromise:U.serverStatus;await M31(Q,Z,F0);let $0=process.hrtime.bigint(),W0=j31(L,F0),i=m6(F0)?A31({userEmail:F0.user.email,features:F0.features}):!1;Fr4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await T(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(o),K){let e=await M1(o.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));x.setInitError($0),await Gj(F0,Z.threadId)});else F=process.hrtime.bigint(),Fr4({dtwEnabled:O,hasV2TUIAccess:w}),_=await T(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let d=await U.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),kb3({configService:U.configService,threadService:U.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(U4((F0)=>{if(!F0)return k0.of({});return F5(F0.thread$,F0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){eS4(U.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await xL4({threadPool:_,...F0});if(await Br($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Ib1();let F0=await _E({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)h=!await U.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)A$.selectConfig($0)}else n=!0}F=process.hrtime.bigint();let c=Er0("0.0.
|
|
7694
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await vo1({get:async(G)=>{if(G!==yg)return;try{let F=await Nr4(E31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==yg)return;await Br4(pL.dirname(E31),{recursive:!0}),await Ob3(E31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:pF()});uu1(Y);let X=await O_4({...J,workspaceTrust:{current:!0,changes:Eb},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await sS4(J.mcpConfig);X=tS4(X,G)}let K=pL.dirname(X.getSettingsFilePath());yW4(ky,K);let V=await X.get("url","global");if(!V)V=z2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!_V(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Pu1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:Bk4(await Jr0(J,X))}}function cb3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function lb3(){AD4();let J=cb3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));fw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ab3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(Rb3(P),P.info("Starting Amp CLI.",{version:"0.0.
|
|
7693
|
+
`),await XD(),process.exit(1);let f=(async()=>{if(q){P.info("Skipping initial free tier status fetch until auth is complete");return}try{let F0=await U.configService.getLatest(),$0=hb(F0),W0=await g6.getUserFreeTierStatus({},{config:U.configService,signal:AbortSignal.timeout($0)});if(W0.ok)return P.info("User free tier status:",W0),W0.result;return}catch(F0){P.error("Failed to fetch free tier status:",F0);return}})(),x=!J.executeMode?new C01:null,_,u=null;if(x)_=x,u=(async()=>{let F0=q?await U.serverStatusPromise:U.serverStatus;await M31(Q,Z,F0);let $0=process.hrtime.bigint(),W0=j31(L,F0),i=m6(F0)?A31({userEmail:F0.user.email,features:F0.features}):!1;Fr4({dtwEnabled:W0,hasV2TUIAccess:i});let o=await T(W0?"dtw":"worker");if(X("runMainThread:createThreadPool",$0),x.attach(o),K){let e=await M1(o.threadHandles$);if(!e)throw new P1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:K}]})}})(),u.catch(async(F0)=>{let $0=F0 instanceof Error?F0:Error(String(F0));x.setInitError($0),await Gj(F0,Z.threadId)});else F=process.hrtime.bigint(),Fr4({dtwEnabled:O,hasV2TUIAccess:w}),_=await T(O?"dtw":"worker"),X("runMainThread:createThreadPool",F);let p=Z.notifications!==void 0?Z.notifications:!J.executeMode;F=process.hrtime.bigint();let d=await U.configService.getLatest();if(X("runMainThread:configService.getLatest",F),F=process.hrtime.bigint(),kb3({configService:U.configService,threadService:U.threadService,config:d,useNotificationsForService:p,threadViewStates$:()=>_.threadHandles$.pipe(U4((F0)=>{if(!F0)return k0.of({});return F5(F0.thread$,F0.threadViewState$).pipe(U1(([$0,W0])=>({[$0.id]:W0})))}))}),X("runMainThread:createCliNotificationService",F),J.executeMode){eS4(U.mcpService,J.settings);let F0={userInput:K,stdinInput:V,dependencies:U,streamJson:G,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:N,agentMode:Z.mode,labels:Z.label},$0=await xL4({threadPool:_,...F0});if(await Br($0,"execute"),Z.archive)await g6.archiveThread({thread:$0,archived:!0},{config:U.configService});await U.asyncDispose(),process.exit(0)}let h=!1,n=!1;if(Z.jetbrains||Z.ide){await Ib1();let F0=await _E({jetbrainsOnly:Z.jetbrains});if(F0.length===0){if(Z.jetbrains)h=!await U.configService.get("jetbrains.skipInstall")}else if(F0.length===1){let $0=F0[0];if($0)A$.selectConfig($0)}else n=!0}F=process.hrtime.bigint();let c=Er0("0.0.1774369119-gbb3185",U.settingsStorage,{startDelayMs:3000});X("runMainThread:createUpdateService",F),F=process.hrtime.bigint();let s=new rk0(U.threadStorage);X("runMainThread:createThreadFuzzyIndexer",F),F=process.hrtime.bigint();let z0=new $s0(U.mcpService,J.settings.getWorkspaceRootPath());if(X("runMainThread:createMcpTrustHandler",F),K&&J.executeMode){let F0=await M1(_.threadHandles$);if(!F0)throw new P1("No active thread is available yet.",1);await F0.sendMessage({content:[{type:"text",text:K}]})}F=process.hrtime.bigint();let a=await fK0();X("runMainThread:loadSessionState",F),P.info("Loaded session state:",a);let q0={...a,launchCount:a.launchCount+1};tj((F0)=>({...F0,launchCount:F0.launchCount+1}));let w0=Z.threadId&&h9(Z.threadId)?Z.threadId:void 0;try{if(F=process.hrtime.bigint(),await Gg4({codebaseContextService:U.codebaseContextService,history:new yl0,fuzzyServer:U.fuzzyServer,settingsStorage:U.settingsStorage,threadService:U.threadService,threadHistoryService:U.threadHistoryService,threadFuzzyIndexer:s,skillService:U.skillService,configService:U.configService,secretStorage:U.secretStorage,internalAPIClient:g6,threadPool:_,createSystemPromptDeps:async()=>Mr4(U),ideClient:A$,mcpService:U.mcpService,toolboxService:U.toolboxService,mcpTrustHandler:z0,updateService:c,pluginPlatform:U.pluginPlatform,pluginService:U.pluginService},{initialServerStatus:U.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:U.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:w0,showJetBrainsInstaller:h,showIdePickerHint:n,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:Z.clientId,sessionState:q0,freeTierStatusPromise:f,workspace:A??null,features:M,isDogfooding:N,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-03-24T16:22:07.349Z"},(F0)=>new a01({...F0,threadPool:F0.threadPool},($0)=>new n61({...$0,threadState:$0.threadState}))),X("runMainThread:mountApp-returned",F),u)await u}finally{}await U.asyncDispose(),X("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function d3(J){if(P.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)R7.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
7694
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;P.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await vo1({get:async(G)=>{if(G!==yg)return;try{let F=await Nr4(E31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==yg)return;await Br4(pL.dirname(E31),{recursive:!0}),await Ob3(E31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:pF()});uu1(Y);let X=await O_4({...J,workspaceTrust:{current:!0,changes:Eb},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await sS4(J.mcpConfig);X=tS4(X,G)}let K=pL.dirname(X.getSettingsFilePath());yW4(ky,K);let V=await X.get("url","global");if(!V)V=z2;if(P.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!_V(V))P.info("Targeting custom Amp server",{ampURL:V});return X=Pu1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:Bk4(await Jr0(J,X))}}function cb3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}async function lb3(){AD4();let J=cb3(process.argv),Z=process.argv.includes("--headless")||process.argv.some((K)=>K.startsWith("--headless="));fw4({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE||(Z?Ab3:void 0)});let Q=process.argv.includes("--no-color"),Y=process.argv.includes("--color"),X=process.stdout.isTTY&&process.stderr.isTTY;if(Q||!Y&&!X)c0.level=0;if(Rb3(P),P.info("Starting Amp CLI.",{version:"0.0.1774369119-gbb3185",buildTimestamp:"2026-03-24T16:22:07.349Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new P1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await gb3().parseAsync(process.argv)}SW4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await lb3().catch(Gj)});async function ib3(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"),V5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
7695
7695
|
`);else if(!_V(J.ampURL))V5.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
7696
7696
|
`);let Y=process.env.AMP_API_KEY;if(Y)V5.write(`API key found in environment variable, storing...
|
|
7697
7697
|
`),await Z.set("apiKey",Y,J.ampURL),V5.write(`API key successfully stored.
|