@sourcegraph/amp 0.0.1768218876-g7c0d4d → 0.0.1768219292-g8af118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -3846,7 +3846,7 @@ How to use the ${M2} tool:
3846
3846
 
3847
3847
  Actions:
3848
3848
  - create: Create a new task with title (required), description, repoURL, status, dependsOn, parentID
3849
- - list: List tasks with optional filters (repoURL, status, limit, ready)
3849
+ - list: List tasks with optional filters (repoURL, status, limit, ready). Completed tasks are excluded by default; use status filter to include them.
3850
3850
  - get: Get a single task by taskID
3851
3851
  - update: Update a task by taskID with new values
3852
3852
  - delete: Soft delete a task by taskID
@@ -4280,11 +4280,11 @@ Actual: ${X}`)}async function DZ8(J,Q,Y){let Z=RV(Q,"package.tgz");P.debug("Do
4280
4280
  ${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
4281
4281
 
4282
4282
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4283
- npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function V61(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=LZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return P.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function LZ8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}K0();function K61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await $R(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=nw(),W=await V61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await G61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Hh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}fn();import{stderr as jV}from"node:process";function C56(J){let Q=new U$().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(Z)=>{await FC1(Z.force||!1,Z.verbose||!1,"0.0.1768218876-g7c0d4d"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new U$("update").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(Z)=>{await OZ8(Z.targetVersion)});J.addCommand(Y)}async function OZ8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")jV.write(Z0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4283
+ npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function V61(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=LZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return P.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return P.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function LZ8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}K0();function K61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await $R(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=nw(),W=await V61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await G61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Hh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await $R(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}fn();import{stderr as jV}from"node:process";function C56(J){let Q=new U$().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(Z)=>{await FC1(Z.force||!1,Z.verbose||!1,"0.0.1768219292-g8af118"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new U$("update").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(Z)=>{await OZ8(Z.targetVersion)});J.addCommand(Y)}async function OZ8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")jV.write(Z0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4284
4284
 
4285
4285
  `));try{if(!J){jV.write(Z0.blue(`Checking for updates...
4286
- `));let Y=nw(),{hasUpdate:Z,latestVersion:X}=await V61("0.0.1768218876-g7c0d4d",Y);if(!Z){jV.write(Z0.green(`✓ Amp CLI is already up to date: ${"0.0.1768218876-g7c0d4d"} (${"released"} ${"2026-01-12T11:59:31.016Z"}${`, ${dA(new Date("2026-01-12T11:59:31.016Z"))} ago`})
4287
- `));let V=await CF("0.0.1768218876-g7c0d4d");if(V.warning)jV.write(`
4286
+ `));let Y=nw(),{hasUpdate:Z,latestVersion:X}=await V61("0.0.1768219292-g8af118",Y);if(!Z){jV.write(Z0.green(`✓ Amp CLI is already up to date: ${"0.0.1768219292-g8af118"} (${"released"} ${"2026-01-12T12:05:44.068Z"}${`, ${dA(new Date("2026-01-12T12:05:44.068Z"))} ago`})
4287
+ `));let V=await CF("0.0.1768219292-g8af118");if(V.warning)jV.write(`
4288
4288
  `+Z0.yellow(V.warning)+`
4289
4289
  `);process.exit(0)}if(!X)jV.write(Z0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}jV.write(Z0.blue(`Updating to version ${J}...
4290
4290
  `)),await Hh(J,void 0,(Y)=>{jV.write(Z0.dim(`Running: ${Y}
@@ -5075,7 +5075,7 @@ exit code: ${G}`,new f({color:Z.foreground,dim:!0,italic:!0})));if(V)K.push(new
5075
5075
  `));let q=K.startsWith("file://")?Q0.parse(K):Q0.file(K),W=q7(q,X??void 0);G.push(new S(` • ${W}`,new f({color:Z.foreground,dim:!0})))}return new e({text:new S("",void 0,G)})}class G$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=Q.length>0,X=[new e({text:new S(Y?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",new f({color:o.yellow,bold:!0}))}),new I1({height:1})],G=$$6(J,Q);if(G)X.push(G),X.push(new I1({height:1}));let V=[{value:"confirm",label:Y?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return X.push(new O5({options:V,onSelect:(K)=>{if(K==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:X})}}class V$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=[],Z=$$6(J,Q);if(Z)Y.push(new e({text:new S("This will restore the following files:",new f({color:o.yellow,bold:!0}))})),Y.push(new I1({height:1})),Y.push(Z),Y.push(new I1({height:1}));let X=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new O5({options:X,onSelect:(G)=>{if(G==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class h81 extends p1{initialText;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;constructor(J){super();this.initialText=J.initialText,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview}createState(){return new K$6}}class K$6 extends u1{controller=new Q7;currentShellModeStatus;imageAttachments=[];initState(){this.controller.text=this.widget.initialText,this.controller.addListener(this.textChangeListener);let J=rF(this.widget.initialText);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Q=this.widget.message.content.filter((Y)=>Y.type==="image");this.imageAttachments=Q}}dispose(){this.controller.removeListener(this.textChangeListener),this.controller.dispose(),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Y=rF(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=(J)=>{let Q=vj(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Q=this.imageAttachments[J];if(Q)this.widget.onShowImagePreview(Q,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,Z)=>Z!==J)})})};build(J){let Q=W0.of(J),Y=Q.colors,Z=Q.app,X=this.currentShellModeStatus?vZ6(Q,this.currentShellModeStatus):Y$6,G=null,V=this.widget.message&&Cl(this.widget.message);if(V)G=fy1(J,V);let K=new Dg({controller:this.controller,triggers:[new YU],completionBuilder:this.widget.completionBuilder,ampURL:"",onSubmitted:this.handleSubmit,theme:Y,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:B81(Q),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0}),q=[];if(q.push(K),G)q.push(new I1({height:1})),q.push(G);let W;if(q.length===1)W=q[0];else W=new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let H=[];if(this.currentShellModeStatus===oF)H.push(new S("shell mode (incognito)",new f({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===U81)H.push(new S("shell mode",new f({color:Q.app.shellMode})));else H.push(new S("esc",new f({color:Z.keybind})),new S(" to cancel",new f({color:Y.foreground,dim:!0})));return new Jh({child:new VY({decoration:{border:y0.all(new j0(X,2,"solid"))},padding:j1.only({left:1,right:1}),overlays:[{child:new e({text:new S("",void 0,H)}),position:"bottom",alignment:"left"}],child:W})})}}class g81 extends x8{}class m81 extends x8{}class hy1 extends x8{}class gy1 extends x8{}class my1 extends x8{}class uy1 extends x8{}class py1 extends x8{}class dy1 extends x8{}function aB8(J,Q,Y){let X=W0.maybeOf(J)?.colors??x0.of(J).colorScheme,V=Q.trimStart().startsWith("You're absolutely right"),K=new y8(`${Y}-text`),q=[];if(V)q.push(new Wy1({key:K,markdown:Q,defaultColor:X.foreground}));else q.push(new f8({key:K,markdown:Q}));if(q.length===1)return q[0];return new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})}function oB8(J,Q){let Z=x0.of(J).colorScheme;if(Q.summary.type!=="message")return new d1;return new k1({crossAxisAlignment:"start",children:[new e({text:new S("Summary:",new f({color:Z.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new I1({height:1}),new f8({markdown:Q.summary.summary,styleScheme:{text:new f({color:Z.foreground,dim:!0,italic:!0}),inlineCode:new f({color:Z.foreground,dim:!0,italic:!0}),codeBlock:new f({color:Z.foreground,dim:!0,italic:!0}),tableBorder:Z.foreground,link:new f({color:Z.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:Z.foreground,string:Z.foreground,number:Z.foreground,comment:Z.foreground,function:Z.foreground,variable:Z.foreground,type:Z.foreground,operator:Z.foreground}}})]})}class u81 extends p1{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onMessageForkSubmit;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Y=this.items[Q];if(Y?.type==="message"){if(Y.message.role==="user"||gO(Y.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Y={},controller:Z,autofocus:X=!1,onNewMessage:G,showScrollbar:V=!0,onCopy:K,onMessageEditSubmit:q,onMessageRestoreSubmit:W,onMessageForkSubmit:H,getAffectedFiles:z,thread:F,focusNode:U,onDismissFocus:D,isInSelectionMode:B=!1,isInHandoffMode:N=!1,completionBuilder:w,onShowImagePreview:M,onSelectionChanged:L}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Y,this.controller=Z,this.autofocus=X,this.onNewMessage=G,this.showScrollbar=V,this.onCopy=K,this.onMessageEditSubmit=q,this.onMessageRestoreSubmit=W,this.onMessageForkSubmit=H,this.getAffectedFiles=z,this.thread=F,this.focusNode=U,this.onDismissFocus=D,this.isInSelectionMode=B,this.isInHandoffMode=N,this.completionBuilder=w,this.onShowImagePreview=M,this.onSelectionChanged=L}createState(){return new q$6}}class q$6 extends u1{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_pendingEditImageAttachments=[];_affectedFiles=[];_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;get controller(){return this._controller}dismiss(){Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=this.getUserMessageIndexFromOrdinal(Y);if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);if(this.setState(()=>{this._selectedUserMessageOrdinal=Y}),X!==null)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=Y!==null?this.getUserMessageIndexFromOrdinal(Y):null;if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);this.setState(()=>{this._editingMessageOrdinal=Y})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Y=this.widget.userMessageIndices.indexOf(J);return Y>=0?Y:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Y=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||gO(Q.message)))this.showRestoreConfirmation(Q.message,J)}return"handled"}return"ignored"};async showRestoreConfirmation(J,Q){let Y=[];if(this.widget.getAffectedFiles)try{Y=await this.widget.getAffectedFiles(J)}catch{Y=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!0,this._affectedFiles=Y}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||gO(Q.message))){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};handleEditConfirmationRequest=async(J,Q)=>{if(J.trim()===""&&Q.length===0)return;if(this._editingMessageOrdinal!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(Y!=null){let Z=this.widget.items[Y],X=[];if(this.widget.getAffectedFiles&&Z?.type==="message")try{X=await this.widget.getAffectedFiles(Z.message)}catch{X=[]}if(X.length===0&&Z?.type==="message"&&(Z.message.role==="user"||Z.message.role==="info")){this.widget.onMessageEditSubmit?.(Z.message,J,Q),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._editingMessageOrdinal=null}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!0,this._pendingEditText=J,this._pendingEditImageAttachments=Q,this._affectedFiles=X,this._editingMessageOrdinal=null}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y)})}}};handleEditConfirm=()=>{if(this._selectedUserMessageOrdinal!==null&&this._pendingEditText!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageEditSubmit?.(Q.message,this._pendingEditText,this._pendingEditImageAttachments),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Y=V7(Q.content),Z=Q.content.filter((X)=>X.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${Z}|${Y}`}else if(Q.role==="assistant"){let Y=V7(Q.content),Z=Q.state?.type??"none",X=Q.content.filter((q)=>q.type==="thinking"),G=Q.content.filter((q)=>q.type==="tool_use"),V=Q.usage,K=V?`${V.credits??""}|${V.inputTokens}|${V.outputTokens}|${V.cacheCreationInputTokens??""}|${V.cacheReadInputTokens??""}|${V.model??""}`:"no-usage";return`${J.id}|assistant|${Z}|${X.length}|${G.length}|${Y}|${K}`}else{let Z=Q.content.map((X)=>X.type).join(",");return`${J.id}|info|${Z}`}}else{let Y=J.toolResult.run.status;return`${J.id}|tool|${Y}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Y=`${J}-${Q}`;return this._thinkingBlockStates.get(Y)??Y7.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Y)=>{let Z=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(Z,Y),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Y,Z,X){let G=Y===X,V=Z.state?.type==="streaming"&&G,K=Z.state?.type==="cancelled"&&G;return new AM({key:new y8(`thinking-${Q}-${Y}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Y),onToggle:this.toggleThinkingBlock(Q,Y),isStreaming:V,isCancelled:K})}buildAssistantMessageWidget(J,Q,Y,Z){let X=Q.content.map((U,D)=>({block:U,index:D})).filter((U)=>U.block.type==="thinking"&&Gg(U.block.thinking).length>0),G=X.length>0,V=X.length>0?X.at(-1).index:-1,K=Q.content.filter((U)=>U.type==="text"),q=[];if(q.push(...X.map(({block:U,index:D})=>this.buildThinkingBlock(U,Y,D,Q,V))),G&&K.length>0)q.push(new I1({height:1}));let W=V7(K);if(W.trim())q.push(aB8(J,W,Z));let H=qy1(J),z=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(H&&z){let D=W0.maybeOf(J)?.colors??x0.of(J).colorScheme,B=$X6(Q.usage);q.push(new J0({padding:j1.only({top:1}),child:new e({text:new S(B,new f({color:D.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new d1;else if(q.length===1)F=q[0];else F=new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Y){let Z=new y8(`thread-item-${Q.id}`);if(Q.type==="message"){let X=Q.message;if(X.role==="user"){let G,V=(K,q)=>{this.widget.onShowImagePreview(K,q,()=>{})};if(!this.widget.isInSelectionMode)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else{let K=this.getOrdinalFromUserMessageIndex(Y);if(K===null)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else if(this._editingMessageOrdinal===K)G=new h81({initialText:V7(X.content),message:X,onSubmitted:(q,W)=>{this.handleEditConfirmationRequest(q,W)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview});else if(this._selectedUserMessageOrdinal===K)G=new f81({message:X,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:V});else G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V})}return G}else if(X.role==="assistant"){let G=this.buildAssistantMessageWidget(J,X,Y,Q.id);return new d1({key:Z,child:G})}else{let G=X,V=[],K=this.getOrdinalFromUserMessageIndex(Y),q=this.widget.isInSelectionMode&&K!==null&&this._selectedUserMessageOrdinal===K,W=(H,z)=>{this.widget.onShowImagePreview(H,z,()=>{})};for(let H of G.content)if(H.type==="manual_bash_invocation")if(this._editingMessageOrdinal===K){let F=`${D81(H.hidden??!1)}${H.args.cmd}`;V.push(new h81({initialText:F,message:G,onSubmitted:(U,D)=>{this.handleEditConfirmationRequest(U,D)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview}))}else if(!this.widget.isInSelectionMode||!q)V.push(new lj({message:G,isFirstMessage:Y>0,onShowImagePreview:W}));else V.push(new f81({message:G,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:W}));else if(H.type==="summary"&&H.summary.type==="message")V.push(oB8(J,H));if(V.length===0)return new d1;if(V.length===1)return V[0];return new k1({crossAxisAlignment:"stretch",children:V})}}else{let X=new HW({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new d1({key:Z,child:X})}}initState(){if(super.initState(),this._controller=this.widget.controller||new a4,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},Y7.instance.addListener(this._globalToggleListener),this.widget.items.length>0)Y4.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Y=this.getLatestUserMessageOrdinal();if(Y!==null)this._selectUserMessageByOrdinal(Y)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Y=0;Y<Q;Y++){let Z=J.items[Y],X=this.widget.items[Y];if(Z&&X){if(Z.type!==X.type){this._widgetCache.delete(Y);continue}if(Z.type==="toolResult"&&X.type==="toolResult"){let G=Z.toolResult.run,V=X.toolResult.run;if(G.status!==V.status||"result"in G!=="result"in V||"error"in G!=="error"in V)this._widgetCache.delete(Y)}if(Z.type==="message"&&X.type==="message"){let G=Z.message,V=X.message;if(G.content!==V.content)this._widgetCache.delete(Y)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Y of this._streamingIndexes)if(Y>=this.widget.items.length)this._streamingIndexes.delete(Y)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Y=this._isMessageStreaming(Q);if(Y&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Y&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)Y7.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=W0.of(J),Y=qy1(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Y)this._widgetCache.clear();this._lastCostDisplayState=Y;let Z=this._getTotalItemCount(J),X=[];for(let F=0;F<Z;F++)if(X.push(this._buildItemAtIndex(J,F)),F<Z-1)X.push(new I1({height:1}));let G=new q4({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new k1({key:new y8("message-list-column"),crossAxisAlignment:"start",children:X})}),K=[new J0({padding:j1.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:G})];if(this.widget.showScrollbar&&this._controller){let F=new C9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});K.push(new f4({right:1,top:0,bottom:0,child:new I1({width:1,child:F})}))}let q=new x4({children:K}),W=new tq({child:q,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),H=new Map([[g81,new h6(this.handleNavigateUserMessageUp)],[m81,new h6(this.handleNavigateUserMessageDown)],[hy1,new h6(this.handleEscape)],[gy1,new h6(this.handleScrollDown)],[my1,new h6(this.handleScrollUp)],[uy1,new h6(this.handleEditMessage)],[py1,new h6(this.handleRestoreMessage)],[dy1,new h6(this.handleForkMessage)]]),z=new Map([[p0.key("Tab"),new g81],[p0.shift("Tab"),new m81],[p0.key("Escape"),new hy1],[p0.key("j"),new gy1],[p0.key("k"),new my1],[p0.key("e"),new uy1],[p0.key("r"),new py1],[p0.key("f"),new dy1]]);if(!J7())z.set(p0.key("ArrowUp"),new g81),z.set(p0.key("ArrowDown"),new m81);if(this.widget.focusNode)return new A6({focusNode:this.widget.focusNode,child:new b5({actions:H,child:new C3({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._isShowingRestoreConfirmation||this._isShowingEditConfirmation){let Q=this._selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}if(this._editingMessageOrdinal!==null){let Q=this.getUserMessageIndexFromOrdinal(this._editingMessageOrdinal);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Q){let Y=this.widget.items[Q];if(!Y)return new d1;let Z=Y.type==="message"&&this._isMessageStreaming(Y),X=Y.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),G=this._shouldDimItem(Q);if(!Z&&!X){let q=`${this._signatureFor(Y)}|dim:${G?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===q)return W.widget;let H=this.buildThreadItemWidget(J,Y,Q),z=G?new GY({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:q,widget:z}),z}let K=this.buildThreadItemWidget(J,Y,Q);return G?new GY({forceDim:!0,child:K}):K}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offsetPercent:Y=0.25,edge:Z="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let G=this._getMessageRelativeOffset(J,Z);if(G===null)return!1;let V=this._getViewportHeight(),K=Math.floor(V*Y),q=G-K;if(Q)this._controller.animateTo(q,X);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new y8("message-list-column"),Y=(Z)=>{if(Z.widget.key?.equals(Q))return Z;for(let X of Z.children){let G=Y(X);if(G)return G}return null};return Y(J)}_getMessageRelativeOffset(J,Q){let Y=this._getColumnElement();if(!Y)return null;let Z=J*2,X=Y.children[Z];if(!X?.renderObject)return null;let G=X.renderObject,V=Y.renderObject;if(!V)return null;let K=G.localToGlobal({x:0,y:0}),q=V.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=G.size.height;return K.y+W-q.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Y=this._controller?.offset??0,Z=J+Q;return{totalContentHeight:Math.max(Z,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Y,0)}}}n6();j6();n6();K0();class cy1{threadService;workers=new Map;threadsMap=new Map;mainThreadSubs=new Map;workerStatusSubs=new Map;mainThreadObservable;workerStatusObservable;emitMainThread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new T1((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.workerStatusObservable=new T1((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(Sl()).subscribe((X)=>{this.threadsMap.set(Q,X);let G=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:X,workerStatus:G})});this.mainThreadSubs.set(Q,Y);let Z=J.status.subscribe((X)=>{if(this.workers.set(Q,X),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:X})});this.workerStatusSubs.set(Q,Z)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);this.workers.delete(J),this.threadsMap.delete(J)}observeThread(J){return{mainThread:new T1((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new T1((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let Z=this.workers.get(Q);if(Z)J[Q]=Zw(Y,Z)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.workerStatusSubs.clear(),this.workers.clear(),this.threadsMap.clear()}}function rB8(J,Q){switch(Q.type){case"main-thread-patch":{let{thread:Y,workerStatus:Z}=Q,{items:X}=p81(Y),G=Zw(Y,Z),V=qH({messages:Y.messages}),K=Array.isArray(V)?V:[];return{...J,items:X,viewState:G,todosList:K,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=Zw(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function p81(J){let Q=[],Y=new Map,Z=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Y.set(W.id,W),K)Z.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let F=J.messages[z];if(F){for(let U of F.content)if(U.type==="tool_result"&&U.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}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:V,message:G});break}case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Y.get(q.toolUseID)??R2(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}class ly1 extends p1{props;constructor(J){super();this.props=J}createState(){return new W$6}}class W$6 extends u1{state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new cy1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((X)=>{this.dispatch({type:"main-thread-patch",thread:X.mainThread,workerStatus:X.workerStatus})});this.subscriptions.push(Y);let Z=Q.workerStatus.subscribe((X)=>{this.dispatch({type:"worker-status-change",workerStatus:X.status})});this.subscriptions.push(Z)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=rB8(this.state,J)})}getThreadData(){let J=(X)=>X===x9||X===T8||X===WG||X===M2,Q=new Map;for(let X of this.state.items)if(X.type==="toolResult"&&J(X.toolUse.name))Q.set(X.toolUse.id,{toolUseId:X.toolUse.id,toolName:X.toolUse.name,toolRun:X.toolResult.run});let Y=Array.from(Q.values()),Z={};for(let{toolUseId:X,toolRun:G}of Y){let V=[],K;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")K=G.progress;if(K){let q=0;for(let W of K)if(W.tool_uses)for(let H of W.tool_uses){let z=`${X}:progress:${q++}`,F=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status};V.push({toolUse:hO(H.tool_name,H.input,z),toolRun:F})}}Z[X]=V}return{...this.state,subagentToolsByParentID:Z}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class iy1 extends p1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new H$6}}class H$6 extends u1{build(J){let Y=W0.of(J).colors,{todos:Z,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return new I1({width:0,height:0});let G=Z.map((V)=>this.buildTodoItem(V,Y));return new d1({child:new J0({padding:j1.symmetric(1,0),child:new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new e({text:new S(X,new f({bold:!0,color:Y.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),Z=J.status==="completed",X=new f({bold:J.status==="in-progress",color:Q.foreground,dim:Z}),G=new f({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Z});return new X0({crossAxisAlignment:"start",children:[new e({text:new S(Y,X)}),new I1({width:1}),new A0({child:new e({text:new S(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class ny1 extends p1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:Z,onImpression:X,onAdInfoClick:G}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=Z,this.onImpression=X,this.onAdInfoClick=G}createState(){return new z$6}}class z$6 extends u1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=W0.of(J),Y=Q.colors.primary,Z=Q.colors.foreground,X=this.widget.ad;return new d1({decoration:new N6(void 0,new y0(new j0(Y,1,"rounded"),new j0(Y,1,"rounded"),void 0,new j0(Y,1,"rounded"))),child:new J0({padding:j1.horizontal(1),child:new k1({children:[new X0({crossAxisAlignment:"start",children:[new A0({child:new e({text:new S(X.content,new f({color:Z}))})}),new I1({width:4}),new H6({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new e({text:new S("Ad",new f({color:Z,dim:!0}))})})]}),new X0({crossAxisAlignment:"start",children:[new _C1({text:X.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:j1.horizontal(1),color:Y,reverse:!0}),new I1({width:2}),new e({text:new S(X.destinationUrlHostname,new f({color:Z,dim:!0}))})]})]})})})}}class ay1 extends p1{props;constructor(J){super();this.props=J}createState(){return new F$6(this.props.autofocus??!0)}}class F$6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=t0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(this.widget.props.title)G.push(new e({text:new S(this.widget.props.title,new f({bold:!0,color:o.blue}))}),new I1({height:1}));if(this.widget.props.message)G.push(new e({text:new S(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new I1({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new e({text:new S("Enter to copy",new f({dim:!0}))}));return V.push(new e({text:new S("Escape to close",new f({dim:!0}))})),G.push(new X0({children:V.flatMap((K,q)=>q<V.length-1?[K,new I1({width:1}),new e({text:new S("•",new f({dim:!0}))}),new I1({width:1})]:[K]),mainAxisSize:"min"})),new b0({child:new d1({constraints:new O0(Z,Z,0,X),decoration:new N6(o.default(),new y0(new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}class oy1 extends p1{props;constructor(J){super();this.props=J}createState(){return new U$6(this.props.autofocus??!0)}}class U$6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"||V.key==="Escape"||V.ctrlKey&&V.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=t0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(G.push(new e({text:new S("Ads make Amp Free possible",new f({bold:!0}))})),this.widget.props.provider)G.push(new I1({height:1}),new e({text:new S(`Ad source: ${this.widget.props.provider}`,new f({dim:!0}))}));return G.push(new I1({height:1}),new e({text:new S("Escape to close",new f({dim:!0}))})),new b0({child:new d1({constraints:new O0(Z,Z,0,X),decoration:new N6(o.default(),new y0(new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"),new j0(o.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}function ry1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}fX();v1();import{spawn as sB8}from"node:child_process";import{promises as tB8}from"node:fs";function D$6(J){return J.kind==="executable"}function B$6(J){return J.kind==="markdown"}var zW=50000,N$6=300000;async function sy1(J,Q,Y,Z={}){let{timeoutMs:X=N$6,signal:G,source:V}=Z;try{let K=await Y.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(P.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),B$6(K))return await eB8(K,Q);else if(D$6(K))return await JN8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return P.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function eB8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await tB8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>zW?Y.slice(0,zW)+`
5076
5076
  ... (output truncated at ${zW} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function JN8(J,Q,Y=N$6,Z){return new Promise((X)=>{let[G,V]=QN8(J,Q);P.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let K=dS(Z),q=!1,W=setTimeout(()=>{q=!0,K.abort(),P.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=sB8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],F=[],U=0;H.stdout?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=zW)z.push(B);else{let N=zW-(U-B.length);if(N>0)z.push(B.slice(0,N))}}),H.stderr?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=zW)F.push(B);else{let N=zW-(U-B.length);if(N>0)F.push(B.slice(0,N))}}),H.on("close",(D)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:D??void 0});return}let B=D===0||D===1,N=z.join(""),w=F.join(""),M=N;if(!B&&!N.trim()&&w.trim())M=w;else if(w.trim())M+=N?`
5077
5077
  ${w}`:w;if(U>zW)M+=`
5078
- ... (output truncated at ${zW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function QN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return ZN8(Y,Z?[...Z]:null,X,Q);else return YN8(Y,Z?[...Z]:null,X,Q)}function YN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function ZN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}v1();aO();RX();b9();K3();MO();MG();N3();RQ();CH();UZ();n6();Fb();t9();MC();K0();var s$6=H0(iH(),1);import{writeFile as i$6}from"fs/promises";import n$6 from"path";v1();N3();class ty1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1768218876-g7c0d4d"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Za(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ZU extends p1{props;constructor(J){super();this.props=J}createState(){return new w$6}}class w$6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class M$6 extends u1{controller=new Q7;focusNode=new r6({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 Q=W0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new j0(Y.foreground,1,"solid")),q=new T3({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:o.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new d1({decoration:{border:K,color:o.default()},padding:j1.all(1),child:new k1({children:[H,new I1({height:1}),W,new O8,F]})})}}class Bg extends p1{props;constructor(J){super();this.props=J}createState(){return new M$6}}import{isDeepStrictEqual as VN8}from"node:util";var XN8=/[\\/_ +.#"@[({&]/,$N8=/[\\/_ +.#"@[({&]/g,GN8=/[\s-]/,L$6=/[\s-]/g;function c81(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=c81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(L$6),D&&X>0)z*=0.999**D.length}else if(XN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match($N8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(F=c81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function d81(J){return J.toLowerCase().replace(L$6," ")}function O$6(J,Q){let Y=c81(J,Q,d81(J),d81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=c81(J,K,d81(J),d81(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class ij{}class nj{}class l81{}class i81{}class A$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new I$6}}class I$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function KN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=O$6(Q,J);return{matches:Y>0.15,score:Y}}class P7 extends p1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new E$6}}class E$6 extends u1{controller=new Q7;focusNode;scrollController=new a4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new r6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!VN8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof l81){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof i81)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...KN8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=W0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=y0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new C3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new l81],[new p0("Escape"),new i81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[l81,new h6(this.invoke)],[i81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new I1({height:10,child:new b0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new b0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?o.yellow:void 0,I=M?o.black:Y.foreground;O=new d1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new A$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:o.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new I1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new d1({padding:j1.vertical(1),child:new b0({child:N})}));else F.push(new I1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new d1({decoration:{border:X,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function R$6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class ey1 extends S0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>R$6(X.pubDate).length));return new P7({items:Q,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,G,V,K)=>{let q=W0.of(K),{colors:W}=q,H=G?o.yellow:void 0,z=G?o.black:W.foreground,F=o.index(8),U=(D,B)=>new I1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new d1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new I1({width:2}),U(R$6(X.pubDate),Y)]})})}})}}class Jx1 extends p1{createState(){return new j$6}}class j$6 extends u1{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){return new e({text:new S("●",new f({color:this.isGreen?o.green:o.index(8),bold:!0})),maxLines:1})}}function qN8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return BY.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function Qx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function WN8(J,Q,Y,Z){return[Qx1("+",J,Z.success),O8.horizontal(1),Qx1("~",Q,Z.warning),O8.horizontal(1),Qx1("-",Y,Z.destructive)]}class n81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=qN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=W0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new b0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:o.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new P7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(z,F,U,D)=>{let B=W0.of(D),{colors:N}=B,w=F?o.yellow:void 0,M=F?o.black:N.foreground,L=o.index(8),O=(m,v)=>new I1({width:v,child:X0.end([new e({text:new S(m,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new N81;if(z.depth>0){let m=[],v=z.ancestorsAreLast.slice(1);for(let d of v)m.push(new S(C.getAncestorPrefix(d),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,g=C.getConnectorText(x);m.push(new S(g,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,m)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:o.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Jx1),y.push(new I1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let m=b.match(/^Forked\((\d+)\): /);if(m)b=b.slice(m[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:o.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:o.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new I1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let m=F?{success:L,warning:L,destructive:L}:N;y.push(...WN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,m)),y.push(new I1({width:2}))}return y.push(O(z.description.timeAgo,K)),new d1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class T$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new C$6}}class C$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var P$6=30,HN8=30;class aj{}class oj{}class a81{}class o81{}class Yx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new _$6}}class _$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new a4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.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 Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof a81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof o81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=W0.of(J),{colors:Z}=Y,V=t0.of(J).size.width>=HN8+P$6,K=y0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:o.yellow,bold:!0}))})}),H=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new C3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new a81],[new p0("Escape"),new o81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[a81,new h6(this.invoke)],[o81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?o.yellow:void 0,y=I?o.black:o.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?o.black:o.green})));return new T$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new d1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new d1({padding:j1.all(1),child:new IM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new I1({width:P$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new d1({decoration:{border:K,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new I1({height:1}),new A0({child:L})]})})}}class Zx1 extends S0{props;constructor(J){super();this.props=J}build(){return new b0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
5078
+ ... (output truncated at ${zW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function QN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return ZN8(Y,Z?[...Z]:null,X,Q);else return YN8(Y,Z?[...Z]:null,X,Q)}function YN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function ZN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}v1();aO();RX();b9();K3();MO();MG();N3();RQ();CH();UZ();n6();Fb();t9();MC();K0();var s$6=H0(iH(),1);import{writeFile as i$6}from"fs/promises";import n$6 from"path";v1();N3();class ty1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1768219292-g8af118"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Za(Q,this.configService)}catch(Q){P.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ZU extends p1{props;constructor(J){super();this.props=J}createState(){return new w$6}}class w$6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class M$6 extends u1{controller=new Q7;focusNode=new r6({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 Q=W0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=y0.all(new j0(Y.foreground,1,"solid")),q=new T3({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:o.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new d1({decoration:{border:K,color:o.default()},padding:j1.all(1),child:new k1({children:[H,new I1({height:1}),W,new O8,F]})})}}class Bg extends p1{props;constructor(J){super();this.props=J}createState(){return new M$6}}import{isDeepStrictEqual as VN8}from"node:util";var XN8=/[\\/_ +.#"@[({&]/,$N8=/[\\/_ +.#"@[({&]/g,GN8=/[\s-]/,L$6=/[\s-]/g;function c81(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=c81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(GN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(L$6),D&&X>0)z*=0.999**D.length}else if(XN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match($N8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(F=c81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function d81(J){return J.toLowerCase().replace(L$6," ")}function O$6(J,Q){let Y=c81(J,Q,d81(J),d81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=c81(J,K,d81(J),d81(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class ij{}class nj{}class l81{}class i81{}class A$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new I$6}}class I$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function KN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=O$6(Q,J);return{matches:Y>0.15,score:Y}}class P7 extends p1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new E$6}}class E$6 extends u1{controller=new Q7;focusNode;scrollController=new a4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new r6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!VN8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof l81){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof i81)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...KN8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=W0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=y0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new C3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new l81],[new p0("Escape"),new i81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[l81,new h6(this.invoke)],[i81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new I1({height:10,child:new b0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new b0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?o.yellow:void 0,I=M?o.black:Y.foreground;O=new d1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new A$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:o.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new I1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new d1({padding:j1.vertical(1),child:new b0({child:N})}));else F.push(new I1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new d1({decoration:{border:X,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function R$6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class ey1 extends S0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>R$6(X.pubDate).length));return new P7({items:Q,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,G,V,K)=>{let q=W0.of(K),{colors:W}=q,H=G?o.yellow:void 0,z=G?o.black:W.foreground,F=o.index(8),U=(D,B)=>new I1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new d1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new I1({width:2}),U(R$6(X.pubDate),Y)]})})}})}}class Jx1 extends p1{createState(){return new j$6}}class j$6 extends u1{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){return new e({text:new S("●",new f({color:this.isGreen?o.green:o.index(8),bold:!0})),maxLines:1})}}function qN8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return BY.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function Qx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function WN8(J,Q,Y,Z){return[Qx1("+",J,Z.success),O8.horizontal(1),Qx1("~",Q,Z.warning),O8.horizontal(1),Qx1("-",Y,Z.destructive)]}class n81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=qN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=W0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new b0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:o.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new P7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(z,F,U,D)=>{let B=W0.of(D),{colors:N}=B,w=F?o.yellow:void 0,M=F?o.black:N.foreground,L=o.index(8),O=(m,v)=>new I1({width:v,child:X0.end([new e({text:new S(m,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new N81;if(z.depth>0){let m=[],v=z.ancestorsAreLast.slice(1);for(let d of v)m.push(new S(C.getAncestorPrefix(d),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,g=C.getConnectorText(x);m.push(new S(g,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,m)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:o.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Jx1),y.push(new I1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let m=b.match(/^Forked\((\d+)\): /);if(m)b=b.slice(m[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:o.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:o.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new I1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let m=F?{success:L,warning:L,destructive:L}:N;y.push(...WN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,m)),y.push(new I1({width:2}))}return y.push(O(z.description.timeAgo,K)),new d1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class T$6 extends p1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new C$6}}class C$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var P$6=30,HN8=30;class aj{}class oj{}class a81{}class o81{}class Yx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new _$6}}class _$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new a4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new r6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.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 Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof a81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof o81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=W0.of(J),{colors:Z}=Y,V=t0.of(J).size.width>=HN8+P$6,K=y0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new d1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:o.yellow,bold:!0}))})}),H=new T3({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new C3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new a81],[new p0("Escape"),new o81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[a81,new h6(this.invoke)],[o81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new d1({decoration:{color:o.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?o.yellow:void 0,y=I?o.black:o.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?o.black:o.green})));return new T$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new d1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new d1({padding:j1.all(1),child:new IM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new I1({width:P$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new d1({decoration:{border:K,color:o.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new I1({height:1}),new A0({child:L})]})})}}class Zx1 extends S0{props;constructor(J){super();this.props=J}build(){return new b0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
5079
5079
 
5080
5080
  `,new f({color:o.white,dim:!0})),new S(`"${this.props.newThreadTitle||"Untitled"}"`,new f({color:o.white}))]),textAlign:"center"})})}}v1();class S$6 extends u1{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){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase 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((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Y=this.widget.props.currentLabels||[],Z=this.labels.some((G)=>G.name===Q),X=Y.includes(Q);return!Z&&!X}build(J){let Q=W0.of(J),{colors:Y}=Q,Z=this.currentQuery.trim().toLowerCase(),X=Z.length>0?this.getValidationError(Z):null,G=this.getAvailableLabels(),K=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...G];return new P7({title:"Add Label",items:K,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(q,W,H,z)=>{let F=W?o.yellow:void 0,U=W?o.black:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let B=this.currentQuery.trim().toLowerCase();return new d1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,[new S("Create new label: ",new f({color:U})),new S(B,new f({color:U,bold:!0}))])})})}return new d1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(q.name,new f({color:U}))})})},filterItem:(q,W)=>{if(this.currentQuery!==W)this.currentQuery=W,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(W);let z=W.trim().toLowerCase();return z.length===0||q.name.includes(z)},sortItems:(q,W,H)=>{let z="__isCreateMarker"in q.item&&q.item.__isCreateMarker,F="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(z&&!F)return-1;if(!z&&F)return 1;return W.score-q.score}})}}class Xx1 extends p1{props;constructor(J){super();this.props=J}createState(){return new S$6}}class XU extends p1{props;constructor(J){super();this.props=J}createState(){return new k$6}}class k$6 extends u1{_spinner=new YJ;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 Q=W0.of(J),{colors:Y}=Q,Z=y0.all(new j0(Y.foreground,1,"solid")),X=this._spinner.toBraille(),G=new e({textAlign:"center",text:new S("",void 0,[new S(X,new f({color:o.yellow})),new S(" ",void 0),new S(this.widget.props.message,new f({color:Y.foreground}))])}),K=[new A0({child:new k1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new I1({height:2,child:new d1({padding:j1.symmetric(2,0),child:new e({text:new S("",new f({dim:!0}),[new S("Press ",new f({color:Y.foreground})),new S("Esc",new f({color:Y.info})),new S(" to cancel",new f({color:Y.foreground}))])})})}));let q=new d1({decoration:new N6(o.default(),Z),child:new I1({width:60,height:7,child:new k1({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new A6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class RM extends p1{props;constructor(J){super();this.props=J}createState(){return new y$6}}class y$6 extends u1{scrollController=new a4;scrollAreaKey=new r7("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 DY}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Y=Q.size;if(typeof Y.height==="number"&&Y.height>0)return this.viewportHeight=Y.height,Y.height}return this.viewportHeight}build(J){let Q=W0.of(J),Y=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Y))return{title:Y.title,type:Y.type};if(Y instanceof Error&&Y.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Y.message};if(Y instanceof Error&&Y.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Y.message};let H=F81(Y);return{title:H.title,type:H.type,description:H.description}})(),X=Z.type==="error"?o.red:o.yellow,G=y0.all(new j0(o.default(),1,"solid")),V=new d1({padding:j1.symmetric(1,0),child:new e({text:new S(Z.title,new f({color:X,bold:!0}))})}),K=this.isWidgetMessage(Y)?Y.widget:new e({text:new S(Z.description,new f({color:o.default()})),selectable:!0}),q=new A0({child:new tq({child:new d1({padding:j1.symmetric(1,0),child:new X0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new A0({child:new q4({controller:this.scrollController,autofocus:!0,child:K})}),new C9({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,z=this.scrollController.offset,F=this.getViewportHeight(),U=H+F;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(z,0)}}})]})})})}),W=new d1({padding:j1.symmetric(1,0),child:new e({text:this.widget.props.onRetry?new S("",void 0,[new S("Press ",new f({color:o.default(),dim:!0})),new S("R",new f({color:o.yellow})),new S(" to retry, ",new f({color:o.default(),dim:!0})),new S("Esc",new f({color:o.yellow})),new S(" to cancel",new f({color:o.default(),dim:!0}))]):new S("Press any key to close",new f({color:o.default(),dim:!0,italic:!0}))})});return new A6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.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 d1({decoration:{border:G,color:o.default()},padding:j1.all(1),child:new k1({mainAxisAlignment:"center",children:[V,new I1({height:1}),q,W]})})})}}class $x1 extends S0{build(){return new b0({child:new e({text:new S("",void 0,[new S(`✓ Thread Shared
5081
5081
 
@@ -5185,7 +5185,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
5185
5185
 
5186
5186
  To use Sonnet 4.5, use large mode instead: amp --mode large
5187
5187
  Learn more: https://ampcode.com/news/large-mode
5188
- `),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")wG("experimental.agentMode",Q.mode)}async function vb1(J){try{await QI8(q51.dirname(kb1),{recursive:!0}),await YI8(kb1,J,"utf-8")}catch(Q){P.debug("Failed to save last thread ID",Q)}}async function $I8(){try{return(await xW6(kb1,"utf-8")).trim()}catch(J){return null}}function GI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var SW6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??gZ,description:`Custom settings file path (overrides the default location ${gZ})`},{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 ${Cw})`},{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:J7(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:DO.SMART.key,description:`Set the agent mode (${dY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dY().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],kW6=(J)=>("deprecated"in J)&&J.deprecated===!0,VI8=(J)=>("hidden"in J)&&J.hidden===!0,KI8=(J)=>("default"in J),qI8=(J)=>("default"in J)?J.default:void 0;function WI8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new t6(vZ.unknownCommand(Y),1,V)}}var vW6=null;function Mb5(){return vW6}async function lg(J){let Q=await J.configService.getLatest(),Y=gT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:UE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new DI(J.fileSystem),generateThreadTitle:Ri0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>jQ(J.configService),internalHooks:mT0(Y)}}var W51=Q0.file(ZI8.homedir()),yb1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(W51,".config");async function qJ(J,Q){sU0("0.0.1768218876-g7c0d4d");let Y=gl({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:W51,userConfigDir:yb1}),Z=I0(jQ(Y).pipe(u4((g)=>g!=="pending"))),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (w91(),N91));X(Y);let G=await Y.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:V,dispose:K}=ur0({configService:Y}),q=new Map,W=()=>q.clear(),H=new oF1(Y,J.settings.getWorkspaceRootPath()),z=_T0({configService:Y,filesystem:Q8}),F=iI0({configService:Y,trustStore:H,skillMCPServers:z.skillMCPServers,createOAuthProvider:async(g,d,h)=>{let i=`${g}:${d}`,u=q.get(i);if(u)return P.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:d}),u;P.debug("Creating OAuth provider for server",{serverName:g,serverUrl:d});let V1=(async()=>{let O1=new OB(J.secrets),n=await O1.getClientInfo(g,d),w1=h?.scopes??n?.scopes,M1=x96();P.info("OAuth headless mode check",{useHeadless:M1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:v8.isTTY});let S1;if(M1)S1=J.executeMode?y96():k96(g);let B1=new lF1({storage:O1,serverName:g,serverUrl:d,clientId:h?.clientId??n?.clientId,clientSecret:h?.clientSecret??n?.clientSecret,authUrl:h?.authUrl??n?.authUrl,tokenUrl:h?.tokenUrl??n?.tokenUrl,scopes:w1,headlessAuthHandler:S1});return P.debug("OAuth provider created",{serverName:g,serverUrl:d,hasManualClientId:!!(h?.clientId??n?.clientId),willUseDCR:!(h?.clientId??n?.clientId),scopes:w1,headlessMode:M1,executeMode:J.executeMode}),B1})();return q.set(i,V1),V1}}),U=Rb({configService:Y,filesystem:Q8,spawn:XF}),{initializeToolProviders:D,startToolProviders:B}=await Promise.resolve().then(() => (_W6(),CW6)),N;if(J.executeMode){let g=await D({toolService:V,providers:[F,U],initialTimeout:15000});N=g.registrations;for(let[d,h]of g.initErrors)P.warn(`${d} provider initialization slow or failed:`,h)}else N=B({toolService:V,providers:[F,U]});if(Q.jetbrains)lO("JetBrains");else if(Q.ide&&F86())lO("VS Code");else if(Q.ide&&U86())lO("Neovim");if(J.executeMode)tU0(!0);let w,M=f9.status.pipe(q0((g)=>Boolean(g.connected&&g.authenticated)),q6()).subscribe((g)=>{if(g){if(!w)w=V.registerTool(ya0)}else w?.dispose(),w=void 0}),L;if(!J.executeMode){let g=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new F01(process.cwd(),{alwaysIncludePaths:g},!0)}else L=new class extends F01{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(v8.write(`No API key found. Starting login flow...
5188
+ `),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")wG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")wG("experimental.agentMode",Q.mode)}async function vb1(J){try{await QI8(q51.dirname(kb1),{recursive:!0}),await YI8(kb1,J,"utf-8")}catch(Q){P.debug("Failed to save last thread ID",Q)}}async function $I8(){try{return(await xW6(kb1,"utf-8")).trim()}catch(J){return null}}function GI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var SW6=[{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)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??gZ,description:`Custom settings file path (overrides the default location ${gZ})`},{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 ${Cw})`},{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:J7(),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:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:DO.SMART.key,description:`Set the agent mode (${dY().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:dY().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],kW6=(J)=>("deprecated"in J)&&J.deprecated===!0,VI8=(J)=>("hidden"in J)&&J.hidden===!0,KI8=(J)=>("default"in J),qI8=(J)=>("default"in J)?J.default:void 0;function WI8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new t6(vZ.unknownCommand(Y),1,V)}}var vW6=null;function Mb5(){return vW6}async function lg(J){let Q=await J.configService.getLatest(),Y=gT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:UE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new DI(J.fileSystem),generateThreadTitle:Ri0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>jQ(J.configService),internalHooks:mT0(Y)}}var W51=Q0.file(ZI8.homedir()),yb1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(W51,".config");async function qJ(J,Q){sU0("0.0.1768219292-g8af118");let Y=gl({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:W51,userConfigDir:yb1}),Z=I0(jQ(Y).pipe(u4((g)=>g!=="pending"))),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (w91(),N91));X(Y);let G=await Y.getLatest();P.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:V,dispose:K}=ur0({configService:Y}),q=new Map,W=()=>q.clear(),H=new oF1(Y,J.settings.getWorkspaceRootPath()),z=_T0({configService:Y,filesystem:Q8}),F=iI0({configService:Y,trustStore:H,skillMCPServers:z.skillMCPServers,createOAuthProvider:async(g,d,h)=>{let i=`${g}:${d}`,u=q.get(i);if(u)return P.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:d}),u;P.debug("Creating OAuth provider for server",{serverName:g,serverUrl:d});let V1=(async()=>{let O1=new OB(J.secrets),n=await O1.getClientInfo(g,d),w1=h?.scopes??n?.scopes,M1=x96();P.info("OAuth headless mode check",{useHeadless:M1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:v8.isTTY});let S1;if(M1)S1=J.executeMode?y96():k96(g);let B1=new lF1({storage:O1,serverName:g,serverUrl:d,clientId:h?.clientId??n?.clientId,clientSecret:h?.clientSecret??n?.clientSecret,authUrl:h?.authUrl??n?.authUrl,tokenUrl:h?.tokenUrl??n?.tokenUrl,scopes:w1,headlessAuthHandler:S1});return P.debug("OAuth provider created",{serverName:g,serverUrl:d,hasManualClientId:!!(h?.clientId??n?.clientId),willUseDCR:!(h?.clientId??n?.clientId),scopes:w1,headlessMode:M1,executeMode:J.executeMode}),B1})();return q.set(i,V1),V1}}),U=Rb({configService:Y,filesystem:Q8,spawn:XF}),{initializeToolProviders:D,startToolProviders:B}=await Promise.resolve().then(() => (_W6(),CW6)),N;if(J.executeMode){let g=await D({toolService:V,providers:[F,U],initialTimeout:15000});N=g.registrations;for(let[d,h]of g.initErrors)P.warn(`${d} provider initialization slow or failed:`,h)}else N=B({toolService:V,providers:[F,U]});if(Q.jetbrains)lO("JetBrains");else if(Q.ide&&F86())lO("VS Code");else if(Q.ide&&U86())lO("Neovim");if(J.executeMode)tU0(!0);let w,M=f9.status.pipe(q0((g)=>Boolean(g.connected&&g.authenticated)),q6()).subscribe((g)=>{if(g){if(!w)w=V.registerTool(ya0)}else w?.dispose(),w=void 0}),L;if(!J.executeMode){let g=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new F01(process.cwd(),{alwaysIncludePaths:g},!0)}else L=new class extends F01{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(v8.write(`No API key found. Starting login flow...
5189
5189
  `),!await HI8(J))await _w(),process.exit(1)}let O=await bT0({isDevelopment:!1}),A=await Z,I=R9(A)&&A.features.some((g)=>g.name===PX.LIVE_SYNC&&g.enabled),j=new AE1(O,Y,I),C=new WE1(O,{lazy:!0}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,k=nr0({playNotificationSound:async(g)=>{if(y){ir0(g);let d=o01(),h=bT1();if((!d||h)&&G.settings["notifications.system.enabled"]!==!1){if(g==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(g==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(o01()),threadService:j,configService:Y});P.info("Starting Amp background services");let b=Si0({threadService:j,threadHistoryService:C,configService:Y,isExtensionDevelopment:!1,liveSyncEnabled:I,fileChangeTrackerStorage:new DI(Q8),fileSystem:Q8,getServerStatus:()=>jQ(Y)}),c;f9.status.subscribe((g)=>{c=g});let m=new uq1({workspaceRoots:[Q0.file(process.cwd())],getCurrentFile:()=>{if(!c?.openFile)return;try{return Q0.parse(c.openFile)}catch(g){P.warn("Failed to parse current file URI",{uri:c.openFile,error:g});return}},getOpenFiles:()=>{if(!c?.visibleFiles?.length)return[];let g=c.openFile;return c.visibleFiles.filter((d)=>d!==g).map((d)=>{try{return Q0.parse(d)}catch(h){return P.warn("Failed to parse visible file URI",{uri:d,error:h}),null}}).filter((d)=>d!==null)}}),v=new Uk1,x={codebaseContextService:m,configService:Y,toolService:V,mcpService:F,skillService:z,toolboxService:U,trustStore:H,threadService:j,threadHistoryService:C,threadSyncService:b,threadStorage:O,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,notificationService:k,fileSystem:Q.jetbrains||Q.ide?HE0:Q8,terminal:v,serverStatus:A};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())P.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let g of N.values())g.dispose();await x.mcpService.dispose(),W(),await x.threadService.asyncDispose(),await x.threadSyncService.flushFileChanges(),x.configService.unsubscribe(),K(),x.fuzzyServer.dispose(),x.threadSyncService.dispose(),x.settingsStorage[Symbol.dispose](),M.unsubscribe(),w?.dispose()}}}async function HI8(J){if(!J.executeMode){if(!await Wk1("Would you like to log in to Amp? [(y)es, (n)o]: "))return v8.write(`Login cancelled. Run the command again to retry.
5190
5190
  `),!1}return await bW6(J)}async function bW6(J){let Q=JI8(32).toString("hex"),Y=await qk1(J.ampURL,Q),Z=new AbortController;try{await WH(Y,Z.signal)}catch(G){P.error("Error opening browser",{error:G})}let X=await qk1(J.ampURL,Q,!1);v8.write(`If your browser does not open automatically, visit:
5191
5191
 
@@ -5193,7 +5193,7 @@ ${Z0.blue.bold(X)}
5193
5193
 
5194
5194
  `);try{return await PQ6(J.ampURL,Q,J.secrets,Z),v8.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(G){return P.error("Login failed",{error:G}),H2.write(`
5195
5195
  Login failed: ${G instanceof Error?G.message:String(G)}
5196
- `),!1}}function zI8(){let J=new U$().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)_R(),process.exit(0);let z=H.originalError??H;c06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${dA(new Date("2026-01-12T11:59:31.016Z"))} ago`}catch{}v8.write(`0.0.1768218876-g7c0d4d (released 2026-01-12T11:59:31.016Z${z??""})
5196
+ `),!1}}function zI8(){let J=new U$().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)_R(),process.exit(0);let z=H.originalError??H;c06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${dA(new Date("2026-01-12T12:05:44.068Z"))} ago`}catch{}v8.write(`0.0.1768219292-g8af118 (released 2026-01-12T12:05:44.068Z${z??""})
5197
5197
  `),process.exit(0)}),J.addHelpText("after",q56()),J.configureHelp({formatHelp:W56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await BI8(U)}),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,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await DI8(U,await GC1(F,U.settings))});let Q=async(H,z,F)=>{gl({storage:z.settings,secretStorage:z.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:W51,userConfigDir:yb1});let U={...z,executeMode:!1};await xb1(U,{...H,openThreadSwitcher:!0},F)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await yW6(F,U,z)});if(Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await EI8(F,U,z)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);if(z.pick)H2.write(`${Z0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
5198
5198
  `);if(z.last||H||D.executeMode)await II8(U,D,H,F);else await Q(U,D,F)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await AI8(U,D,H,F)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await X7(F);await yW6(F,U,z)}),Y.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
5199
5199
 
@@ -5205,11 +5205,11 @@ Query syntax:
5205
5205
 
5206
5206
  All matching is case-insensitive. File paths use partial matching.`).option("-n, --limit <number>","Maximum number of threads to return","20").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await jI8(U,D,H,z.limit?parseInt(z.limit,10):20)}),Y.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, unlisted, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, unlisted, workspace, group)").option("--support [message]","Share thread with Amp support for debugging").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await OI8(U,D,H,F,z.support)}),Y.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(H,z,F,U)=>{let D=U.optsWithGlobals(),B=await X7(D);await NI8(D,B,H,z,U)}),Y.command("archive <threadId>").summary("Archive a thread").description("Archive a thread to hide it from the thread switcher and navigation. Use --unarchive to restore.").option("--unarchive","Unarchive the thread instead of archiving").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await wI8(U,D,H,!z.unarchive)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await MI8(U,D,H,F)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await X7(U);await LI8(U,D,H,z,F)}),Ts0(Y,X7,QQ,qJ,H51,hM,W2),zY6(J,async(H,z)=>{let F=await X7(z);QQ(H,z);let U=await qJ(F,z);return{context:F,mcpService:U.mcpService,toolService:U.toolService,toolServices:U.toolService,configService:U.configService,cleanupTerminal:_R,asyncDispose:U.asyncDispose.bind(U)}}),tQ6(J,async(H)=>{let z=H.optsWithGlobals(),F=await X7(z);QQ(H,z);let U=await qJ(F,z);return{settings:F.settings,configService:U.configService,skillService:U.skillService,asyncDispose:U.asyncDispose.bind(U)}}),uQ6(J,async(H)=>{let z=H.optsWithGlobals();return await X7(z)}),yQ6(J,async(H)=>{let z=await X7(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(F)=>{QQ(F,H);let U=await qJ(z,H);return{mcpService:U.mcpService,settings:z.settings,asyncDispose:U.asyncDispose.bind(U)}}}}),process.env.AMP_EXPERIMENTAL_REMOTE==="1")cQ6(J,async(H,z)=>{let F=await X7(z);QQ(H,z);let U=gl({storage:F.settings,secretStorage:F.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:W51,userConfigDir:yb1}),D=await I0(jQ(U).pipe(u4((N)=>N!=="pending"))),B=R9(D)?D.features:[];return{ampURL:F.ampURL,secretStorage:F.secrets,features:B,asyncDispose:async()=>{}}});function X(H,z,F){let D=typeof H.description==="string"?H.description:F===void 0?H.description(!0):H.description(F),B=new hq(z,D),N=qI8(H);if(N)B.default(N);if(B.hidden=VI8(H)||kW6(H),"choices"in H)B.choices([...H.choices]);return B}for(let H of SW6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new hq("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new hq("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new hq("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new hq("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new hq("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_EXPERIMENTAL_REMOTE==="1"){let H=new hq("--headless","Run in headless mode: listen for remote commands without showing TUI").default(!1);J.addOption(H)}if(process.env.AMP_CONNECT==="1"){let H=new hq("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let F=H,U=await X7(F);if(Object.keys(F).forEach((D)=>{let B=SW6.find((N)=>N.name===D);if(B&&kW6(B)&&!KI8(B))H2.write(Z0.yellow(`Warning: '--${D}' flag is deprecated
5207
5207
  `))}),z.args.length>0)WI8(U,z);await xb1(U,F,z)}),C56(J),J}async function K51(J,Q){let{thread:Y,visibility:Z}=Q,X=Y?.id??nY(),G=await lg(J);if(Y)await J.threadStorage.set(X,Y);let V=await b8.getOrCreateForThread(G,X),K=await J.threadStorage.get(X);if(Q.agentMode&&!K?.agentMode&&(!K||K7(K)===0))await V.handle({type:"agent-mode",mode:Q.agentMode});if(Z)await J.threadSyncService.updateThreadMeta(X,R41(Z));let q=J.threadService.observe(X).subscribe(async(W)=>{if(H5(W,"assistant"))await vb1(X),q.unsubscribe()});return await V.resume(),V}async function xb1(J,Q,Y){let Z=E41(Q);if(Z instanceof Error)W2(Z.message);let X,G=null;if(Q.streamJsonInput)X="";else if(typeof Q.execute==="string"){X=Q.execute;let m=(await Fk1()).trimEnd();if(m)G=m}else X=(await Fk1()).trimEnd();if(Q.remote&&!J.executeMode)throw new t6("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new t6("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new t6("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new t6("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new t6("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new t6("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"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&X===""&&!Q.streamJsonInput&&!Q.jmap)throw new t6("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"
5208
- Or pipe via stdin: echo "your message" | amp --execute`);QQ(Y,Q);let V=await qJ(J,Q);vW6=V;let K=await lg(V),{serverStatus:q}=V,W=R9(q)?q.user.email:void 0,H=R9(q)?q.features:[],z=R9(q)?q.workspace:null,F=GI8(W);if((J.executeMode||Q.streamJson)&&A9(Q.mode)&&!F)throw new t6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H.some((x)=>x.name===PX.AMP_CONNECT&&x.enabled))throw new t6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new t6("API key required for headless mode. Please run `amp login` first.",1);await S96({ampURL:J.ampURL,apiKey:v,version:"0.0.1768218876-g7c0d4d",dependencies:V,workerDeps:K}),await V.asyncDispose(),process.exit(0)}if(Q.jmap)throw new t6("JMAP mode is only available in development builds",1);let U=async(m)=>{let v=await xW6(m,"utf-8"),x=JSON.parse(v);if(!W3(x.id))throw new t6(vZ.invalidThreadId);return K51(V,{visibility:Z,agentMode:Q.mode,thread:x})},D=async(m)=>{if(!W3(m))throw new t6(vZ.invalidThreadId);try{let[x,g]=await Promise.all([S4.getThreadLinkInfo({thread:m},{config:V.configService}),S4.getUserInfo({},{config:V.configService})]);if(x.ok&&g.ok){let d=x.result.creatorUserID,h=g.result.id;if(d&&d!==h&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new t6(`Cannot resume thread created by another user.
5208
+ Or pipe via stdin: echo "your message" | amp --execute`);QQ(Y,Q);let V=await qJ(J,Q);vW6=V;let K=await lg(V),{serverStatus:q}=V,W=R9(q)?q.user.email:void 0,H=R9(q)?q.features:[],z=R9(q)?q.workspace:null,F=GI8(W);if((J.executeMode||Q.streamJson)&&A9(Q.mode)&&!F)throw new t6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(!H.some((x)=>x.name===PX.AMP_CONNECT&&x.enabled))throw new t6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new t6("API key required for headless mode. Please run `amp login` first.",1);await S96({ampURL:J.ampURL,apiKey:v,version:"0.0.1768219292-g8af118",dependencies:V,workerDeps:K}),await V.asyncDispose(),process.exit(0)}if(Q.jmap)throw new t6("JMAP mode is only available in development builds",1);let U=async(m)=>{let v=await xW6(m,"utf-8"),x=JSON.parse(v);if(!W3(x.id))throw new t6(vZ.invalidThreadId);return K51(V,{visibility:Z,agentMode:Q.mode,thread:x})},D=async(m)=>{if(!W3(m))throw new t6(vZ.invalidThreadId);try{let[x,g]=await Promise.all([S4.getThreadLinkInfo({thread:m},{config:V.configService}),S4.getUserInfo({},{config:V.configService})]);if(x.ok&&g.ok){let d=x.result.creatorUserID,h=g.result.id;if(d&&d!==h&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new t6(`Cannot resume thread created by another user.
5209
5209
 
5210
5210
  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.`)}}catch(x){if(x instanceof t6)throw x;P.warn("Failed to validate thread ownership in CLI, allowing to open",{error:x})}let v=await V.threadService.get(m)??void 0;return P.info(`[fetchAndStartThread] Loaded thread ${m}, agentMode: ${v?.agentMode??"undefined"}`),K51(V,{visibility:Z,agentMode:v?void 0:Q.mode,thread:v})},B=async()=>{try{if(Q.threadId)return D(Q.threadId);else return K51(V,{visibility:Z,agentMode:Q.mode})}catch(m){if(m instanceof t6)throw m;throw await Vf(m,Q.threadId),Error("handleError should have called process.exit()")}},N=async()=>{return K51(V,{visibility:Z,agentMode:Q.mode})};if(Q.format==="jsonl")H2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
5211
- `),await _w(),process.exit(1);if(J.executeMode&&Q.remote)await pQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)fQ6(V.mcpService,J.settings),await J66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await qD0();let m=rO({jetbrainsOnly:Q.jetbrains});if(m.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(m.length===1){let v=m[0];if(v)f9.selectConfig(v)}else O=!0}let A=K61("0.0.1768218876-g7c0d4d",V.settingsStorage),I=new Se(V.threadStorage),j=T1.of([Q0.file(process.cwd())]),C=pq1(void 0,j),y=new I41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)w.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await(async()=>{try{let m=await S4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(m.ok)return P.info("User free tier status:",m),m.result}catch(m){throw P.error("Failed to fetch free tier status:",m),m}})(),c=await rQ6();P.info("Loaded session state:",c),await Xv1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:w.threadID,threadFuzzyIndexer:I,worker:w,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:S4,ampURL:J.ampURL,startNewThread:N,switchToThread:D,ideClient:f9,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:y,showJetBrainsInstaller:L,showIdePicker:M,showIdePickerHint:O,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:c,freeTierStatus:b,workspace:z??null,features:H,isDogfooding:F,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function X7(J){if(J.interactive)H2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5212
- `);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await n96({...J,workspaceTrust:{current:!0,changes:OC},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await vQ6(J.mcpConfig);X=bQ6(X,K)}let G=q51.dirname(X.getSettingsFilePath());lr0($h,G);let V=await X.get("url","global");if(!V)V=c3;if(!HH(V))P.info("Targeting custom Amp server",{ampURL:V});return X=cU0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:nQ6(await GC1(J,X))}}function FI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function UI8(){let J=FI8(process.argv);if(m06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),XI8(P),P.info("Starting Amp CLI.",{version:"0.0.1768218876-g7c0d4d",buildTimestamp:"2026-01-12T11:59:31.016Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new t6(vZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await zI8().parseAsync(process.argv)}dr0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await UI8().catch(Vf)});async function DI8(J,Q){let Y=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Y)await J.settings.set("url",process.env.AMP_URL,"global"),v8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5211
+ `),await _w(),process.exit(1);if(J.executeMode&&Q.remote)await pQ6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)fQ6(V.mcpService,J.settings),await J66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await qD0();let m=rO({jetbrainsOnly:Q.jetbrains});if(m.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(m.length===1){let v=m[0];if(v)f9.selectConfig(v)}else O=!0}let A=K61("0.0.1768219292-g8af118",V.settingsStorage),I=new Se(V.threadStorage),j=T1.of([Q0.file(process.cwd())]),C=pq1(void 0,j),y=new I41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)w.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await(async()=>{try{let m=await S4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(m.ok)return P.info("User free tier status:",m),m.result}catch(m){throw P.error("Failed to fetch free tier status:",m),m}})(),c=await rQ6();P.info("Loaded session state:",c),await Xv1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:w.threadID,threadFuzzyIndexer:I,worker:w,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:S4,ampURL:J.ampURL,startNewThread:N,switchToThread:D,ideClient:f9,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:y,showJetBrainsInstaller:L,showIdePicker:M,showIdePickerHint:O,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:c,freeTierStatus:b,workspace:z??null,features:H,isDogfooding:F,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function X7(J){if(J.interactive)H2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
5212
+ `);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await n96({...J,workspaceTrust:{current:!0,changes:OC},getHook:process.env.AMP_URL?(K,q)=>{if(K==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let K=await vQ6(J.mcpConfig);X=bQ6(X,K)}let G=q51.dirname(X.getSettingsFilePath());lr0($h,G);let V=await X.get("url","global");if(!V)V=c3;if(!HH(V))P.info("Targeting custom Amp server",{ampURL:V});return X=cU0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:nQ6(await GC1(J,X))}}function FI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function UI8(){let J=FI8(process.argv);if(m06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),XI8(P),P.info("Starting Amp CLI.",{version:"0.0.1768219292-g8af118",buildTimestamp:"2026-01-12T12:05:44.068Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new t6(vZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await zI8().parseAsync(process.argv)}dr0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await UI8().catch(Vf)});async function DI8(J,Q){let Y=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Y)await J.settings.set("url",process.env.AMP_URL,"global"),v8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
5213
5213
  `);else if(!HH(J.ampURL))v8.write(`Logging in to ${new URL(J.ampURL).hostname}
5214
5214
  `);let Z=process.env.AMP_API_KEY;if(Z)v8.write(`API key found in environment variable, storing...
5215
5215
  `),await Q.set("apiKey",Z,J.ampURL),v8.write(`API key successfully stored.
@@ -5223,7 +5223,7 @@ This thread belongs to a different user and cannot be continued for security rea
5223
5223
  `);process.exit(0)}async function NI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=ig(Y);if(!V)ng(Y);let K=V,q=Z.trim();if(q.length===0)W2("Thread name cannot be empty");if(q.length>256)W2("Thread name cannot exceed 256 characters");if(!(await hM(K,G)).messages.length)W2("Cannot rename an empty thread.");let H=await lg(G);await(await b8.getOrCreateForThread(H,K)).handle({type:"title",value:q}),P.info("GOT HERE"),await G.threadSyncService.sync(),P.info("GOT THERE"),v8.write(Z0.green(`✓ Thread ${K} renamed to "${q}"
5224
5224
  `)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;W2(K)}}async function wI8(J,Q,Y,Z){let X=await qJ(Q,J);try{let G=ig(Y);if(!G)ng(Y);let V=await S4.archiveThread({thread:G,archived:Z},{config:X.configService});if(!V.ok)W2(`Failed to ${Z?"archive":"unarchive"} thread: ${V.error.message??V.error.code}`);v8.write(Z0.green(`✓ Thread ${Z?"archived":"unarchived"} successfully
5225
5225
  `)),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose(),W2(`Failed to ${Z?"archive":"unarchive"} thread: ${G instanceof Error?G.message:String(G)}`)}}async function MI8(J,Q,Y,Z){QQ(Z,J);let X=await qJ(Q,J);try{let G=ig(Y);if(!G)ng(Y);let K=await hM(G,X),q=GR(K);v8.write(q+`
5226
- `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;W2(V)}}async function LI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=await H51(Y),K=await hM(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await lg(G),B=K.id;await G.threadStorage.set(B,K);let N=await b8.getOrCreateForThread(D,B);await N.resume();let w=_e.fromWorker(N),M=new Se(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=pq1(void 0,L),A=new I41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=K61("0.0.1768218876-g7c0d4d",G.settingsStorage),j=Rb({configService:G.configService,filesystem:Q8,spawn:XF});await Xv1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:M,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:S4,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:f9,commandRegistry:O,mcpService:G.mcpService,toolboxService:j,mcpTrustHandler:A,showJetBrainsInstaller:!1,updateService:I,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatus:{canUseAmpFree:!0,isDailyGrantEnabled:!1},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await Vf(V,Y)}}async function OI8(J,Q,Y,Z,X){QQ(Z,J);let G=await qJ(Q,J);try{let V=ig(Y);if(!V)ng(Y);let K=V,q=await S4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=E41(J,W);if(!H&&!X)W2("Must specify either --visibility or --support");if(H&&X)W2("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)W2(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,R41(H)),v8.write(Z0.green("✓ ")+`Thread ${K} visibility changed to ${H}.
5226
+ `),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;W2(V)}}async function LI8(J,Q,Y,Z,X){QQ(X,J);let G=await qJ(Q,J);try{let V=await H51(Y),K=await hM(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await lg(G),B=K.id;await G.threadStorage.set(B,K);let N=await b8.getOrCreateForThread(D,B);await N.resume();let w=_e.fromWorker(N),M=new Se(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=pq1(void 0,L),A=new I41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=K61("0.0.1768219292-g8af118",G.settingsStorage),j=Rb({configService:G.configService,filesystem:Q8,spawn:XF});await Xv1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new G01,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:M,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:S4,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:f9,commandRegistry:O,mcpService:G.mcpService,toolboxService:j,mcpTrustHandler:A,showJetBrainsInstaller:!1,updateService:I,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatus:{canUseAmpFree:!0,isDailyGrantEnabled:!1},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await Vf(V,Y)}}async function OI8(J,Q,Y,Z,X){QQ(Z,J);let G=await qJ(Q,J);try{let V=ig(Y);if(!V)ng(Y);let K=V,q=await S4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=E41(J,W);if(!H&&!X)W2("Must specify either --visibility or --support");if(H&&X)W2("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)W2(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,R41(H)),v8.write(Z0.green("✓ ")+`Thread ${K} visibility changed to ${H}.
5227
5227
  `);if(X){await hM(K,G);let z=typeof X==="string"?X:void 0;await uR0(G.threadService,K,G.configService,z),v8.write(Z0.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
5228
5228
  `)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),W2(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function AI8(J,Q,Y,Z){QQ(Z,J);let X=await qJ(Q,J),G=await lg(X);try{let V=await H51(Y),q=(await hM(V,X)).messages.length-1,W=await b8.getOrCreateForThread(G,V),H=await qR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await vb1(H),v8.write(`${H}
5229
5229
  `),await X.asyncDispose(),process.exit(0)}catch(V){H2.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1768218876-g7c0d4d",
3
+ "version": "0.0.1768219292-g8af118",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {