@sourcegraph/amp 0.0.1761923019-g9e7b76 → 0.0.1761926491-gb46bb9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +13 -13
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -6042,11 +6042,11 @@ Actual: ${Y}`)}async function G89(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
6042
6042
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
6043
6043
|
|
|
6044
6044
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6045
|
-
npm install -g @sourcegraph/amp`;G(Error(M))}},error:(F)=>{if(!W)W=!0,G(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,q()}})})}q0();q0();async function l71(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=F89(J,q),z=G<0,U,W;if(K.time){let H=K.time[J],F=K.time[q],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function F89(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}I0();function Yy1(J,Q){let Z=new A8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new cG().scoped("update"),K=X.subscribe({next:(q)=>{Y.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){Y.debug("using fake update status for testing",{status:q}),await W_(500),Z.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let G=await Q.get("updates.mode");if(G==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:G});let z=await l71(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await c71();if(!G)G=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:G});if(G==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await yu(z.latestVersion,U);let W=await QN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(q){Y.debug("check failed",{error:q})}finally{await W_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as aU}from"node:process";function LJ6(J){let Q=new ew().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(X)=>{await Qy1(X.force||!1,X.verbose||!1,"0.0.
|
|
6045
|
+
npm install -g @sourcegraph/amp`;G(Error(M))}},error:(F)=>{if(!W)W=!0,G(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,q()}})})}q0();q0();async function l71(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let G=F89(J,q),z=G<0,U,W;if(K.time){let H=K.time[J],F=K.time[q],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:G,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:q,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function F89(J,Q){let Z=(q)=>{let[G,z]=q.split("-");return{parts:G?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let q=0;q<K;q++){let G=X.parts[q]||0,z=Y.parts[q]||0;if(G<z)return-1;if(G>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}I0();function Yy1(J,Q){let Z=new A8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new cG().scoped("update"),K=X.subscribe({next:(q)=>{Y.debug("emit new state",q)}});try{let q=process.env.AMP_TEST_UPDATE_STATUS;if(q){Y.debug("using fake update status for testing",{status:q}),await W_(500),Z.next(q);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let G=await Q.get("updates.mode");if(G==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:G});let z=await l71(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await c71();if(!G)G=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:G});if(G==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await yu(z.latestVersion,U);let W=await QN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(q){Y.debug("check failed",{error:q})}finally{await W_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as aU}from"node:process";function LJ6(J){let Q=new ew().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(X)=>{await Qy1(X.force||!1,X.verbose||!1,"0.0.1761926491-gb46bb9"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new ew("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("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await B89(X.version)});J.addCommand(Z)}async function B89(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")aU.write(U8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6046
6046
|
|
|
6047
6047
|
`));try{if(!J){aU.write(U8.blue(`Checking for updates...
|
|
6048
|
-
`));let{hasUpdate:Z,latestVersion:X}=await l71("0.0.
|
|
6049
|
-
`));let Y=await QN("0.0.
|
|
6048
|
+
`));let{hasUpdate:Z,latestVersion:X}=await l71("0.0.1761926491-gb46bb9");if(!Z){aU.write(U8.green(`✓ Amp CLI is already up to date.
|
|
6049
|
+
`));let Y=await QN("0.0.1761926491-gb46bb9");if(Y.warning)aU.write(`
|
|
6050
6050
|
`+U8.yellow(Y.warning)+`
|
|
6051
6051
|
`);process.exit(0)}if(!X)aU.write(U8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}aU.write(U8.blue(`Updating to version ${J}...
|
|
6052
6052
|
`)),await yu(J,void 0,(Z)=>{aU.write(U8.dim(`Running: ${Z}
|
|
@@ -6516,10 +6516,10 @@ The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J
|
|
|
6516
6516
|
`;if(Y<Q.length&&Q[Y]===`
|
|
6517
6517
|
`)Y++;this._selectionBase=X,this._selectionExtent=Y,this._cursorPosition=K?X:Y,this._preferredColumn=this._getLayoutColumnFromOffset(this._cursorPosition),this._notifyListeners()}startSelectionAt(J){this._setCursorPosition(J,!1)}extendSelectionTo(J){this._setCursorPosition(J,!0)}_getVerticalPosition(J){let Q=this.cursorPosition,Z=this.getLayoutLines(),X=-1;for(let W=0;W<Z.length;W++){let H=Z[W];if(H&&Q>=H.startOffset&&Q<=H.endOffset){X=W;break}}if(X===-1)return-1;let Y=this._getLayoutColumnFromOffset(Q);if(this._preferredColumn===this._getColumnFromOffset(Q))this._preferredColumn=Y;let K=J<0?Math.max(0,X+J):Math.min(Z.length-1,X+J),q=Z[K];if(!q)return-1;let G=this.graphemes.slice(q.startOffset,q.endOffset).join(""),z=j2(G),U=Math.min(this._preferredColumn,z.length);return q.startOffset+U}_getLineStartPosition(){let J=this.graphemes,Q=0;for(let Z=this.cursorPosition-1;Z>=0;Z--)if(J[Z]===`
|
|
6518
6518
|
`){Q=Z+1;break}return Q}_getLineEndPosition(){let J=this.graphemes,Q=J.length;for(let Z=this.cursorPosition;Z<J.length;Z++)if(J[Z]===`
|
|
6519
|
-
`){Q=Z;break}return Q}_getHorizontalPosition(J){return Math.max(0,Math.min(this.graphemes.length,this._cursorPosition+J))}}class sF extends l0{controller;placeholder;style;onChanged;onSubmitted;onOpenInEditor;maxWidth;maxLines;minLines;expands;wrap;enabled;focusNode;autofocus;submitKey;prompts;clipboard;ensureVisible;onCopy;copyOnSelectionEnabled;_ownsController;constructor({key:J,controller:Q,placeholder:Z="",style:X={},onChanged:Y,onSubmitted:K,onOpenInEditor:q,maxWidth:G,maxLines:z=1,minLines:U=1,expands:W=!1,wrap:H=!1,enabled:F=!0,focusNode:B,autofocus:M=!1,submitKey:V,prompts:N=[],clipboard:L,ensureVisible:A=!1,onCopy:w,copyOnSelectionEnabled:R=!1}){super(J?{key:J}:void 0);if(z!==null&&U>z)throw Error("minLines must be <= maxLines");this._ownsController=!Q,this.controller=Q||new sK,this.placeholder=Z,this.style={backgroundColor:E1.default(),textColor:E1.default(),border:m8.all(new _8(E1.default(),1,"rounded")),padding:V0.symmetric(1,0),cursorColor:E1.default(),placeholderColor:E1.index(8),...X},this.onChanged=Y,this.onSubmitted=K,this.onOpenInEditor=q,this.maxWidth=G,this.maxLines=z,this.minLines=U,this.expands=W,this.wrap=H,this.enabled=F,this.focusNode=B,this.autofocus=M,this.prompts=N,this.clipboard=L??bG,this.ensureVisible=A,this.onCopy=w,this.copyOnSelectionEnabled=R,this.submitKey=V??{character:"Enter",modifiers:z===1?{}:{ctrl:!0}}}get isMultiline(){return this.maxLines===null||this.maxLines>1||this.minLines>1}createState(){return new CC}}class CC extends c0{static _allInstances=new Set;static AUTO_COPY_DELAY_MS=500;static AUTO_COPY_HIGHLIGHT_DURATION_MS=300;_hScrollOffset=0;_vScrollOffset=0;_textChangeListener;_focusChangeListener;_internalFocusNode=null;_lastLayoutLineCount=0;_isDragging=!1;_didMouseMove=!1;_globalReleaseCallback;_copyHighlightActive=!1;_copyHighlightTimer;_autoCopyTimer;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}initState(){if(super.initState(),CC._allInstances.add(this),!this.widget.focusNode)this._internalFocusNode=new i8({debugLabel:`TextField(${this.widget.key?.value||"unlabeled"})`});this._textChangeListener=()=>{if(this._updateScrollOffset(this.context),this.setState(()=>{}),this.widget.isMultiline){let Q=this.widget.controller.getLayoutLines().length;if(Q!==this._lastLayoutLineCount){this._lastLayoutLineCount=Q;let Z=this.context.element;if(Z&&Z.renderObject&&"markNeedsLayout"in Z.renderObject){Z.renderObject.markNeedsLayout();let X=0,Y=Z.parent;while(Y&&Y.renderObject){if("markNeedsLayout"in Y.renderObject)Y.renderObject.markNeedsLayout(),X++;Y=Y.parent}}}e9.instance.addPostFrameCallback(()=>{this._ensureCursorVisibleInAncestorScroll()})}if(this.widget.onChanged)this.widget.onChanged(this.widget.controller.text)},this.widget.controller.addListener(this._textChangeListener),this._focusChangeListener=(J)=>{if(J.hasFocus)this._updateScrollOffset(this.context),this.setState(()=>{});else this._endDrag(),this.setState(()=>{})},this.effectiveFocusNode.addListener(this._focusChangeListener)}didUpdateWidget(J){super.didUpdateWidget(J)}dispose(){try{if(CC._allInstances.delete(this),this._releaseGlobalMouse(),this._internalFocusNode){try{this._internalFocusNode.dispose()}catch{}this._internalFocusNode=null}if(this._textChangeListener)try{this.widget.controller.removeListener(this._textChangeListener)}catch{}if(this._focusChangeListener)try{this.effectiveFocusNode.removeListener(this._focusChangeListener)}catch{}if(this._clearCopyHighlight(),this._clearAutoCopyTimer(),this.widget._ownsController)try{this.widget.controller.dispose()}catch{}super.dispose()}catch{}}_captureGlobalMouse(){this._globalReleaseCallback=()=>{if(this._isDragging)this._endDrag()},I5.instance.addGlobalReleaseCallback(this._globalReleaseCallback)}_releaseGlobalMouse(){if(this._globalReleaseCallback)I5.instance.removeGlobalReleaseCallback(this._globalReleaseCallback),this._globalReleaseCallback=void 0}async _endDrag(){let J=this._didMouseMove;if(this._isDragging=!1,this._didMouseMove=!1,this._releaseGlobalMouse(),J)this._scheduleAutoCopy()}async _autoCopySelection(){if(!this.widget.copyOnSelectionEnabled)return;let J=this.widget.controller.selectedText;if(J&&J.length>0){try{await this.widget.clipboard.writeText(J)}catch(Q){u.debug("Failed to write selection to clipboard:",Q)}this._startCopyHighlight(),this.widget.onCopy?.(J)}}_scheduleAutoCopy(){this._clearAutoCopyTimer(),this._autoCopyTimer=setTimeout(()=>{this._autoCopySelection(),this._autoCopyTimer=void 0},CC.AUTO_COPY_DELAY_MS)}_startCopyHighlight(){this._clearHighlightTimer(),this._copyHighlightActive=!0,this.setState(()=>{}),this._copyHighlightTimer=setTimeout(()=>{this._copyHighlightActive=!1,this.setState(()=>{}),this._copyHighlightTimer=void 0},CC.AUTO_COPY_HIGHLIGHT_DURATION_MS)}_clearCopyHighlight(){this._clearHighlightTimer(),this._copyHighlightActive=!1}_clearHighlightTimer(){if(this._copyHighlightTimer)clearTimeout(this._copyHighlightTimer),this._copyHighlightTimer=void 0}_clearAutoCopyTimer(){if(this._autoCopyTimer)clearTimeout(this._autoCopyTimer),this._autoCopyTimer=void 0}_updateScrollOffset(J){let Q=this.widget.controller,Z=this.widget.isMultiline;if(J){let Y=f8.of(J).supportsEmojiWidth,K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=J.findRenderObject()?.size?.width||120,W=(this.widget.maxWidth||z)-G*2-q.left-q.right;Q.updateLayoutConfig(Math.max(1,W),this.widget.wrap?"word":"none",Y)}if(Z)this._updateVerticalScrollOffset(J);else this._updateHorizontalScrollOffset(J)}_ensureCursorVisibleInAncestorScroll(){if(!this.widget.ensureVisible)return;if(!this.widget.isMultiline||!this.widget.expands)return;let J=this.widget.controller,Q=J.getLayoutLines(),Z=J.cursorPosition,X=0;for(let W=0;W<Q.length;W++){let H=Q[W];if(Z>=H.startOffset&&Z<=H.endOffset){X=W;break}}let Y=1,K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=q.top+G+X*Y,U=z+Y;R51(this.context,{top:z,bottom:U},{padding:1})}_updateHorizontalScrollOffset(J){let Q=this.widget.controller,Z=Q.cursorPosition,X=Q.graphemes,Y=!1;if(J)Y=f8.of(J).supportsEmojiWidth;let K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=J?.findRenderObject()?.size?.width||120,W=(this.widget.maxWidth||z)-G*2-q.left-q.right;if(W<=0)return;let H=0;for(let F=this._hScrollOffset;F<Z&&F<X.length;F++)H+=c4(X[F],Y);if(H>=W){let F=this._hScrollOffset;while(H>=W&&F<Z){let B=c4(X[F],Y);H-=B,F++}this._hScrollOffset=F}else if(Z<this._hScrollOffset)this._hScrollOffset=Z;this._hScrollOffset=Math.max(0,Math.min(this._hScrollOffset,Math.max(0,X.length-1)))}_updateVerticalScrollOffset(J){let Q=this.widget.controller,Z=Q.cursorPosition,X=Q.getLayoutLines(),Y=-1;for(let B=0;B<X.length;B++){let M=X[B];if(Z>=M.startOffset&&Z<=M.endOffset){Y=B;break}}if(Y===-1)return;let K=X.length,q=this.widget.minLines,G=this.widget.maxLines===null?Number.MAX_SAFE_INTEGER:this.widget.maxLines,z;if(this.widget.expands)z=K;else z=Math.max(q,Math.min(K,G));let U=z;if(J){let B=J.findRenderObject();if(B?.size){let M=this.widget.style,V=M.padding||V0.all(0),N=M.border?1:0;U=B.size.height-V.top-V.bottom-N*2}}if(U=Math.max(1,Math.floor(U)),K<=U){if(this._vScrollOffset!==0)this._vScrollOffset=0,Q.setScrollOffset(0);return}let W=Q.getScrollOffset(),H=W;if(Y<W)H=Y;else if(Y>=W+U)H=Y-U+1;let F=Math.max(0,K-U);if(H=Math.floor(Math.max(0,Math.min(H,F))),H!==this._vScrollOffset)this._vScrollOffset=H,Q.setScrollOffset(H)}build(J){let Z=Y8.maybeOf(J)?.colorScheme.border??E1.default(),X={...this.widget.style,border:this.widget.style.border===null?null:this.widget.style.border??m8.all(new _8(Z,1,"rounded"))},Y=(V)=>{let N=this.widget.controller;if(!this.widget.enabled)return"ignored";let L=this.widget.submitKey,A=L.character,w=L.modifiers?.shift??!1;if(w&&L.character.length===1&&L.character.toLowerCase()===L.character)A=L.character.toUpperCase();let R=V.key===A&&V.shiftKey===w&&V.ctrlKey===(L.modifiers?.ctrl??!1)&&V.altKey===(L.modifiers?.alt??!1)&&V.metaKey===(L.modifiers?.meta??!1);if(R&&V.key==="Enter"){let{graphemes:O,cursorPosition:$}=N;if($>0&&O[$-1]==="\\")return N.deleteText(1),N.insertText(`
|
|
6519
|
+
`){Q=Z;break}return Q}_getHorizontalPosition(J){return Math.max(0,Math.min(this.graphemes.length,this._cursorPosition+J))}}class sF extends l0{controller;placeholder;style;onChanged;onSubmitted;onOpenInEditor;maxWidth;maxLines;minLines;expands;wrap;enabled;focusNode;autofocus;submitKey;prompts;clipboard;ensureVisible;onCopy;copyOnSelectionEnabled;onBackspaceWhenEmpty;_ownsController;constructor({key:J,controller:Q,placeholder:Z="",style:X={},onChanged:Y,onSubmitted:K,onOpenInEditor:q,maxWidth:G,maxLines:z=1,minLines:U=1,expands:W=!1,wrap:H=!1,enabled:F=!0,focusNode:B,autofocus:M=!1,submitKey:V,prompts:N=[],clipboard:L,ensureVisible:A=!1,onCopy:w,copyOnSelectionEnabled:R=!1,onBackspaceWhenEmpty:O}){super(J?{key:J}:void 0);if(z!==null&&U>z)throw Error("minLines must be <= maxLines");this._ownsController=!Q,this.controller=Q||new sK,this.placeholder=Z,this.style={backgroundColor:E1.default(),textColor:E1.default(),border:m8.all(new _8(E1.default(),1,"rounded")),padding:V0.symmetric(1,0),cursorColor:E1.default(),placeholderColor:E1.index(8),...X},this.onChanged=Y,this.onSubmitted=K,this.onOpenInEditor=q,this.maxWidth=G,this.maxLines=z,this.minLines=U,this.expands=W,this.wrap=H,this.enabled=F,this.focusNode=B,this.autofocus=M,this.prompts=N,this.clipboard=L??bG,this.ensureVisible=A,this.onCopy=w,this.copyOnSelectionEnabled=R,this.onBackspaceWhenEmpty=O,this.submitKey=V??{character:"Enter",modifiers:z===1?{}:{ctrl:!0}}}get isMultiline(){return this.maxLines===null||this.maxLines>1||this.minLines>1}createState(){return new CC}}class CC extends c0{static _allInstances=new Set;static AUTO_COPY_DELAY_MS=500;static AUTO_COPY_HIGHLIGHT_DURATION_MS=300;_hScrollOffset=0;_vScrollOffset=0;_textChangeListener;_focusChangeListener;_internalFocusNode=null;_lastLayoutLineCount=0;_isDragging=!1;_didMouseMove=!1;_globalReleaseCallback;_copyHighlightActive=!1;_copyHighlightTimer;_autoCopyTimer;get effectiveFocusNode(){return this.widget.focusNode??this._internalFocusNode}initState(){if(super.initState(),CC._allInstances.add(this),!this.widget.focusNode)this._internalFocusNode=new i8({debugLabel:`TextField(${this.widget.key?.value||"unlabeled"})`});this._textChangeListener=()=>{if(this._updateScrollOffset(this.context),this.setState(()=>{}),this.widget.isMultiline){let Q=this.widget.controller.getLayoutLines().length;if(Q!==this._lastLayoutLineCount){this._lastLayoutLineCount=Q;let Z=this.context.element;if(Z&&Z.renderObject&&"markNeedsLayout"in Z.renderObject){Z.renderObject.markNeedsLayout();let X=0,Y=Z.parent;while(Y&&Y.renderObject){if("markNeedsLayout"in Y.renderObject)Y.renderObject.markNeedsLayout(),X++;Y=Y.parent}}}e9.instance.addPostFrameCallback(()=>{this._ensureCursorVisibleInAncestorScroll()})}if(this.widget.onChanged)this.widget.onChanged(this.widget.controller.text)},this.widget.controller.addListener(this._textChangeListener),this._focusChangeListener=(J)=>{if(J.hasFocus)this._updateScrollOffset(this.context),this.setState(()=>{});else this._endDrag(),this.setState(()=>{})},this.effectiveFocusNode.addListener(this._focusChangeListener)}didUpdateWidget(J){super.didUpdateWidget(J)}dispose(){try{if(CC._allInstances.delete(this),this._releaseGlobalMouse(),this._internalFocusNode){try{this._internalFocusNode.dispose()}catch{}this._internalFocusNode=null}if(this._textChangeListener)try{this.widget.controller.removeListener(this._textChangeListener)}catch{}if(this._focusChangeListener)try{this.effectiveFocusNode.removeListener(this._focusChangeListener)}catch{}if(this._clearCopyHighlight(),this._clearAutoCopyTimer(),this.widget._ownsController)try{this.widget.controller.dispose()}catch{}super.dispose()}catch{}}_captureGlobalMouse(){this._globalReleaseCallback=()=>{if(this._isDragging)this._endDrag()},I5.instance.addGlobalReleaseCallback(this._globalReleaseCallback)}_releaseGlobalMouse(){if(this._globalReleaseCallback)I5.instance.removeGlobalReleaseCallback(this._globalReleaseCallback),this._globalReleaseCallback=void 0}async _endDrag(){let J=this._didMouseMove;if(this._isDragging=!1,this._didMouseMove=!1,this._releaseGlobalMouse(),J)this._scheduleAutoCopy()}async _autoCopySelection(){if(!this.widget.copyOnSelectionEnabled)return;let J=this.widget.controller.selectedText;if(J&&J.length>0){try{await this.widget.clipboard.writeText(J)}catch(Q){u.debug("Failed to write selection to clipboard:",Q)}this._startCopyHighlight(),this.widget.onCopy?.(J)}}_scheduleAutoCopy(){this._clearAutoCopyTimer(),this._autoCopyTimer=setTimeout(()=>{this._autoCopySelection(),this._autoCopyTimer=void 0},CC.AUTO_COPY_DELAY_MS)}_startCopyHighlight(){this._clearHighlightTimer(),this._copyHighlightActive=!0,this.setState(()=>{}),this._copyHighlightTimer=setTimeout(()=>{this._copyHighlightActive=!1,this.setState(()=>{}),this._copyHighlightTimer=void 0},CC.AUTO_COPY_HIGHLIGHT_DURATION_MS)}_clearCopyHighlight(){this._clearHighlightTimer(),this._copyHighlightActive=!1}_clearHighlightTimer(){if(this._copyHighlightTimer)clearTimeout(this._copyHighlightTimer),this._copyHighlightTimer=void 0}_clearAutoCopyTimer(){if(this._autoCopyTimer)clearTimeout(this._autoCopyTimer),this._autoCopyTimer=void 0}_updateScrollOffset(J){let Q=this.widget.controller,Z=this.widget.isMultiline;if(J){let Y=f8.of(J).supportsEmojiWidth,K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=J.findRenderObject()?.size?.width||120,W=(this.widget.maxWidth||z)-G*2-q.left-q.right;Q.updateLayoutConfig(Math.max(1,W),this.widget.wrap?"word":"none",Y)}if(Z)this._updateVerticalScrollOffset(J);else this._updateHorizontalScrollOffset(J)}_ensureCursorVisibleInAncestorScroll(){if(!this.widget.ensureVisible)return;if(!this.widget.isMultiline||!this.widget.expands)return;let J=this.widget.controller,Q=J.getLayoutLines(),Z=J.cursorPosition,X=0;for(let W=0;W<Q.length;W++){let H=Q[W];if(Z>=H.startOffset&&Z<=H.endOffset){X=W;break}}let Y=1,K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=q.top+G+X*Y,U=z+Y;R51(this.context,{top:z,bottom:U},{padding:1})}_updateHorizontalScrollOffset(J){let Q=this.widget.controller,Z=Q.cursorPosition,X=Q.graphemes,Y=!1;if(J)Y=f8.of(J).supportsEmojiWidth;let K=this.widget.style,q=K.padding||V0.all(0),G=K.border?1:0,z=J?.findRenderObject()?.size?.width||120,W=(this.widget.maxWidth||z)-G*2-q.left-q.right;if(W<=0)return;let H=0;for(let F=this._hScrollOffset;F<Z&&F<X.length;F++)H+=c4(X[F],Y);if(H>=W){let F=this._hScrollOffset;while(H>=W&&F<Z){let B=c4(X[F],Y);H-=B,F++}this._hScrollOffset=F}else if(Z<this._hScrollOffset)this._hScrollOffset=Z;this._hScrollOffset=Math.max(0,Math.min(this._hScrollOffset,Math.max(0,X.length-1)))}_updateVerticalScrollOffset(J){let Q=this.widget.controller,Z=Q.cursorPosition,X=Q.getLayoutLines(),Y=-1;for(let B=0;B<X.length;B++){let M=X[B];if(Z>=M.startOffset&&Z<=M.endOffset){Y=B;break}}if(Y===-1)return;let K=X.length,q=this.widget.minLines,G=this.widget.maxLines===null?Number.MAX_SAFE_INTEGER:this.widget.maxLines,z;if(this.widget.expands)z=K;else z=Math.max(q,Math.min(K,G));let U=z;if(J){let B=J.findRenderObject();if(B?.size){let M=this.widget.style,V=M.padding||V0.all(0),N=M.border?1:0;U=B.size.height-V.top-V.bottom-N*2}}if(U=Math.max(1,Math.floor(U)),K<=U){if(this._vScrollOffset!==0)this._vScrollOffset=0,Q.setScrollOffset(0);return}let W=Q.getScrollOffset(),H=W;if(Y<W)H=Y;else if(Y>=W+U)H=Y-U+1;let F=Math.max(0,K-U);if(H=Math.floor(Math.max(0,Math.min(H,F))),H!==this._vScrollOffset)this._vScrollOffset=H,Q.setScrollOffset(H)}build(J){let Z=Y8.maybeOf(J)?.colorScheme.border??E1.default(),X={...this.widget.style,border:this.widget.style.border===null?null:this.widget.style.border??m8.all(new _8(Z,1,"rounded"))},Y=(V)=>{let N=this.widget.controller;if(!this.widget.enabled)return"ignored";let L=this.widget.submitKey,A=L.character,w=L.modifiers?.shift??!1;if(w&&L.character.length===1&&L.character.toLowerCase()===L.character)A=L.character.toUpperCase();let R=V.key===A&&V.shiftKey===w&&V.ctrlKey===(L.modifiers?.ctrl??!1)&&V.altKey===(L.modifiers?.alt??!1)&&V.metaKey===(L.modifiers?.meta??!1);if(R&&V.key==="Enter"){let{graphemes:O,cursorPosition:$}=N;if($>0&&O[$-1]==="\\")return N.deleteText(1),N.insertText(`
|
|
6520
6520
|
`),"handled"}if(R){if(this.widget.onSubmitted)this.widget.onSubmitted(N.text);return"handled"}if(V.key==="Enter"){if(V.shiftKey&&this.widget.isMultiline)return N.insertText(`
|
|
6521
6521
|
`),"handled";if(V.altKey&&this.widget.isMultiline)return N.insertText(`
|
|
6522
|
-
`),"handled";return"ignored"}else if(V.key==="Backspace"){try{if(V.altKey)N.deleteWordLeft();else N.deleteSelectedOrText(1)}catch(O){throw u.error("TextField: Error in deleteText:",O),O}return"handled"}else if(V.key==="Delete"){if(N.hasSelection)N.deleteSelectedText();else N.deleteForward(1);return"handled"}else if(V.key==="Tab")return"ignored";else if(V.key==="Escape")return"ignored";if(V.ctrlKey){if(V.key==="g"){if(this.widget.onOpenInEditor)this.widget.onOpenInEditor(N.text);return"handled"}if(V.key==="a"){if(this.widget.isMultiline)N.moveCursorToLineStart(V.shiftKey);else N.moveCursorToStart(V.shiftKey);return"handled"}else if(V.key==="e"){if(this.widget.isMultiline)N.moveCursorToLineEnd(V.shiftKey);else N.moveCursorToEnd(V.shiftKey);return"handled"}else if(V.key==="u")return N.deleteToLineStart(),"handled";else if(V.key==="k")return N.deleteToLineEnd(),"handled";else if(V.key==="f")return N.moveCursorRight(1,V.shiftKey),"handled";else if(V.key==="b")return N.moveCursorLeft(1,V.shiftKey),"handled";else if(V.key==="n"){let{line:O,column:$}=N.cursorTextPosition,j=N.getLineCount();if(O===j-1){let I=N.getLine(O),T=j2(I).length;if($===T)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let I=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="p"){let{line:O,column:$}=N.cursorTextPosition;if(O===0&&$===0)return"ignored";else if(O===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let j=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===j?"ignored":"handled"}}else if(V.key==="d")return N.deleteForward(1),"handled";else if(V.key==="h")return N.deleteText(1),"handled";else if(V.key==="ArrowLeft")return N.moveCursorWordBoundary(-1,V.shiftKey),"handled";else if(V.key==="ArrowRight")return N.moveCursorWordBoundary(1,V.shiftKey),"handled";else if(V.key==="w")return N.deleteWordLeft(),"handled";else if(V.key==="y")return N.yankText(),"handled"}else if(V.altKey||V.metaKey){if(V.metaKey&&V.key==="ArrowLeft"){if(this.widget.isMultiline)N.moveCursorToLineStart(V.shiftKey);else N.moveCursorToStart(V.shiftKey);return"handled"}else if(V.metaKey&&V.key==="ArrowRight"){if(this.widget.isMultiline)N.moveCursorToLineEnd(V.shiftKey);else N.moveCursorToEnd(V.shiftKey);return"handled"}else if(V.key==="ArrowUp"){let{line:j,column:E}=N.cursorTextPosition;if(j===0&&E===0)return"ignored";else if(j===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let I=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="ArrowDown"){let{line:j,column:E}=N.cursorTextPosition,I=N.getLineCount();if(j===I-1){let S=N.getLine(j),x=j2(S).length;if(E===x)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let S=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===S?"ignored":"handled"}}let O=V.key==="ArrowLeft"||V.key.toLowerCase()==="b",$=V.key==="ArrowRight"||V.key.toLowerCase()==="f";if(O||$)return N.moveCursorWordBoundary(O?-1:1,V.shiftKey),"handled"}else if(V.key==="ArrowLeft")return N.moveCursorLeft(1,V.shiftKey),"handled";else if(V.key==="ArrowRight")return N.moveCursorRight(1,V.shiftKey),"handled";else if(V.key==="ArrowUp"){let{line:O,column:$}=N.cursorTextPosition;if(O===0&&$===0)return"ignored";else if(O===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let j=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===j?"ignored":"handled"}}else if(V.key==="ArrowDown"){let{line:O,column:$}=N.cursorTextPosition,j=N.getLineCount();if(O===j-1){let I=N.getLine(O),T=j2(I).length;if($===T)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let I=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="Home"||V.key==="End")return"ignored";else if(V.key==="PageUp"||V.key==="PageDown")return"ignored";if(V.key&&!wZ6(V))return N.insertText(V.key),"handled";return"ignored"},K=(V)=>{if(!this.widget.enabled)return"ignored";let N=this.widget.controller,L=this.widget.isMultiline,A=V.text;if(!L)A=A.replace(/[\r\n]+/g," ");return N.insertText(A),"handled"},q=(V)=>{if(!this.widget.enabled||!this.widget.isMultiline)return;let N=this.widget.controller,L=N.getLayoutLines();if(L.length<=1)return;let A=N.getScrollOffset(),w=3;if(V.direction==="up")A=Math.max(0,A-w);else{let R=this.widget.style,O=R.padding||V0.all(0),$=R.border?1:0,E=(J.findRenderObject()?.size?.height||10)-$*2-O.top-O.bottom,I=Math.max(0,L.length-E);A=Math.min(I,A+w)}N.setScrollOffset(A),this.setState(()=>{})},G=(V)=>{if(!this.widget.enabled)return;if(V.button==="middle"){this.widget.clipboard.readPrimarySelection().then((N)=>{if(N)K({type:"paste",text:N})}).catch((N)=>{u.debug("Failed to read primary selection for middle-click paste:",N)});return}if(V.button==="left"){this._clearCopyHighlight();let N=W(V.localPosition.x,V.localPosition.y);if(V.clickCount===3)this.widget.controller.selectLineAt(N),this._scheduleAutoCopy();else if(V.clickCount===2)this.widget.controller.selectWordAt(N),this._scheduleAutoCopy();else if(V.clickCount===1)this._clearAutoCopyTimer(),this.widget.controller.startSelectionAt(N),this._isDragging=!0,this._didMouseMove=!1,this.effectiveFocusNode.requestFocus(),this._captureGlobalMouse()}},z=(V)=>{if(!this.widget.enabled||!this._isDragging)return;if(V.button!=="left")return;this._didMouseMove=!0;let N=W(V.localPosition.x,V.localPosition.y);this.widget.controller.extendSelectionTo(N)},U=(V)=>{if(V.button==="left")this._endDrag()},W=(V,N)=>{let A=f8.of(J).supportsEmojiWidth,w=this.widget.style.padding||V0.all(0),R=this.widget.style.border?1:0,O=V-R-w.left,$=N-R-w.top,j=this.widget.controller.text,E=this.widget.prompts.find((x)=>x.match(j)),I=this.widget.controller.graphemes,T=this.widget.isMultiline,S=0;if(T){let x=this.widget.controller.getLayoutLines(),h=Math.max(0,Math.min(Math.floor($)+this.widget.controller.getScrollOffset(),x.length-1));if(E&&h===0){O-=E.spacing??0;let v=LY(E.display,A),_=E.spacing??0;if(O<v+_)return v}if(h<x.length){let v=x[h],_=I.slice(v.startOffset,v.endOffset),b=0,g=0;for(let k=0;k<_.length;k++){let f=c4(_[k],A),y=b+f;if(O<=y){if((O-b)/f<0.6)g=k;else g=k+1;break}b=y,g=k+1}S=v.startOffset+g}}else{if(E){O-=E.spacing??0;let h=LY(E.display,A),v=E.spacing??0;if(O<h+v)return h}let x=0;for(let h=0;h<I.length;h++){let v=c4(I[h],A),_=x+v;if(O<=_){if((O-x)/v<0.6)S=h;else S=h+1;break}x=_,S=h+1}}return S},F=f8.of(J).supportsEmojiWidth,B=new RZ6({controller:this.widget.controller,style:X,placeholder:this.widget.placeholder,hScrollOffset:this._hScrollOffset,vScrollOffset:this._vScrollOffset,maxWidth:this.widget.maxWidth,maxLines:this.widget.maxLines,minLines:this.widget.minLines,expands:this.widget.expands,wrap:this.widget.wrap,enabled:this.widget.enabled,emojiSupported:F,prompts:this.widget.prompts,copyHighlightActive:this._copyHighlightActive}),M=new b9({onClick:G,onDrag:z,onRelease:U,onScroll:q,cursor:this.widget.enabled?z7.TEXT:z7.DEFAULT,child:B});return new t8({key:this.widget.key??void 0,autofocus:this.widget.autofocus,focusNode:this.effectiveFocusNode,onKey:Y,onPaste:K,child:M})}}class RZ6 extends aF{controller;style;placeholder;hScrollOffset;vScrollOffset;maxWidth;maxLines;minLines;expands;wrap;enabled;emojiSupported;prompts;copyHighlightActive;constructor({controller:J,style:Q,placeholder:Z,hScrollOffset:X,vScrollOffset:Y,maxWidth:K,maxLines:q,minLines:G,expands:z,wrap:U,enabled:W,emojiSupported:H,prompts:F,copyHighlightActive:B=!1}){super({});this.controller=J,this.style=Q,this.placeholder=Z,this.hScrollOffset=X,this.vScrollOffset=Y,this.maxWidth=K,this.maxLines=q,this.minLines=G,this.expands=z,this.wrap=U,this.enabled=W,this.emojiSupported=H,this.prompts=F,this.copyHighlightActive=B}createRenderObject(){return new OZ6(this.controller,this.style,this.placeholder,this.hScrollOffset,this.vScrollOffset,this.maxWidth,this.maxLines,this.minLines,this.expands,this.wrap,this.enabled,this.emojiSupported,this.prompts,this.copyHighlightActive)}updateRenderObject(J){J.updateProperties(this.controller,this.style,this.placeholder,this.hScrollOffset,this.vScrollOffset,this.maxWidth,this.maxLines,this.minLines,this.expands,this.wrap,this.enabled,this.emojiSupported,this.prompts,this.copyHighlightActive)}}class OZ6 extends J8{_controller;_style;_placeholder;_hScrollOffset;_vScrollOffset;_maxWidth;_maxLines;_minLines;_expands;_wrap;_enabled;_emojiSupported;_prompts;_copyHighlightActive;_contentChanged=!1;constructor(J,Q,Z,X,Y,K,q,G,z,U,W=!0,H=!1,F=[],B=!1){super();this._controller=J,this._style=Q,this._placeholder=Z,this._hScrollOffset=X,this._vScrollOffset=Y,this._maxWidth=K,this._maxLines=q,this._minLines=G,this._expands=z,this._wrap=U,this._enabled=W,this._emojiSupported=H,this._prompts=F,this._copyHighlightActive=B}get isMultiline(){return this._maxLines===null||this._maxLines>1||this._minLines>1}updateProperties(J,Q,Z,X,Y,K,q,G,z,U,W=!0,H=!1,F=[],B=!1){this._controller=J,this._style=Q,this._placeholder=Z,this._hScrollOffset=X,this._vScrollOffset=Y,this._maxWidth=K,this._maxLines=q,this._minLines=G,this._expands=z,this._wrap=U,this._enabled=W,this._emojiSupported=H,this._prompts=F,this._copyHighlightActive=B,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=Q.left+Q.right+X*2+1,K=Q.top+Q.bottom+X*2+1,q=this._maxWidth||J.maxWidth,G=Math.max(Y,Number.isFinite(q)?Math.min(q,J.maxWidth):Y),z;if(this._expands)if(J.minHeight===J.maxHeight)z=J.maxHeight;else{let H=this.getMinIntrinsicHeight(G);z=Math.min(Math.max(H,J.minHeight),J.maxHeight)}else{let H=this.getMinIntrinsicHeight(G);if(z=Math.max(K,H),z>J.maxHeight)z=J.maxHeight}this.setSize(G,z);let U=this.getPromptPrefixWidth(),W=G-X*2-Q.left-Q.right-U;if(this._controller.updateLayoutConfig(Math.max(1,W),this._wrap?"word":"none",this._emojiSupported),this.isMultiline&&this._expands)this._updateScrollOffsetFromLayout(J,z)}getPromptPrefixWidth(){let J=this._controller.text;return this._prompts.find((Q)=>Q.match(J))?.spacing??0}getMinIntrinsicWidth(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=this._maxWidth||20;return Math.max(Q.left+Q.right+X*2+K+Y,Q.left+Q.right+X*2+1+Y)}getMaxIntrinsicWidth(J){let Q=this.getPromptPrefixWidth();if(this._maxWidth)return this._maxWidth+Q;return Number.POSITIVE_INFINITY}getMinIntrinsicHeight(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=J-X*2-Q.left-Q.right-Y,q=this._wrap?"word":"none",z=this._controller.calculateLayoutLines(Math.max(1,K),q,!1).length,U=this._minLines,W=this._maxLines===null?Number.MAX_SAFE_INTEGER:this._maxLines,H=Math.max(U,Math.min(z,W));return Q.top+Q.bottom+X*2+H}getMaxIntrinsicHeight(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=J-X*2-Q.left-Q.right-Y,q=this._wrap?"word":"none",z=this._controller.calculateLayoutLines(Math.max(1,K),q,!1).length,U=this._minLines,W=this._maxLines===null?Number.MAX_SAFE_INTEGER:this._maxLines,H=Math.max(U,Math.min(z,W));return Q.top+Q.bottom+X*2+H}dispose(){super.dispose()}paint(J,Q=0,Z=0){let X=Q+this.offset.x,Y=Z+this.offset.y,K=this.size.width,q=this.size.height,G=this._style.backgroundColor||E1.default();for(let O=0;O<q;O++)for(let $=0;$<K;$++)J.setChar(X+$,Y+O," ",{bg:G,fg:this._style.textColor||E1.default()},1);let z=this._style.border;if(z){for(let O=0;O<K;O++)J.setChar(X+O,Y,"─",{fg:z.top?.color||E1.default(),bg:G},1);for(let O=0;O<K;O++)J.setChar(X+O,Y+q-1,"─",{fg:z.bottom?.color||E1.default(),bg:G},1);for(let O=0;O<q;O++)J.setChar(X,Y+O,"│",{fg:z.left?.color||E1.default(),bg:G},1);for(let O=0;O<q;O++)J.setChar(X+K-1,Y+O,"│",{fg:z.right?.color||E1.default(),bg:G},1);J.setChar(X,Y,"╭",{fg:z.top?.color||E1.default(),bg:G},1),J.setChar(X+K-1,Y,"╮",{fg:z.top?.color||E1.default(),bg:G},1),J.setChar(X,Y+q-1,"╰",{fg:z.bottom?.color||E1.default(),bg:G},1),J.setChar(X+K-1,Y+q-1,"╯",{fg:z.bottom?.color||E1.default(),bg:G},1)}let U=this._style.padding||V0.all(0),W=z?1:0,H=X+W+U.left,F=Y+W+U.top,B=K-W*2-U.left-U.right,M=q-W*2-U.top-U.bottom;if(B<=0||M<=0)return;let V=this._emojiSupported,N=this.isMultiline,L=this._controller.text,A=L||this._placeholder,w=L?this._style.textColor||E1.default():this._style.placeholderColor||E1.index(8),R=!this._enabled;if(N)this._paintMultilineText(J,A,w,G,H,F,B,M,V,R);else this._paintSingleLineText(J,A,w,G,H,F,B,V,R);if(this._enabled)this._paintCursor(J,H,F,B,M,V)}_paintSingleLineText(J,Q,Z,X,Y,K,q,G,z=!1){if(!Q)return;let U=j2(Q),W=Y,H=this._controller.text,F=this._prompts.find((N)=>N.match(H));if(F){let N=j2(F.display),L=F.style?.color??Z;for(let w of N){let R=c4(w,G);if(W+R<=Y+q)J.setChar(W,K,w,{fg:L,bg:X},R),W+=R}let A=F.spacing??0;for(let w=0;w<A;w++)if(W<Y+q)J.setChar(W,K," ",{fg:Z,bg:X},1),W+=1}let B=F?.concealPrefix?j2(F.display).length:0,M=Math.max(this._hScrollOffset,B),V=this._controller.selectionRange;for(let N=M;N<U.length&&W<Y+q;N++){let L=U[N];if(L===`
|
|
6522
|
+
`),"handled";return"ignored"}else if(V.key==="Backspace"){try{if(N.cursorPosition===0&&this.widget.onBackspaceWhenEmpty){if(this.widget.onBackspaceWhenEmpty())return"handled"}if(V.altKey)N.deleteWordLeft();else N.deleteSelectedOrText(1)}catch(O){throw u.error("TextField: Error in deleteText:",O),O}return"handled"}else if(V.key==="Delete"){if(N.hasSelection)N.deleteSelectedText();else N.deleteForward(1);return"handled"}else if(V.key==="Tab")return"ignored";else if(V.key==="Escape")return"ignored";if(V.ctrlKey){if(V.key==="g"){if(this.widget.onOpenInEditor)this.widget.onOpenInEditor(N.text);return"handled"}if(V.key==="a"){if(this.widget.isMultiline)N.moveCursorToLineStart(V.shiftKey);else N.moveCursorToStart(V.shiftKey);return"handled"}else if(V.key==="e"){if(this.widget.isMultiline)N.moveCursorToLineEnd(V.shiftKey);else N.moveCursorToEnd(V.shiftKey);return"handled"}else if(V.key==="u")return N.deleteToLineStart(),"handled";else if(V.key==="k")return N.deleteToLineEnd(),"handled";else if(V.key==="f")return N.moveCursorRight(1,V.shiftKey),"handled";else if(V.key==="b")return N.moveCursorLeft(1,V.shiftKey),"handled";else if(V.key==="n"){let{line:O,column:$}=N.cursorTextPosition,j=N.getLineCount();if(O===j-1){let I=N.getLine(O),T=j2(I).length;if($===T)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let I=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="p"){let{line:O,column:$}=N.cursorTextPosition;if(O===0&&$===0)return"ignored";else if(O===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let j=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===j?"ignored":"handled"}}else if(V.key==="d")return N.deleteForward(1),"handled";else if(V.key==="h")return N.deleteText(1),"handled";else if(V.key==="ArrowLeft")return N.moveCursorWordBoundary(-1,V.shiftKey),"handled";else if(V.key==="ArrowRight")return N.moveCursorWordBoundary(1,V.shiftKey),"handled";else if(V.key==="w")return N.deleteWordLeft(),"handled";else if(V.key==="y")return N.yankText(),"handled"}else if(V.altKey||V.metaKey){if(V.metaKey&&V.key==="ArrowLeft"){if(this.widget.isMultiline)N.moveCursorToLineStart(V.shiftKey);else N.moveCursorToStart(V.shiftKey);return"handled"}else if(V.metaKey&&V.key==="ArrowRight"){if(this.widget.isMultiline)N.moveCursorToLineEnd(V.shiftKey);else N.moveCursorToEnd(V.shiftKey);return"handled"}else if(V.key==="ArrowUp"){let{line:j,column:E}=N.cursorTextPosition;if(j===0&&E===0)return"ignored";else if(j===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let I=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="ArrowDown"){let{line:j,column:E}=N.cursorTextPosition,I=N.getLineCount();if(j===I-1){let S=N.getLine(j),x=j2(S).length;if(E===x)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let S=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===S?"ignored":"handled"}}let O=V.key==="ArrowLeft"||V.key.toLowerCase()==="b",$=V.key==="ArrowRight"||V.key.toLowerCase()==="f";if(O||$)return N.moveCursorWordBoundary(O?-1:1,V.shiftKey),"handled"}else if(V.key==="ArrowLeft")return N.moveCursorLeft(1,V.shiftKey),"handled";else if(V.key==="ArrowRight")return N.moveCursorRight(1,V.shiftKey),"handled";else if(V.key==="ArrowUp"){let{line:O,column:$}=N.cursorTextPosition;if(O===0&&$===0)return"ignored";else if(O===0)return N.moveCursorToLineStart(V.shiftKey),"handled";else{let j=N.cursorPosition;return N.moveCursorUp(1,V.shiftKey),N.cursorPosition===j?"ignored":"handled"}}else if(V.key==="ArrowDown"){let{line:O,column:$}=N.cursorTextPosition,j=N.getLineCount();if(O===j-1){let I=N.getLine(O),T=j2(I).length;if($===T)return"ignored";else return N.moveCursorToLineEnd(V.shiftKey),"handled"}else{let I=N.cursorPosition;return N.moveCursorDown(1,V.shiftKey),N.cursorPosition===I?"ignored":"handled"}}else if(V.key==="Home"||V.key==="End")return"ignored";else if(V.key==="PageUp"||V.key==="PageDown")return"ignored";if(V.key&&!wZ6(V))return N.insertText(V.key),"handled";return"ignored"},K=(V)=>{if(!this.widget.enabled)return"ignored";let N=this.widget.controller,L=this.widget.isMultiline,A=V.text;if(!L)A=A.replace(/[\r\n]+/g," ");return N.insertText(A),"handled"},q=(V)=>{if(!this.widget.enabled||!this.widget.isMultiline)return;let N=this.widget.controller,L=N.getLayoutLines();if(L.length<=1)return;let A=N.getScrollOffset(),w=3;if(V.direction==="up")A=Math.max(0,A-w);else{let R=this.widget.style,O=R.padding||V0.all(0),$=R.border?1:0,E=(J.findRenderObject()?.size?.height||10)-$*2-O.top-O.bottom,I=Math.max(0,L.length-E);A=Math.min(I,A+w)}N.setScrollOffset(A),this.setState(()=>{})},G=(V)=>{if(!this.widget.enabled)return;if(V.button==="middle"){this.widget.clipboard.readPrimarySelection().then((N)=>{if(N)K({type:"paste",text:N})}).catch((N)=>{u.debug("Failed to read primary selection for middle-click paste:",N)});return}if(V.button==="left"){this._clearCopyHighlight();let N=W(V.localPosition.x,V.localPosition.y);if(V.clickCount===3)this.widget.controller.selectLineAt(N),this._scheduleAutoCopy();else if(V.clickCount===2)this.widget.controller.selectWordAt(N),this._scheduleAutoCopy();else if(V.clickCount===1)this._clearAutoCopyTimer(),this.widget.controller.startSelectionAt(N),this._isDragging=!0,this._didMouseMove=!1,this.effectiveFocusNode.requestFocus(),this._captureGlobalMouse()}},z=(V)=>{if(!this.widget.enabled||!this._isDragging)return;if(V.button!=="left")return;this._didMouseMove=!0;let N=W(V.localPosition.x,V.localPosition.y);this.widget.controller.extendSelectionTo(N)},U=(V)=>{if(V.button==="left")this._endDrag()},W=(V,N)=>{let A=f8.of(J).supportsEmojiWidth,w=this.widget.style.padding||V0.all(0),R=this.widget.style.border?1:0,O=V-R-w.left,$=N-R-w.top,j=this.widget.controller.text,E=this.widget.prompts.find((x)=>x.match(j)),I=this.widget.controller.graphemes,T=this.widget.isMultiline,S=0;if(T){let x=this.widget.controller.getLayoutLines(),h=Math.max(0,Math.min(Math.floor($)+this.widget.controller.getScrollOffset(),x.length-1));if(E&&h===0){O-=E.spacing??0;let v=LY(E.display,A),_=E.spacing??0;if(O<v+_)return v}if(h<x.length){let v=x[h],_=I.slice(v.startOffset,v.endOffset),b=0,g=0;for(let k=0;k<_.length;k++){let f=c4(_[k],A),y=b+f;if(O<=y){if((O-b)/f<0.6)g=k;else g=k+1;break}b=y,g=k+1}S=v.startOffset+g}}else{if(E){O-=E.spacing??0;let h=LY(E.display,A),v=E.spacing??0;if(O<h+v)return h}let x=0;for(let h=0;h<I.length;h++){let v=c4(I[h],A),_=x+v;if(O<=_){if((O-x)/v<0.6)S=h;else S=h+1;break}x=_,S=h+1}}return S},F=f8.of(J).supportsEmojiWidth,B=new RZ6({controller:this.widget.controller,style:X,placeholder:this.widget.placeholder,hScrollOffset:this._hScrollOffset,vScrollOffset:this._vScrollOffset,maxWidth:this.widget.maxWidth,maxLines:this.widget.maxLines,minLines:this.widget.minLines,expands:this.widget.expands,wrap:this.widget.wrap,enabled:this.widget.enabled,emojiSupported:F,prompts:this.widget.prompts,copyHighlightActive:this._copyHighlightActive}),M=new b9({onClick:G,onDrag:z,onRelease:U,onScroll:q,cursor:this.widget.enabled?z7.TEXT:z7.DEFAULT,child:B});return new t8({key:this.widget.key??void 0,autofocus:this.widget.autofocus,focusNode:this.effectiveFocusNode,onKey:Y,onPaste:K,child:M})}}class RZ6 extends aF{controller;style;placeholder;hScrollOffset;vScrollOffset;maxWidth;maxLines;minLines;expands;wrap;enabled;emojiSupported;prompts;copyHighlightActive;constructor({controller:J,style:Q,placeholder:Z,hScrollOffset:X,vScrollOffset:Y,maxWidth:K,maxLines:q,minLines:G,expands:z,wrap:U,enabled:W,emojiSupported:H,prompts:F,copyHighlightActive:B=!1}){super({});this.controller=J,this.style=Q,this.placeholder=Z,this.hScrollOffset=X,this.vScrollOffset=Y,this.maxWidth=K,this.maxLines=q,this.minLines=G,this.expands=z,this.wrap=U,this.enabled=W,this.emojiSupported=H,this.prompts=F,this.copyHighlightActive=B}createRenderObject(){return new OZ6(this.controller,this.style,this.placeholder,this.hScrollOffset,this.vScrollOffset,this.maxWidth,this.maxLines,this.minLines,this.expands,this.wrap,this.enabled,this.emojiSupported,this.prompts,this.copyHighlightActive)}updateRenderObject(J){J.updateProperties(this.controller,this.style,this.placeholder,this.hScrollOffset,this.vScrollOffset,this.maxWidth,this.maxLines,this.minLines,this.expands,this.wrap,this.enabled,this.emojiSupported,this.prompts,this.copyHighlightActive)}}class OZ6 extends J8{_controller;_style;_placeholder;_hScrollOffset;_vScrollOffset;_maxWidth;_maxLines;_minLines;_expands;_wrap;_enabled;_emojiSupported;_prompts;_copyHighlightActive;_contentChanged=!1;constructor(J,Q,Z,X,Y,K,q,G,z,U,W=!0,H=!1,F=[],B=!1){super();this._controller=J,this._style=Q,this._placeholder=Z,this._hScrollOffset=X,this._vScrollOffset=Y,this._maxWidth=K,this._maxLines=q,this._minLines=G,this._expands=z,this._wrap=U,this._enabled=W,this._emojiSupported=H,this._prompts=F,this._copyHighlightActive=B}get isMultiline(){return this._maxLines===null||this._maxLines>1||this._minLines>1}updateProperties(J,Q,Z,X,Y,K,q,G,z,U,W=!0,H=!1,F=[],B=!1){this._controller=J,this._style=Q,this._placeholder=Z,this._hScrollOffset=X,this._vScrollOffset=Y,this._maxWidth=K,this._maxLines=q,this._minLines=G,this._expands=z,this._wrap=U,this._enabled=W,this._emojiSupported=H,this._prompts=F,this._copyHighlightActive=B,this.markNeedsLayout(),this.markNeedsPaint()}performLayout(){super.performLayout();let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=Q.left+Q.right+X*2+1,K=Q.top+Q.bottom+X*2+1,q=this._maxWidth||J.maxWidth,G=Math.max(Y,Number.isFinite(q)?Math.min(q,J.maxWidth):Y),z;if(this._expands)if(J.minHeight===J.maxHeight)z=J.maxHeight;else{let H=this.getMinIntrinsicHeight(G);z=Math.min(Math.max(H,J.minHeight),J.maxHeight)}else{let H=this.getMinIntrinsicHeight(G);if(z=Math.max(K,H),z>J.maxHeight)z=J.maxHeight}this.setSize(G,z);let U=this.getPromptPrefixWidth(),W=G-X*2-Q.left-Q.right-U;if(this._controller.updateLayoutConfig(Math.max(1,W),this._wrap?"word":"none",this._emojiSupported),this.isMultiline&&this._expands)this._updateScrollOffsetFromLayout(J,z)}getPromptPrefixWidth(){let J=this._controller.text;return this._prompts.find((Q)=>Q.match(J))?.spacing??0}getMinIntrinsicWidth(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=this._maxWidth||20;return Math.max(Q.left+Q.right+X*2+K+Y,Q.left+Q.right+X*2+1+Y)}getMaxIntrinsicWidth(J){let Q=this.getPromptPrefixWidth();if(this._maxWidth)return this._maxWidth+Q;return Number.POSITIVE_INFINITY}getMinIntrinsicHeight(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=J-X*2-Q.left-Q.right-Y,q=this._wrap?"word":"none",z=this._controller.calculateLayoutLines(Math.max(1,K),q,!1).length,U=this._minLines,W=this._maxLines===null?Number.MAX_SAFE_INTEGER:this._maxLines,H=Math.max(U,Math.min(z,W));return Q.top+Q.bottom+X*2+H}getMaxIntrinsicHeight(J){let Q=this._style.padding||V0.all(0),X=this._style.border?1:0,Y=this.getPromptPrefixWidth(),K=J-X*2-Q.left-Q.right-Y,q=this._wrap?"word":"none",z=this._controller.calculateLayoutLines(Math.max(1,K),q,!1).length,U=this._minLines,W=this._maxLines===null?Number.MAX_SAFE_INTEGER:this._maxLines,H=Math.max(U,Math.min(z,W));return Q.top+Q.bottom+X*2+H}dispose(){super.dispose()}paint(J,Q=0,Z=0){let X=Q+this.offset.x,Y=Z+this.offset.y,K=this.size.width,q=this.size.height,G=this._style.backgroundColor||E1.default();for(let O=0;O<q;O++)for(let $=0;$<K;$++)J.setChar(X+$,Y+O," ",{bg:G,fg:this._style.textColor||E1.default()},1);let z=this._style.border;if(z){for(let O=0;O<K;O++)J.setChar(X+O,Y,"─",{fg:z.top?.color||E1.default(),bg:G},1);for(let O=0;O<K;O++)J.setChar(X+O,Y+q-1,"─",{fg:z.bottom?.color||E1.default(),bg:G},1);for(let O=0;O<q;O++)J.setChar(X,Y+O,"│",{fg:z.left?.color||E1.default(),bg:G},1);for(let O=0;O<q;O++)J.setChar(X+K-1,Y+O,"│",{fg:z.right?.color||E1.default(),bg:G},1);J.setChar(X,Y,"╭",{fg:z.top?.color||E1.default(),bg:G},1),J.setChar(X+K-1,Y,"╮",{fg:z.top?.color||E1.default(),bg:G},1),J.setChar(X,Y+q-1,"╰",{fg:z.bottom?.color||E1.default(),bg:G},1),J.setChar(X+K-1,Y+q-1,"╯",{fg:z.bottom?.color||E1.default(),bg:G},1)}let U=this._style.padding||V0.all(0),W=z?1:0,H=X+W+U.left,F=Y+W+U.top,B=K-W*2-U.left-U.right,M=q-W*2-U.top-U.bottom;if(B<=0||M<=0)return;let V=this._emojiSupported,N=this.isMultiline,L=this._controller.text,A=L||this._placeholder,w=L?this._style.textColor||E1.default():this._style.placeholderColor||E1.index(8),R=!this._enabled;if(N)this._paintMultilineText(J,A,w,G,H,F,B,M,V,R);else this._paintSingleLineText(J,A,w,G,H,F,B,V,R);if(this._enabled)this._paintCursor(J,H,F,B,M,V)}_paintSingleLineText(J,Q,Z,X,Y,K,q,G,z=!1){if(!Q)return;let U=j2(Q),W=Y,H=this._controller.text,F=this._prompts.find((N)=>N.match(H));if(F){let N=j2(F.display),L=F.style?.color??Z;for(let w of N){let R=c4(w,G);if(W+R<=Y+q)J.setChar(W,K,w,{fg:L,bg:X},R),W+=R}let A=F.spacing??0;for(let w=0;w<A;w++)if(W<Y+q)J.setChar(W,K," ",{fg:Z,bg:X},1),W+=1}let B=F?.concealPrefix?j2(F.display).length:0,M=Math.max(this._hScrollOffset,B),V=this._controller.selectionRange;for(let N=M;N<U.length&&W<Y+q;N++){let L=U[N];if(L===`
|
|
6523
6523
|
`)continue;let A=c4(L,G);if(W+A<=Y+q){let R=V&&N>=V.start&&N<V.end?this._copyHighlightActive?E1.yellow:this._style.selectionBackgroundColor??E1.blue:X;J.setChar(W,K,L,{fg:Z,bg:R,dim:z},A),W+=A}else break}}_paintMultilineText(J,Q,Z,X,Y,K,q,G,z,U=!1){if(!Q)return;let W=this._controller.text,H,F,B;if(W)H=this._controller.getLayoutLines(),F=this._controller.getScrollOffset(),B=this._controller.graphemes;else H=new Wp(Q,{maxWidth:q,wrapMode:this._wrap?"word":"none",emojiSupported:z}).lines,F=0,B=j2(Q);let M=Math.min(F+G,H.length),V=this._controller.selectionRange;for(let N=F;N<M;N++){let L=K+(N-F),A=H[N];if(A){let w=B.slice(A.startOffset,A.endOffset),R=Y,O=N===0,$=this._controller.text,j=O?this._prompts.find((I)=>I.match($)):void 0;if(j){let I=j2(j.display),T=j.style?.color??Z;for(let x of I){let h=c4(x,z);if(R+h<=Y+q)J.setChar(R,L,x,{fg:T,bg:X},h),R+=h}let S=j.spacing??0;for(let x=0;x<S;x++)if(R<Y+q)J.setChar(R,L," ",{fg:Z,bg:X},1),R+=1}let E=j?.concealPrefix?j2(j.display).length:0;for(let I=E;I<w.length&&R<Y+q;I++){let T=w[I],S=c4(T,z);if(R+S<=Y+q){let x=A.startOffset+I,v=V&&x>=V.start&&x<V.end?this._copyHighlightActive?E1.yellow:this._style.selectionBackgroundColor??E1.blue:X;J.setChar(R,L,T,{fg:Z,bg:v,dim:U},S),R+=S}else break}}}}_paintCursor(J,Q,Z,X,Y,K){if(this.isMultiline){let G=this._controller.cursorPosition,z=this._controller.getLayoutLines(),U=-1,W=0;for(let F=0;F<z.length;F++){let B=z[F];if(G>=B.startOffset&&G<=B.endOffset){U=F,W=G-B.startOffset;break}}let H=this._controller.getScrollOffset();if(U>=H&&U<H+Y){let F=Z+(U-H),B=z[U],M=this._controller.graphemes,V=Q,N=U===0,L=this._controller.text,A=N?this._prompts.find((O)=>O.match(L)):void 0;if(A){let O=j2(A.display);for(let $ of O)V+=c4($,K);V+=A.spacing??0}let w=A?.concealPrefix?j2(A.display).length:0,R=Math.max(0,W-w);for(let O=0;O<R;O++){let $=B.startOffset+w+O;if($<M.length){let j=M[$],E=c4(j,K);V+=E}}if(V>=Q&&V<=Q+X)J.setCursor(V,F);else J.clearCursor()}else J.clearCursor()}else{let G=this._controller.cursorPosition,z=this._controller.graphemes,U=this._controller.text,W=this._prompts.find((V)=>V.match(U)),H=Q;if(W){let V=j2(W.display);for(let N of V)H+=c4(N,K);H+=W.spacing??0}let F=W?.concealPrefix?j2(W.display).length:0,B=Math.max(this._hScrollOffset,F),M=Math.max(G,F);for(let V=B;V<M&&V<z.length;V++){let N=z[V];if(N!==`
|
|
6524
6524
|
`)H+=c4(N,K)}if(H>=Q&&H<=Q+X)J.setCursor(H,Z);else J.clearCursor()}}_updateScrollOffsetFromLayout(J,Q){let Z=this._controller;if(!(Q>=J.maxHeight)){Z.setScrollOffset(0);return}let Y=Z.getLayoutLines(),K=Z.cursorPosition,q=-1;for(let L=0;L<Y.length;L++){let A=Y[L];if(K>=A.startOffset&&K<=A.endOffset){q=L;break}}if(q===-1)return;let G=this._style.padding||V0.all(0),U=this._style.border?1:0,W=Q-G.top-G.bottom-U*2,H=Z.getScrollOffset(),F=H,B=H+W-1;if(q<F)Z.setScrollOffset(q);else if(q>B){let L=q-W+1;Z.setScrollOffset(L)}let M=Math.max(0,Y.length-W),V=Z.getScrollOffset(),N=Math.max(0,Math.min(V,M));Z.setScrollOffset(N)}}var q49=new Set([" ","\t",`
|
|
6525
6525
|
`,"\r","\v","\f"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," ","\uFEFF"]),G49=new Set(["/","\\",".",",",";",":","!","?","(",")","[","]","{","}","<",">","'",'"',"=","+","-","*","&","|","^","%","$","#","@","~","`","_"]);q0();class oK{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function O51(J){if(J instanceof oK)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}D9();var Wf1=C6(bZ6(),1);a8();b2();var yZ6=20,fZ6=" .:-=+*#%@",I49=" ",P49=[0,55,0],T49=[0,255,136],C49=[128,51,0],S49=[255,215,0],v49=[0,26,51],k49=[0,184,255],hZ6=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],S51=0.5,Uf1=(J,Q,Z)=>J+(Q-J)*Z;function _49(J,Q){let Z=Math.max(0,Math.min(1,J));if(Q==="low"){let Y=Math.floor(Z*(hZ6.length-1));return E1.index(hZ6[Y])}if(Q==="fast"){let Y=C49.map((K,q)=>Math.round(Uf1(K,S49[q],Z)));return E1.rgb(Y[0],Y[1],Y[2])}if(Q==="free"){let Y=v49.map((K,q)=>Math.round(Uf1(K,k49[q],Z)));return E1.rgb(Y[0],Y[1],Y[2])}let X=P49.map((Y,K)=>Math.round(Uf1(Y,T49[K],Z)));return E1.rgb(X[0],X[1],X[2])}var Hf1=1,x49=30,gZ6=3;class Ff1 extends l0{width;height;minWidth;minHeight;maxWidth;maxHeight;colorMode;t;onFrame;fps;seed;constructor({key:J,width:Q=40,height:Z=40,minWidth:X,minHeight:Y,maxWidth:K,maxHeight:q,colorMode:G="high",t:z,onFrame:U,fps:W=60,seed:H}){super(J?{key:J}:{});this.width=Q,this.height=Z,this.minWidth=X??8,this.minHeight=Y??8,this.maxWidth=K??40,this.maxHeight=q??40,this.colorMode=G,this.t=z,this.onFrame=U,this.fps=W,this.seed=H}createState(){return new mZ6}}class mZ6 extends c0{_t=0;_timer=null;_shockwaves=[];initState(){if(super.initState(),this.widget.t!==void 0||this.widget.fps===0){this._t=this.widget.t??0;return}if(this.widget.fps==0)return;this._timer=setInterval(()=>{if(this._t+=1/this.widget.fps,this.widget.onFrame){let J=this._t;setImmediate(()=>this.widget.onFrame?.(J))}this._shockwaves=this._shockwaves.filter((J)=>this._t-J.startTime<Hf1),this.setState(()=>{})},1000/this.widget.fps)}didUpdateWidget(J){if(super.didUpdateWidget(J),this.widget.t!==void 0&&this.widget.t!==J.t)this._t=this.widget.t,this.setState(()=>{})}dispose(){if(this._timer)clearInterval(this._timer),this._timer=null;super.dispose()}handleClick=(J)=>{this._shockwaves.push({x:J.localPosition.x,y:J.localPosition.y,startTime:this._t}),this.setState(()=>{})};build(J){let Q=new uZ6({width:this.widget.width,height:this.widget.height,minWidth:this.widget.minWidth,minHeight:this.widget.minHeight,maxWidth:this.widget.maxWidth,maxHeight:this.widget.maxHeight,time:this._t,colorMode:this.widget.colorMode,seed:this.widget.seed,shockwaves:this._shockwaves});return new b9({onClick:this.handleClick,child:Q})}}class uZ6 extends aF{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new qN(this)}createRenderObject(){return new pZ6(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.colorMode,this.props.seed,this.props.shockwaves)}updateRenderObject(J){J.update(this.props.width,this.props.height,this.props.minWidth,this.props.minHeight,this.props.maxWidth,this.props.maxHeight,this.props.time,this.props.colorMode,this.props.seed,this.props.shockwaves)}}class pZ6 extends J8{_width;_height;_minWidth;_minHeight;_maxWidth;_maxHeight;_time;_colorMode;_seed;_shockwaves;_noise2D;constructor(J,Q,Z,X,Y,K,q,G,z,U=[]){super();this._width=J;this._height=Q;this._minWidth=Z;this._minHeight=X;this._maxWidth=Y;this._maxHeight=K;this._time=q;this._colorMode=G;this._seed=z;this._shockwaves=U;this._noise2D=Wf1.makeNoise2D(this._seed??Date.now())}getMinIntrinsicWidth(J){return this._minWidth}getMaxIntrinsicWidth(J){return this._maxWidth}getMinIntrinsicHeight(J){return this._minHeight}getMaxIntrinsicHeight(J){return this._maxHeight}update(J,Q,Z,X,Y,K,q,G,z,U=[]){let W=!1;if(J!==this._width||Q!==this._height||Z!==this._minWidth||X!==this._minHeight||Y!==this._maxWidth||K!==this._maxHeight)this._width=J,this._height=Q,this._minWidth=Z,this._minHeight=X,this._maxWidth=Y,this._maxHeight=K,W=!0;if(z!==this._seed)this._seed=z,this._noise2D=Wf1.makeNoise2D(this._seed??Date.now());if(this._time=q,this._colorMode=G,this._shockwaves=U,W)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints;u6(!!J,"performLayout called without constraints");let Q=J.constrain(this._width,this._height);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Q+this.offset.x,Y=Z+this.offset.y,K=Math.floor(this.size.width),q=Math.floor(this.size.height),G=K/2,z=q/2,U=Math.max(1,K/2-1),W=Math.max(1,q/(2*S51)-1),H=Math.min(U,W);for(let F=0;F<q;F++){let B=Y+F,M=!0;if(F>0){M=!0;for(let N=0;N<K;N++){let L=N-G,A=(F-1-z)/S51;if(Math.sqrt(L*L+A*A)/H<1){M=!1;break}}}let V=!0;for(let N=0;N<K;N++){let L=N-G,A=(F-z)/S51,w=Math.sqrt(L*L+A*A),R=w/H;if(R>=1)continue;let O=1-R*R,$=this._colorMode==="fast"?2.5:1,E=(this._noise2D(N/yZ6,F/yZ6+this._time*$)+1)*0.5*O;for(let x of this._shockwaves){let h=this._time-x.startTime;if(h<0||h>Hf1)continue;let v=N-x.x,_=(F-x.y)/S51,b=Math.sqrt(v*v+_*_),g=h*x49,k=Math.abs(b-g);if(k<gZ6){let f=w/H;if(f<0.95){let y=1-h/Hf1,m=(1-k/gZ6)*y,a=1-Math.pow(f,3);E=Math.min(1,E+m*0.8*a)}}}let I=fZ6[Math.floor(E*fZ6.length)]||I49,T=_49(E,this._colorMode),S=X+N;if(S<0||S>=J.getSize().width)continue;J.setCell(S,B,{char:I,width:1,style:{fg:T}}),V=!1}if(V&&M)continue}}}class v51{toolRunning;toolSuccess;toolError;toolCancelled;toolName;userMessage;assistantMessage;systemMessage;codeBlock;inlineCode;syntaxHighlight;fileReference;processing;waiting;completed;cancelled;recommendation;suggestion;command;filename;keybind;button;shellMode;shellModeHidden;diffAdded;diffRemoved;diffChanged;diffContext;ideConnected;ideDisconnected;ideWarning;scrollbarThumb;scrollbarTrack;tableBorder;constructor({toolRunning:J,toolSuccess:Q,toolError:Z,toolCancelled:X,toolName:Y,userMessage:K,assistantMessage:q,systemMessage:G,codeBlock:z,inlineCode:U,syntaxHighlight:W,fileReference:H,processing:F,waiting:B,completed:M,cancelled:V,suggestion:N,command:L,filename:A,keybind:w,button:R,shellMode:O,shellModeHidden:$,diffAdded:j,diffRemoved:E,diffChanged:I,diffContext:T,ideConnected:S,ideDisconnected:x,ideWarning:h,scrollbarThumb:v,scrollbarTrack:_,tableBorder:b,recommendation:g}){this.toolRunning=J,this.toolSuccess=Q,this.toolError=Z,this.toolCancelled=X,this.toolName=Y,this.userMessage=K,this.assistantMessage=q,this.systemMessage=G,this.codeBlock=z,this.inlineCode=U,this.syntaxHighlight=W,this.fileReference=H,this.processing=F,this.waiting=B,this.completed=M,this.cancelled=V,this.suggestion=N,this.command=L,this.filename=A,this.keybind=w,this.button=R,this.shellMode=O,this.shellModeHidden=$,this.diffAdded=j,this.diffRemoved=E,this.diffChanged=I,this.diffContext=T,this.ideConnected=S,this.ideDisconnected=x,this.ideWarning=h,this.scrollbarThumb=v,this.scrollbarTrack=_,this.tableBorder=b,this.recommendation=g}static default(){return new v51({toolRunning:E1.blue,toolSuccess:E1.green,toolError:E1.red,toolCancelled:E1.yellow,toolName:E1.default(),userMessage:E1.cyan,assistantMessage:E1.white,systemMessage:E1.index(8),codeBlock:E1.default(),inlineCode:E1.yellow,syntaxHighlight:{keyword:E1.blue,string:E1.green,number:E1.yellow,comment:E1.index(8),function:E1.cyan,variable:E1.default(),type:E1.magenta,operator:E1.white},fileReference:E1.cyan,processing:E1.blue,waiting:E1.yellow,completed:E1.green,cancelled:E1.index(8),recommendation:E1.blue,suggestion:E1.magenta,command:E1.yellow,filename:E1.cyan,keybind:E1.blue,button:E1.cyan,shellMode:E1.blue,shellModeHidden:E1.index(8),diffAdded:E1.green,diffRemoved:E1.red,diffChanged:E1.yellow,diffContext:E1.index(8),ideConnected:E1.green,ideDisconnected:E1.red,ideWarning:E1.yellow,scrollbarThumb:E1.index(7),scrollbarTrack:E1.index(8),tableBorder:E1.index(8)})}}class SC{base;app;constructor({base:J,app:Q}){this.base=J,this.app=Q}get colors(){return this.base.colorScheme}static default(){return new SC({base:rK.default(),app:v51.default()})}static fromBaseTheme(J){return new SC({base:J,app:v51.default()})}}class A6 extends GZ{data;constructor({key:J,data:Q,child:Z}){super({key:J,child:Z});this.data=Q}static of(J){let Q=J.dependOnInheritedWidgetOfExactType(A6);if(Q)return Q.widget.data;return SC.default()}static maybeOf(J){let Q=J.dependOnInheritedWidgetOfExactType(A6);if(Q)return Q.widget.data;return null}updateShouldNotify(J){return this.data!==J.data}}D9();class dZ6{vertical="│";tee="├";elbow="╰";horizontal="─";indent=4;connectorColor=E1.white;connectorDim=!0}class Dp extends wY{style;showTreeCharacters;constructor({key:J,children:Q,style:Z,showTreeCharacters:X=!0}){super({key:J,children:Q});this.style=Z??new dZ6,this.showTreeCharacters=X}createRenderObject(){return new cZ6({style:this.style,showTreeCharacters:this.showTreeCharacters})}updateRenderObject(J){J.updateTreeView({style:this.style,showTreeCharacters:this.showTreeCharacters})}}class cZ6 extends J8{style;showTreeCharacters;constructor({style:J,showTreeCharacters:Q}){super();this.style=J,this.showTreeCharacters=Q}updateTreeView({style:J,showTreeCharacters:Q}){this.style=J,this.showTreeCharacters=Q,this.markNeedsLayout()}performLayout(){let J=this._lastConstraints;if(!J)return;let Z=(this.style.tee+this.style.horizontal+" ").length,X=Math.max(0,J.maxWidth-Z),Y=0;for(let q of this.children){let G=q,z=new j6(X,X,0,1/0);G.layout(z),G.setOffset(Z,Y),Y+=G.size.height}let K=J.constrain(J.maxWidth,Y);this.setSize(K.width,K.height)}paint(J,Q,Z){if(this.showTreeCharacters){let X=Z+this.offset.y;for(let Y=0;Y<this.children.length;Y++){let q=this.children[Y],G=Y===this.children.length-1,z=q.size.height,W=(G?this.style.elbow:this.style.tee)+this.style.horizontal+" ",H=Q+this.offset.x;for(let F of W){let B=B9(F,{fg:this.style.connectorColor,dim:this.style.connectorDim});J.setCell(H,X,B),H++}if(H=Q+this.offset.x,!G){let F=B9(this.style.vertical,{fg:this.style.connectorColor,dim:this.style.connectorDim});for(let B=1;B<z;B++)J.setCell(H,X+B,F)}X+=q.size.height}}super.paint(J,Q,Z)}}class k51 extends O6{bashInvocations;constructor({bashInvocations:J,key:Q}){super(Q?{key:Q}:{});this.bashInvocations=J}build(J){if(this.bashInvocations.length===0)return new u0({children:[]});let Q=A6.of(J),Z=Q.colors,X=this.bashInvocations.map((K)=>{let q=K.hidden,G=q?Q.app.shellModeHidden:Q.app.shellMode,U=[new a1({text:new D1("",void 0,[new D1(`${q?"$$":"$"} `,new j1({color:G,bold:!0})),new D1(K.args.cmd,new j1({color:E1.green}))]),selectable:!0})];if(K.toolRun.status==="in-progress"||K.toolRun.status==="done"){let W=K.toolRun.progress;if(W?.output){let H=this.getLastOutputLines(W.output);U.push(...H.map((F)=>new a1({text:new D1(F,new j1({color:E1.white,dim:!0})),selectable:!0})))}}if(K.toolRun.status==="blocked-on-user"){let W=K.toolRun.reason?` (${K.toolRun.reason})`:"";U.push(new a1({text:new D1(`Waiting for confirmation${W}`,new j1({color:E1.white,italic:!0})),selectable:!0}))}return new u0({crossAxisAlignment:"start",children:U})}),Y=[new H0({height:1}),new a1({text:new D1("Shell Mode:",new j1({color:E1.blue,bold:!0})),selectable:!0}),new Dp({children:X})];return new u0({crossAxisAlignment:"start",children:Y})}getLastOutputLines(J){if(!J)return[];return J.split(`
|
|
@@ -6606,7 +6606,7 @@ exit code: ${G}`,new j1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
|
|
|
6606
6606
|
`,B),...M],N=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a1({text:new D1("",void 0,V)})]}),L="high";if(this.agentMode==="fast")L="fast";else if(this.agentMode==="free")L="free";return J2.child(new g0({constraints:new j6(40,120,0,1/0),child:new Q8({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new R8({flex:1,child:new Ff1({width:40,height:40,colorMode:L,fps:q==="fast"?60:q==="slow"?15:0,...q==="disabled"&&{seed:42,t:3}})}),new H0({width:1}),new R8({flex:2,child:N})]})}))}}a8();class Bg1 extends l0{props;constructor(J){super({key:J.key});this.props=J;this.props.enabled??=!0}createState(){return new FK6}}class FK6 extends c0{build(J){let Z=A6.of(J).colors,{todos:X,title:Y="TODOs",enabled:K=!0}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new H0({width:0,height:0});let q=K?Z.foreground:Z.mutedForeground,G=X.map((z)=>this.buildTodoItem(z,Z,K));return new g0({child:new T6({padding:V0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a1({text:new D1(Y,new j1({bold:!0,color:q}))}),...G]})})})}buildTodoItem(J,Q,Z){let X=this.getStatusIcon(J.status),Y=Z?Q.foreground:Q.mutedForeground,K=new j1({bold:J.status==="in-progress",color:Y}),q=new j1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Y});return new Q8({crossAxisAlignment:"start",children:[new a1({text:new D1(X,K)}),new H0({width:1}),new R8({child:new a1({text:new D1(J.content,q)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Dg1 extends O6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=X}build(J){let Q=A6.of(J),Z=Q.colors.primary,X=Q.colors.foreground;return new g0({decoration:new q9(void 0,new m8(new _8(Z,1,"rounded"),new _8(Z,1,"rounded"),void 0,new _8(Z,1,"rounded"))),child:new T6({padding:V0.horizontal(1),child:new u0({children:[new Q8({crossAxisAlignment:"start",children:[new R8({child:new a1({text:new D1(this.ad.content,new j1({color:X}))})}),new H0({width:4}),new DQ({uri:"https://ampcode.com/free",text:"Ad",style:new j1({color:X,dim:!0}),onError:(Y)=>{}})]}),new Q8({crossAxisAlignment:"start",children:[new ny1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:V0.horizontal(1),color:Z,reverse:!0}),new H0({width:2}),new a1({text:new D1(this.ad.destinationUrlHostname,new j1({color:X,dim:!0}))})]})]})})})}}D9();a8();class Mg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new BK6(this.props.autofocus??!0)}}class BK6 extends c0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(G)=>{if(G.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(G.ctrlKey&&G.key==="c"||G.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=f8.sizeOf(J),X=Math.min(60,Z.width-4),Y=Z.height-4,K=[];if(this.widget.props.title)K.push(new a1({text:new D1(this.widget.props.title,new j1({bold:!0,color:E1.blue}))}),new H0({height:1}));if(this.widget.props.message)K.push(new a1({text:new D1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new H0({height:1}));let q=[];if(this.widget.props.showCopyOption)q.push(new a1({text:new D1("Enter to copy",new j1({dim:!0}))}));return q.push(new a1({text:new D1("Escape to close",new j1({dim:!0}))})),K.push(new Q8({children:q.flatMap((G,z)=>z<q.length-1?[G,new H0({width:1}),new a1({text:new D1("•",new j1({dim:!0}))}),new H0({width:1})]:[G]),mainAxisSize:"min"})),new J2({child:new g0({constraints:new j6(X,X,0,Y),decoration:new q9(E1.default(),new m8(new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"))),padding:new V0(2,2,2,2),child:new t8({autofocus:this.autofocus,onKey:Q,child:new u0({children:K,mainAxisSize:"min"})})})})}}function Vg1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}eB();q0();import{spawn as jQ9}from"node:child_process";import{promises as $Q9}from"node:fs";function DK6(J){return J.kind==="executable"}function MK6(J){return J.kind==="markdown"}var ZB=50000,VK6=300000;async function Ng1(J,Q,Z,X={}){let{timeoutMs:Y=VK6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(u.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),MK6(q))return await EQ9(q,Q);else if(DK6(q))return await IQ9(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return u.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function EQ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await $Q9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>ZB?Z.slice(0,ZB)+`
|
|
6607
6607
|
... (output truncated at ${ZB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function IQ9(J,Q,Z=VK6,X){return new Promise((Y)=>{let[K,q]=PQ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=vt1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=jQ9(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),H=[],F=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=ZB)H.push(V);else{let N=ZB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=ZB)F.push(V);else{let N=ZB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:H.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:H.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=H.join(""),L=F.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6608
6608
|
${L}`:L;if(B>ZB)A+=`
|
|
6609
|
-
... (output truncated at ${ZB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function PQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return CQ9(Z,X?[...X]:null,Y,Q);else return TQ9(Z,X?[...X]:null,Y,Q)}function TQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}q0();H2();TB();gY();hW();cC();import{execSync as NK6}from"child_process";import{writeFile as SQ9}from"fs/promises";import vQ9 from"path";q0();gY();class Lg1{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,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.
|
|
6609
|
+
... (output truncated at ${ZB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function PQ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return CQ9(Z,X?[...X]:null,Y,Q);else return TQ9(Z,X?[...X]:null,Y,Q)}function TQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CQ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}q0();H2();TB();gY();hW();cC();import{execSync as NK6}from"child_process";import{writeFile as SQ9}from"fs/promises";import vQ9 from"path";q0();gY();class Lg1{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,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761926491-gb46bb9"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await ea(Q,this.configService)}catch(Q){u.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}}function kQ9(J){return J.startsWith("custom-command-")}function LK6(J){return J.startsWith("agent-mode-")}function _Q9(J){return J.replace(/^custom-command-/,"")}class Ag1{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new Lg1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[]){this.telemetrySubmitter.submit(J).catch((W)=>{u.debug("Failed to submit command telemetry",W)});let X=new AbortController,Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,q=this.commands.get(J);if(q){this.onExecute({id:K,name:q.id,startTime:Y,abortController:X});let W=await q.execute(Q,Z);return this.onExecutionComplete(),W}let G=_Q9(J),z=this.latestCustom.find((W)=>W.name===G);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let U=await Ng1(G,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),U.success){let W=Q.editorState.text,F=W.trim()&&!W.endsWith(`
|
|
6610
6610
|
|
|
6611
6611
|
`)?`
|
|
6612
6612
|
${U.output}`:U.output;Q.editorDispatch({type:"insert-text",text:F});return}return Error(U.error??`Command '${J}' failed`)}getPriority(J,Q){if(kQ9(J))return 4;if(Q.editorState.hasSelection)switch(J){case"copy-selection":return 60}if(this.isThreadEmpty(Q)){if(LK6(J))return 59;switch(J){case"set-agent-mode":return 58;case"toggle-agent-mode":return 57}}if(this.hasPromptText(Q)&&Q.isProcessing)switch(J){case"queue":return 39;case"dequeue":return 37}if(Q.isProcessing)switch(J){case"queue":return 29;case"dequeue":return 27}if(this.hasPromptText(Q))switch(J){case"handoff":return 19;case"editor":return 18;case"clear":return 17}if(LK6(J))return 0;switch(J){case"help":return 10;case"continue":return 9;case"new":return 8;case"handoff":return 7;case"editor":return 6;case"browser":case"url":case"visibility":case"toggle-thinking-blocks":case"queue":case"clear":case"copy-selection":case"dequeue":case"generate-agent-file":case"agent-files":case"connect":case"disconnect":case"settings":case"permissions":case"permissions-enable":case"permissions-disable":case"ide":case"toggle-agent-mode":case"set-agent-mode":case"show-costs":case"refresh":case"debug-thread-json":return 1;case"quit":return 0}}getCommandFollows(J){switch(J){case"handoff":return["new"];case"quit":return["queue","dequeue"];case"set-agent-mode":case"toggle-agent-mode":return qW().map(({mode:Q})=>`agent-mode-${Q}`);default:return[]}}registerCommands(J){this.register({id:"new",noun:"thread",verb:"new",description:"Start new thread",aliases:["start"],execute:async(X)=>{await X.startNewThread()},isEnabled:(X)=>!this.isThreadEmpty(X)}),this.register({id:"continue",noun:"thread",verb:"switch",description:"Switch to existing thread",aliases:["continue"],gatherArguments:async(X,Y)=>{return await Y.launchThreadPicker()},execute:async(X,Y)=>{await X.switchToThread(Y)},isEnabled:()=>!0}),this.register({id:"handoff",noun:"thread",verb:"handoff",description:"Draft a new thread based on current thread",gatherArguments:async(X,Y)=>{if(this.hasPromptText(X))return{text:X.editorState.text,images:[]};return await Y.launchMultilinePrompt("handoff","Describe a prompt to hand off...")},execute:async(X,Y)=>{if(typeof Y==="string")return X.handleHandoff(Y,[]);return X.handleHandoff(Y.text,Y.images)},isEnabled:(X)=>!this.isThreadEmpty(X),getPromptText:(X)=>{if(this.hasPromptText(X))return this.truncatedPromptText(X)},nonBlocking:!0}),this.register({id:"browser",noun:"thread",verb:"open in browser",description:"Open thread in browser",execute:async({thread:X,ampURL:Y})=>{let K=z_(new URL(Y),X.id).toString();try{await $X(K)}catch(q){u.error("Failed to open browser",{error:q})}},isEnabled:(X)=>!this.isThreadEmpty(X)}),this.register({id:"url",noun:"thread",verb:"copy URL",description:"Copy thread URL",execute:async(X)=>{let Y=z_(new URL(X.ampURL),X.thread.id).toString();try{return await y9.instance.tuiInstance.clipboard.writeText(Y),new oK(`Thread URL: ${Y}
|
|
@@ -6618,7 +6618,7 @@ ${U.output}`:U.output;Q.editorDispatch({type:"insert-text",text:F});return}retur
|
|
|
6618
6618
|
`);return new oK(`${q}
|
|
6619
6619
|
|
|
6620
6620
|
${G}`)}catch(Y){return u.error("Failed to get guidance files",Y),Error("Failed to retrieve guidance files")}},isEnabled:()=>!0}),this.register({id:"settings",noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",execute:async(X)=>{let Y=await AC();if(Y===null)return Error("No editor found, please set $EDITOR to edit settings");try{y9.instance.tuiInstance.suspend(),NK6(`${Y} "${X.settingsFilePath}"`,{stdio:"inherit"}),y9.instance.tuiInstance.resume()}catch(K){return u.error("Failed to open settings in editor",K),Error(`Failed to open ${Y}`)}},isEnabled:()=>!0}),this.register({id:"permissions",noun:"permissions",verb:"open in editor",description:"Edit permissions in $EDITOR",execute:async(X)=>{let Y=await AC();if(Y===null)return Error("No editor found, please set $EDITOR to edit permissions");let K="";try{let q={stdin:process.stdin,stdout:process.stdout,stderr:{write:(G)=>{return K=G.toString(),!0}},exit:(G)=>{if(G!==0)throw u.error("editPermissions exited with status",G),Error(K)},settingsFile:X.settingsFilePath,resolveEditor:AC};y9.instance.tuiInstance.suspend(),await r71(q),y9.instance.tuiInstance.resume()}catch(q){u.error("failed to open permissions editor:",q);let G=q instanceof Error?`: ${q.message}`:"";return Error(`Failed to open ${Y}${G}`)}},isEnabled:()=>!0}),this.register({id:"permissions-enable",noun:"permissions",verb:"enable",description:"Enable permissions",execute:async()=>{try{return Xq("dangerouslyAllowAll",!1),new oK("Amp is now following permissions rules for this session")}catch(X){return u.error("Failed to set dangerously allow all setting",X),Error("Failed to enable permissions for this session")}},isEnabled:()=>!0}),this.register({id:"permissions-disable",noun:"permissions",verb:"dangerously allow all",description:"Disable permissions (dangerously allow all)",execute:async()=>{try{return Xq("dangerouslyAllowAll",!0),new oK("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(X){return u.error("Failed to set dangerously allow all setting",X),Error("Failed to disable permissions for this session")}},isEnabled:()=>!0}),this.register({id:"ide",noun:"ide",verb:"connect",description:"Connect to an IDE",execute:async(X)=>{X.openIdePicker()},isEnabled:(X)=>!!X.openIdePicker}),this.register({id:"set-agent-mode",noun:"mode",verb:"set",description:"Set agent mode",gatherArguments:async(X,Y)=>{let K=await this.getCurrentAgentMode(X),q=qW(J.settings);return await Y.launchFuzzyPicker({items:q.map((G)=>G.mode).filter((G)=>G!==K),getLabel:(G)=>{let U=q.find((H)=>H.mode===G)?.description||"",W=G===K?" (current)":"";return`${G}${U?` - ${U}`:""}${W}`},title:"Select Agent Mode"})},execute:async(X,Y)=>{try{if(!Y)return;if(!this.isThreadEmpty(X))return Error("Cannot change agent mode after messages have been sent in this thread");let K=await this.getCurrentAgentMode(X);if(Y==="free"&&K!=="free"){X.toggleAgentMode();return}X.setInMemoryAgentModeOverride(Y);let q=await X.configService.getLatest(),G=qW(q.settings),z=fc1(Y,G);return new oK(`Mode set to: ${Y}${z?` - ${z}`:""} (session override)`)}catch(K){return u.error("Failed to access agent mode setting",K),Error("Failed to access agent mode setting")}},isEnabled:(X)=>{if(this.threadHasMessages(X))return!1;return qW(J.settings).length>2}}),qW(J.settings).forEach((X)=>{this.register(this.createAgentModeCommand(X.mode))}),this.register({id:"show-costs",noun:"dev",verb:"toggle costs",description:"Toggle cost display",shortcut:f6.alt("d"),execute:async(X)=>{let Y=await X.configService.getLatest();Xq("internal.showCost",!(Y.settings["internal.showCost"]??!0))},isEnabled:()=>!0}),this.register({id:"refresh",noun:"screen",verb:"refresh",description:"Refresh screen",shortcut:f6.ctrl("l"),execute:async(X)=>{y9.instance.tuiInstance.getScreen().markForRefresh(),e9.instance.requestFrame()},isEnabled:()=>!0}),this.register({id:"help",noun:"amp",verb:"help",description:"Show this help",execute:async(X)=>{X.openHelp()},isEnabled:()=>!0}),this.register({id:"quit",noun:"amp",verb:"quit",description:"Exit application",aliases:["exit"],shortcut:new f6("c",{ctrl:!0}),execute:async(X)=>{X.exitApp()},isEnabled:()=>!0}),this.register({id:"debug-thread-json",noun:"dev",verb:"open thread JSON",description:"Open thread JSON in editor",execute:async(X)=>{try{let Y=process.env.EDITOR||process.env.VISUAL||"nano",K=vQ9.join("/tmp",`amp-thread-${X.thread.id}-${Date.now()}.json`),q=JSON.stringify(X.thread,null,2);await SQ9(K,q,"utf-8"),y9.instance.tuiInstance.suspend(),NK6(`${Y} "${K}"`,{stdio:"inherit"}),y9.instance.tuiInstance.resume(),u.info("Thread JSON written and opened in editor",{file:K});return}catch(Y){return u.error("Failed to write thread JSON or open editor",Y),Error("Failed to write thread JSON or open editor")}},isEnabled:(X)=>!1})}async getCurrentAgentMode(J){let Q=await J.configService.getLatest(),Z=mq(Q.settings);return J.getInMemoryAgentModeOverride()??Z}isThreadEmpty(J){return J.thread.messages.length===0}threadHasMessages(J){return!this.isThreadEmpty(J)}getQueuedMessages(J){return J.thread.queuedMessages??[]}hasPromptText(J){return J.editorState.text.trim().length>0}truncatedPromptText(J){let Q=J.editorState.text.trim().replace(/\n/g," ");return Q.length>20?`${Q.slice(0,20)}...`:Q}register(J){if(this.commands.has(J.id))throw Error(`Command with id ${J.id} already registered`);this.commands.set(J.id,J)}createAgentModeCommand(J){return{id:`agent-mode-${J}`,noun:"mode",verb:`use ${J}`,description:`Use ${J} mode`,execute:async(Q)=>{try{if(this.threadHasMessages(Q))return Error("Cannot change agent mode after messages have been sent in this thread");Q.setInMemoryAgentModeOverride(J)}catch(Z){return u.error("Failed to access agent mode setting",Z),Error("Failed to access agent mode setting")}},isEnabled:(Q)=>{if(this.threadHasMessages(Q))return!1;let Z=Q.getInMemoryAgentModeOverride();if(Z===null)return!0;return Z!==J}}}getAllCommands(){let J=this.latestCustom.filter((Z)=>Z.available).map((Z)=>({id:`custom-command-${Z.name}`,noun:"custom",verb:Z.name,description:`Run custom command ${Z.name}`,isEnabled:()=>!0,gatherArguments:Z.kind==="executable"?async(X,Y)=>{let K=await Y.launchArgumentPrompt(Z.name);if(K===null)return null;return Vg1(K)}:void 0,execute:(X,Y)=>this.execute(Z.name,X,Y??[])}));return[...Array.from(this.commands.values()).filter((Z)=>Z.noun!=="dev"),...J]}}a8();a8();class AK6 extends c0{controller=new sK;focusNode=new i8({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});initState(){this.focusNode.requestFocus()}dispose(){this.focusNode.dispose()}build(J){let Q=A6.of(J),{colors:Z}=Q,X=m8.all(new _8(Z.foreground,1,"solid")),Y=new sF({controller:this.controller,focusNode:this.focusNode,placeholder:"Enter command argument...",onSubmitted:(G)=>{this.widget.props.onSubmit(G.trim())},autofocus:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),K=new Q8({children:[new g0({decoration:{color:E1.default()},child:new a1({text:new D1(">",new j1({color:Z.foreground}))})}),new R8({child:Y})]}),q=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1("",void 0,[new D1("Command: ",new j1({color:Z.foreground})),new D1(this.widget.props.commandName,new j1({color:E1.yellow,bold:!0}))])})});return new g0({decoration:{border:X,color:E1.default()},padding:V0.all(1),child:new u0({children:[q,new H0({height:1}),K]})})}}class wg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new AK6}}EW();q0();a8();q0();class wK6{_listeners=new Set;_disposed=!1;addListener(J){if(this._disposed)throw Error("Cannot add listener to disposed ChangeNotifier");this._listeners.add(J)}removeListener(J){this._listeners.delete(J)}notifyListeners(){if(this._disposed)return;let J=Array.from(this._listeners);for(let Q of J)try{Q()}catch(Z){}}dispose(){this._disposed=!0,this._listeners.clear()}get disposed(){return this._disposed}get hasListeners(){return this._listeners.size>0}}class bR extends wK6{_value;constructor(J){super();this._value=J}get value(){return this._value}set value(J){let Q=typeof J==="object"||this._value!==J;if(this._value=J,Q)this.notifyListeners()}}function RK6(J,Q){let Z=()=>{Q()};return J.addListener(Z),{dispose:()=>J.removeListener(Z)}}a8();b2();D9();class Rg1 extends w4{link;showWhenUnlinked;offset;constructor({key:J,link:Q,showWhenUnlinked:Z=!0,offset:X={x:0,y:0},child:Y}){super({key:J,child:Y});this.link=Q,this.showWhenUnlinked=Z,this.offset=X}createElement(){return new KN(this)}createRenderObject(){return new OK6(this.link,this.showWhenUnlinked,this.offset)}updateRenderObject(J){J.link=this.link,J.showWhenUnlinked=this.showWhenUnlinked,J.setFollowerOffset(this.offset)}}class OK6 extends J8{_link;_showWhenUnlinked;_followerOffset;_cachedPosition=null;_instanceId;constructor(J,Q,Z){super();this._link=J,this._showWhenUnlinked=Q,this._followerOffset=Z,this._instanceId=Math.random().toString(36).substring(2,8)}get link(){return this._link}set link(J){this._link=J,this._cachedPosition=null,this.markNeedsLayout()}get showWhenUnlinked(){return this._showWhenUnlinked}set showWhenUnlinked(J){if(this._showWhenUnlinked!==J)this._showWhenUnlinked=J,this.markNeedsLayout()}setFollowerOffset(J){if(this._followerOffset.x!==J.x||this._followerOffset.y!==J.y)this._followerOffset={...J},this.markNeedsLayout()}calculatePosition(){let J=this._link.getTargetTransform();if(!J)return null;return{x:J.position.x+this._followerOffset.x,y:J.position.y+this._followerOffset.y}}shouldShow(){return this._link.target!==null||this._showWhenUnlinked}performLayout(){let J=this._lastConstraints;if(u6(!!J,"performLayout called without constraints"),!this.shouldShow()){this.setSize(0,0),super.performLayout();return}let Q=this.calculatePosition();if(this._cachedPosition=Q,Q)this.setOffset(Q.x,Q.y);if(this.children.length>0){let Z=this.children[0];Z.layout(J);let X=Z.size;this.setSize(X.width,X.height)}else this.setSize(0,0);super.performLayout()}getCurrentPosition(){return this._cachedPosition}setOffset(J,Q){super.setOffset(J,Q)}paint(J,Q=0,Z=0){super.paint(J,Q,Z)}}b2();D9();class Og1 extends w4{link;constructor({key:J,link:Q,child:Z}){super({key:J,child:Z});this.link=Q}createElement(){return new KN(this)}createRenderObject(){return new jK6(this.link)}updateRenderObject(J){J.link=this.link}}class jK6 extends J8{_link;_globalPosition={x:0,y:0};constructor(J){super();this._link=J}get link(){return this._link}set link(J){if(this._link===J)return;this._link._setTarget(null),this._link=J,this._link._setTarget(this)}attach(){super.attach(),this._link._setTarget(this)}detach(){this._link._setTarget(null),super.detach()}getGlobalPosition(){let J=this.offset.x,Q=this.offset.y,Z=this.parent;while(Z&&Z instanceof J8)J+=Z.offset.x,Q+=Z.offset.y,Z=Z.parent;return{x:J,y:Q}}getSize(){let J=this.size;return{width:J.width,height:J.height}}updateGlobalPosition(){let J={...this._globalPosition};if(this._globalPosition=this.getGlobalPosition(),J.x!==this._globalPosition.x||J.y!==this._globalPosition.y)this._link._notifyFollowers()}performLayout(){let J=this._lastConstraints;if(u6(!!J,"performLayout called without constraints"),this.children.length>0){let Q=this.children[0];Q.layout(J);let Z=Q.size;this.setSize(Z.width,Z.height)}else this.setSize(0,0);this.updateGlobalPosition(),super.performLayout()}}q0();class jg1{_target=null;_followers=new Set;get target(){return this._target}_setTarget(J){if(this._target===J)return;this._target=J,this._notifyFollowers()}_addFollower(J){this._followers.add(J)}_removeFollower(J){this._followers.delete(J)}_notifyFollowers(){for(let J of this._followers)try{J()}catch(Q){u.error("Error in LayerLink follower callback:",Q)}}getTargetTransform(){if(!this._target)return null;return{position:this._target.getGlobalPosition(),size:this._target.getSize()}}}q0();class $g1{_state;_textController=null;_triggers=[];_optionsBuilder=null;_onSelected=null;_disposed=!1;constructor(){let J={trigger:null,options:[],selectedIndex:-1,isActive:!1,generationId:0};this._state=new bR(J)}get state(){return this._state}get currentState(){return this._state.value}initialize({textController:J,triggers:Q,optionsBuilder:Z,onSelected:X}){if(this._disposed)throw Error("Cannot initialize disposed AutocompleteController");this._cleanup(),this._textController=J,this._triggers=Q,this._optionsBuilder=Z,this._onSelected=X||null,this._textController.addListener(this._handleTextChange)}selectNext(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex<J.options.length-1?J.selectedIndex+1:0;this._updateState({selectedIndex:Q})}selectPrevious(){let J=this.currentState;if(!J.isActive||J.options.length===0)return;let Q=J.selectedIndex>0?J.selectedIndex-1:J.options.length-1;this._updateState({selectedIndex:Q})}acceptSelected(){let J=this.currentState;if(!J.isActive||J.selectedIndex<0||J.selectedIndex>=J.options.length)return;let Q=J.options[J.selectedIndex];if(!Q)return;if(this.dismiss(),this._onSelected)this._onSelected(Q)}dismiss(){this._updateState({trigger:null,options:[],selectedIndex:-1,isActive:!1})}dispose(){this._disposed=!0,this._cleanup(),this._state.dispose()}_handleTextChange=()=>{if(!this._textController||!this._optionsBuilder)return;let J=this._textController.text,Q=this._textController.cursorPosition,Z=null;for(let Y of this._triggers){let K=Y.detect(J,Q);if(K&&(!Z||K.start>Z.start))Z=K}if(!Z){if(this.currentState.isActive)this.dismiss();return}let X=this.currentState.generationId+1;this._updateState({trigger:Z,generationId:X,isActive:!0,selectedIndex:-1}),this._buildOptions(Z.query,X)};async _buildOptions(J,Q){if(!this._optionsBuilder)return;try{let Z=await this._optionsBuilder(J);if(this.currentState.generationId===Q&&!this._disposed)this._updateState({options:Z,selectedIndex:Z.length>0?0:-1,isActive:Z.length>0})}catch(Z){if(u.error("Error building autocomplete options:",Z),this.currentState.generationId===Q&&!this._disposed)this._updateState({options:[],selectedIndex:-1,isActive:!1})}}_updateState(J){if(this._disposed)return;this._state.value={...this.currentState,...J}}_cleanup(){if(this._textController)this._textController.removeListener(this._handleTextChange)}}class Pp{}class Tp{}class Cp{}class VJ1{}class NJ1 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new $K6(this.props)}}class $K6 extends c0{props;controller;stateListener=null;overlayEntry=null;layerLink=new jg1;scrollOffset=0;_effectiveFocusNode;constructor(J){super();this.props=J}initState(){if(super.initState(),this._effectiveFocusNode=this.props.focusNode||new i8({debugLabel:"AutocompleteFocusOwned"}),this.controller=new $g1,this.controller.initialize({textController:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.props.optionsBuilder,onSelected:this.props.onSelected}),this.stateListener=RK6(this.controller.state,()=>{this.updateOverlay(),this.setState(()=>{})}),this.props.canStealFocus)e9.instance.addPostFrameCallback(()=>{this._effectiveFocusNode.requestFocus()})}didUpdateWidget(J){super.didUpdateWidget(J);let Q=J.props,Z=this.widget.props;if(this.props=Z,Q.controller!==Z.controller||Q.triggers!==Z.triggers||Q.optionsBuilder!==Z.optionsBuilder||Q.textFieldProps!==Z.textFieldProps||Q.onSelected!==Z.onSelected)this.controller.initialize({textController:Z.controller,triggers:Z.triggers,optionsBuilder:Z.optionsBuilder,onSelected:Z.onSelected});this.setState(()=>{})}dispose(){this.removeOverlay(),this.stateListener?.dispose(),this.controller.dispose(),this._effectiveFocusNode.dispose(),super.dispose()}invoke=(J)=>{if(!this.controller.currentState.isActive)return"ignored";if(J instanceof Pp)return this.controller.selectNext(),this.updateScrollPosition(),"handled";if(J instanceof Tp)return this.controller.selectPrevious(),this.updateScrollPosition(),"handled";if(J instanceof Cp)return this.controller.acceptSelected(),"handled";if(J instanceof VJ1)return this.controller.dismiss(),"handled";return"ignored"};updateScrollPosition(){let J=this.controller.currentState;if(!J.isActive||J.selectedIndex<0)return;let Q=J.selectedIndex,Z=J.options.length,X=Z;try{let z=this.layerLink.getTargetTransform();if(z){let U=z.position.y,W=2,H=U-2;X=Math.min(Z,Math.max(1,H))}}catch{}if(X>=Z){this.scrollOffset=0;return}let Y=Q-this.scrollOffset,K=1,q=this.scrollOffset;if(Y>=X-K)q=Math.max(0,Q-(X-K-1));if(Y<K)q=Math.max(0,Q-K);let G=Math.max(0,Z-X);q=Math.min(q,G),this.scrollOffset=q}build(J){let Q=new sF({...this.props.textFieldProps,controller:this.props.controller,focusNode:this._effectiveFocusNode,autofocus:!1}),Z=new hG({shortcuts:new Map([[new f6("ArrowDown"),new Pp],[new f6("ArrowUp"),new Tp],[new f6("n",{ctrl:!0}),new Pp],[new f6("p",{ctrl:!0}),new Tp],[new f6("Enter"),new Cp],[new f6("Escape"),new VJ1],[new f6("Tab"),new Cp]]),focusNode:this._effectiveFocusNode,child:Q}),X=new zZ({actions:new Map([[Pp,new v9(this.invoke)],[Tp,new v9(this.invoke)],[Cp,new v9(this.invoke)],[VJ1,new v9(this.invoke)]]),child:Z});return new Og1({link:this.layerLink,child:X})}updateOverlay(){let J=this.controller.currentState;if(J.isActive&&J.options.length>0)if(!this.overlayEntry)this.createOverlay();else this.overlayEntry.markNeedsBuild();else this.removeOverlay()}createOverlay(){if(this.overlayEntry)return;this.overlayEntry=new Zf1((J)=>{let Q=this.controller.currentState;return this.buildOverlayContent(J,Q)});try{zN.of(this.context).insert(this.overlayEntry)}catch(J){u.error("Failed to insert autocomplete overlay:",J),this.overlayEntry=null}}removeOverlay(){if(this.overlayEntry)this.overlayEntry.remove(),this.overlayEntry=null}buildOverlayContent(J,Q){let Z=Y8.maybeOf(J),X=Z?.colorScheme.background??E1.black,Y=this.props.overlayBorderColor??Z?.colorScheme.border??E1.white,K=Q.options.length;try{let w=this.layerLink.getTargetTransform();if(w){let R=w.position.y,O=2,$=R-2;K=Math.min(K,Math.max(1,$))}}catch{}this.updateScrollPosition();let q=this.scrollOffset,G=Math.min(Q.options.length,q+K),z=[],U=0;for(let w=q;w<G;w++){let R=Q.options[w];if(!R)continue;let O=w===Q.selectedIndex,$,j;if(this.props.optionViewBuilder){$=this.props.optionViewBuilder(J,R,O);let T=this.props.displayStringForOption?.(R)??String(R),S="",x=T,h="",v=R;if(v&&typeof v==="object"&&"type"in v)switch(v.type){case"file":S="@",x=v.path||T;break;case"thread":x=v.title||T,h=v.description||"";break}j=S+x+(h?" - "+h:"")}else{let T=this.props.displayStringForOption?.(R)??String(R),S=Z?.colorScheme.selection??E1.index(8),x=Z?.colorScheme.foreground??E1.white;$=new a1({text:new D1(T,new j1({color:x,backgroundColor:O?S:void 0}))}),j=T}let E=f8.of(J),I=LY(j,E.supportsEmojiWidth);U=Math.max(U,I),z.push($)}let W=f8.sizeOf(J).width,H=U+4,F=Math.floor(W*0.9),B=Math.max(Math.min(H,F),Math.min(30,F)),N=z.length+2,L=this.props.showMenuBelow?1:-N,A=new H0({width:B,child:new g0({height:N,padding:V0.symmetric(1,0),decoration:new q9(X,m8.all(new _8(Y,1,"rounded"))),child:new u0({crossAxisAlignment:"start",children:z})})});return new Rg1({link:this.layerLink,showWhenUnlinked:!1,offset:{x:0,y:L},child:A})}}function EK6(J){if(J.kind!=="file"&&J.kind!=="folder")throw Error("Invalid completion item: missing path or kind");return{type:"file",path:J.path,kind:J.kind}}function IK6(J,Q,Z){return{type:"thread",threadId:J,title:Q,description:Z}}function Eg1(J){switch(J.type){case"file":return J.path;case"thread":return J.title;case"hint":return J.message}}function PK6(J){switch(J.type){case"file":return;case"thread":return J.description||J.title;case"hint":return}}class NN{detect(J,Q){if(!J||Q<1)return null;let Z=j2(J);if(Q>Z.length)return null;let X=this.findWordStart(Z,Q);if(X>=Z.length||Z[X]!=="@")return null;let Y=Z.slice(X+1,Q).join("");if(Y.includes(" ")||Y.includes("\t")||Y.includes(`
|
|
6621
|
-
`))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class Sp extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new TK6(this.props)}}class TK6 extends c0{props;_effectiveFocusNode;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=new NN().detect(Q,Z);if(Y)return await this.props.completionBuilder.buildOptions(Y);return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":return;case"file":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.props.onSubmitted?.(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let q=Q.slice(0,K),G=Q.slice(Z),U=`${this.props.ampURL.replace(/\/$/,"")}/threads/${J.threadId}`,W=q+`${U} `+G;this.props.controller.clear(),this.props.controller.insertText(W),this.props.controller.cursorPosition=K+U.length+1}}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new i8({debugLabel:"PromptEditorFocus"}),this.props.controller.onInsertText=(J,Q)=>{if(J.length<=3)return!0;let Z=HQ6(J);if(!Z)return!0;if(this.props.onInsertImage)return this.props.onInsertImage(Z);return!0}}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props}dispose(){if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}_handleOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{y9.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),H=z.join(W,"message.amp.md");await q(H,J,"utf-8"),Q(`${U} "${H}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let F=await X(H,"utf-8");this.props.controller.text=F}catch(F){if(F?.code!=="ENOENT")u.error("Failed to read temporary file",F)}try{await Y(H),await K(W)}catch(F){u.warn("Failed to clean up temporary file",F)}y9.instance.tuiInstance.resume()}catch(W){try{y9.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};build(J){let Q=this.props.theme,Z=this.props.imageAttachments.length>0?new g0({padding:V0.only({bottom:1,left:1}),child:new a1({text:new D1("",void 0,[new D1("Images: ",new j1({color:Q.foreground,dim:!0})),...this.props.imageAttachments.flatMap((Y,K)=>[new D1(`[image ${K+1}]`,new j1({color:Q.success})),...K<this.props.imageAttachments.length-1?[new D1(" ")]:[]])])})}):null,X=new NJ1({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(Y)=>Eg1(Y),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,canStealFocus:this.props.canStealFocus??!0,showMenuBelow:this.props.showMenuBelow??!1,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:this.props.autofocus??!1,enabled:this.props.enabled??!0,onSubmitted:this.props.onSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:{character:"Enter"},prompts:this.props.shellPromptRules,style:{border:null},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0},optionViewBuilder:(Y,K,q)=>{let G=q?Q.selection:void 0,z=K.type==="thread"?Q.warning:Q.secondary,U=Q.foreground,W=Q.foreground,H,F;switch(K.type){case"file":H="@",F=K.path;break;case"thread":H="@",F=K.title;break;case"hint":H="",F=K.message;break;default:H="",F=Eg1(K);break}let B=PK6(K),M=new D1(H,new j1({color:z})),V=new D1(F,new j1({color:U})),N=[M,V];if(B){let L=new D1(" - ",new j1({color:W,dim:!0})),A=new D1(B,new j1({color:W,dim:!0}));N.push(L,A)}return new g0({decoration:new q9(G),child:new a1({text:new D1("",void 0,N),maxLines:1,overflow:"ellipsis"})})}});if(Z)return new u0({crossAxisAlignment:"start",children:[Z,X]});return X}requestFocus(){this._effectiveFocusNode.requestFocus()}}D9();a8();class CK6 extends c0{controller=new sK;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new i8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=Li)return!1;let Q=t71(J);if(Q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=A6.of(J),{colors:Z,app:X}=Q,Y=m8.all(new _8(Z.foreground,1,"solid")),q=f8.of(J).size.height,G=Math.max(Math.floor(q*0.5),10),z=new Sp({controller:this.controller,triggers:[new NN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(M)=>{this.widget.props.onSubmit(M.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:!0,autofocus:!0,canStealFocus:!0,clipboard:y9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments}),U=new t8({focusNode:this.focusNode,child:z}),W=new g0({constraints:new j6({maxHeight:G}),child:U}),H=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1("",void 0,[new D1("Command: ",new j1({color:Z.foreground})),new D1(this.widget.props.commandName,new j1({color:E1.yellow,bold:!0}))])})}),F=new g0({padding:V0.symmetric(1,0),child:new a1({text:this.isConfirmingClearInput?new D1("",void 0,[new D1("Esc",new j1({color:X.keybind})),new D1(" again to clear input",new j1({color:Z.foreground,dim:!0}))]):new D1("",void 0,[new D1("Press ",new j1({color:Z.foreground,dim:!0})),new D1("Enter",new j1({color:X.keybind})),new D1(" to submit, ",new j1({color:Z.foreground,dim:!0})),new D1("Esc",new j1({color:X.keybind})),new D1(" to clear",new j1({color:Z.foreground,dim:!0}))])})}),B=[H,new H0({height:1}),new R8({child:W}),new H0({height:1}),F];return new g0({decoration:{border:Y,color:E1.default()},padding:V0.all(1),child:new u0({children:B})})}}class Ig1 extends l0{props;constructor(J){super();this.props=J}createState(){return new CK6}}a8();var xQ9=/[\\/_ +.#"@[({&]/,bQ9=/[\\/_ +.#"@[({&]/g,yQ9=/[\s-]/,SK6=/[\s-]/g;function AJ1(J,Q,Z,X,Y,K,q){if(K===Q.length){if(Y===J.length)return 1;return 0.99}let G=`${Y},${K}`;if(q[G]!==void 0)return q[G];let z=X.charAt(K),U=Z.indexOf(z,Y),W=0,H,F,B,M;while(U>=0){if(H=AJ1(J,Q,Z,X,U+1,K+1,q),H>W){if(U===Y)H*=1;else if(yQ9.test(J.charAt(U-1))){if(H*=0.9,M=J.slice(Y,U-1).match(SK6),M&&Y>0)H*=Math.pow(0.999,M.length)}else if(xQ9.test(J.charAt(U-1))){if(H*=0.8,B=J.slice(Y,U-1).match(bQ9),B&&Y>0)H*=Math.pow(0.999,B.length)}else if(H*=0.3,Y>0)H*=Math.pow(0.999,U-Y);if(J.charAt(U)!==Q.charAt(K))H*=0.9999}if(H<0.1&&(Z.charAt(U-1)===X.charAt(K+1)||X.charAt(K+1)===X.charAt(K)&&Z.charAt(U-1)!==X.charAt(K))){if(F=AJ1(J,Q,Z,X,U+1,K+2,q),F*0.1>H)H=F*0.1}if(H>W)W=H;U=Z.indexOf(z,U+1)}return q[G]=W,W}function LJ1(J){return J.toLowerCase().replace(SK6," ")}function vK6(J,Q){let Z=AJ1(J,Q,LJ1(J),LJ1(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let Y=0,K=0;for(let G of X){let z=AJ1(J,G,LJ1(J),LJ1(G),0,0,{});if(z===0)return Z;Y+=z,K+=G.length}let q=Y/X.length*0.95;return Math.max(Z,q)}return Z}class hC{}class gC{}class wJ1{}class RJ1{}class kK6 extends l0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new _K6}}class _K6 extends c0{build(J){return this.widget.onContext(J),this.widget.child}}function fQ9(J,Q){if(J==="")return{matches:!0,score:1};let Z=vK6(Q,J);return{matches:Z>0.15,score:Z}}class yR extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xK6}}class xK6 extends c0{controller=new sK;focusNode;scrollController=new OY;selectedIndex=0;itemContexts=[];initState(){this.focusNode=new i8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}didUpdateWidget(J){if(J.props.items!==this.widget.props.items)e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof hC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof gC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof wJ1){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof RJ1)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text;return this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...fQ9(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)}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,X=Q.size.height;R51(J,{top:Z,bottom:X},{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(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let X=Z[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!Y){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=A6.of(J),{colors:Z}=Q,X=this.getFilteredItems(),Y=m8.all(new _8(Z.foreground,1,"solid")),K=this.widget.props.enabled??!0,q=new sF({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{textColor:Z.foreground,border:null},maxLines:1}),G=new hG({shortcuts:new Map([[new f6("ArrowDown"),new hC],[new f6("ArrowUp"),new gC],[new f6("Tab"),new hC],[new f6("Tab",{shift:!0}),new gC],[new f6("n",{ctrl:!0}),new hC],[new f6("p",{ctrl:!0}),new gC],[new f6("Enter"),new wJ1],[new f6("Escape"),new RJ1]]),focusNode:this.focusNode,child:q}),z=new zZ({actions:new Map([[hC,new v9(this.invoke)],[gC,new v9(this.invoke)],[wJ1,new v9(this.invoke)],[RJ1,new v9(this.invoke)]]),child:G}),U=new Q8({children:[new g0({decoration:{color:E1.default()},child:new a1({text:new D1(">",new j1({color:Z.foreground}))})}),new R8({child:z})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";W=new H0({height:10,child:new J2({child:new a1({text:new D1(B,new j1({color:Z.foreground}))})})})}else{let B=X.map((M,V)=>{let N=V===this.selectedIndex,L=this.widget.props.isItemDisabled?.(M)??!1,A;if(this.widget.props.renderItem)A=this.widget.props.renderItem(M,N,L,J);else{let w=N?E1.yellow:void 0,R=N?E1.black:Z.foreground;A=new g0({decoration:w?{color:w}:void 0,padding:V0.symmetric(2,0),child:new a1({text:new D1(this.widget.props.getLabel(M),new j1({color:R,dim:L}))})})}return new kK6(new b9({onClick:(w)=>this.handleItemClick(V,w.clickCount),child:A}),(w)=>{this.itemContexts[V]=w})});W=new u0({children:B,crossAxisAlignment:"start"})}let H=new R8({child:new b9({onScroll:this.handleScroll,opaque:!1,child:new gG({controller:this.scrollController,autofocus:!1,child:W})})}),F=[];if(this.widget.props.title){let B=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(this.widget.props.title,new j1({color:E1.yellow,bold:!0}))})});F.push(B)}return F.push(U,new H0({height:1}),H),new g0({decoration:{border:Y,color:E1.default()},padding:V0.symmetric(1,0),child:new u0({children:F})})}}class Pg1 extends O6{props;debugLabel="CommandPalette";constructor(J){super();this.props=J}build(J){let{context:Q,enabled:Z,paletteController:X,commands:Y,onExecuteResult:K,onDismiss:q}=this.props,G=Y.getAllCommands(),z="";return new yR({items:G,enabled:Z??!0,isItemDisabled:(W)=>W.isEnabled?!W.isEnabled(Q):!1,filterItem:(W,H)=>{if(H==="")return W.isEnabled?W.isEnabled(Q):!0;return!0},getLabel:(W)=>{let H=W.noun?`${W.noun.toLowerCase()} ${W.verb.toLowerCase()}`:W.verb.toLowerCase(),F=W.getPromptText&&W.getPromptText(Q),B=W.aliases?W.aliases.join(" "):"",M=F?`${H} ${F}`:H;return B?`${M} ${B}`:M},sortItems:(W,H,F)=>{if(z=F,F!==""){let B=Y.getCommandFollows(W.item.id),M=Y.getCommandFollows(H.item.id);if(B.includes(H.item.id))return 1;if(M.includes(W.item.id))return-1}if(H.score!==W.score)return H.score-W.score;return Y.getPriority(H.item.id,Q)-Y.getPriority(W.item.id,Q)},onAccept:async(W)=>{let H=W.gatherArguments?await W.gatherArguments(Q,X):void 0;if(W.gatherArguments&&!H)return;if(W.nonBlocking)return Y.execute(W.id,Q,H),q();let F=await Y.execute(W.id,Q,H);if(F)K(F);else q()},onDismiss:q,title:"Command Palette",renderItem:(W,H,F,B)=>{let M=A6.of(B),{colors:V}=M,N=H?E1.yellow:void 0,L=H?E1.black:V.foreground,A=F||!H,w=[];if(W.noun)w.push(new D1(W.noun.toLowerCase(),new j1({color:L,dim:A}))),w.push(new D1(": ",new j1({color:L,dim:A})));let R=W.verb.toLowerCase(),O=R.match(/^(\$_|md)\s+(.+)$/);if(O)w.push(new D1(O[1],new j1({color:E1.blue,bold:!0,dim:F}))),w.push(new D1(" ")),w.push(new D1(O[2],new j1({color:L,bold:!0,dim:F})));else w.push(new D1(R,new j1({color:L,bold:!0,dim:F})));if(F)w.push(new D1(" (unavailable)",new j1({color:L,dim:!0})));let $=W.getPromptText&&W.getPromptText(Q);if($&&!F)w.push(new D1(' "',new j1({color:L,dim:F}))),w.push(new D1($,new j1({color:L,dim:F}))),w.push(new D1('"',new j1({color:L,dim:F})));if(z&&W.aliases){let I=z.toLowerCase(),T=W.aliases.find((S)=>S.toLowerCase().includes(I));if(T)w.push(new D1(" (alias: ",new j1({color:L,dim:F}))),w.push(new D1(T,new j1({color:L,dim:F}))),w.push(new D1(")",new j1({color:L,dim:F})))}let j=[new a1({text:new D1("",void 0,w)})],E=[];if(W.shortcut){let T=W.shortcut.toString().split("+"),S=[];for(let x=0;x<T.length;x++){let h=T[x],_=h==="Ctrl"||h==="Shift"||h==="Alt"||h==="Meta"?E1.blue:E1.index(8);if(S.push(new D1(h,new j1({color:_,bold:!0,dim:F}))),x<T.length-1)S.push(new D1(" ",new j1({color:E1.index(8),dim:F})))}E.push(new a1({text:new D1("",void 0,S)}))}return new g0({decoration:N?{color:N}:void 0,padding:V0.symmetric(2,0),child:new Q8({children:[...j,new R8({child:new H0({height:1})}),...E]})})}})}}class Tg1 extends O6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.threads,Z=(q)=>`${q.messageCount} msgs`,X=Math.max(0,...Q.map((q)=>Z(q).length)),Y=Math.max(0,...Q.map((q)=>q.description.timeAgo.length)),K=Math.max(0,...Q.map((q)=>q.description.shortThreadID.length));return new yR({items:this.props.threads,getLabel:(q)=>q.title,onAccept:(q)=>this.props.onSelect?.(q.id),onDismiss:this.props.onDismiss,onSelectionChange:(q)=>this.props.onPreview?.(q?.id??null),title:"Switch Thread",isLoading:this.props.isLoading,loadingText:"Loading threads...",renderItem:(q,G,z,U)=>{let W=A6.of(U),{colors:H}=W,F=G?E1.yellow:void 0,B=G?E1.black:H.foreground,M=E1.index(8),V=(N,L)=>new H0({width:L,child:Q8.end([new a1({text:new D1(N,new j1({color:M}))})])});return new g0({decoration:F?{color:F}:void 0,padding:V0.symmetric(2,0),child:new Q8({children:[new R8({child:new a1({text:new D1(q.title,new j1({color:B})),overflow:"ellipsis",maxLines:1})}),new H0({width:2}),V(Z(q),X),new H0({width:1}),new a1({text:new D1("│",new j1({color:M}))}),new H0({width:1}),V(q.description.timeAgo,Y),new H0({width:1}),new a1({text:new D1("│",new j1({color:M}))}),new H0({width:1}),V(q.description.shortThreadID,K)]})})}})}}a8();class Cg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new bK6}}class bK6 extends c0{dispose(){super.dispose()}build(J){let Q=O51(this.widget.props.message),Z=Q.type==="error"?E1.red:E1.yellow,X=m8.all(new _8(E1.white,1,"solid")),Y=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(Q.title,new j1({color:Z,bold:!0}))})}),K=new R8({child:new LR({child:new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(Q.description,new j1({color:E1.white})),selectable:!0})})})}),q=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1("Press any key to close",new j1({color:E1.white,dim:!0,italic:!0}))})});return new t8({onKey:()=>{return this.widget.props.onDismiss(),"handled"},autofocus:!0,child:new g0({decoration:{border:X,color:E1.default()},padding:V0.all(1),child:new u0({mainAxisAlignment:"center",children:[Y,new H0({height:1}),K,q]})})})}}class Sg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new yK6}}class yK6 extends c0{activeModal=null;pushModal(J){return new Promise((Q)=>{let Z=!1,K=J((q)=>{if(Z)return;Z=!0,this.popModal(),Q(q)},()=>{if(Z)return;Z=!0,this.popModal(),Q(null)});this.setState(()=>{this.activeModal=K})})}paletteController={launchThreadPicker:async()=>await this.pushThreadPicker(),launchArgumentPrompt:async(J)=>await this.pushCommandArgumentPrompt(J),launchMultilinePrompt:async(J,Q)=>await this.pushCommandMultilinePrompt(J,Q),launchFuzzyPicker:async(J)=>await this.pushFuzzyPicker(J)};buildCommandPalette(){if(!this.widget.props.mainThread)return new H0;return new Pg1({commands:this.widget.props.commands,thread:this.widget.props.mainThread,context:this.widget.props.commandContext,onDismiss:()=>this.popModal(),paletteController:this.paletteController,onExecuteResult:(J)=>this.showMessage(J),enabled:this.activeModal===null})}async pushCommandArgumentPrompt(J){return this.pushModal((Q,Z)=>({type:"argument-prompt",commandId:J,resolve:Q,dismiss:Z}))}async pushCommandMultilinePrompt(J,Q){return this.pushModal((Z,X)=>({type:"multiline-prompt",commandId:J,placeholder:Q,resolve:Z,dismiss:X}))}async pushThreadPicker(){return this.pushModal((J,Q)=>({type:"thread-picker",resolve:J,dismiss:Q}))}async pushFuzzyPicker(J){return this.pushModal((Q,Z)=>({type:"fuzzy-picker",items:J.items,getLabel:J.getLabel,title:J.title,resolve:Q,dismiss:Z}))}showMessage(J){this.setState(()=>{this.activeModal={type:"message",message:J,dismiss:()=>{this.popModal(),this.widget.props.onDismiss()}}})}popModal(){if(this.activeModal!==null)this.setState(()=>{this.activeModal=null});else this.widget.props.onDismiss()}build(J){let Q=[this.buildCommandPalette()];if(this.activeModal!==null){let Z;switch(this.activeModal.type){case"thread-picker":Z=new Tg1({threads:this.widget.props.threads,onSelect:this.activeModal.resolve,onDismiss:this.activeModal.dismiss,onPreview:this.widget.props.onThreadPreview,isLoading:this.widget.props.isLoadingThreads});break;case"argument-prompt":Z=new wg1({commandName:this.activeModal.commandId,onSubmit:this.activeModal.resolve,onDismiss:this.activeModal.dismiss});break;case"multiline-prompt":{let X=this.activeModal;Z=new Ig1({commandName:X.commandId,placeholder:X.placeholder,onSubmit:(Y,K)=>{X.resolve({text:Y,images:K})},onDismiss:X.dismiss,completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL});break}case"fuzzy-picker":Z=new yR({items:this.activeModal.items,getLabel:this.activeModal.getLabel,title:this.activeModal.title,onAccept:this.activeModal.resolve,onDismiss:this.activeModal.dismiss});break;case"message":Z=new Cg1({message:this.activeModal.message,onDismiss:this.activeModal.dismiss});break}Q.push(Z)}return new EJ({fit:"expand",children:Q})}}W3();b6();I0();class vg1{fuzzyClient;threadIndexer;constructor(J,Q){this.fuzzyClient=J;this.threadIndexer=Q}async buildOptions(J){if(J.trigger==="@"){let[Q,Z]=await Promise.all([this.buildFileOptions(J.query),this.buildThreadMentionOptions(J.query)]);return[...Q,...Z]}return[]}async buildFileOptions(J){try{let Q=await this.getOpenFiles();return(await this.fuzzyClient.queryCompletions(J,20,Q)).map((X)=>EK6(X))}catch(Q){return[]}}async buildThreadMentionOptions(J){return(await this.threadIndexer.search(J,5)).map(({id:Z,title:X})=>IK6(Z,X,Z))}async getOpenFiles(){let J=await W6(C7.status);if(!J.connected||!J.visibleFiles?.length)return;return J.visibleFiles.map((Q)=>{return L0.parse(Q).fsPath})}}D9();class kg1 extends O6{details;constructor({key:J,details:Q}){super(J?{key:J}:{});this.details=Q}build(J){let Z=Y8.of(J).colorScheme,X=f8.of(J),Y=new j1({color:Z.primary,bold:!0}),K=new j1({color:Z.foreground}),q=new j1({color:Z.foreground}),G=new j1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,W=z-4,H=Math.min(U-4,Math.floor(U*0.6)),F=Math.min(80,W),B=new gG({autofocus:!0,child:new T6({padding:V0.only({left:2,right:2}),child:new u0({crossAxisAlignment:"start",children:[new J2({child:new a1({text:new D1(`Details
|
|
6621
|
+
`))return null;return{start:X,end:Q,query:Y,trigger:"@"}}findWordStart(J,Q){let Z=Q;for(let X=Q-1;X>=0;X--){let Y=J[X];if(!Y||/[\s([{]/.test(Y)){Z=X+1;break}if(X===0)Z=0}return Z}}class Sp extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new TK6(this.props)}}class TK6 extends c0{props;_effectiveFocusNode;constructor(J){super();this.props=J}buildOptions=async(J)=>{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=new NN().detect(Q,Z);if(Y)return await this.props.completionBuilder.buildOptions(Y);return[]};defaultOnOptionSelected=(J)=>{switch(J.type){case"hint":return;case"file":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.props.controller.clear(),this.props.controller.insertText(G),this.props.controller.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Q=this.props.controller.text,Z=this.props.controller.cursorPosition,X=Q.split(" ");if(X.length>=1&&X[0]==="/continue"){let Y=`/continue ${J.threadId} `;this.props.onSubmitted?.(Y)}else{let K=Q.slice(0,Z).lastIndexOf("@");if(K!==-1){let q=Q.slice(0,K),G=Q.slice(Z),U=`${this.props.ampURL.replace(/\/$/,"")}/threads/${J.threadId}`,W=q+`${U} `+G;this.props.controller.clear(),this.props.controller.insertText(W),this.props.controller.cursorPosition=K+U.length+1}}break}}};initState(){super.initState(),this._effectiveFocusNode=this.props.focusNode||new i8({debugLabel:"PromptEditorFocus"}),this.props.controller.onInsertText=(J,Q)=>{if(J.length<=3)return!0;let Z=HQ6(J);if(!Z)return!0;if(this.props.onInsertImage)return this.props.onInsertImage(Z);return!0}}didUpdateWidget(J){super.didUpdateWidget(J),this.props=this.widget.props}dispose(){if(!this.props.focusNode)this._effectiveFocusNode.dispose();super.dispose()}_handleOpenInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{y9.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),H=z.join(W,"message.amp.md");await q(H,J,"utf-8"),Q(`${U} "${H}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let F=await X(H,"utf-8");this.props.controller.text=F}catch(F){if(F?.code!=="ENOENT")u.error("Failed to read temporary file",F)}try{await Y(H),await K(W)}catch(F){u.warn("Failed to clean up temporary file",F)}y9.instance.tuiInstance.resume()}catch(W){try{y9.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};_handleBackspaceAtStart=()=>{if(this.props.imageAttachments.length>0&&this.props.popImage)return this.props.popImage(),!0;return!1};build(J){let Q=this.props.theme,Z=this.props.imageAttachments.length>0?new g0({padding:V0.only({bottom:1,left:1}),child:new a1({text:new D1("",void 0,[new D1("Images: ",new j1({color:Q.foreground,dim:!0})),...this.props.imageAttachments.flatMap((Y,K)=>[new D1(`[image ${K+1}]`,new j1({color:Q.success})),...K<this.props.imageAttachments.length-1?[new D1(" ")]:[]])])})}):null,X=new NJ1({controller:this.props.controller,triggers:this.props.triggers,optionsBuilder:this.buildOptions,onSelected:this.props.onOptionSelected??this.defaultOnOptionSelected,displayStringForOption:(Y)=>Eg1(Y),overlayBorderColor:Q.border,focusNode:this._effectiveFocusNode,canStealFocus:this.props.canStealFocus??!0,showMenuBelow:this.props.showMenuBelow??!1,textFieldProps:{placeholder:this.props.placeholder,wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:this.props.autofocus??!1,enabled:this.props.enabled??!0,onSubmitted:this.props.onSubmitted,onOpenInEditor:this._handleOpenInEditor,submitKey:{character:"Enter"},prompts:this.props.shellPromptRules,style:{border:null},clipboard:this.props.clipboard,onCopy:this.props.onCopy,copyOnSelectionEnabled:!0,onBackspaceWhenEmpty:this._handleBackspaceAtStart},optionViewBuilder:(Y,K,q)=>{let G=q?Q.selection:void 0,z=K.type==="thread"?Q.warning:Q.secondary,U=Q.foreground,W=Q.foreground,H,F;switch(K.type){case"file":H="@",F=K.path;break;case"thread":H="@",F=K.title;break;case"hint":H="",F=K.message;break;default:H="",F=Eg1(K);break}let B=PK6(K),M=new D1(H,new j1({color:z})),V=new D1(F,new j1({color:U})),N=[M,V];if(B){let L=new D1(" - ",new j1({color:W,dim:!0})),A=new D1(B,new j1({color:W,dim:!0}));N.push(L,A)}return new g0({decoration:new q9(G),child:new a1({text:new D1("",void 0,N),maxLines:1,overflow:"ellipsis"})})}});if(Z)return new u0({crossAxisAlignment:"start",children:[Z,X]});return X}requestFocus(){this._effectiveFocusNode.requestFocus()}}D9();a8();class CK6 extends c0{controller=new sK;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new i8({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){this.focusNode.requestFocus()}_handleInsertImage=(J)=>{if(this.imageAttachments.length>=Li)return!1;let Q=t71(J);if(Q)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Q=A6.of(J),{colors:Z,app:X}=Q,Y=m8.all(new _8(Z.foreground,1,"solid")),q=f8.of(J).size.height,G=Math.max(Math.floor(q*0.5),10),z=new Sp({controller:this.controller,triggers:[new NN],completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL,onSubmitted:(M)=>{this.widget.props.onSubmit(M.trim(),this.imageAttachments)},theme:Z,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:!0,autofocus:!0,canStealFocus:!0,clipboard:y9.instance.tuiInstance.clipboard,showMenuBelow:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),U=new t8({focusNode:this.focusNode,child:z}),W=new g0({constraints:new j6({maxHeight:G}),child:U}),H=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1("",void 0,[new D1("Command: ",new j1({color:Z.foreground})),new D1(this.widget.props.commandName,new j1({color:E1.yellow,bold:!0}))])})}),F=new g0({padding:V0.symmetric(1,0),child:new a1({text:this.isConfirmingClearInput?new D1("",void 0,[new D1("Esc",new j1({color:X.keybind})),new D1(" again to clear input",new j1({color:Z.foreground,dim:!0}))]):new D1("",void 0,[new D1("Press ",new j1({color:Z.foreground,dim:!0})),new D1("Enter",new j1({color:X.keybind})),new D1(" to submit, ",new j1({color:Z.foreground,dim:!0})),new D1("Esc",new j1({color:X.keybind})),new D1(" to clear",new j1({color:Z.foreground,dim:!0}))])})}),B=[H,new H0({height:1}),new R8({child:W}),new H0({height:1}),F];return new g0({decoration:{border:Y,color:E1.default()},padding:V0.all(1),child:new u0({children:B})})}}class Ig1 extends l0{props;constructor(J){super();this.props=J}createState(){return new CK6}}a8();var xQ9=/[\\/_ +.#"@[({&]/,bQ9=/[\\/_ +.#"@[({&]/g,yQ9=/[\s-]/,SK6=/[\s-]/g;function AJ1(J,Q,Z,X,Y,K,q){if(K===Q.length){if(Y===J.length)return 1;return 0.99}let G=`${Y},${K}`;if(q[G]!==void 0)return q[G];let z=X.charAt(K),U=Z.indexOf(z,Y),W=0,H,F,B,M;while(U>=0){if(H=AJ1(J,Q,Z,X,U+1,K+1,q),H>W){if(U===Y)H*=1;else if(yQ9.test(J.charAt(U-1))){if(H*=0.9,M=J.slice(Y,U-1).match(SK6),M&&Y>0)H*=Math.pow(0.999,M.length)}else if(xQ9.test(J.charAt(U-1))){if(H*=0.8,B=J.slice(Y,U-1).match(bQ9),B&&Y>0)H*=Math.pow(0.999,B.length)}else if(H*=0.3,Y>0)H*=Math.pow(0.999,U-Y);if(J.charAt(U)!==Q.charAt(K))H*=0.9999}if(H<0.1&&(Z.charAt(U-1)===X.charAt(K+1)||X.charAt(K+1)===X.charAt(K)&&Z.charAt(U-1)!==X.charAt(K))){if(F=AJ1(J,Q,Z,X,U+1,K+2,q),F*0.1>H)H=F*0.1}if(H>W)W=H;U=Z.indexOf(z,U+1)}return q[G]=W,W}function LJ1(J){return J.toLowerCase().replace(SK6," ")}function vK6(J,Q){let Z=AJ1(J,Q,LJ1(J),LJ1(Q),0,0,{}),X=Q.trim().split(/\s+/);if(X.length>1){let Y=0,K=0;for(let G of X){let z=AJ1(J,G,LJ1(J),LJ1(G),0,0,{});if(z===0)return Z;Y+=z,K+=G.length}let q=Y/X.length*0.95;return Math.max(Z,q)}return Z}class hC{}class gC{}class wJ1{}class RJ1{}class kK6 extends l0{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new _K6}}class _K6 extends c0{build(J){return this.widget.onContext(J),this.widget.child}}function fQ9(J,Q){if(J==="")return{matches:!0,score:1};let Z=vK6(Q,J);return{matches:Z>0.15,score:Z}}class yR extends l0{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new xK6}}class xK6 extends c0{controller=new sK;focusNode;scrollController=new OY;selectedIndex=0;itemContexts=[];initState(){this.focusNode=new i8({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.getFilteredItems();this.widget.props.onSelectionChange?.(Q[0]??null)});let J=this.getFilteredItems();this.widget.props.onSelectionChange?.(J[0]??null),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}didUpdateWidget(J){if(J.props.items!==this.widget.props.items)e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof hC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof gC){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof wJ1){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Z=Q[this.selectedIndex];if(Z){if(!(this.widget.props.isItemDisabled?.(Z)??!1))this.widget.props.onAccept(Z)}}return"handled"}if(J instanceof RJ1)return this.widget.props.onDismiss?.(),"handled";return"ignored"};getFilteredItems(){let J=this.controller.text;return this.widget.props.items.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...fQ9(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)}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Z=0,X=Q.size.height;R51(J,{top:Z,bottom:X},{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(),e9.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Z=this.getFilteredItems();if(J>=0&&J<Z.length){let X=Z[J],Y=X?this.widget.props.isItemDisabled?.(X)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Z[this.selectedIndex]??null);else if(Q===2&&!Y){if(X)this.widget.props.onAccept(X)}}};build(J){let Q=A6.of(J),{colors:Z}=Q,X=this.getFilteredItems(),Y=m8.all(new _8(Z.foreground,1,"solid")),K=this.widget.props.enabled??!0,q=new sF({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:K,style:{textColor:Z.foreground,border:null},maxLines:1}),G=new hG({shortcuts:new Map([[new f6("ArrowDown"),new hC],[new f6("ArrowUp"),new gC],[new f6("Tab"),new hC],[new f6("Tab",{shift:!0}),new gC],[new f6("n",{ctrl:!0}),new hC],[new f6("p",{ctrl:!0}),new gC],[new f6("Enter"),new wJ1],[new f6("Escape"),new RJ1]]),focusNode:this.focusNode,child:q}),z=new zZ({actions:new Map([[hC,new v9(this.invoke)],[gC,new v9(this.invoke)],[wJ1,new v9(this.invoke)],[RJ1,new v9(this.invoke)]]),child:G}),U=new Q8({children:[new g0({decoration:{color:E1.default()},child:new a1({text:new D1(">",new j1({color:Z.foreground}))})}),new R8({child:z})]});this.itemContexts=[];let W;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";W=new H0({height:10,child:new J2({child:new a1({text:new D1(B,new j1({color:Z.foreground}))})})})}else{let B=X.map((M,V)=>{let N=V===this.selectedIndex,L=this.widget.props.isItemDisabled?.(M)??!1,A;if(this.widget.props.renderItem)A=this.widget.props.renderItem(M,N,L,J);else{let w=N?E1.yellow:void 0,R=N?E1.black:Z.foreground;A=new g0({decoration:w?{color:w}:void 0,padding:V0.symmetric(2,0),child:new a1({text:new D1(this.widget.props.getLabel(M),new j1({color:R,dim:L}))})})}return new kK6(new b9({onClick:(w)=>this.handleItemClick(V,w.clickCount),child:A}),(w)=>{this.itemContexts[V]=w})});W=new u0({children:B,crossAxisAlignment:"start"})}let H=new R8({child:new b9({onScroll:this.handleScroll,opaque:!1,child:new gG({controller:this.scrollController,autofocus:!1,child:W})})}),F=[];if(this.widget.props.title){let B=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(this.widget.props.title,new j1({color:E1.yellow,bold:!0}))})});F.push(B)}return F.push(U,new H0({height:1}),H),new g0({decoration:{border:Y,color:E1.default()},padding:V0.symmetric(1,0),child:new u0({children:F})})}}class Pg1 extends O6{props;debugLabel="CommandPalette";constructor(J){super();this.props=J}build(J){let{context:Q,enabled:Z,paletteController:X,commands:Y,onExecuteResult:K,onDismiss:q}=this.props,G=Y.getAllCommands(),z="";return new yR({items:G,enabled:Z??!0,isItemDisabled:(W)=>W.isEnabled?!W.isEnabled(Q):!1,filterItem:(W,H)=>{if(H==="")return W.isEnabled?W.isEnabled(Q):!0;return!0},getLabel:(W)=>{let H=W.noun?`${W.noun.toLowerCase()} ${W.verb.toLowerCase()}`:W.verb.toLowerCase(),F=W.getPromptText&&W.getPromptText(Q),B=W.aliases?W.aliases.join(" "):"",M=F?`${H} ${F}`:H;return B?`${M} ${B}`:M},sortItems:(W,H,F)=>{if(z=F,F!==""){let B=Y.getCommandFollows(W.item.id),M=Y.getCommandFollows(H.item.id);if(B.includes(H.item.id))return 1;if(M.includes(W.item.id))return-1}if(H.score!==W.score)return H.score-W.score;return Y.getPriority(H.item.id,Q)-Y.getPriority(W.item.id,Q)},onAccept:async(W)=>{let H=W.gatherArguments?await W.gatherArguments(Q,X):void 0;if(W.gatherArguments&&!H)return;if(W.nonBlocking)return Y.execute(W.id,Q,H),q();let F=await Y.execute(W.id,Q,H);if(F)K(F);else q()},onDismiss:q,title:"Command Palette",renderItem:(W,H,F,B)=>{let M=A6.of(B),{colors:V}=M,N=H?E1.yellow:void 0,L=H?E1.black:V.foreground,A=F||!H,w=[];if(W.noun)w.push(new D1(W.noun.toLowerCase(),new j1({color:L,dim:A}))),w.push(new D1(": ",new j1({color:L,dim:A})));let R=W.verb.toLowerCase(),O=R.match(/^(\$_|md)\s+(.+)$/);if(O)w.push(new D1(O[1],new j1({color:E1.blue,bold:!0,dim:F}))),w.push(new D1(" ")),w.push(new D1(O[2],new j1({color:L,bold:!0,dim:F})));else w.push(new D1(R,new j1({color:L,bold:!0,dim:F})));if(F)w.push(new D1(" (unavailable)",new j1({color:L,dim:!0})));let $=W.getPromptText&&W.getPromptText(Q);if($&&!F)w.push(new D1(' "',new j1({color:L,dim:F}))),w.push(new D1($,new j1({color:L,dim:F}))),w.push(new D1('"',new j1({color:L,dim:F})));if(z&&W.aliases){let I=z.toLowerCase(),T=W.aliases.find((S)=>S.toLowerCase().includes(I));if(T)w.push(new D1(" (alias: ",new j1({color:L,dim:F}))),w.push(new D1(T,new j1({color:L,dim:F}))),w.push(new D1(")",new j1({color:L,dim:F})))}let j=[new a1({text:new D1("",void 0,w)})],E=[];if(W.shortcut){let T=W.shortcut.toString().split("+"),S=[];for(let x=0;x<T.length;x++){let h=T[x],_=h==="Ctrl"||h==="Shift"||h==="Alt"||h==="Meta"?E1.blue:E1.index(8);if(S.push(new D1(h,new j1({color:_,bold:!0,dim:F}))),x<T.length-1)S.push(new D1(" ",new j1({color:E1.index(8),dim:F})))}E.push(new a1({text:new D1("",void 0,S)}))}return new g0({decoration:N?{color:N}:void 0,padding:V0.symmetric(2,0),child:new Q8({children:[...j,new R8({child:new H0({height:1})}),...E]})})}})}}class Tg1 extends O6{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.threads,Z=(q)=>`${q.messageCount} msgs`,X=Math.max(0,...Q.map((q)=>Z(q).length)),Y=Math.max(0,...Q.map((q)=>q.description.timeAgo.length)),K=Math.max(0,...Q.map((q)=>q.description.shortThreadID.length));return new yR({items:this.props.threads,getLabel:(q)=>q.title,onAccept:(q)=>this.props.onSelect?.(q.id),onDismiss:this.props.onDismiss,onSelectionChange:(q)=>this.props.onPreview?.(q?.id??null),title:"Switch Thread",isLoading:this.props.isLoading,loadingText:"Loading threads...",renderItem:(q,G,z,U)=>{let W=A6.of(U),{colors:H}=W,F=G?E1.yellow:void 0,B=G?E1.black:H.foreground,M=E1.index(8),V=(N,L)=>new H0({width:L,child:Q8.end([new a1({text:new D1(N,new j1({color:M}))})])});return new g0({decoration:F?{color:F}:void 0,padding:V0.symmetric(2,0),child:new Q8({children:[new R8({child:new a1({text:new D1(q.title,new j1({color:B})),overflow:"ellipsis",maxLines:1})}),new H0({width:2}),V(Z(q),X),new H0({width:1}),new a1({text:new D1("│",new j1({color:M}))}),new H0({width:1}),V(q.description.timeAgo,Y),new H0({width:1}),new a1({text:new D1("│",new j1({color:M}))}),new H0({width:1}),V(q.description.shortThreadID,K)]})})}})}}a8();class Cg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new bK6}}class bK6 extends c0{dispose(){super.dispose()}build(J){let Q=O51(this.widget.props.message),Z=Q.type==="error"?E1.red:E1.yellow,X=m8.all(new _8(E1.white,1,"solid")),Y=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(Q.title,new j1({color:Z,bold:!0}))})}),K=new R8({child:new LR({child:new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1(Q.description,new j1({color:E1.white})),selectable:!0})})})}),q=new g0({padding:V0.symmetric(1,0),child:new a1({text:new D1("Press any key to close",new j1({color:E1.white,dim:!0,italic:!0}))})});return new t8({onKey:()=>{return this.widget.props.onDismiss(),"handled"},autofocus:!0,child:new g0({decoration:{border:X,color:E1.default()},padding:V0.all(1),child:new u0({mainAxisAlignment:"center",children:[Y,new H0({height:1}),K,q]})})})}}class Sg1 extends l0{props;constructor(J){super();this.props=J}createState(){return new yK6}}class yK6 extends c0{activeModal=null;pushModal(J){return new Promise((Q)=>{let Z=!1,K=J((q)=>{if(Z)return;Z=!0,this.popModal(),Q(q)},()=>{if(Z)return;Z=!0,this.popModal(),Q(null)});this.setState(()=>{this.activeModal=K})})}paletteController={launchThreadPicker:async()=>await this.pushThreadPicker(),launchArgumentPrompt:async(J)=>await this.pushCommandArgumentPrompt(J),launchMultilinePrompt:async(J,Q)=>await this.pushCommandMultilinePrompt(J,Q),launchFuzzyPicker:async(J)=>await this.pushFuzzyPicker(J)};buildCommandPalette(){if(!this.widget.props.mainThread)return new H0;return new Pg1({commands:this.widget.props.commands,thread:this.widget.props.mainThread,context:this.widget.props.commandContext,onDismiss:()=>this.popModal(),paletteController:this.paletteController,onExecuteResult:(J)=>this.showMessage(J),enabled:this.activeModal===null})}async pushCommandArgumentPrompt(J){return this.pushModal((Q,Z)=>({type:"argument-prompt",commandId:J,resolve:Q,dismiss:Z}))}async pushCommandMultilinePrompt(J,Q){return this.pushModal((Z,X)=>({type:"multiline-prompt",commandId:J,placeholder:Q,resolve:Z,dismiss:X}))}async pushThreadPicker(){return this.pushModal((J,Q)=>({type:"thread-picker",resolve:J,dismiss:Q}))}async pushFuzzyPicker(J){return this.pushModal((Q,Z)=>({type:"fuzzy-picker",items:J.items,getLabel:J.getLabel,title:J.title,resolve:Q,dismiss:Z}))}showMessage(J){this.setState(()=>{this.activeModal={type:"message",message:J,dismiss:()=>{this.popModal(),this.widget.props.onDismiss()}}})}popModal(){if(this.activeModal!==null)this.setState(()=>{this.activeModal=null});else this.widget.props.onDismiss()}build(J){let Q=[this.buildCommandPalette()];if(this.activeModal!==null){let Z;switch(this.activeModal.type){case"thread-picker":Z=new Tg1({threads:this.widget.props.threads,onSelect:this.activeModal.resolve,onDismiss:this.activeModal.dismiss,onPreview:this.widget.props.onThreadPreview,isLoading:this.widget.props.isLoadingThreads});break;case"argument-prompt":Z=new wg1({commandName:this.activeModal.commandId,onSubmit:this.activeModal.resolve,onDismiss:this.activeModal.dismiss});break;case"multiline-prompt":{let X=this.activeModal;Z=new Ig1({commandName:X.commandId,placeholder:X.placeholder,onSubmit:(Y,K)=>{X.resolve({text:Y,images:K})},onDismiss:X.dismiss,completionBuilder:this.widget.props.completionBuilder,ampURL:this.widget.props.ampURL});break}case"fuzzy-picker":Z=new yR({items:this.activeModal.items,getLabel:this.activeModal.getLabel,title:this.activeModal.title,onAccept:this.activeModal.resolve,onDismiss:this.activeModal.dismiss});break;case"message":Z=new Cg1({message:this.activeModal.message,onDismiss:this.activeModal.dismiss});break}Q.push(Z)}return new EJ({fit:"expand",children:Q})}}W3();b6();I0();class vg1{fuzzyClient;threadIndexer;constructor(J,Q){this.fuzzyClient=J;this.threadIndexer=Q}async buildOptions(J){if(J.trigger==="@"){let[Q,Z]=await Promise.all([this.buildFileOptions(J.query),this.buildThreadMentionOptions(J.query)]);return[...Q,...Z]}return[]}async buildFileOptions(J){try{let Q=await this.getOpenFiles();return(await this.fuzzyClient.queryCompletions(J,20,Q)).map((X)=>EK6(X))}catch(Q){return[]}}async buildThreadMentionOptions(J){return(await this.threadIndexer.search(J,5)).map(({id:Z,title:X})=>IK6(Z,X,Z))}async getOpenFiles(){let J=await W6(C7.status);if(!J.connected||!J.visibleFiles?.length)return;return J.visibleFiles.map((Q)=>{return L0.parse(Q).fsPath})}}D9();class kg1 extends O6{details;constructor({key:J,details:Q}){super(J?{key:J}:{});this.details=Q}build(J){let Z=Y8.of(J).colorScheme,X=f8.of(J),Y=new j1({color:Z.primary,bold:!0}),K=new j1({color:Z.foreground}),q=new j1({color:Z.foreground}),G=new j1({color:Z.secondary,bold:!0}),z=X.size.width,U=X.size.height,W=z-4,H=Math.min(U-4,Math.floor(U*0.6)),F=Math.min(80,W),B=new gG({autofocus:!0,child:new T6({padding:V0.only({left:2,right:2}),child:new u0({crossAxisAlignment:"start",children:[new J2({child:new a1({text:new D1(`Details
|
|
6622
6622
|
`,Y)})}),new H0({height:1}),new a1({text:new D1(this.details,K)}),new H0({height:1})]})})}),M=new J2({child:new a1({text:new D1("",q,[new D1("Press ",q),new D1("Escape",G),new D1(" to close • Use ",q),new D1("↑↓",G),new D1(" or ",q),new D1("j/k",G),new D1(" to scroll",q)])})}),V=new u0({crossAxisAlignment:"stretch",children:[new R8({child:B}),M]});return new J2({child:new g0({constraints:new j6(F,F,0,H),decoration:new q9(Z.background,m8.all(new _8(Z.primary,1,"rounded"))),child:V})})}}G_();lv();KH();H8();a8();a8();class XB extends l0{options;onSelect;title;body;borderColor;backgroundColor;padding;selectedIndex;autofocus;showDismissalMessage;enableMouseInteraction;constructor({key:J,options:Q,onSelect:Z,title:X,body:Y,borderColor:K=E1.index(8),backgroundColor:q,padding:G=new V0(1,0,1,0),selectedIndex:z=0,autofocus:U=!0,showDismissalMessage:W=!0,enableMouseInteraction:H=!0}){super({key:J});this.options=Q,this.onSelect=Z,this.title=X,this.body=Y,this.borderColor=K,this.backgroundColor=q,this.padding=G,this.selectedIndex=Math.max(0,Math.min(z,Q.length-1)),this.autofocus=U,this.showDismissalMessage=W,this.enableMouseInteraction=H}createState(){return new fK6}}class fK6 extends c0{selectedIndex=0;focusNode=new i8({});initState(){super.initState(),this.selectedIndex=this.widget.selectedIndex,this.focusNode.addKeyHandler(this.handleKeyEvent.bind(this))}dispose(){this.focusNode.dispose(),super.dispose()}handleKeyEvent(J){let Q=(Z,X)=>{return J.key===Z&&J.shiftKey===(X?.shift??!1)&&J.ctrlKey===(X?.ctrl??!1)&&J.altKey===(X?.alt??!1)&&J.metaKey===(X?.meta??!1)};if(Q("ArrowDown")||Q("n",{ctrl:!0})||Q("Tab")||Q("j"))return this.moveSelection(1),"handled";if(Q("ArrowUp")||Q("p",{ctrl:!0})||Q("Tab",{shift:!0})||Q("k"))return this.moveSelection(-1),"handled";if(Q("Enter")){let Z=this.widget.options[this.selectedIndex];if(Z&&(Z.enabled??!0))this.widget.onSelect(Z.value);return"handled"}if(Q("Escape"))return this.widget.onSelect(null),"handled";return"ignored"}moveSelection(J){if(this.widget.options.length===0)return;let Q=this.selectedIndex+J;if(Q<0)Q=this.widget.options.length-1;else if(Q>=this.widget.options.length)Q=0;let Z=0;while(Z<this.widget.options.length){let X=this.widget.options[Q];if(X&&(X.enabled??!0))break;Q=(Q+J+this.widget.options.length)%this.widget.options.length,Z++}if(this.selectedIndex!==Q)this.setState(()=>{this.selectedIndex=Q})}build(J){if(this.widget.options.length===0)return new H0({width:0,height:0});let Q=[];if(this.widget.title)Q.push(new a1({text:new D1(this.widget.title,new j1({bold:!0}))})),Q.push(new H0({height:1}));if(this.widget.body){if(typeof this.widget.body==="string")Q.push(new a1({text:new D1(this.widget.body)}));else Q.push(this.widget.body);Q.push(new H0({height:1}))}for(let Y=0;Y<this.widget.options.length;Y++){let K=this.widget.options[Y],q=Y===this.selectedIndex,G=K.enabled??!0,z=HJ1(K,q,G&&this.widget.enableMouseInteraction?()=>this.widget.onSelect(K.value):void 0);if(Q.push(z),K.description)Q.push(new H0({height:1}))}if(this.widget.showDismissalMessage)Q.push(new H0({height:1})),Q.push(new a1({text:new D1("Escape to close",new j1({color:E1.index(8)}))}));let Z=new u0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:Q}),X=new g0({child:new T6({padding:this.widget.padding,child:Z}),decoration:new q9(this.widget.backgroundColor,m8.all(new _8(this.widget.borderColor,1,"rounded")))});return new t8({focusNode:this.focusNode,child:X,autofocus:this.widget.autofocus})}}class _g1 extends l0{confirmationRequest;onResponse;onShowOverlay;constructor({key:J,confirmationRequest:Q,onResponse:Z,onShowOverlay:X}){super({key:J});this.confirmationRequest=Q,this.onResponse=Z,this.onShowOverlay=X}createState(){return new hK6}}class hK6 extends c0{initState(){super.initState()}dispose(){super.dispose()}handleKeyEvent(J){if(J.key==="?"&&!J.shiftKey&&!J.ctrlKey&&!J.altKey&&!J.metaKey){let Q=this.getOverlayContent();if(Q&&this.widget.onShowOverlay)return this.widget.onShowOverlay(Q),"handled"}return"ignored"}getOverlayContent(){if(this.widget.confirmationRequest.type==="tool-use"&&this.widget.confirmationRequest.tools.length===1){let J=this.widget.confirmationRequest.tools[0];if(!J?.useBlock)return null;if(J.useBlock.name===l4)return J.useBlock.input.cmd;if(J.useBlock.name===AQ){let Q=J.useBlock.input;return GH(Q.old_str,Q.new_str,Q.path)}if(J.useBlock.name===SJ){let Q=J.useBlock.input,Z=Q.content||"";return GH("",Z,Q.path)}}return null}build(J){let Z=Y8.of(J).colorScheme,X=this.formatConfirmationTitle(this.widget.confirmationRequest),Y=this.createConfirmationOptions(this.widget.confirmationRequest);return new gK6({title:X,options:Y,onSelect:this.widget.onResponse,borderColor:Z.warning,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!1,onShowCommand:()=>{let q=this.getOverlayContent();if(q&&this.widget.onShowOverlay)this.widget.onShowOverlay(q)}})}formatConfirmationTitle(J){switch(J.type){case"tool-use":{if(J.tools.length===1){let Q=J.tools[0];if(Q?.useBlock)return this.formatToolConfirmation(Q.useBlock,J.reason);return"Confirm tool call"}return`Confirm ${J.tools.length} tool calls`}case"out-of-credits":return"Insufficient usage balance. Retry?";case"agent-file-creation":return`Create ${fJ} file for this codebase?`}}formatToolConfirmation(J,Q){if(J.name===l4){let Z=J.input,X=this.truncateCommand(Z.cmd),K=Z.cmd!==X?`
|
|
6623
6623
|
|
|
6624
6624
|
Press ? for full command`:"";return`${`Run this command?
|
|
@@ -6657,12 +6657,12 @@ ${J.helpMessage}`);return}if(!J.requiresManualInstall&&J.products.length===0){th
|
|
|
6657
6657
|
${this.stateNotifier.value.getDownloadPath()}.`,new j1({color:Q.colorScheme.foreground}))}),new H0({height:1}),new a1({text:new D1(`Go to Settings > Plugins > Cogwheel > Install Plugin from Disk or see
|
|
6658
6658
|
https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_disk`,new j1({color:Q.colorScheme.foreground}))}),new H0({height:1}),new a1({text:new D1(`Finally restart your JetBrains IDE${!HQ()&&" and Amp"}.`,new j1({color:Q.colorScheme.foreground}))}),new H0({height:1}),new a1({text:new D1("Press any key to exit...",new j1({color:Q.colorScheme.foreground,dim:!0}))})]})})});return new t8({autofocus:!0,onKey:(U)=>{return this.widget.onExit(),"handled"},child:z})}return new g0({decoration:new q9(Q.colorScheme.background),child:new T6({padding:V0.all(2),child:new a1({text:new D1("Discovering JetBrains IDEs...",new j1({color:Q.colorScheme.foreground}))})})})}}function uZ9(J){let Q=J.reduce((Z,X)=>{return(Z[X.name]??=[]).push(X),Z},{});return Object.entries(Q).map(([Z,X])=>({name:Z,versions:X.map((Y)=>Y.version).sort()}))}function pZ9(J){if(J.length<=1)return"";if(J.length>=3)return` (${J[0]}-${J.at(-1)})`;return` (${J.join(", ")})`}D9();a8();class tg1 extends l0{color;trigger;trail;fps;speed;leftOffset;constructor({key:J,color:Q,trigger:Z,trail:X=5,fps:Y=60,speed:K=1,leftOffset:q=0}){super(J?{key:J}:{});this.color=Q,this.trigger=Z,this.trail=X,this.fps=Y,this.speed=K,this.leftOffset=q}createState(){return new Aq6}}class Aq6 extends c0{progress=0;timer=null;initState(){this.restart()}didUpdateWidget(J){if(J.trigger!==this.widget.trigger)this.restart()}dispose(){this.stop()}restart(){this.stop(),this.progress=-this.widget.trail,this.start()}start(){if(this.timer)return;let J=Math.max(16,Math.round(1000/Math.max(1,this.widget.fps)));this.timer=setInterval(()=>{this.setState(()=>{this.progress+=this.widget.speed})},J)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}build(J){return new wq6({color:this.widget.color,trail:this.widget.trail,head:this.progress,leftOffset:this.widget.leftOffset},this.widget.key)}}class wq6 extends aF{props;constructor(J,Q){super(Q?{key:Q}:{});this.props=J}createElement(){return new qN(this)}createRenderObject(){return new Rq6(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}updateRenderObject(J){J.update(this.props.color,this.props.trail,this.props.head,this.props.leftOffset)}}class Rq6 extends J8{_color;_trail;_head;_leftOffset;constructor(J,Q,Z,X){super();this._color=J;this._trail=Q;this._head=Z;this._leftOffset=X}update(J,Q,Z,X){let Y=!1;if(Q!==this._trail)this._trail=Q,Y=!0;if(this._color=J,this._head=Z,this._leftOffset=X,Y)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let J=this._lastConstraints,Q=J.constrain(J.biggest.width,1);this.setSize(Q.width,Q.height),super.performLayout()}paint(J,Q=0,Z=0){let X=Math.floor(Q+this.offset.x),Y=Math.floor(Z+this.offset.y),K=Math.floor(this.size.width),q=[1,0.7,0.5,0.35,0.25,0.15];for(let G=0;G<=this._trail&&G<q.length;G++){let z=Math.floor(this._head)-G+this._leftOffset;if(z<this._leftOffset||z>=K)continue;let U=dZ9(this._color,q[G]);J.setChar(X+z,Y,"━",{fg:U},1)}super.paint(J,Q,Z)}}function dZ9(J,Q){if(J.type==="rgb")return E1.rgb(J.value.r,J.value.g,J.value.b,Q);if(J.type==="index")return E1.index(J.value,Q);return E1.default(Q)}class eg1 extends O6{message;onDismiss;constructor({key:J,message:Q,onDismiss:Z}){super({key:J});this.message=Q,this.onDismiss=Z}build(J){let Z=Y8.of(J).colorScheme,X=O51(this.message),Y=[{value:"dismiss",label:"Dismiss"}],K=X.type==="error"?Z.destructive:Z.primary,q=new LR({child:new a1({text:new D1(X.description),selectable:!0})});return new XB({title:X.title,body:q,options:Y,onSelect:(G)=>{this.onDismiss()},borderColor:K,autofocus:!0,showDismissalMessage:!1,enableMouseInteraction:!0})}}a8();class Jm1 extends l0{props;constructor(J){super({key:J.key});this.props=J}createState(){return new Oq6}}class Oq6 extends c0{build(J){let{queuedMessages:Q,title:Z="Queue"}=this.widget.props;if(!Array.isArray(Q)||Q.length===0)return new H0({width:0,height:0});let X=Q.map((Y)=>this.buildQueueItem(Y));return new g0({child:new T6({padding:V0.symmetric(1,0),child:new u0({crossAxisAlignment:"stretch",children:[new a1({text:new D1(Z,new j1({bold:!0}))}),...X]})})})}buildQueueItem(J){let Z=J.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join(" ").trim(),X=Z.split(`
|
|
6659
6659
|
`)[0],Y=Z.includes(`
|
|
6660
|
-
`)?`${X}...`:Z,K=new j1({color:E1.index(8)});return new T6({padding:V0.only({bottom:0}),child:new Q8({crossAxisAlignment:"start",children:[new T6({padding:V0.only({right:1}),child:new a1({text:new D1("•",new j1({color:E1.index(8)}))})}),new R8({child:new a1({text:new D1(Y,K)})})]})})}}WW();var cZ9=Q1.string(),jq6=Q1.object({id:cZ9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public_unlisted","public_discoverable","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});q0();gY();WW();var lZ9=Q1.object({id:Q1.string()});function iZ9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),q=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${q}mo ago`}class hJ1{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await hJ("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=lZ9.parse(await X.json())}catch(W){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),q=await hJ(`/api/threads?${K}`,void 0,this.configService);if(!q.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${q.status})`};let G;try{G=Q1.array(jq6).parse(await q.json())}catch(W){return u.error("failed to parse thread data from server",{error:W}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:G.filter((W)=>W.messageCount>0).filter((W)=>{if(!J.trim())return!0;let H=W.title?.toLowerCase()||"untitled",F=W.id.toLowerCase(),B=J.toLowerCase();return H.includes(B)||F.includes(B)}).slice(0,Z).map((W)=>{let H=W.title||"Untitled",F=new Date(W.updatedAt),B=iZ9(F),M=W.id.slice(-8);return{id:W.id,title:H,messageCount:W.messageCount,updatedAt:W.updatedAt,description:{timeAgo:B,title:H,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}a8();class Qm1 extends l0{props;constructor(J){super();this.props=J}createState(){return new $q6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class $q6 extends c0{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(q)=>{if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1("Loading threads...")})});let Z=f8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1("No threads found.")})});let X=this.allThreads.map((q)=>({value:q.id,label:q.title,description:this.formatThreadDescription(q)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new t8({autofocus:this.autofocus,onKey:Q,child:new vp({title:"Select a thread to continue:",options:X,onSelect:(q)=>{this.widget.props.onSelect(q)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}x51();function Eq6(J,Q){switch(J){case"update-available":return[new D1("A newer Amp is available. Run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new D1("Update complete, run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning})),new D1(" to see warnings",new j1({color:Q.foreground,dim:!0}))];case"update-error":return[new D1("Update failed, run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning})),new D1(" to see warnings",new j1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function tZ9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new j1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new j1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class Sq6 extends l0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new vq6}}class vq6 extends c0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;previewThread=null;previewCache=new Map;previewScrollController=new OY;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new i8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new i8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=qW();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new D1(this.submitDisabledHint,new j1({color:J.foreground,dim:!0}));if(this.isExiting)return new D1("Exiting...",new j1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new D1("",void 0,[new D1("Ctrl+C",new j1({color:Q.keybind})),new D1(" again to exit",new j1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new D1("",void 0,[new D1("Esc",new j1({color:Q.keybind})),new D1(" again to clear input",new j1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new D1("",void 0,[new D1("Escape",new j1({color:Q.keybind})),new D1(" to close help",new j1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=Wm1(X);return new D1("",void 0,[new D1("Images aren't supported in ",new j1({color:J.warning,dim:!1})),new D1(X,new j1({color:Y})),new D1(" mode.",new j1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new D1("",void 0,[new D1("Esc",new j1({color:Q.keybind})),new D1(" to cancel",new j1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new D1("Selection copied to clipboard",new j1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new D1(this.showingCannotToggleMessage,new j1({color:J.warning,dim:!1}));let Z=Eq6(this.updateState,J);if(Z)return new D1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){u.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let q=Q.mainThread?.messages.findIndex((G)=>G===J);if(q===void 0||q<=0)return;try{let G=await zJ.getOrCreateForThread(Z,K),z=await ur(G,X,q),U=await Y(z);tF(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let W=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=W})}catch(G){u.error("Failed to fork thread:",G),this.showErrorMessage(`Failed to fork thread: ${G}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((q)=>q===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=[{type:"text",text:Q}];if(this.imageAttachments.length>0)q.push(...this.imageAttachments);let G={content:q,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&G.agentMode!==Y.agentMode){u.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:G,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){u.error("Failed to edit message:",q)}};textController=new sK;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new OY);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(wy1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new a7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.setState(()=>{this.isShowingIdePicker=!1});return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}showCommandPalette(){if(!this.isShowingPalette)this.loadThreadsForPicker();this.setState(()=>{this.isShowingPalette=!this.isShowingPalette})}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Ag1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})});return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new vg1(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.isShowingPalette=!1,this.setState(()=>{this.previewThread=null})};handleThreadPreview=async(J)=>{if(J===null){this.setState(()=>{this.previewThread=null});return}if(this.previewCache.has(J)){this.setState(()=>{this.previewThread=this.previewCache.get(J)??null});return}let Q=await this.widget.dependencies.threadService.get(J);if(Q)this.previewCache.set(J,Q),this.setState(()=>{this.previewThread=Q})};getCommandPaletteContext=(J)=>{let{threadState:Q}=this.widget.dependencies;if(!Q.mainThread)return null;return{worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},editorDispatch:(Z)=>{switch(Z.type){case"set-input":this.textController.clear(),this.textController.insertText(Z.input);break;case"insert-text":this.textController.insertText(Z.text);break;case"clear":this.textController.clear();break}},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{let Z=await this.widget.dependencies.startNewThread();tF(Z)},switchToThread:async(Z)=>{await this.switchToExistingThread(Z)},handleHandoff:async(Z,X)=>{let Y=Z.trim();if(!Y){this.setState(()=>{this.displayMessage=Error("Cannot handoff with empty prompt text")});return}try{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let q=new AbortController,G=setTimeout(()=>q.abort(),60000);try{let z=await this.widget.dependencies.threadService.createHandoffThread(K,Y,X||[],this.widget.dependencies.configService,q.signal);clearTimeout(G),await this.switchToExistingThread(z)}catch(z){if(clearTimeout(G),z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")))throw Error("Handoff took too long and was aborted (timeout: 60s)");throw z}}catch(K){u.error("Failed to create handoff thread",K),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${K instanceof Error?K.message:String(K)}`)})}},getGuidanceFiles:async()=>{if(!Q.mainThread)return[];return(await ta({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,J.signal)).map((X)=>({uri:X.uri,type:X.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEditorText:()=>this.textController.text}};async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.setState(()=>{this.isLoadingThreads=!0});try{let Q=await new hJ1(this.widget.dependencies.configService).fetchThreadSummaries("",0,50);if(Q.ok){let Z=this.widget.dependencies.threadID;this.setState(()=>{this.threadsForPicker=Q.threads.filter((X)=>X.id!==Z)})}}finally{this.setState(()=>{this.isLoadingThreads=!1})}}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{if((MX()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=vd(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=vd(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Sd(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=Li)return!1;let Z=t71(J);if(Z)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error("Failed to attach image: file may be empty, too large, or unsupported")}),!1};openInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{y9.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),H=z.join(W,"message.amp.md");await q(H,J,"utf-8"),Q(`${U} "${H}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let F=await X(H,"utf-8");this.textController.text=F}catch(F){if(F?.code!=="ENOENT")u.error("Failed to read temporary file",F)}try{await Y(H),await K(W)}catch(F){u.warn("Failed to clean up temporary file",F)}y9.instance.tuiInstance.resume()}catch(W){try{y9.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=this.parseShellModeInput(J);if(Q){if(Q.cmd&&!this.isProcessing())this.invokeBashCommand(Q.cmd,{hidden:Q.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let Z=zQ6(J);this.textController.clear(),this.resetHistory(),await this.sendUserMessage(Z)};initState(){if(NY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;y9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),y9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),y9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{e9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=UQ6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);u.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.adSubscription=Fy1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&Hy1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=sZ9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (mJ1(),gJ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,q=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:q?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}}),tF(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=MX();if(!X){u.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),u.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),u.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=qW(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(wy1("")),this.shouldUseProgressBar())process.stdout.write(kQ6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){u.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){u.error("No tool use block found in confirmation");return}if(J==="allow-all-session")Xq("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else u.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await $X(Y)}catch(K){u.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(rG))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,rG],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await zJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){u.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();tF(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),Gy1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();tF(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await zJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{u.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;if(u.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,tF(Q),_51()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{u.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z}),Q.thread.draft)if(u.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Q.thread.draft==="string")this.textController.insertText(Q.thread.draft);else{let X=Q.thread.draft.filter((q)=>q.type==="text"),Y=Q.thread.draft.filter((q)=>q.type==="image"),K=X.map((q)=>q.text).join(`
|
|
6661
|
-
`);if(K)this.textController.insertText(K);if(Y.length>0)this.setState(()=>{this.imageAttachments=Y})}}catch(Q){throw u.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=MX()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();Gy1({agentMode:Q}).catch((Z)=>{u.warn("Failed to save session state on exit:",Z)}).finally(()=>{y9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=oZ9();if(J===Q)return"~";if(J.startsWith(Q+fp.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fp.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fp.sep),"…",Q.slice(-2).join(fp.sep)].join(fp.sep)}build(J){let Q=f8.of(J),Z=A6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let G=(MX()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new zN({child:new Qm1({onSelect:async(w1)=>{if(w1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(w1);else process.exit(0)},pageSize:50,threadFetcher:new hJ1(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,H=z.mainThread?.id,F=z.mainThread||void 0,B=this.isTranscriptEmpty(),M=(w1)=>new DJ1({key:new a7(`preview-message-view-${w1.id}`),items:Vp(w1).items,controller:this.previewScrollController,autofocus:!1,thread:w1,focusNode:new i8({debugLabel:"PreviewFocus"})}),V=this.previewThread?M(this.previewThread):B?new MJ1({agentMode:this.getEffectiveAgentMode()}):new DJ1({key:H?new a7(`message-view-${H}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:H?this.getMessageScrollController(H):new OY,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:F,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),N=Math.max(Math.floor(Q.size.height*0.4),12),L=this.getCurrentEphemeralError(),A=this.buildBottomWidget(L,U,Y,Z,z,W,N,G?this.randomAd:null),w=Q.size.width<40,R=z.mainThread?bl1(z.mainThread):void 0,O=new b51({threadViewState:z.viewState,threadTokenUsage:R,threadID:H??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:w,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),$=new k51({bashInvocations:this.bashInvocations}),j=[],E=this.getEffectiveAgentMode(),I=this.currentShellModeStatus,T=Wm1(E),S=!I?E.length+1:0,x=Q.capabilities.animationSupport,h=x==="disabled"?0:x==="slow"?30:60,v=1,_=h>0&&this.agentModePulseSeq>0?new EJ({children:[A,new DX({top:0,left:1,right:1,height:1,child:new tg1({color:T,trigger:this.agentModePulseSeq,fps:h,speed:v,leftOffset:S})})]}):A;if(j.push(new R8({child:V}),$),G)j.push(new Dg1({ad:this.randomAd,onButtonClick:async()=>{let w1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (mJ1(),gJ1)).then(({recordAdEvent:B1})=>{let y1=this.widget.dependencies.worker.thread,l1=y1.messages[y1.messages.length-1];B1("clicked",{adId:w1.id,advertiserId:w1.advertiserId,threadId:y1.id,messageId:l1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await $X(w1.shortDestinationUrl)}catch(B1){let l1=y9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:l1,url:w1.shortDestinationUrl}})}}}));j.push(new g0({constraints:new j6(0,Q.size.width,0,N),child:_}),new H0({height:1,child:new T6({padding:V0.horizontal(1),child:O})}));let b=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),g=new v9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return u.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((B1)=>{u.error("Failed to mark message as interrupted:",B1)}),this.cancelStreamingMessage().catch((B1)=>{u.error("Failed to cancel streaming message:",B1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),k=new v9(()=>{return this.onExitPressed(),"handled"}),f=new v9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),y=new v9(()=>{return NX.instance.toggleAll(),"handled"}),m=new v9(()=>{return this.widget.dependencies.configService.getLatest().then((w1)=>{Xq("internal.showCost",!(w1.settings["internal.showCost"]??!0))}),"handled"}),a=new v9(()=>{return y9.instance.toggleFrameStatsOverlay(),"handled"}),p=new v9(()=>{return y9.instance.tuiInstance.getScreen().markForRefresh(),e9.instance.requestFrame(),"handled"}),e=new v9(()=>{return this.toggleAgentMode(),"handled"}),q1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;B1.animatePageUp(l1,100)}return"handled"}),W1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;B1.animatePageDown(l1,100)}return"handled"}),Z1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1)B1.animateTo(0,100);return"handled"}),H1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1)B1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new v9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:w1}=this.widget.dependencies;if(!w1.mainThread?.messages.some((y1)=>y1.role==="user"))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),d=new v9((w1)=>{if(w1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[f6.ctrl("c"),new Zp],[f6.ctrl("l"),new Gp],[f6.ctrl("o"),new A51],[f6.alt("s"),new PC],[f6.ctrl("s"),new PC],[f6.alt("p"),new qp],[f6.ctrl("r"),new Yp],[f6.alt("d"),new Kp],[f6.key("PageUp"),new M51],[f6.key("PageDown"),new V51],[f6.key("Home"),new N51],[f6.key("End"),new L51],[f6.key("Escape"),new Qp],[f6.ctrl("p"),new TC("previous")],[f6.ctrl("n"),new TC("next")],[f6.key("Tab"),new Up]]);if(!HQ())i.set(f6.key("ArrowUp"),new Up);if(!1)i.set(f6.alt("c"),new Xp);let s=new v9(()=>{return this.showCommandPalette(),"handled"}),Y1=new Map([[Qp,g],[Gp,p],[PC,e],[A51,s],[Xp,f],[Yp,y],[Kp,m],[qp,a],[Zp,k],[M51,q1],[V51,W1],[N51,Z1],[L51,H1],[Up,l],[TC,d]]),J1=[b];if(this.isShowingConsoleOverlay)J1.push(new xg1);if(this.isShowingHelp){let w1=this.getPaletteCommands().getAllCommands();J1.push(new fg1({commands:w1}))}if(this.adActionModal)J1.push(new Mg1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(w1)=>{let B1=this.adActionModal.url;if(w1==="copy")try{await y9.instance.tuiInstance.clipboard.writeText(B1),this.setState(()=>{this.displayMessage=new oK("Link copied to clipboard")})}catch(y1){u.error("Failed to copy to clipboard",{error:y1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)J1.push(new $f1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)J1.push(new bg1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)J1.push(new kg1({details:this.confirmationOverlayContent}));let F1=this.getCommandPaletteContext(new AbortController);if(F1&&this.isShowingPalette)J1.push(new J2({child:new g0({constraints:j6.loose(80,20),child:new Sg1({commandContext:F1,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,threads:this.threadsForPicker,onThreadPreview:this.handleThreadPreview,completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,isLoadingThreads:this.isLoadingThreads})})}));if(this.isShowingIdePicker)J1.push(new hg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let z1=new EJ({children:J1});if(this.isShowingJetBrainsInstaller)return new zN({child:new zZ({actions:Y1,child:new hG({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new og1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let U1=new UN({onError:(w1)=>{this.showErrorMessage(w1.message)},child:z1});return new zN({child:new zZ({actions:Y1,child:new hG({shortcuts:i,debugLabel:"main-app-shortcuts",child:U1})})})}buildBottomWidget(J,Q,Z,X,Y,K,q,G){if(J)return new yg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new _g1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new eg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=tZ9(X),W=this.isInRestrictedFreeMode(),H=new Sp({key:this.textFieldKey,controller:this.textController,triggers:[new NN],completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:this.onTextSubmitted,theme:Z,placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!W,autofocus:!1,shellPromptRules:U,focusNode:this.autocompleteFocusNode,canStealFocus:!this.isMessageViewInSelectionMode,clipboard:y9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments}),F=Y.mainThread?.queuedMessages??[],B=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0?new Jm1({queuedMessages:F}):void 0,N=B?new fy1(new Bg1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,L=[],A=this.currentShellModeStatus;if(A)L.push({text:new D1(A==="hidden"?"shell mode (incognito)":"shell mode",new j1({color:A==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});let w=this.getEffectiveAgentMode();if(!A&&this.cachedVisibleModes.length>1){let E=Wm1(w),T=vd(w,this.cachedVisibleModes)!==w,x=(MX()||this.widget.dependencies.worker).thread.messages.length===0,v=W||!this.hasToggledAgentMode&&T&&x?new D1("",void 0,[new D1(w,new j1({color:E})),new D1(" (click or ",new j1({color:Z.foreground,dim:!0})),new D1("Ctrl+S",new j1({color:z.keybind})),new D1(" to switch)",new j1({color:Z.foreground,dim:!0}))]):new D1(w,new j1({color:E}));L.push({text:v,position:"top-left",offsetY:0,onClick:x?this.toggleAgentMode:void 0})}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let E=this.connectedClientsStatus,I=E.mode||"disconnected",T=!!E.errorMessage,S=E.clientID||"unknown",x,h;if(T)x="●",h=E1.red;else if(I==="presence")x="○",h=E1.yellow;else if(I==="connected"&&E.connected)x="●",h=E1.green;else x="○",h=E1.yellow;let v=this.connectedClientsStatusExpanded?`${S} ${x}`:x;L.push({text:new D1(v,new j1({color:h})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let R=Y.mainThread?.metadata?.treeInfo?.uri,O;if(R)O=L0.isUri(R)?R.fsPath:R;else O=process.cwd();let $=this.toHomeRelative(O),j=this.shorten($);return L.push({text:new D1(j,new j1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Bf1({leftChild:new R8({child:H}),rightChild1:V,rightChild2:N,maxHeight:q,overlayTexts:L,borderColor:W||!this.isTextfieldAndAutocompleteFocused?E1.index(8):void 0,hasBanner:G!==null})}}async function kq6(J){if(J.threadDependencies&&process.env.AMP_CONNECT==="1"){let{startAutomaticPresence:F}=await Promise.resolve().then(() => (Um1(),zm1));F(J.threadDependencies,J.configService,J.connectedClientsService,J.clientId,J.startNewThread).catch((B)=>{u.error("Failed to start automatic presence:",B)})}let Z=!1,X=new cF(Z,1000,J.inspectorPort),Y=new Rf1({threadService:J.threadService,worker:J.worker,builder:(F,B)=>{let M=MX(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new Sq6({...N,threadState:B})}}),K=new Lf1({configService:J.configService,child:Y}),q=new Mf1({configService:J.configService,child:K}),G=new sy1(q),z=new A6({data:SC.fromBaseTheme(rK.default()),child:G});try{await by1(z,{onRootElementMounted:Z?(F)=>{X.start(F)}:void 0})}finally{if(Z)X.stop();if(J.threadDependencies&&process.env.AMP_CONNECT==="1"){let{stopGlobalSession:F}=await Promise.resolve().then(() => (Um1(),zm1));F()}}let W=MX()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let F=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6660
|
+
`)?`${X}...`:Z,K=new j1({color:E1.index(8)});return new T6({padding:V0.only({bottom:0}),child:new Q8({crossAxisAlignment:"start",children:[new T6({padding:V0.only({right:1}),child:new a1({text:new D1("•",new j1({color:E1.index(8)}))})}),new R8({child:new a1({text:new D1(Y,K)})})]})})}}WW();var cZ9=Q1.string(),jq6=Q1.object({id:cZ9,title:Q1.string().optional(),messageCount:Q1.number(),updatedAt:Q1.string(),firstSyncAt:Q1.string(),created:Q1.number(),creatorUserID:Q1.string(),meta:Q1.object({visibility:Q1.enum(["private","public_unlisted","public_discoverable","thread_workspace_shared"]),sharedGroupIDs:Q1.array(Q1.string())})});q0();gY();WW();var lZ9=Q1.object({id:Q1.string()});function iZ9(J){let Z=new Date().getTime()-J.getTime(),X=Math.floor(Z/3600000),Y=Math.floor(X/24),K=Math.floor(Y/7),q=Math.floor(Y/30);if(X<1)return"Just now";if(X<24)return`${X}h ago`;if(Y<7)return`${Y}d ago`;if(K<=4)return`${K}w ago`;return`${q}mo ago`}class hJ1{configService;constructor(J){this.configService=J}async fetchThreadSummaries(J="",Q=0,Z=20){try{let X=await hJ("/api/user",void 0,this.configService);if(!X.ok)return{ok:!1,errorMsg:`Failed to get user info (${X.status})`};let Y;try{Y=lZ9.parse(await X.json())}catch(W){return{ok:!1,errorMsg:"Invalid user data format from server"}}let K=new URLSearchParams({createdByUserID:Y.id,limit:String(Z),offset:String(Q*Z)}),q=await hJ(`/api/threads?${K}`,void 0,this.configService);if(!q.ok)return{ok:!1,errorMsg:`Failed to fetch threads (${q.status})`};let G;try{G=Q1.array(jq6).parse(await q.json())}catch(W){return u.error("failed to parse thread data from server",{error:W}),{ok:!1,errorMsg:"Invalid thread data format from server"}}return{ok:!0,threads:G.filter((W)=>W.messageCount>0).filter((W)=>{if(!J.trim())return!0;let H=W.title?.toLowerCase()||"untitled",F=W.id.toLowerCase(),B=J.toLowerCase();return H.includes(B)||F.includes(B)}).slice(0,Z).map((W)=>{let H=W.title||"Untitled",F=new Date(W.updatedAt),B=iZ9(F),M=W.id.slice(-8);return{id:W.id,title:H,messageCount:W.messageCount,updatedAt:W.updatedAt,description:{timeAgo:B,title:H,shortThreadID:M}}})}}catch(X){return{ok:!1,errorMsg:X instanceof Error?X.message:"An unexpected error occurred"}}}}a8();class Qm1 extends l0{props;constructor(J){super();this.props=J}createState(){return new $q6(this.props.pageSize,this.props.loadBuffer,this.props.autofocus??!0)}}class $q6 extends c0{pageSize;loadBuffer;autofocus;allThreads=[];isLoading=!1;currentPage=0;hasMoreToLoad=!0;error=null;constructor(J=20,Q=J*2,Z){super();this.pageSize=J;this.loadBuffer=Q;this.autofocus=Z}async initState(){await this.loadThreads()}async loadThreads(){if(this.isLoading||!this.hasMoreToLoad)return;this.isLoading=!0,this.error=null;try{let J=await this.widget.props.threadFetcher.fetchThreadSummaries("",this.currentPage,this.pageSize);if(!this.mounted)return;if(!J.ok){this.error=J.errorMsg,this.hasMoreToLoad=!1,this.setState();return}let Q=J.threads;if(Q.length===0)this.hasMoreToLoad=!1;else{let Z=new Set(this.allThreads.map((Y)=>Y.id)),X=Q.filter((Y)=>!Z.has(Y.id));this.allThreads=[...this.allThreads,...X],this.currentPage++}this.setState()}finally{this.isLoading=!1}}onChange=async(J)=>{if(this.allThreads.length-J<=this.loadBuffer&&this.hasMoreToLoad&&!this.isLoading)await this.loadThreads()};formatThreadDescription(J){let Z=`${String(J.messageCount)} msgs`.padEnd(8),X=J.description.timeAgo.padEnd(9);return`${Z} │ ${X}│ ${J.description.shortThreadID}`}build(J){let Q=(q)=>{if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"};if(this.error)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1(this.error)})});if(this.isLoading&&this.allThreads.length===0)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1("Loading threads...")})});let Z=f8.sizeOf(J);if(this.allThreads.length===0&&!this.isLoading)return new t8({autofocus:this.autofocus,onKey:Q,child:new a1({text:new D1("No threads found.")})});let X=this.allThreads.map((q)=>({value:q.id,label:q.title,description:this.formatThreadDescription(q)})),Y=Math.max(5,Z.height);Y-=6;let K=Math.floor(Math.max(1,Y/2));return new t8({autofocus:this.autofocus,onKey:Q,child:new vp({title:"Select a thread to continue:",options:X,onSelect:(q)=>{this.widget.props.onSelect(q)},onChange:this.onChange,maxVisibleItems:K,autofocus:this.autofocus})})}}x51();function Eq6(J,Q){switch(J){case"update-available":return[new D1("A newer Amp is available. Run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning}))];case"updated":return null;case"updated-with-warning":return[new D1("Update complete, run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning})),new D1(" to see warnings",new j1({color:Q.foreground,dim:!0}))];case"update-error":return[new D1("Update failed, run ",new j1({color:Q.foreground,dim:!0})),new D1("amp update",new j1({color:Q.warning})),new D1(" to see warnings",new j1({color:Q.foreground,dim:!0}))];case"hidden":return null}}function tZ9(J){return[{match:(Q)=>Q.startsWith("$$"),display:"$$",style:new j1({color:J.app.shellModeHidden}),spacing:1,concealPrefix:!0},{match:(Q)=>Q.startsWith("$")&&!Q.startsWith("$$"),display:"$",style:new j1({color:J.app.shellMode}),spacing:1,concealPrefix:!0}]}class Sq6 extends l0{dependencies;constructor(J){super();this.dependencies=J}createState(){return new vq6}}class vq6 extends c0{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;connectedClientsStatus=null;connectedClientsStatusExpanded=!1;randomAd=null;adSubscription=null;lastAdImpressionId=null;lastUserInteractionTime=Date.now();isConfirmingExit=!1;isExiting=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;isShowingCostBreakdownOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;isShowingPalette=!1;threadsForPicker=[];isLoadingThreads=!1;previewThread=null;previewCache=new Map;previewScrollController=new OY;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;agentModePulseSeq=0;messageViewFocusNode=new i8({debugLabel:"MessageViewFocus"});autocompleteFocusNode=new i8({debugLabel:"AutocompleteFocus"});isTextfieldAndAutocompleteFocused=!1;submitDisabledHint=null;submitDisabledHintTimer=null;showingCannotToggleMessage=null;showImageUnsupportedHint=!1;imageUnsupportedHintTimer=null;adActionModal=null;agentModeSubscription=null;currentAgentMode="smart";hasToggledAgentMode=!1;inMemoryAgentModeOverride=null;cachedVisibleModes=qW();freeTierStatus=void 0;updateState="hidden";updateServiceSubscription=null;isMessageViewInSelectionMode=!1;getEffectiveAgentMode(){return this.inMemoryAgentModeOverride??this.currentAgentMode}isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;if(J.viewState.state!=="active")return!1;if(Boolean(J.viewState.inferenceState==="running"))return!0;let Z=J.items.filter((K)=>K.type==="toolResult").filter((K)=>K.toolResult.run.status==="in-progress"||K.toolResult.run.status==="queued"),X=J.subagentActiveTools.filter((K)=>K.toolRun.status==="in-progress"||K.toolRun.status==="queued");return[...Z,...X].length>0}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new D1(this.submitDisabledHint,new j1({color:J.foreground,dim:!0}));if(this.isExiting)return new D1("Exiting...",new j1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new D1("",void 0,[new D1("Ctrl+C",new j1({color:Q.keybind})),new D1(" again to exit",new j1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new D1("",void 0,[new D1("Esc",new j1({color:Q.keybind})),new D1(" again to clear input",new j1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new D1("",void 0,[new D1("Escape",new j1({color:Q.keybind})),new D1(" to close help",new j1({color:J.foreground,dim:!0}))]);if(this.showImageUnsupportedHint){let X=this.getEffectiveAgentMode(),Y=Wm1(X);return new D1("",void 0,[new D1("Images aren't supported in ",new j1({color:J.warning,dim:!1})),new D1(X,new j1({color:Y})),new D1(" mode.",new j1({color:J.warning,dim:!1}))])}if(this.isProcessing()||this.bashInvocations.length>0)return new D1("",void 0,[new D1("Esc",new j1({color:Q.keybind})),new D1(" to cancel",new j1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new D1("Selection copied to clipboard",new j1({color:J.foreground,dim:!0}));if(this.showingCannotToggleMessage)return new D1(this.showingCannotToggleMessage,new j1({color:J.warning,dim:!1}));let Z=Eq6(this.updateState,J);if(Z)return new D1("",void 0,Z);return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}handleMessageRestoreSubmit=async(J)=>{let{threadState:Q,worker:Z}=this.widget.dependencies;if(!Q.mainThread?.id)return;let Y=Q.mainThread?.messages.findIndex((K)=>K===J);if(Y===void 0||Y===-1)return;try{this.cancelBashInvocations(),await Z.cancel(),await Z.handle({type:"thread:truncate",fromIndex:Y}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(K){u.error("Failed to edit message:",K)}};forkMessage=async(J)=>{let{threadState:Q,workerDeps:Z,threadSyncService:X,switchToThread:Y}=this.widget.dependencies,K=Q.mainThread?.id;if(!K)return;let q=Q.mainThread?.messages.findIndex((G)=>G===J);if(q===void 0||q<=0)return;try{let G=await zJ.getOrCreateForThread(Z,K),z=await ur(G,X,q),U=await Y(z);tF(U),this.widget.dependencies.worker=U,this.widget.dependencies.threadID=U.thread.id;let W=U.thread.agentMode??null;this.setState(()=>{this.inMemoryAgentModeOverride=W})}catch(G){u.error("Failed to fork thread:",G),this.showErrorMessage(`Failed to fork thread: ${G}`)}};handleMessageEditSubmit=async(J,Q)=>{let{threadState:Z,worker:X}=this.widget.dependencies,Y=Z.mainThread;if(!Y)return;let K=Y.messages.findIndex((q)=>q===J);if(K===-1)return;try{this.cancelBashInvocations(),await X.cancel(),this.widget.dependencies.history.add(Q);let q=[{type:"text",text:Q}];if(this.imageAttachments.length>0)q.push(...this.imageAttachments);let G={content:q,agentMode:Y.agentMode},z=K===0;if(Y.agentMode&&!z&&G.agentMode!==Y.agentMode){u.error(`Cannot edit message: This thread uses ${Y.agentMode} mode. To change mode, create a new thread.`);return}await X.handle({type:"user:message",message:G,index:K}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})}catch(q){u.error("Failed to edit message:",q)}};textController=new sK;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new OY);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(wy1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new a7("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;connectedClientsStatusSubscription=null;paletteCommands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text;if(J==="/"){this.showCommandPalette(),this.textController.clear();return}let Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J,Q)=>{if(this.widget.dependencies.ideClient.getSelectedConfig()?.pid===J.pid){this.setState(()=>{this.isShowingIdePicker=!1});return}try{await this.connectToSelectedIde(J,Q)}catch(Z){let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})}this.widget.dependencies.ideClient.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J,Q){await this.widget.dependencies.ideClient.start(J,!0,Q)}showCommandPalette(){if(!this.isShowingPalette)this.loadThreadsForPicker();this.setState(()=>{this.isShowingPalette=!this.isShowingPalette})}getPaletteCommands(){if(!this.paletteCommands)this.paletteCommands=new Ag1(this.widget.dependencies.configService,this.widget.dependencies.commandRegistry,(J)=>{this.setState(()=>{this.executingCommand=J})},()=>{this.setState(()=>{this.executingCommand=null})});return this.paletteCommands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new vg1(this.widget.dependencies.fuzzyServer,this.widget.dependencies.threadFuzzyIndexer);return this.completionBuilder}dismissPalette=()=>{this.isShowingPalette=!1,this.setState(()=>{this.previewThread=null})};handleThreadPreview=async(J)=>{if(J===null){this.setState(()=>{this.previewThread=null});return}if(this.previewCache.has(J)){this.setState(()=>{this.previewThread=this.previewCache.get(J)??null});return}let Q=await this.widget.dependencies.threadService.get(J);if(Q)this.previewCache.set(J,Q),this.setState(()=>{this.previewThread=Q})};getCommandPaletteContext=(J)=>{let{threadState:Q}=this.widget.dependencies;if(!Q.mainThread)return null;return{worker:this.widget.dependencies.worker,editorState:this.textController,isProcessing:this.isProcessing(),thread:Q.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,configService:this.widget.dependencies.configService,openInEditor:this.openInEditor,takeImageAttachments:()=>{let Z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),Z},editorDispatch:(Z)=>{switch(Z.type){case"set-input":this.textController.clear(),this.textController.insertText(Z.input);break;case"insert-text":this.textController.insertText(Z.text);break;case"clear":this.textController.clear();break}},submitMessage:(Z)=>{return this.proceedWithUserMessage(Z)},exitApp:this.exitApplication,openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,clientId:this.widget.dependencies.clientId,connectedClientsService:this.widget.dependencies.connectedClientsService,startNewThread:async()=>{let Z=await this.widget.dependencies.startNewThread();tF(Z)},switchToThread:async(Z)=>{await this.switchToExistingThread(Z)},handleHandoff:async(Z,X)=>{let Y=Z.trim();if(!Y){this.setState(()=>{this.displayMessage=Error("Cannot handoff with empty prompt text")});return}try{let K=this.widget.dependencies.threadState.mainThread?.id;if(!K){this.setState(()=>{this.displayMessage=Error("No active thread")});return}let q=new AbortController,G=setTimeout(()=>q.abort(),60000);try{let z=await this.widget.dependencies.threadService.createHandoffThread(K,Y,X||[],this.widget.dependencies.configService,q.signal);clearTimeout(G),await this.switchToExistingThread(z)}catch(z){if(clearTimeout(G),z instanceof Error&&(z.name==="AbortError"||z.message.includes("aborted")))throw Error("Handoff took too long and was aborted (timeout: 60s)");throw z}}catch(K){u.error("Failed to create handoff thread",K),this.setState(()=>{this.displayMessage=Error(`Failed to create handoff: ${K instanceof Error?K.message:String(K)}`)})}},getGuidanceFiles:async()=>{if(!Q.mainThread)return[];return(await ta({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Q.mainThread,J.signal)).map((X)=>({uri:X.uri,type:X.type}))},openIdePicker:()=>{this.openIdePicker()},getInMemoryAgentModeOverride:()=>{return this.inMemoryAgentModeOverride},setInMemoryAgentModeOverride:(Z)=>{this.setState(()=>{this.inMemoryAgentModeOverride=Z,this.hasToggledAgentMode=!0})},toggleAgentMode:this.toggleAgentMode,getEditorText:()=>this.textController.text}};async loadThreadsForPicker(){if(this.isLoadingThreads)return;this.setState(()=>{this.isLoadingThreads=!0});try{let Q=await new hJ1(this.widget.dependencies.configService).fetchThreadSummaries("",0,50);if(Q.ok){let Z=this.widget.dependencies.threadID;this.setState(()=>{this.threadsForPicker=Q.threads.filter((X)=>X.id!==Z)})}}finally{this.setState(()=>{this.isLoadingThreads=!1})}}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};toggleConnectedClientsStatus=()=>{this.setState(()=>{this.connectedClientsStatusExpanded=!this.connectedClientsStatusExpanded})};toggleAgentMode=()=>{if((MX()||this.widget.dependencies.worker).thread.messages.length>0)return;if(this.freeTierStatus?.canUseAmpFree){let X=this.inMemoryAgentModeOverride??this.currentAgentMode,Y=vd(X,this.cachedVisibleModes);if(Y!==X)this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Y,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1});return}let Q=this.inMemoryAgentModeOverride??this.currentAgentMode,Z=vd(Q,this.cachedVisibleModes);if(Z===Q)return;if(this.setState(()=>{this.hasToggledAgentMode=!0,this.inMemoryAgentModeOverride=Z,this.agentModePulseSeq++,this.showingCannotToggleMessage=null,this.showImageUnsupportedHint=!1}),Z==="free")this.checkAndShowFreeModeModal()};checkAndShowFreeModeModal=()=>{if(this.freeTierStatus?.canUseAmpFree)return;if(this.freeTierStatus){if(!this.freeTierStatus.eligible){this.setState(()=>{this.showingCannotToggleMessage="Amp Free is unavailable. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}else if(!this.freeTierStatus.workspaceAllowsAmpFree){this.setState(()=>{this.showingCannotToggleMessage="Your workspace does not allow Amp Free. Switch to another mode."}),setTimeout(()=>{this.setState(()=>{this.showingCannotToggleMessage=null})},3000);return}}};isInRestrictedFreeMode(){if(this.getEffectiveAgentMode()!=="free")return!1;if(this.freeTierStatus?.canUseAmpFree)return!1;return!0}handleInsertImage=(J)=>{let Q=this.getEffectiveAgentMode();if(!Sd(Q)){if(this.imageUnsupportedHintTimer)clearTimeout(this.imageUnsupportedHintTimer);return this.setState(()=>{this.showImageUnsupportedHint=!0}),this.imageUnsupportedHintTimer=setTimeout(()=>{this.setState(()=>{this.showImageUnsupportedHint=!1}),this.imageUnsupportedHintTimer=null},5000),!1}if(this.imageAttachments.length>=Li)return!1;let Z=t71(J);if(Z)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z]}),!1;return this.setState(()=>{this.displayMessage=Error("Failed to attach image: file may be empty, too large, or unsupported")}),!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};openInEditor=async(J)=>{let{execSync:Q}=await import("node:child_process"),{mkdtemp:Z,readFile:X,unlink:Y,rmdir:K,writeFile:q}=await import("node:fs/promises"),{tmpdir:G}=await import("node:os"),z=await import("node:path"),U=process.env.EDITOR||process.env.VISUAL||"nano";try{y9.instance.tuiInstance.suspend();let W=await Z(z.join(G(),"amp-edit-")),H=z.join(W,"message.amp.md");await q(H,J,"utf-8"),Q(`${U} "${H}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let F=await X(H,"utf-8");this.textController.text=F}catch(F){if(F?.code!=="ENOENT")u.error("Failed to read temporary file",F)}try{await Y(H),await K(W)}catch(F){u.warn("Failed to clean up temporary file",F)}y9.instance.tuiInstance.resume()}catch(W){try{y9.instance.tuiInstance.resume()}catch{}u.error("Error opening editor:",W)}};onTextSubmitted=async(J)=>{if(!J.trim())return;let Q=this.parseShellModeInput(J);if(Q){if(Q.cmd&&!this.isProcessing())this.invokeBashCommand(Q.cmd,{hidden:Q.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let Z=zQ6(J);this.textController.clear(),this.resetHistory(),await this.sendUserMessage(Z)};initState(){if(NY.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;y9.instance.on("key",()=>{this.lastUserInteractionTime=Date.now()}),y9.instance.on("mouse",()=>{this.lastUserInteractionTime=Date.now()}),y9.instance.on("paste",()=>{this.lastUserInteractionTime=Date.now()}),this.autocompleteFocusNode.addListener((Z)=>{e9.instance.addPostFrameCallback(()=>{this.setState(()=>{this.isTextfieldAndAutocompleteFocused=Z.hasFocus})})}),this.freeTierStatus=this.widget.dependencies.freeTierStatus;let J=UQ6(this.widget.dependencies.worker.thread,this.widget.dependencies.sessionState??null,this.freeTierStatus);u.info(`[initState] Resolved agentMode: ${J}`),this.inMemoryAgentModeOverride=J,this.adSubscription=Fy1(this.widget.dependencies.internalAPIClient,this.widget.dependencies.configService,()=>{return(this.inMemoryAgentModeOverride==="free"||this.randomAd===null)&&Hy1(this.lastUserInteractionTime)}).subscribe({next:(Z)=>{if(Z){let X=sZ9(16).toString("hex");this.lastAdImpressionId=X,Promise.resolve().then(() => (mJ1(),gJ1)).then(({recordAdEvent:Y})=>{let K=this.widget.dependencies.worker.thread,q=K.messages[K.messages.length-1];Y("viewed",{adId:Z.id,advertiserId:Z.advertiserId,threadId:K.id,messageId:q?.messageId,impressionId:X,placement:"tui"})})}this.setState(()=>{this.randomAd=Z})}}),tF(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Z)=>{this.setState(()=>{this.ideStatus=Z})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Z)=>{let X=MX();if(!X){u.warn("No active thread worker found to handle IDE message");return}await new Promise((Y)=>setTimeout(Y,50)),await X.handle({type:"user:message",message:{content:[{type:"text",text:Z}]}}),u.debug("Message sent from IDE to agent",{message:Z.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Z)=>{this.textController.insertText(Z),u.debug("Appended text to CLI prompt from IDE",{text:Z.slice(0,100)})}),this.connectedClientsStatusSubscription=this.widget.dependencies.connectedClientsService.status.subscribe((Z)=>{this.setState(()=>{this.connectedClientsStatus=Z})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Z)=>{this.setState(()=>{this.updateState=Z})}),this.agentModeSubscription=this.widget.dependencies.configService.config.subscribe((Z)=>{let X=qW(Z.settings);this.setState(()=>{this.cachedVisibleModes=X})}),this.textController.addListener(this.textChangeListener),this.updateTerminalTitle();let Q=this.widget.dependencies.ideClient.getSelectedConfig();if(Q)this.connectToSelectedIde(Q,"auto-startup").catch((Z)=>{let X=Z instanceof Error?Z.message:String(Z);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${X}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.connectedClientsStatusSubscription)this.connectedClientsStatusSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.adSubscription)this.adSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.textController.removeListener(this.textChangeListener);for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(wy1("")),this.shouldUseProgressBar())process.stdout.write(kQ6())}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,X=[...J.items.filter((G)=>G.type==="toolResult").map((G)=>({toolUse:G.toolUse,toolRun:G.toolResult.run,subthreadID:void 0})),...J.subagentActiveTools].filter((G)=>G.toolRun.status==="blocked-on-user");if(X.length===0)return null;let Y=X[0],K=Y.toolRun.status==="blocked-on-user"?Y.toolRun.toAllow??[]:[],q=Y.toolRun.status==="blocked-on-user"?Y.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:Y.toolUse,toAllow:K}],subthreadID:Y.subthreadID,reason:q}}shouldUseProgressBar(){return!1}updateProgressBar(){}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){u.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){u.error("No tool use block found in confirmation");return}if(J==="allow-all-session")Xq("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0,"global")}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else u.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q,"global")}if(J==="connect-github"){let Y=new URL("/settings#code-host-connections",this.widget.dependencies.ampURL).toString();try{await $X(Y)}catch(K){u.error("Failed to open settings page:",K),await this.showErrorMessage(`Cannot open browser. Please go to ${Y} to connect to GitHub`)}return}if(J==="disable-librarian"){let Y=await this.widget.dependencies.settingsStorage.get("tools.disable")??[];if(!Y.includes(rG))await this.widget.dependencies.settingsStorage.set("tools.disable",[...Y,rG],"global")}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await zJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){u.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break;case"new-thread":{this.setState(()=>{this.dismissedEphemeralErrorKey=null});let X=await this.widget.dependencies.startNewThread();tF(X);break}case"new-smart-thread":{this.setState(()=>{this.inMemoryAgentModeOverride="smart",this.dismissedEphemeralErrorKey=null}),Gy1({agentMode:"smart"});let X=await this.widget.dependencies.startNewThread();tF(X);break}}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await zJ.cancel(this.widget.dependencies.threadID)};markLastUserMessageAsInterrupted=async()=>{let J=this.widget.dependencies.threadState.mainThread;if(!J)return;for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z?.role==="user"&&!Z.interrupted){await this.widget.dependencies.worker.handle({type:"user:message:interrupt",messageIndex:Q});break}}};switchToExistingThread=async(J)=>{try{u.info(`[switchToExistingThread] Switching to thread: ${J}`);let Q=await this.widget.dependencies.switchToThread(J),Z=Q.thread.agentMode??null;if(u.info(`[switchToExistingThread] Thread ${J} has agentMode: ${Z??"null"}`),this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,tF(Q),_51()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{u.info(`[switchToExistingThread] Setting inMemoryAgentModeOverride to: ${Z??"null"}`),this.inMemoryAgentModeOverride=Z}),Q.thread.draft)if(u.info("[switchToExistingThread] Loading draft content into text controller"),this.textController.clear(),typeof Q.thread.draft==="string")this.textController.insertText(Q.thread.draft);else{let X=Q.thread.draft.filter((q)=>q.type==="text"),Y=Q.thread.draft.filter((q)=>q.type==="image"),K=X.map((q)=>q.text).join(`
|
|
6661
|
+
`);if(K)this.textController.insertText(K);if(Y.length>0)this.setState(()=>{this.imageAttachments=Y})}}catch(Q){throw u.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=MX()||this.widget.dependencies.worker,Z=Q.thread.messages.length===0,X=this.getEffectiveAgentMode();if(Q.thread.agentMode&&!Z&&X!==Q.thread.agentMode){await this.showErrorMessage(`This thread uses ${Q.thread.agentMode} mode. To change mode, edit the first message or create a new thread.`);return}let Y=[{type:"text",text:J}];if(this.imageAttachments.length>0)Y.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Y,agentMode:this.getEffectiveAgentMode()}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}exitApplication=async()=>{this.setState(()=>{this.isExiting=!0});let J=this.widget.dependencies.threadState.mainThread;if(J?.messages.length===0){if(J.relationships?.find((X)=>X.type==="handoff"&&X.role==="child"))await this.widget.dependencies.threadService.discardHandoffThread(J.id).catch(()=>{})}let Q=this.getEffectiveAgentMode();Gy1({agentMode:Q}).catch((Z)=>{u.warn("Failed to save session state on exit:",Z)}).finally(()=>{y9.instance.stop()})};onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;this.exitApplication()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=oZ9();if(J===Q)return"~";if(J.startsWith(Q+fp.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fp.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fp.sep),"…",Q.slice(-2).join(fp.sep)].join(fp.sep)}build(J){let Q=f8.of(J),Z=A6.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let G=(MX()||this.widget.dependencies.worker).thread.agentMode==="free"&&this.randomAd!==null,{threadState:z}=this.widget.dependencies;if(this.isShowingThreadPicker)return new zN({child:new Qm1({onSelect:async(w1)=>{if(w1)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(w1);else process.exit(0)},pageSize:50,threadFetcher:new hJ1(this.widget.dependencies.configService)})});this.updateTerminalTitle(),this.updateProgressBar();let U=this.getCurrentConfirmation(),W=z.todosList,H=z.mainThread?.id,F=z.mainThread||void 0,B=this.isTranscriptEmpty(),M=(w1)=>new DJ1({key:new a7(`preview-message-view-${w1.id}`),items:Vp(w1).items,controller:this.previewScrollController,autofocus:!1,thread:w1,focusNode:new i8({debugLabel:"PreviewFocus"})}),V=this.previewThread?M(this.previewThread):B?new MJ1({agentMode:this.getEffectiveAgentMode()}):new DJ1({key:H?new a7(`message-view-${H}`):void 0,items:z.items,subagentToolsByParentID:z.subagentToolsByParentID,controller:H?this.getMessageScrollController(H):new OY,autofocus:!1,onCopy:this._handleTextCopy.bind(this),thread:F,onMessageEditSubmit:this.handleMessageEditSubmit,onMessageRestoreSubmit:this.handleMessageRestoreSubmit,onMessageForkSubmit:this.forkMessage,focusNode:this.messageViewFocusNode,onDismissFocus:()=>{this.setState(()=>{this.isMessageViewInSelectionMode=!1}),this.autocompleteFocusNode.requestFocus()},isInSelectionMode:this.isMessageViewInSelectionMode}),N=Math.max(Math.floor(Q.size.height*0.4),12),L=this.getCurrentEphemeralError(),A=this.buildBottomWidget(L,U,Y,Z,z,W,N,G?this.randomAd:null),w=Q.size.width<40,R=z.mainThread?bl1(z.mainThread):void 0,O=new b51({threadViewState:z.viewState,threadTokenUsage:R,threadID:H??null,thread:z.mainThread??void 0,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},onCostBreakdownClick:()=>{this.setState(()=>{this.isShowingCostBreakdownOverlay=!this.isShowingCostBreakdownOverlay})},onShowIdePicker:this.openIdePicker,ideStatus:this.ideStatus,connectedClientsStatus:this.connectedClientsStatus,isNarrow:w,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!U,showingEphemeralError:Boolean(z.viewState.state==="active"&&z.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null,executingCommandMessage:this.executingCommand?.statusMessage??null}),$=new k51({bashInvocations:this.bashInvocations}),j=[],E=this.getEffectiveAgentMode(),I=this.currentShellModeStatus,T=Wm1(E),S=!I?E.length+1:0,x=Q.capabilities.animationSupport,h=x==="disabled"?0:x==="slow"?30:60,v=1,_=h>0&&this.agentModePulseSeq>0?new EJ({children:[A,new DX({top:0,left:1,right:1,height:1,child:new tg1({color:T,trigger:this.agentModePulseSeq,fps:h,speed:v,leftOffset:S})})]}):A;if(j.push(new R8({child:V}),$),G)j.push(new Dg1({ad:this.randomAd,onButtonClick:async()=>{let w1=this.randomAd;if(this.lastAdImpressionId)Promise.resolve().then(() => (mJ1(),gJ1)).then(({recordAdEvent:B1})=>{let y1=this.widget.dependencies.worker.thread,l1=y1.messages[y1.messages.length-1];B1("clicked",{adId:w1.id,advertiserId:w1.advertiserId,threadId:y1.id,messageId:l1?.messageId,impressionId:this.lastAdImpressionId,placement:"tui",actionType:"link_to"})});try{await $X(w1.shortDestinationUrl)}catch(B1){let l1=y9.instance.tuiInstance.clipboard.isOsc52Supported();this.setState(()=>{this.adActionModal={showCopyOption:l1,url:w1.shortDestinationUrl}})}}}));j.push(new g0({constraints:new j6(0,Q.size.width,0,N),child:_}),new H0({height:1,child:new T6({padding:V0.horizontal(1),child:O})}));let b=new u0({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),g=new v9(()=>{if(this.isShowingPalette)return this.dismissPalette(),"handled";if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingCostBreakdownOverlay)return this.setState(()=>{this.isShowingCostBreakdownOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.textController.hasSelection)return this.textController.clearSelection(),"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return u.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.markLastUserMessageAsInterrupted().catch((B1)=>{u.error("Failed to mark message as interrupted:",B1)}),this.cancelStreamingMessage().catch((B1)=>{u.error("Failed to cancel streaming message:",B1)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),k=new v9(()=>{return this.onExitPressed(),"handled"}),f=new v9(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),y=new v9(()=>{return NX.instance.toggleAll(),"handled"}),m=new v9(()=>{return this.widget.dependencies.configService.getLatest().then((w1)=>{Xq("internal.showCost",!(w1.settings["internal.showCost"]??!0))}),"handled"}),a=new v9(()=>{return y9.instance.toggleFrameStatsOverlay(),"handled"}),p=new v9(()=>{return y9.instance.tuiInstance.getScreen().markForRefresh(),e9.instance.requestFrame(),"handled"}),e=new v9(()=>{return this.toggleAgentMode(),"handled"}),q1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;B1.animatePageUp(l1,100)}return"handled"}),W1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1){let y1=Math.max(Math.floor(Q.size.height*0.4),10),l1=Q.size.height-y1;B1.animatePageDown(l1,100)}return"handled"}),Z1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1)B1.animateTo(0,100);return"handled"}),H1=new v9(()=>{let B1=this.isShowingPalette&&this.previewThread?this.previewScrollController:(()=>{let{threadState:y1}=this.widget.dependencies,l1=y1.mainThread?.id;return l1?this.getMessageScrollController(l1):null})();if(B1)B1.animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),l=new v9(()=>{if(!this.isTextfieldAndAutocompleteFocused)return"ignored";let{threadState:w1}=this.widget.dependencies;if(!w1.mainThread?.messages.some((y1)=>y1.role==="user"))return"ignored";return this.setState(()=>{this.isMessageViewInSelectionMode=!0}),"handled"}),d=new v9((w1)=>{if(w1.direction==="previous")this.navigateHistoryPrevious();else this.navigateHistoryNext();return"handled"}),i=new Map([[f6.ctrl("c"),new Zp],[f6.ctrl("l"),new Gp],[f6.ctrl("o"),new A51],[f6.alt("s"),new PC],[f6.ctrl("s"),new PC],[f6.alt("p"),new qp],[f6.ctrl("r"),new Yp],[f6.alt("d"),new Kp],[f6.key("PageUp"),new M51],[f6.key("PageDown"),new V51],[f6.key("Home"),new N51],[f6.key("End"),new L51],[f6.key("Escape"),new Qp],[f6.ctrl("p"),new TC("previous")],[f6.ctrl("n"),new TC("next")],[f6.key("Tab"),new Up]]);if(!HQ())i.set(f6.key("ArrowUp"),new Up);if(!1)i.set(f6.alt("c"),new Xp);let s=new v9(()=>{return this.showCommandPalette(),"handled"}),Y1=new Map([[Qp,g],[Gp,p],[PC,e],[A51,s],[Xp,f],[Yp,y],[Kp,m],[qp,a],[Zp,k],[M51,q1],[V51,W1],[N51,Z1],[L51,H1],[Up,l],[TC,d]]),J1=[b];if(this.isShowingConsoleOverlay)J1.push(new xg1);if(this.isShowingHelp){let w1=this.getPaletteCommands().getAllCommands();J1.push(new fg1({commands:w1}))}if(this.adActionModal)J1.push(new Mg1({title:"Failed to open browser",message:this.adActionModal.url,showCopyOption:this.adActionModal.showCopyOption,onSelect:async(w1)=>{let B1=this.adActionModal.url;if(w1==="copy")try{await y9.instance.tuiInstance.clipboard.writeText(B1),this.setState(()=>{this.displayMessage=new oK("Link copied to clipboard")})}catch(y1){u.error("Failed to copy to clipboard",{error:y1}),this.setState(()=>{this.displayMessage=Error("Failed to copy to clipboard")})}this.setState(()=>{this.adActionModal=null})}}));if(this.isShowingFileChangesOverlay)J1.push(new $f1);if(this.isShowingCostBreakdownOverlay&&z.mainThread)J1.push(new bg1({thread:z.mainThread}));if(this.isShowingConfirmationOverlay)J1.push(new kg1({details:this.confirmationOverlayContent}));let F1=this.getCommandPaletteContext(new AbortController);if(F1&&this.isShowingPalette)J1.push(new J2({child:new g0({constraints:j6.loose(80,20),child:new Sg1({commandContext:F1,mainThread:z.mainThread,commands:this.getPaletteCommands(),onDismiss:this.dismissPalette,threads:this.threadsForPicker,onThreadPreview:this.handleThreadPreview,completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,isLoadingThreads:this.isLoadingThreads})})}));if(this.isShowingIdePicker)J1.push(new hg1({onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection,jetbrainsMode:this.widget.dependencies.jetbrainsMode}));let z1=new EJ({children:J1});if(this.isShowingJetBrainsInstaller)return new zN({child:new zZ({actions:Y1,child:new hG({shortcuts:i,debugLabel:"jetbrains-installer-shortcuts",child:new og1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});let U1=new UN({onError:(w1)=>{this.showErrorMessage(w1.message)},child:z1});return new zN({child:new zZ({actions:Y1,child:new hG({shortcuts:i,debugLabel:"main-app-shortcuts",child:U1})})})}buildBottomWidget(J,Q,Z,X,Y,K,q,G){if(J)return new yg1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new _g1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new eg1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let z=X.app,U=tZ9(X),W=this.isInRestrictedFreeMode(),H=new Sp({key:this.textFieldKey,controller:this.textController,triggers:[new NN],completionBuilder:this.getCompletionBuilder(),ampURL:this.widget.dependencies.ampURL,onSubmitted:this.onTextSubmitted,theme:Z,placeholder:W?"Amp Free is not enabled. Press Ctrl+S to switch modes.":void 0,enabled:this.isTextfieldAndAutocompleteFocused&&!W,autofocus:!1,shellPromptRules:U,focusNode:this.autocompleteFocusNode,canStealFocus:!this.isMessageViewInSelectionMode,clipboard:y9.instance.tuiInstance.clipboard,onCopy:this._handleTextCopy.bind(this),onInsertImage:this.handleInsertImage,imageAttachments:this.imageAttachments,popImage:this.handlePopImage}),F=Y.mainThread?.queuedMessages??[],B=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0?new Jm1({queuedMessages:F}):void 0,N=B?new fy1(new Bg1({todos:K,enabled:this.isTextfieldAndAutocompleteFocused&&!W}),{clipBehavior:"antiAlias"}):void 0,L=[],A=this.currentShellModeStatus;if(A)L.push({text:new D1(A==="hidden"?"shell mode (incognito)":"shell mode",new j1({color:A==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left"});let w=this.getEffectiveAgentMode();if(!A&&this.cachedVisibleModes.length>1){let E=Wm1(w),T=vd(w,this.cachedVisibleModes)!==w,x=(MX()||this.widget.dependencies.worker).thread.messages.length===0,v=W||!this.hasToggledAgentMode&&T&&x?new D1("",void 0,[new D1(w,new j1({color:E})),new D1(" (click or ",new j1({color:Z.foreground,dim:!0})),new D1("Ctrl+S",new j1({color:z.keybind})),new D1(" to switch)",new j1({color:Z.foreground,dim:!0}))]):new D1(w,new j1({color:E}));L.push({text:v,position:"top-left",offsetY:0,onClick:x?this.toggleAgentMode:void 0})}if(this.connectedClientsStatus&&this.connectedClientsStatus.enabled){let E=this.connectedClientsStatus,I=E.mode||"disconnected",T=!!E.errorMessage,S=E.clientID||"unknown",x,h;if(T)x="●",h=E1.red;else if(I==="presence")x="○",h=E1.yellow;else if(I==="connected"&&E.connected)x="●",h=E1.green;else x="○",h=E1.yellow;let v=this.connectedClientsStatusExpanded?`${S} ${x}`:x;L.push({text:new D1(v,new j1({color:h})),position:"top-right",offsetX:-2,offsetY:0,onClick:this.toggleConnectedClientsStatus})}let R=Y.mainThread?.metadata?.treeInfo?.uri,O;if(R)O=L0.isUri(R)?R.fsPath:R;else O=process.cwd();let $=this.toHomeRelative(O),j=this.shorten($);return L.push({text:new D1(j,new j1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new Bf1({leftChild:new R8({child:H}),rightChild1:V,rightChild2:N,maxHeight:q,overlayTexts:L,borderColor:W||!this.isTextfieldAndAutocompleteFocused?E1.index(8):void 0,hasBanner:G!==null})}}async function kq6(J){if(J.threadDependencies&&process.env.AMP_CONNECT==="1"){let{startAutomaticPresence:F}=await Promise.resolve().then(() => (Um1(),zm1));F(J.threadDependencies,J.configService,J.connectedClientsService,J.clientId,J.startNewThread).catch((B)=>{u.error("Failed to start automatic presence:",B)})}let Z=!1,X=new cF(Z,1000,J.inspectorPort),Y=new Rf1({threadService:J.threadService,worker:J.worker,builder:(F,B)=>{let M=MX(),V=M?.thread.id||J.threadID,N={...J,worker:M||J.worker,threadID:V};return new Sq6({...N,threadState:B})}}),K=new Lf1({configService:J.configService,child:Y}),q=new Mf1({configService:J.configService,child:K}),G=new sy1(q),z=new A6({data:SC.fromBaseTheme(rK.default()),child:G});try{await by1(z,{onRootElementMounted:Z?(F)=>{X.start(F)}:void 0})}finally{if(Z)X.stop();if(J.threadDependencies&&process.env.AMP_CONNECT==="1"){let{stopGlobalSession:F}=await Promise.resolve().then(() => (Um1(),zm1));F()}}let W=MX()?.thread.id||J.threadID;if((await J.threadService.get(W))?.messages.length!==0){let F=`${J.ampURL.replace(/\/$/,"")}/threads/${W}`;J.stdout.write(`
|
|
6662
6662
|
`),J.stdout.write(`Thread: ${F}
|
|
6663
6663
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6664
6664
|
`)}}function Wm1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):eZ9(J)}function eZ9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return E1.index(Z[X])}xy1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){eK.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6665
|
-
`)}var Fm1=Hm1.join(gd1||Hm1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function YX9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function JW(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Xq("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new _9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${U8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")Xq("experimental.agentMode",Q.agentMode)}async function Dm1(J){try{await QX9(Hm1.dirname(Fm1),{recursive:!0}),await ZX9(Fm1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function KX9(){try{return(await yq6(Fm1,"utf-8")).trim()}catch(J){return null}}function qX9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return _d("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var _q6=[{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??$J,description:`Custom settings file path (overrides the default location ${$J})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bb1})`},{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:HQ(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:bc1}],xq6=(J)=>("deprecated"in J)&&J.deprecated===!0,GX9=(J)=>("hidden"in J)&&J.hidden===!0,zX9=(J)=>("default"in J),UX9=(J)=>("default"in J)?J.default:void 0;function WX9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new _9(cK.unknownCommand(Z),1,q)}}var fq6=null;function $a2(){return fq6}function dJ1(J){return{...J,getThreadEnvironment:$71,vfs:e90({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new R_(J.fileSystem),generateThreadTitle:Fq0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Mm1=L0.file(XX9.homedir()),hq6=process.env.XDG_CONFIG_HOME?L0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Mm1,".config");async function QW(J,Q){al1("0.0.
|
|
6665
|
+
`)}var Fm1=Hm1.join(gd1||Hm1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function YX9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function JW(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")Xq("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new _9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${U8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")Xq("experimental.agentMode",Q.agentMode)}async function Dm1(J){try{await QX9(Hm1.dirname(Fm1),{recursive:!0}),await ZX9(Fm1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function KX9(){try{return(await yq6(Fm1,"utf-8")).trim()}catch(J){return null}}function qX9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return _d("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var _q6=[{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??$J,description:`Custom settings file path (overrides the default location ${$J})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${bb1})`},{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:HQ(),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:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:bc1}],xq6=(J)=>("deprecated"in J)&&J.deprecated===!0,GX9=(J)=>("hidden"in J)&&J.hidden===!0,zX9=(J)=>("default"in J),UX9=(J)=>("default"in J)?J.default:void 0;function WX9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new _9(cK.unknownCommand(Z),1,q)}}var fq6=null;function $a2(){return fq6}function dJ1(J){return{...J,getThreadEnvironment:$71,vfs:e90({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new R_(J.fileSystem),generateThreadTitle:Fq0,deleteThread:(Q)=>J.threadService.delete(Q)}}var Mm1=L0.file(XX9.homedir()),hq6=process.env.XDG_CONFIG_HOME?L0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(Mm1,".config");async function QW(J,Q){al1("0.0.1761926491-gb46bb9");let Z=tZ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:o1.of([L0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Mm1,userConfigDir:hq6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (mJ1(),gJ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=_90(RO({configService:Z})),q=new Map,G=()=>q.clear(),z=T90({configService:Z,toolService:K,createOAuthProvider:async(E)=>{let I=q.get(E);if(I)return u.debug("Reusing existing OAuth provider for server",{serverName:E}),I;u.debug("Creating OAuth provider for server",{serverName:E});let T=(async()=>{let S=new M3(J.secrets),x=await S.getClientInfo(E),h=new OU1({storage:S,serverName:E,clientId:x?.clientId,clientSecret:x?.clientSecret,scopes:x?.scopes});return u.debug("OAuth provider created",{serverName:E,hasManualClientId:!!x?.clientId,willUseDCR:!x?.clientId}),h})();return q.set(E,T),T}}),U=Gw0(K,$2,_e).catch((E)=>{u.warn("Toolbox registration failed, continuing anyway:",E)}),W=z.initialized.catch((E)=>{u.warn("MCP service initialization failed, continuing anyway:",E)}),H=Promise.all([W,U]).then(()=>{});if(Q.jetbrains)jO("JetBrains");else if(Q.ide&&ZJ6())jO("VS Code");else if(Q.ide&&XJ6())jO("Neovim");if(J.executeMode)nl1(!0);z86(K,{configService:Z});let F,B=C7.status.pipe(k0((E)=>Boolean(E.connected&&E.authenticated)),q8()).subscribe((E)=>{if(E){if(!F)F=K.registerTool(l$)}else F?.dispose(),F=void 0}),M;if(!J.executeMode)M=new x71(process.cwd(),{},!0);else M=new class extends x71{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(t2.write(`No API key found. Starting login flow...
|
|
6666
6666
|
`),!await HX9(J))await WR(),process.exit(1)}let V=await K20({isDevelopment:!1}),N=new QV1(V,Z),L=new mF1(V,{lazy:!0}),A=Q.notifications!==void 0?Q.notifications:!J.executeMode,w=W86({playNotificationSound:async(E)=>{if(A){U86(E);let I=ky1(),T=_y1();if((!I||T)&&Y.settings["notifications.system.enabled"]!==!1){if(E==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(E==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:N,configService:Z});u.info("Starting Amp background services");let R=Hq0({threadService:N,threadHistoryService:L,configService:Z,isExtensionDevelopment:!1}),O;C7.status.subscribe((E)=>{O=E});let j={codebaseContextService:new lQ1({workspaceRoots:[L0.file(process.cwd())],getCurrentFile:()=>{if(!O?.openFile)return;try{return L0.parse(O.openFile)}catch(E){u.warn("Failed to parse current file URI",{uri:O.openFile,error:E});return}},getOpenFiles:()=>{if(!O?.visibleFiles?.length)return[];let E=O.openFile;return O.visibleFiles.filter((I)=>I!==E).map((I)=>{try{return L0.parse(I)}catch(T){return u.warn("Failed to parse visible file URI",{uri:I,error:T}),null}}).filter((I)=>I!==null)}}),configService:Z,toolService:K,mcpService:z,threadService:N,threadHistoryService:L,threadSyncService:R,threadStorage:V,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:w,backgroundInit:H,fileSystem:Q.jetbrains||Q.ide?s90:$2};return{...j,async asyncDispose(){await j.mcpService.dispose(),G(),await j.threadService.asyncDispose(),j.configService.unsubscribe(),j.toolService.dispose(),j.fuzzyServer.dispose(),j.threadSyncService.dispose(),j.settingsStorage[Symbol.dispose](),B.unsubscribe(),F?.dispose()}}}async function HX9(J){if(!J.executeMode){if(!await qy1("Would you like to log in to Amp? [(y)es, (n)o]: "))return t2.write(`Login cancelled. Run the command again to retry.
|
|
6667
6667
|
`),!1}return await gq6(J)}async function gq6(J){let Q=JX9(32).toString("hex"),Z=await Ky1(J.ampURL,Q),X=new AbortController;try{await $X(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await Ky1(J.ampURL,Q,!1);t2.write(`If your browser does not open automatically, visit:
|
|
6668
6668
|
|
|
@@ -6672,13 +6672,13 @@ ${U8.blue.bold(Y)}
|
|
|
6672
6672
|
Login successful! You can now use the Amp CLI.
|
|
6673
6673
|
`),!0}catch(K){return u.error("Login failed",{error:K}),eK.write(`
|
|
6674
6674
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6675
|
-
`),!1}}function FX9(){let J=new ew().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)UC(),process.exit(0);let H=W.originalError??W;Z56(H)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.
|
|
6675
|
+
`),!1}}function FX9(){let J=new ew().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)UC(),process.exit(0);let H=W.originalError??W;Z56(H)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.1761926491-gb46bb9 (released 2025-10-31T16:06:40.836Z)
|
|
6676
6676
|
`),process.exit(0)}),J.addHelpText("after",e56()),J.configureHelp({formatHelp:JJ6}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await $Y(F);await VX9(B)}),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(W,H)=>{let F=H.optsWithGlobals(),B=await $Y(F);await MX9(B,await nb1(F,B.settings))});let Q=async(W,H,F)=>{tZ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:o1.of([L0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Mm1,userConfigDir:hq6});let B={...H,executeMode:!1};await Bm1(B,{...W,startWithPicker:!0},F)},Z=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(W,H)=>{let F=H.optsWithGlobals(),B=await $Y(F);await bq6(F,B,H)});Z.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(W,H)=>{let F=H.optsWithGlobals(),B=await $Y(F);await OX9(F,B,H)}),Z.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(W,H,F)=>{let B=F.optsWithGlobals(),M=await $Y(B);if(H.pick)eK.write(`${U8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6677
6677
|
`);if(H.last||W||M.executeMode)await RX9(B,M,W,F);else await Q(B,M,F)}),Z.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(W,H,F)=>{let B=F.optsWithGlobals(),M=await $Y(B);await wX9(B,M,W,F)}),Z.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(W,H)=>{let F=H.optsWithGlobals(),B=await $Y(F);await bq6(F,B,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, 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, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await $Y(B);await AX9(B,M,W,F,H.support)}),Z.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(W,H,F,B)=>{let M=B.optsWithGlobals(),V=await $Y(M);await NX9(M,V,W,H,B)}),Z.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(W,H,F)=>{let B=F.optsWithGlobals(),M=await $Y(B);await LX9(B,M,W,F)}),KQ6(J,async(W,H)=>{let F=await $Y(H);JW(W,H);let B=await QW(F,H);return{context:F,mcpService:B.mcpService,toolService:B.toolService,configService:B.configService,cleanupTerminal:UC,asyncDispose:B.asyncDispose.bind(B)}}),_J6(J),EJ6(J,async(W)=>{let H=await $Y(W);return{settings:H.settings,secretStorage:H.secrets,getThreadDeps:async(F)=>{JW(F,W);let B=await QW(H,W);return{mcpService:B.mcpService,asyncDispose:B.asyncDispose.bind(B)}}}});function Y(W,H,F){let M=typeof W.description==="string"?W.description:F===void 0?W.description(!0):W.description(F),V=new aV(H,M),N=UX9(W);if(N)V.default(N);if(V.hidden=GX9(W)||xq6(W),"choices"in W)V.choices([...W.choices]);return V}for(let W of _q6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new aV("-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(K);let q=new aV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(q);let G=new aV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let z=new aV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new aV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(U),process.env.AMP_CONNECT==="1"){let W=new aV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(W)}return J.action(async(W,H)=>{let F=W,B=await $Y(F);if(Object.keys(F).forEach((M)=>{let V=_q6.find((N)=>N.name===M);if(V&&xq6(V)&&!zX9(V))eK.write(U8.yellow(`Warning: '--${M}' flag is deprecated
|
|
6678
6678
|
`))}),H.args.length>0)WX9(B,H);await Bm1(B,F,H)}),LJ6(J),J}async function pJ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Jz(),K=dJ1(J);if(Z)await J.threadStorage.set(Y,Z);let q=await zJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,a71(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(t7(z,"assistant"))await Dm1(Y),G.unsubscribe()});return await q.resume(),q}async function Bm1(J,Q,Z){let X=i71(Q);if(X instanceof Error)tK(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await zy1()).trimEnd();if(O)K=O}else Y=(await zy1()).trimEnd();if(Q.remote&&!J.executeMode)throw new _9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new _9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new _9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new _9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new _9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new _9("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 _9("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&&Y===""&&!Q.streamJsonInput)throw new _9("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"
|
|
6679
6679
|
Or pipe via stdin: echo "your message" | amp --execute`);JW(Z,Q);let q=await QW(J,Q);if(J.executeMode||Q.threadId)await q.backgroundInit;fq6=q;let G=dJ1(q),z=async(O)=>{let $=await yq6(O,"utf-8"),j=JSON.parse($);if(!Uq(j.id))throw new _9(cK.invalidThreadId);return pJ1(q,{visibility:X,thread:j})},U=async(O)=>{if(!Uq(O))throw new _9(cK.invalidThreadId);let $=await q.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${$?.agentMode??"undefined"}`),$?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${$.agentMode}`),Xq("experimental.agentMode",$.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return pJ1(q,{visibility:X,thread:$})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return pJ1(q,{visibility:X})}catch(O){if(O instanceof _9)throw O;throw await E71(O,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return pJ1(q,{visibility:X})};if(Q.format==="jsonl")eK.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6680
|
-
`),await WR(),process.exit(1);if(J.executeMode&&Q.remote)await xJ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)await M56(F,F.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Wn1();let O=await mO({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)C7.selectConfig($)}else B=!0}let V=Yy1("0.0.
|
|
6681
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await f56({...J,workspaceTrust:{current:!0,changes:tC},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 IJ6(J.mcpConfig);X=qX9(X,K)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!wB(Y))u.info("Targeting custom Amp server",{ampURL:Y});return X=qc1(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:bJ6(await nb1(J,X))}}function BX9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function DX9(){let J=BX9(process.argv);if(n76({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),YX9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6680
|
+
`),await WR(),process.exit(1);if(J.executeMode&&Q.remote)await xJ6(Y,K,q.configService),await q.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)await M56(F,F.threadID,Y,K,q,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await q.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Wn1();let O=await mO({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await q.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)C7.selectConfig($)}else B=!0}let V=Yy1("0.0.1761926491-gb46bb9",q.settingsStorage),N=new gF1(q.threadStorage),L=o1.of([L0.file(process.cwd())]),A=od1(void 0,L);if(Y)F.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await XJ.getUserFreeTierStatus({},{config:q.configService,signal:AbortSignal.timeout(5000)})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await hJ6();u.info("Loaded session state:",R),await kq6({codebaseContextService:q.codebaseContextService,stdout:process.stdout,history:new mb1,fuzzyServer:q.fuzzyServer,settingsStorage:q.settingsStorage,threadService:q.threadService,threadSyncService:q.threadSyncService,threadID:F.threadID,threadFuzzyIndexer:N,worker:F,workerDeps:G,configService:q.configService,internalAPIClient:XJ,ampURL:J.ampURL,startNewThread:H,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:C7,connectedClientsService:new QX1,commandRegistry:A,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:w.ok?w.result:void 0,threadDependencies:q}),await q.asyncDispose(),process.exit(0)}async function $Y(J){if(J.interactive)eK.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6681
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await f56({...J,workspaceTrust:{current:!0,changes:tC},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 IJ6(J.mcpConfig);X=qX9(X,K)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!wB(Y))u.info("Targeting custom Amp server",{ampURL:Y});return X=qc1(X),{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:bJ6(await nb1(J,X))}}function BX9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function DX9(){let J=BX9(process.argv);if(n76({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),YX9(u),u.info("Starting Amp CLI.",{version:"0.0.1761926491-gb46bb9",buildTimestamp:"2025-10-31T16:06:40.836Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _9(cK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await FX9().parseAsync(process.argv)}DX9().catch(E71);async function MX9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),t2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6682
6682
|
`);else if(!wB(J.ampURL))t2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6683
6683
|
`);let Z=process.env.AMP_API_KEY;if(Z)t2.write(`API key found in environment variable, storing...
|
|
6684
6684
|
`),await Q.set("apiKey",Z,J.ampURL),t2.write(`API key successfully stored.
|