@sourcegraph/amp 0.0.1768291296-g18aa0d → 0.0.1768305708-gbd5551
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +12 -12
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4058,7 +4058,7 @@ The context used was: `+J.widget.constructor.name);return Q}updateShouldNotify(J
|
|
|
4058
4058
|
`)z+=M9(N,G)}if(z>=Q&&z<=Q+Z)this._paintSoftwareCursor(J,z,Y,q,K,this._style.textColor??a.white,this._style.backgroundColor??a.black,this._style.cursorColor??a.default(),G)}}_updateScrollOffsetFromLayout(J,Q){let Y=this._controller;if(!(Q>=J.maxHeight)){Y.setScrollOffset(0);return}let X=Y.getLayoutLines(),G=Y.cursorPosition,V=-1;for(let w=0;w<X.length;w++){let M=X[w];if(G>=M.startOffset&&G<=M.endOffset){V=w;break}}if(V===-1)return;let K=this._style.padding||j1.all(0),W=this._style.border?1:0,H=Q-K.top-K.bottom-W*2,z=Y.getScrollOffset(),F=z,U=z+H-1;if(V<F)Y.setScrollOffset(V);else if(V>U){let w=V-H+1;Y.setScrollOffset(w)}let D=Math.max(0,X.length-H),B=Y.getScrollOffset(),N=Math.max(0,Math.min(B,D));Y.setScrollOffset(N)}}var iQ8=new Set([" ","\t",`
|
|
4059
4059
|
`,"\r","\v","\f"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," ","\uFEFF"]),nQ8=new Set(["/","\\",".",",",";",":","!","?","(",")","[","]","{","}","<",">","'",'"',"=","+","-","*","&","|","^","%","$","#","@","~","`","_"]);class $C1 extends d1{onSend;onCancel;constructor({onSend:J,onCancel:Q,key:Y}){super(Y?{key:Y}:{});this.onSend=J,this.onCancel=Q}createState(){return new _96}}var XC1=[{value:"directory",label:"Local Directory"},{value:"url",label:"Repository URL"}];class _96 extends u1{focusedField="sourceType";sourceType="directory";sourcePathController=new Q7(".");workingDirectoryController=new Q7;branchNameController=new Q7;dispose(){this.sourcePathController.dispose(),this.workingDirectoryController.dispose(),this.branchNameController.dispose()}handleKeyEvent=(J)=>{if(J.key==="Escape")return this.widget.onCancel(),"handled";if(J.key==="Tab")return this.setState(()=>{this.cycleField(J.shiftKey?-1:1)}),"handled";return"ignored"};cycleField(J){let Q=["sourceType","sourcePath","workingDirectory","branchName"],Z=(Q.indexOf(this.focusedField)+J+Q.length)%Q.length;this.focusedField=Q[Z]}handleSourceTypeSelect=(J)=>{if(J===null){this.widget.onCancel();return}this.setState(()=>{this.sourceType=J,this.focusedField="sourcePath"})};handleSubmit(){let J=this.sourcePathController.text.trim(),Q=this.workingDirectoryController.text.trim(),Y=this.branchNameController.text.trim();if(!J||!Q||!Y)return;let Z=this.sourceType==="directory"?{type:"directory",path:J}:{type:"url",url:J};this.widget.onSend({workingDirectory:Q,source:Z,branchName:Y})}build(J){let Y=k0.of(J).colorScheme,Z=x0.all(new j0(Y.foreground,1,"rounded"));return new A6({onKey:this.handleKeyEvent,autofocus:!0,child:new p1({decoration:new N6(Y.background,Z),padding:j1.all(1),child:new k1({mainAxisAlignment:"start",crossAxisAlignment:"stretch",children:[new J0({padding:j1.only({bottom:1}),child:new e({text:new S("Clone Worker",new f({color:Y.primary,bold:!0})),maxLines:1})}),new A1({height:1}),this.buildFormFields(Y),new A1({height:1}),new e({text:new S("Tab: cycle fields • Enter: clone • Esc: cancel",new f({color:Y.foreground,dim:!0}))})]})})})}buildFormFields(J){let Q=this.sourceType==="directory"?"Source Path:":"Repository URL:";return new k1({crossAxisAlignment:"stretch",children:[this.buildFieldRow("Source Type:",this.buildSourceTypeField(J),J),new A1({height:1}),this.buildFieldRow(Q,new e2({key:new u8(`sourcePath-${this.focusedField==="sourcePath"}`),controller:this.sourcePathController,placeholder:this.sourceType==="directory"?"/path/to/source/repo":"https://github.com/org/repo",autofocus:this.focusedField==="sourcePath",onSubmitted:()=>this.handleSubmit(),submitKey:{character:"Enter"}}),J),new A1({height:1}),this.buildFieldRow("Working Dir:",new e2({key:new u8(`workingDirectory-${this.focusedField==="workingDirectory"}`),controller:this.workingDirectoryController,placeholder:"/path/to/new/working/directory",autofocus:this.focusedField==="workingDirectory",onSubmitted:()=>this.handleSubmit(),submitKey:{character:"Enter"}}),J),new A1({height:1}),this.buildFieldRow("Branch Name:",new e2({key:new u8(`branchName-${this.focusedField==="branchName"}`),controller:this.branchNameController,placeholder:"feature/my-branch",autofocus:this.focusedField==="branchName",onSubmitted:()=>this.handleSubmit(),submitKey:{character:"Enter"}}),J)]})}buildSourceTypeField(J){if(this.focusedField==="sourceType")return new L5({options:XC1,onSelect:this.handleSourceTypeSelect,autofocus:!0,showBorder:!1,showDismissalMessage:!1,selectedIndex:this.sourceType==="directory"?0:1});let Q=this.sourceType==="directory"?XC1[0].label:XC1[1].label;return new e({text:new S(Q,new f({color:J.primary}))})}buildFieldRow(J,Q,Y){return new X0({children:[new A1({width:14,child:new e({text:new S(J,new f({color:Y.foreground,dim:!0}))})}),new A0({child:new J0({padding:j1.only({left:1}),child:Q})})]})}}class GC1 extends S0{entry;isSelected;isExpanded;constructor({entry:J,isSelected:Q=!1,isExpanded:Y=!1,key:Z}){super(Z?{key:Z}:{});this.entry=J,this.isSelected=Q,this.isExpanded=Y}build(J){let Y=k0.of(J).colorScheme,Z=this.buildSummaryRow(Y);if(!this.isExpanded)return this.isSelected?new p1({decoration:new N6(Y.selection),child:Z}):Z;let X=this.buildDetailFields(Y),G=this.isSelected?new p1({decoration:new N6(Y.selection),child:Z}):Z;return new k1({children:[G,new J0({padding:j1.only({left:4}),child:new k1({children:X,crossAxisAlignment:"start"})})],crossAxisAlignment:"stretch"})}buildSummaryRow(J){let Q=this.formatTimestamp(this.entry.timestamp),Y=this.getStatusIcon(),Z=this.getStatusColor(J),X=this.entry.threadID?this.entry.threadID:"",G=[new e({text:new S(`[${Q}]`,new f({color:J.foreground,dim:!0})),maxLines:1}),O8.horizontal(1),new e({text:new S(this.entry.type,new f({color:J.primary})),maxLines:1})];if(X)G.push(O8.horizontal(1)),G.push(new e({text:new S(X,new f({color:J.foreground,dim:!0})),maxLines:1}));if(G.push(O8.horizontal(1)),G.push(new e({text:new S(Y,new f({color:Z})),maxLines:1})),this.entry.status==="error"&&this.entry.result&&!this.entry.result.success)G.push(O8.horizontal(1)),G.push(new e({text:new S(this.entry.result.error,new f({color:J.destructive,dim:!0})),maxLines:1,overflow:"ellipsis"}));if(this.entry.status==="success"&&this.entry.result&&"threadID"in this.entry.result)G.push(O8.horizontal(1)),G.push(new e({text:new S(`→ ${this.entry.result.threadID}`,new f({color:J.foreground,dim:!0})),maxLines:1}));return new X0({children:G,mainAxisSize:"min"})}formatTimestamp(J){let Q=J.getHours().toString().padStart(2,"0"),Y=J.getMinutes().toString().padStart(2,"0"),Z=J.getSeconds().toString().padStart(2,"0"),X=J.getMilliseconds().toString().padStart(3,"0");return`${Q}:${Y}:${Z}.${X}`}getStatusIcon(){switch(this.entry.status){case"dispatched":return"○";case"success":return"✓";case"error":return"✗"}}getStatusColor(J){switch(this.entry.status){case"dispatched":return J.foreground;case"success":return J.success;case"error":return J.destructive}}buildDetailFields(J){let Q=[];if(Q.push(new e({text:new S(`id: ${this.entry.id}`,new f({color:J.foreground,dim:!0}))})),Q.push(new e({text:new S(`type: ${this.entry.type}`,new f({color:J.foreground,dim:!0}))})),Q.push(new e({text:new S(`threadID: ${this.entry.threadID??"(none)"}`,new f({color:J.foreground,dim:!0}))})),Q.push(new e({text:new S(`timestamp: ${this.entry.timestamp.toISOString()}`,new f({color:J.foreground,dim:!0}))})),Q.push(new e({text:new S(`status: ${this.entry.status}`,new f({color:J.foreground,dim:!0}))})),Q.push(new e({text:new S(`duration: ${this.entry.duration!==void 0?`${this.entry.duration}ms`:"(pending)"}`,new f({color:J.foreground,dim:!0}))})),this.entry.payload){let Z=JSON.stringify(this.entry.payload,null,2).split(`
|
|
4060
4060
|
`);for(let X of Z)Q.push(new e({text:new S(`${Z.indexOf(X)===0?"payload: ":" "}${X}`,new f({color:J.foreground,dim:!0}))}))}if(this.entry.result){let Z=JSON.stringify(this.entry.result,null,2).split(`
|
|
4061
|
-
`);for(let X of Z)Q.push(new e({text:new S(`${Z.indexOf(X)===0?"result: ":" "}${X}`,new f({color:this.entry.result.success?J.foreground:J.destructive,dim:this.entry.result.success}))}))}else Q.push(new e({text:new S("result: (pending)",new f({color:J.foreground,dim:!0}))}));return Q}}class VC1 extends d1{filterThreadID;selectedIndex;expandedEntryIds;constructor({filterThreadID:J=null,selectedIndex:Q,expandedEntryIds:Y,key:Z}={}){super(Z?{key:Z}:{});this.filterThreadID=J,this.selectedIndex=Q,this.expandedEntryIds=Y}createState(){return new S96}}class S96 extends u1{entries=[];store=oJ.getInstance();initState(){this.updateEntries(),this.store.addListener(this.handleStoreChange)}dispose(){this.store.removeListener(this.handleStoreChange)}didUpdateWidget(J){this.updateEntries()}updateEntries(){this.entries=this.store.getEntriesForThread(this.widget.filterThreadID)}handleStoreChange=()=>{this.setState(()=>{this.updateEntries()})};build(J){let Q=this.entries.map((Y,Z)=>{let X=this.widget.selectedIndex===Z,G=this.widget.expandedEntryIds?.has(Y.id)??!1;return new GC1({entry:Y,isSelected:X,isExpanded:G,key:new u8(`${Y.id}-${Z}`)})});return new q4({child:new k1({children:Q,mainAxisAlignment:"start",crossAxisAlignment:"start"})})}}xq();class KC1 extends S0{threadID;viewState;lastCommand;isSelected;constructor({threadID:J,viewState:Q,lastCommand:Y,isSelected:Z=!1,key:X}){super(X?{key:X}:{});this.threadID=J,this.viewState=Q,this.lastCommand=Y,this.isSelected=Z}build(J){let Y=k0.of(J).colorScheme,Z=this.getStatusInfo(Y),X=this.threadID,G=this.getMessagePreview();return new J0({padding:j1.symmetric(1,0),child:new k1({children:[new e({text:new S("",void 0,[new S(Z.icon,new f({color:Z.color})),new S(" ",new f({})),new S(X,new f({color:this.isSelected?Y.foreground:Y.primary,bold:this.isSelected}))]),maxLines:1,overflow:"ellipsis"}),new e({text:new S(` ${Z.label}`,new f({color:Y.foreground,dim:!0})),maxLines:1,overflow:"ellipsis"}),new e({text:new S(` ${G}`,new f({color:Y.foreground,dim:!0})),maxLines:1,overflow:"ellipsis"})],mainAxisAlignment:"start",crossAxisAlignment:"stretch"})})}getStatusInfo(J){if(!this.viewState)return{icon:"◌",label:"Idle",color:J.foreground};if(this.viewState.state==="active"){if(this.viewState.inferenceState==="running")return{icon:"●",label:"Running",color:J.success};if(this.viewState.interactionState==="tool-running")return{icon:"●",label:"Running tools",color:J.success};if(this.viewState.interactionState==="handoff")return{icon:"●",label:"Handoff",color:J.success};if(this.viewState.interactionState==="user-tool-approval"||this.viewState.interactionState==="user-message-initial"||this.viewState.interactionState==="user-message-reply")return{icon:"○",label:"Waiting",color:J.warning}}return{icon:"◌",label:"Idle",color:J.foreground}}getMessagePreview(){if(!this.lastCommand)return"(no commands yet)";let J=this.lastCommand.status==="success"?"✓":this.lastCommand.status==="error"?"✗":"○";return`${this.lastCommand.type} ${J}`}}class qC1 extends d1{selectedIndex;onSelectionChange;constructor({selectedIndex:J=0,onSelectionChange:Q,key:Y}={}){super(Y?{key:Y}:{});this.selectedIndex=J,this.onSelectionChange=Q}createState(){return new k96}}class k96 extends u1{statuses={};subscription;commandLogStore=oJ.getInstance();initState(){this.subscription=v8.statuses.subscribe((J)=>{this.setState(()=>{this.statuses=J})}),this.commandLogStore.addListener(this.handleCommandLogChange)}dispose(){this.subscription?.unsubscribe(),this.commandLogStore.removeListener(this.handleCommandLogChange)}handleCommandLogChange=()=>{this.setState(()=>{})};build(J){let Q=Object.keys(this.statuses),Y=this.widget.selectedIndex,Z=Q.map((X,G)=>{let V=this.statuses[X],K=this.commandLogStore.getLastCommandForThread(X);return new KC1({threadID:X,viewState:V,lastCommand:K,isSelected:G===Y,key:new u8(X)})});return new q4({child:new k1({children:Z,mainAxisAlignment:"start",crossAxisAlignment:"stretch"})})}}class WC1 extends d1{isConnected;onQuit;onClone;socketId;sessionsType;constructor({isConnected:J=!1,onQuit:Q,onClone:Y,socketId:Z,sessionsType:X,key:G}={}){super(G?{key:G}:{});this.isConnected=J,this.onQuit=Q,this.onClone=Y,this.socketId=Z,this.sessionsType=X}createState(){return new y96}}class y96 extends u1{focusedPane="workers";workerSelectedIndex=0;workerCount=0;selectedThreadID=null;statuses={};subscription;logSelectedIndex=0;expandedEntryIds=new Set;commandLogStore=oJ.getInstance();isShowingCloneComposer=!1;initState(){this.subscription=v8.statuses.subscribe((J)=>{this.setState(()=>{this.statuses=J,this.workerCount=Object.keys(J).length,this.updateSelectedThreadID()})}),this.commandLogStore.addListener(this.handleCommandLogChange)}dispose(){this.subscription?.unsubscribe(),this.commandLogStore.removeListener(this.handleCommandLogChange)}handleCommandLogChange=()=>{this.setState(()=>{})};handleKeyEvent=(J)=>{if(this.isShowingCloneComposer)return"ignored";if(J.key==="q")return this.widget.onQuit?.(),"handled";if(J.key==="c"&&J.ctrlKey)return this.widget.onQuit?.(),"handled";if(J.key==="c")return this.setState(()=>{this.isShowingCloneComposer=!0}),"handled";if(J.key==="Tab")return this.setState(()=>{this.cyclePane()}),"handled";if(J.key==="1")return this.setState(()=>{this.focusedPane="workers"}),"handled";if(J.key==="2")return this.setState(()=>{this.focusedPane="incoming-log"}),"handled";if(this.focusedPane==="workers")return this.handleWorkerListKey(J);return this.handleCommandLogKey(J)};handleWorkerListKey(J){if(J.key==="ArrowUp"||J.key==="k")return this.setState(()=>{this.workerSelectedIndex=Math.max(0,this.workerSelectedIndex-1),this.updateSelectedThreadID(),this.logSelectedIndex=0}),"handled";if(J.key==="ArrowDown"||J.key==="j")return this.setState(()=>{this.workerSelectedIndex=Math.min(this.workerCount-1,this.workerSelectedIndex+1),this.updateSelectedThreadID(),this.logSelectedIndex=0}),"handled";return"ignored"}handleCommandLogKey(J){if(J.key==="ArrowUp"||J.key==="k")return this.setState(()=>{this.logSelectedIndex=Math.max(0,this.logSelectedIndex-1)}),"handled";if(J.key==="ArrowDown"||J.key==="j")return this.setState(()=>{let Q=this.getFilteredEntryCount()-1;this.logSelectedIndex=Math.min(Math.max(0,Q),this.logSelectedIndex+1)}),"handled";if(J.key==="Enter")return this.setState(()=>{let Q=this.getSelectedEntry();if(Q)if(this.expandedEntryIds.has(Q.id))this.expandedEntryIds.delete(Q.id);else this.expandedEntryIds.add(Q.id)}),"handled";if(J.key==="Escape")return this.setState(()=>{this.selectedThreadID=null,this.logSelectedIndex=0}),"handled";return"ignored"}updateSelectedThreadID(){let J=Object.keys(this.statuses);this.selectedThreadID=J[this.workerSelectedIndex]??null}getFilteredEntries(){return this.commandLogStore.getEntriesForThread(this.selectedThreadID)}getFilteredEntryCount(){return this.getFilteredEntries().length}getSelectedEntry(){return this.getFilteredEntries()[this.logSelectedIndex]}cyclePane(){this.focusedPane=this.focusedPane==="workers"?"incoming-log":"workers"}closeCloneComposer(){this.setState(()=>{this.isShowingCloneComposer=!1})}handleClone(J){this.widget.onClone?.(J),this.closeCloneComposer()}build(J){let Y=k0.of(J).colorScheme,Z=this.buildHeader(Y),X=this.buildFooter(Y),G=this.buildMainContent(Y),V=new k1({children:[Z,new A0({child:G}),X],mainAxisAlignment:"start",crossAxisAlignment:"stretch"});if(this.isShowingCloneComposer)V=new k1({crossAxisAlignment:"stretch",children:[new A0({child:new $C1({onSend:(K)=>this.handleClone(K),onCancel:()=>this.closeCloneComposer()})})]});return new A6({onKey:this.handleKeyEvent,autofocus:!0,child:V})}buildHeader(J){let Q=this.widget.socketId??"",Y=this.widget.isConnected?new S(`● Connected (${Q})`,new f({color:J.success})):new S("○ Disconnected",new f({color:J.destructive})),Z=this.widget.sessionsType??"unknown",X=new S(` | Workers: ${this.workerCount} | Sessions: ${Z}`,new f({color:J.foreground,dim:!0}));return new p1({decoration:new N6(void 0,new x0(void 0,void 0,new j0(J.foreground,1,"solid"),void 0)),child:new J0({padding:j1.symmetric(1,0),child:new X0({children:[new e({text:new S("Amp Headless",new f({color:J.primary,bold:!0})),maxLines:1}),new e({text:new S(" ",new f({})),maxLines:1}),new e({text:new S("",void 0,[Y,X]),maxLines:1})],mainAxisAlignment:"start",mainAxisSize:"max"})})})}buildFooter(J){let Q=this.focusedPane==="workers"?"q: quit • ↑↓/jk: select worker • c: clone • Tab: switch pane • 1-2: jump pane":"q: quit • ↑↓/jk: select entry • Enter: expand • Esc: clear filter • Tab: switch pane";return new p1({decoration:new N6(void 0,new x0(new j0(J.foreground,1,"solid"),void 0,void 0,void 0)),child:new J0({padding:j1.symmetric(1,0),child:new e({text:new S(Q,new f({color:J.foreground,dim:!0})),maxLines:1})})})}buildMainContent(J){let Q=this.buildLeftPanel(J),Y=this.buildRightPanel(J);return new X0({children:[new oq({flex:2,child:new p1({decoration:new N6(void 0,new x0(void 0,new j0(J.foreground,1,"solid"),void 0,void 0)),child:Q})}),new oq({flex:3,child:Y})],crossAxisAlignment:"stretch"})}buildLeftPanel(J){let Q=this.buildPaneTitle("Workers",this.focusedPane==="workers",J),Y=new qC1({selectedIndex:this.workerSelectedIndex});return new k1({children:[Q,new A0({child:Y})],crossAxisAlignment:"stretch"})}buildRightPanel(J){let Q=this.selectedThreadID?`: ${this.selectedThreadID.slice(0,20)}...`:": All",Y=this.buildPaneTitle(`Incoming${Q}`,this.focusedPane==="incoming-log",J),Z=new VC1({filterThreadID:this.selectedThreadID,selectedIndex:this.focusedPane==="incoming-log"?this.logSelectedIndex:void 0,expandedEntryIds:this.expandedEntryIds});return new k1({children:[Y,new A0({child:Z})],crossAxisAlignment:"stretch"})}buildPaneTitle(J,Q,Y){let Z=new f({color:Q?Y.primary:Y.foreground,bold:Q,dim:!Q}),X=Q?"►":" ";return new J0({padding:j1.only({left:1}),child:new e({text:new S(`${X}${J}`,Z),maxLines:1})})}}class RF{static instance=null;clients=new Map;ownSocketId=null;listeners=new Set;static getInstance(){if(!RF.instance)RF.instance=new RF;return RF.instance}static resetInstance(){RF.instance=null}setOwnSocketId(J){this.ownSocketId=J,this.notifyListeners()}handleClientConnected(J){this.clients.set(J.socketId,J),this.notifyListeners()}handleClientDisconnected(J){this.clients.delete(J),this.notifyListeners()}setClients(J){this.clients.clear();for(let Q of J)this.clients.set(Q.socketId,Q);this.notifyListeners()}addThreadToClient(J,Q){let Y=this.clients.get(J);if(!Y)return;if(!Y.activeThreadIDs.includes(Q)){let Z={...Y,activeThreadIDs:[...Y.activeThreadIDs,Q]};this.clients.set(J,Z),this.notifyListeners()}}getClients(){return[...this.clients.values()].filter((J)=>J.socketId!==this.ownSocketId)}getClientCount(){return this.getClients().length}addListener(J){this.listeners.add(J)}removeListener(J){this.listeners.delete(J)}notifyListeners(){for(let J of this.listeners)J()}}function sQ8(){return new Date().toISOString()}function jF(J){rq.stdout.write(`[${sQ8()}] ${J}
|
|
4061
|
+
`);for(let X of Z)Q.push(new e({text:new S(`${Z.indexOf(X)===0?"result: ":" "}${X}`,new f({color:this.entry.result.success?J.foreground:J.destructive,dim:this.entry.result.success}))}))}else Q.push(new e({text:new S("result: (pending)",new f({color:J.foreground,dim:!0}))}));return Q}}class VC1 extends d1{filterThreadID;selectedIndex;expandedEntryIds;constructor({filterThreadID:J=null,selectedIndex:Q,expandedEntryIds:Y,key:Z}={}){super(Z?{key:Z}:{});this.filterThreadID=J,this.selectedIndex=Q,this.expandedEntryIds=Y}createState(){return new S96}}class S96 extends u1{entries=[];store=oJ.getInstance();initState(){this.updateEntries(),this.store.addListener(this.handleStoreChange)}dispose(){this.store.removeListener(this.handleStoreChange)}didUpdateWidget(J){this.updateEntries()}updateEntries(){this.entries=this.store.getEntriesForThread(this.widget.filterThreadID)}handleStoreChange=()=>{this.setState(()=>{this.updateEntries()})};build(J){let Q=this.entries.map((Y,Z)=>{let X=this.widget.selectedIndex===Z,G=this.widget.expandedEntryIds?.has(Y.id)??!1;return new GC1({entry:Y,isSelected:X,isExpanded:G,key:new u8(`${Y.id}-${Z}`)})});return new q4({child:new k1({children:Q,mainAxisAlignment:"start",crossAxisAlignment:"start"})})}}xq();class KC1 extends S0{threadID;viewState;lastCommand;isSelected;constructor({threadID:J,viewState:Q,lastCommand:Y,isSelected:Z=!1,key:X}){super(X?{key:X}:{});this.threadID=J,this.viewState=Q,this.lastCommand=Y,this.isSelected=Z}build(J){let Y=k0.of(J).colorScheme,Z=this.getStatusInfo(Y),X=this.threadID,G=this.getMessagePreview();return new J0({padding:j1.symmetric(1,0),child:new k1({children:[new e({text:new S("",void 0,[new S(Z.icon,new f({color:Z.color})),new S(" ",new f({})),new S(X,new f({color:this.isSelected?Y.foreground:Y.primary,bold:this.isSelected}))]),maxLines:1,overflow:"ellipsis"}),new e({text:new S(` ${Z.label}`,new f({color:Y.foreground,dim:!0})),maxLines:1,overflow:"ellipsis"}),new e({text:new S(` ${G}`,new f({color:Y.foreground,dim:!0})),maxLines:1,overflow:"ellipsis"})],mainAxisAlignment:"start",crossAxisAlignment:"stretch"})})}getStatusInfo(J){if(!this.viewState)return{icon:"◌",label:"Idle",color:J.foreground};if(this.viewState.state==="active"){if(this.viewState.inferenceState==="running")return{icon:"●",label:"Running",color:J.success};if(this.viewState.interactionState==="tool-running")return{icon:"●",label:"Running tools",color:J.success};if(this.viewState.interactionState==="handoff")return{icon:"●",label:"Handoff",color:J.success};if(this.viewState.interactionState==="user-tool-approval"||this.viewState.interactionState==="user-message-initial"||this.viewState.interactionState==="user-message-reply")return{icon:"○",label:"Waiting",color:J.warning}}return{icon:"◌",label:"Idle",color:J.foreground}}getMessagePreview(){if(!this.lastCommand)return"(no commands yet)";let J=this.lastCommand.status==="success"?"✓":this.lastCommand.status==="error"?"✗":"○";return`${this.lastCommand.type} ${J}`}}class qC1 extends d1{selectedIndex;onSelectionChange;constructor({selectedIndex:J=0,onSelectionChange:Q,key:Y}={}){super(Y?{key:Y}:{});this.selectedIndex=J,this.onSelectionChange=Q}createState(){return new k96}}class k96 extends u1{statuses={};subscription;commandLogStore=oJ.getInstance();initState(){this.subscription=v8.statuses.subscribe((J)=>{this.setState(()=>{this.statuses=J})}),this.commandLogStore.addListener(this.handleCommandLogChange)}dispose(){this.subscription?.unsubscribe(),this.commandLogStore.removeListener(this.handleCommandLogChange)}handleCommandLogChange=()=>{this.setState(()=>{})};build(J){let Q=Object.keys(this.statuses),Y=this.widget.selectedIndex,Z=Q.map((X,G)=>{let V=this.statuses[X],K=this.commandLogStore.getLastCommandForThread(X);return new KC1({threadID:X,viewState:V,lastCommand:K,isSelected:G===Y,key:new u8(X)})});return new q4({child:new k1({children:Z,mainAxisAlignment:"start",crossAxisAlignment:"stretch"})})}}class WC1 extends d1{isConnected;onQuit;onClone;socketId;sessionsType;constructor({isConnected:J=!1,onQuit:Q,onClone:Y,socketId:Z,sessionsType:X,key:G}={}){super(G?{key:G}:{});this.isConnected=J,this.onQuit=Q,this.onClone=Y,this.socketId=Z,this.sessionsType=X}createState(){return new y96}}class y96 extends u1{focusedPane="workers";workerSelectedIndex=0;workerCount=0;selectedThreadID=null;statuses={};subscription;logSelectedIndex=0;expandedEntryIds=new Set;commandLogStore=oJ.getInstance();isShowingCloneComposer=!1;initState(){this.subscription=v8.statuses.subscribe((J)=>{this.setState(()=>{this.statuses=J,this.workerCount=Object.keys(J).length,this.updateSelectedThreadID()})}),this.commandLogStore.addListener(this.handleCommandLogChange)}dispose(){this.subscription?.unsubscribe(),this.commandLogStore.removeListener(this.handleCommandLogChange)}handleCommandLogChange=()=>{this.setState(()=>{})};handleKeyEvent=(J)=>{if(this.isShowingCloneComposer)return"ignored";if(J.key==="q")return this.widget.onQuit?.(),"handled";if(J.key==="c"&&J.ctrlKey)return this.widget.onQuit?.(),"handled";if(J.key==="c")return this.setState(()=>{this.isShowingCloneComposer=!0}),"handled";if(J.key==="Tab")return this.setState(()=>{this.cyclePane()}),"handled";if(J.key==="1")return this.setState(()=>{this.focusedPane="workers"}),"handled";if(J.key==="2")return this.setState(()=>{this.focusedPane="incoming-log"}),"handled";if(this.focusedPane==="workers")return this.handleWorkerListKey(J);return this.handleCommandLogKey(J)};handleWorkerListKey(J){if(J.key==="ArrowUp"||J.key==="k")return this.setState(()=>{this.workerSelectedIndex=Math.max(0,this.workerSelectedIndex-1),this.updateSelectedThreadID(),this.logSelectedIndex=0}),"handled";if(J.key==="ArrowDown"||J.key==="j")return this.setState(()=>{this.workerSelectedIndex=Math.min(this.workerCount-1,this.workerSelectedIndex+1),this.updateSelectedThreadID(),this.logSelectedIndex=0}),"handled";return"ignored"}handleCommandLogKey(J){if(J.key==="ArrowUp"||J.key==="k")return this.setState(()=>{this.logSelectedIndex=Math.max(0,this.logSelectedIndex-1)}),"handled";if(J.key==="ArrowDown"||J.key==="j")return this.setState(()=>{let Q=this.getFilteredEntryCount()-1;this.logSelectedIndex=Math.min(Math.max(0,Q),this.logSelectedIndex+1)}),"handled";if(J.key==="Enter")return this.setState(()=>{let Q=this.getSelectedEntry();if(Q)if(this.expandedEntryIds.has(Q.id))this.expandedEntryIds.delete(Q.id);else this.expandedEntryIds.add(Q.id)}),"handled";if(J.key==="Escape")return this.setState(()=>{this.selectedThreadID=null,this.logSelectedIndex=0}),"handled";return"ignored"}updateSelectedThreadID(){let J=Object.keys(this.statuses);this.selectedThreadID=J[this.workerSelectedIndex]??null}getFilteredEntries(){return this.commandLogStore.getEntriesForThread(this.selectedThreadID)}getFilteredEntryCount(){return this.getFilteredEntries().length}getSelectedEntry(){return this.getFilteredEntries()[this.logSelectedIndex]}cyclePane(){this.focusedPane=this.focusedPane==="workers"?"incoming-log":"workers"}closeCloneComposer(){this.setState(()=>{this.isShowingCloneComposer=!1})}handleClone(J){this.widget.onClone?.(J),this.closeCloneComposer()}build(J){let Y=k0.of(J).colorScheme,Z=this.buildHeader(Y),X=this.buildFooter(Y),G=this.buildMainContent(Y),V=new k1({children:[Z,new A0({child:G}),X],mainAxisAlignment:"start",crossAxisAlignment:"stretch"});if(this.isShowingCloneComposer)V=new k1({crossAxisAlignment:"stretch",children:[new A0({child:new $C1({onSend:(K)=>this.handleClone(K),onCancel:()=>this.closeCloneComposer()})})]});return new A6({onKey:this.handleKeyEvent,autofocus:!0,child:V})}buildHeader(J){let Q=this.widget.socketId??"",Y=this.widget.isConnected?new S(`● Connected (${Q})`,new f({color:J.success})):new S("○ Disconnected",new f({color:J.destructive})),Z=this.widget.sessionsType??"unknown",X=new S(` | Agents: ${this.workerCount} | Sessions: ${Z}`,new f({color:J.foreground,dim:!0}));return new p1({decoration:new N6(void 0,new x0(void 0,void 0,new j0(J.foreground,1,"solid"),void 0)),child:new J0({padding:j1.symmetric(1,0),child:new X0({children:[new e({text:new S("Amp Headless",new f({color:J.primary,bold:!0})),maxLines:1}),new e({text:new S(" ",new f({})),maxLines:1}),new e({text:new S("",void 0,[Y,X]),maxLines:1})],mainAxisAlignment:"start",mainAxisSize:"max"})})})}buildFooter(J){let Q=this.focusedPane==="workers"?"q: quit • ↑↓/jk: select agent • c: clone • Tab: switch pane • 1-2: jump pane":"q: quit • ↑↓/jk: select entry • Enter: expand • Esc: clear filter • Tab: switch pane";return new p1({decoration:new N6(void 0,new x0(new j0(J.foreground,1,"solid"),void 0,void 0,void 0)),child:new J0({padding:j1.symmetric(1,0),child:new e({text:new S(Q,new f({color:J.foreground,dim:!0})),maxLines:1})})})}buildMainContent(J){let Q=this.buildLeftPanel(J),Y=this.buildRightPanel(J);return new X0({children:[new oq({flex:2,child:new p1({decoration:new N6(void 0,new x0(void 0,new j0(J.foreground,1,"solid"),void 0,void 0)),child:Q})}),new oq({flex:3,child:Y})],crossAxisAlignment:"stretch"})}buildLeftPanel(J){let Q=this.buildPaneTitle("Agents",this.focusedPane==="workers",J),Y=new qC1({selectedIndex:this.workerSelectedIndex});return new k1({children:[Q,new A0({child:Y})],crossAxisAlignment:"stretch"})}buildRightPanel(J){let Q=this.selectedThreadID?`: ${this.selectedThreadID.slice(0,20)}...`:": All",Y=this.buildPaneTitle(`Incoming${Q}`,this.focusedPane==="incoming-log",J),Z=new VC1({filterThreadID:this.selectedThreadID,selectedIndex:this.focusedPane==="incoming-log"?this.logSelectedIndex:void 0,expandedEntryIds:this.expandedEntryIds});return new k1({children:[Y,new A0({child:Z})],crossAxisAlignment:"stretch"})}buildPaneTitle(J,Q,Y){let Z=new f({color:Q?Y.primary:Y.foreground,bold:Q,dim:!Q}),X=Q?"►":" ";return new J0({padding:j1.only({left:1}),child:new e({text:new S(`${X}${J}`,Z),maxLines:1})})}}class RF{static instance=null;clients=new Map;ownSocketId=null;listeners=new Set;static getInstance(){if(!RF.instance)RF.instance=new RF;return RF.instance}static resetInstance(){RF.instance=null}setOwnSocketId(J){this.ownSocketId=J,this.notifyListeners()}handleClientConnected(J){this.clients.set(J.socketId,J),this.notifyListeners()}handleClientDisconnected(J){this.clients.delete(J),this.notifyListeners()}setClients(J){this.clients.clear();for(let Q of J)this.clients.set(Q.socketId,Q);this.notifyListeners()}addThreadToClient(J,Q){let Y=this.clients.get(J);if(!Y)return;if(!Y.activeThreadIDs.includes(Q)){let Z={...Y,activeThreadIDs:[...Y.activeThreadIDs,Q]};this.clients.set(J,Z),this.notifyListeners()}}getClients(){return[...this.clients.values()].filter((J)=>J.socketId!==this.ownSocketId)}getClientCount(){return this.getClients().length}addListener(J){this.listeners.add(J)}removeListener(J){this.listeners.delete(J)}notifyListeners(){for(let J of this.listeners)J()}}function sQ8(){return new Date().toISOString()}function jF(J){rq.stdout.write(`[${sQ8()}] ${J}
|
|
4062
4062
|
`)}var tQ8=rQ8(aQ8);async function eQ8(){try{let{stdout:J}=await tQ8("git remote get-url origin",{cwd:rq.cwd()}),Q=J.trim();if(!Q)return;let Y=Q.replace(/\.git$/,"").match(/^git@([^:]+):(.+)$/);if(Y&&Y[1]&&Y[2])return`https://${Y[1]}/${Y[2]}`;return Q.replace(/\.git$/,"")}catch{return}}async function x96(J,Q,Y){if(J instanceof gZ)return{success:!0,status:"ok"};if(J instanceof o2)return(await v8.getOrCreateForThread(Q,J.threadID)).handle({type:"user:message",message:{content:J.message.content}}).catch((X)=>{R.error("UserMessageCommand handler failed",{threadID:J.threadID,error:X})}),{success:!0};if(J instanceof VY){let Z=v8.get(J.threadID);if(!Z)return R.warn("Interrupt command: no active worker found",{threadID:J.threadID}),{success:!1,error:`No active worker for thread ${J.threadID}`};return R.info("Interrupt command: cancelling worker",{threadID:J.threadID}),await Z.cancel(),{success:!0}}if(J instanceof GY){let Z="accepted"in J.input?J.input.accepted:J.input.response==="yes"||J.input.response==="allow-all-session"||J.input.response==="allow-all-persistent";return Q.toolService.resolveApproval(J.toolUseID,Z),{success:!0}}if(J instanceof a2){let Z=J.threadID??PJ(),X=await v8.getOrCreateForThread(Q,Z);if(await X.resume(),J.initialMessage)X.handle({type:"user:message",message:{content:[{type:"text",text:J.initialMessage}]}}).catch((G)=>{R.error("ThreadNewCommand initial message handler failed",{threadID:Z,error:G})});return{success:!0,threadID:Z}}if(J instanceof $Y){if(J.createWorkerIfNeeded)await v8.getOrCreateForThread(Q,J.threadID);return{success:!0}}if(J instanceof n2)return await v8.dispose(J.threadID),{success:!0};if(J instanceof KY)return N86({workingDirectory:J.workingDirectory,source:J.source,branchName:J.branchName,sessions:Y}).catch((Z)=>{R.error("WorkerCloneCommand failed",{workingDirectory:J.workingDirectory,source:J.source,error:Z})}),{success:!0};return{success:!1,error:"Unknown command type"}}function v96(J){if("threadID"in J&&typeof J.threadID==="string")return J.threadID;return}function JY8(J){if(!J)return"idle";if(J.state==="active"){let Q=J.inferenceState;if(Q==="running"||Q==="retrying")return"running";if(Q==="cancelled")return"waiting"}if(J.toolState.running>0)return"running";if(J.toolState.blocked>0)return"waiting";if(J.interactionState==="tool-running")return"running";if(J.interactionState==="user-tool-approval"||J.interactionState==="handoff")return"waiting";return"idle"}function QY8(J){let Q=J.messages.find((X)=>X.role==="user");if(!Q)return;let Y=Q.content.find((X)=>X.type==="text"&&X.text);if(!Y||Y.type!=="text")return;let Z=Y.text??"";return Z.length>100?Z.slice(0,100)+"...":Z}function YY8(J){let Q=J.messages.filter((G)=>G.role==="user"&&G.content.some((V)=>V.type==="text"&&V.text));if(Q.length<=1)return;let Y=Q[Q.length-1];if(!Y)return;let Z=Y.content.find((G)=>G.type==="text"&&G.text);if(!Z||Z.type!=="text")return;let X=Z.text??"";return X.length>120?X.slice(0,120)+"...":X}function ZY8(J){let Q=[...J.messages].reverse().find((X)=>X.role==="assistant");if(!Q)return;let Y=Q.content.find((X)=>X.type==="text"&&X.text);if(!Y||Y.type!=="text")return;let Z=Y.text??"";return Z.length>100?Z.slice(0,100)+"...":Z}function XY8(J){let Q=J.messages.at(-1);if(!Q||Q.role!=="user")return[];let Y=Q.content.filter((V)=>V.type==="tool_result"&&V.run?.status==="blocked-on-user");if(Y.length===0)return[];let Z=J.messages.at(-2);if(!Z||Z.role!=="assistant")return[];let X=Z.content.filter((V)=>V.type==="tool_use"),G=new Map(X.map((V)=>[V.id,V]));return Y.map((V)=>{let K=G.get(V.toolUseID),q=K?.input?JSON.stringify(K.input).slice(0,200):void 0;return{toolUseID:V.toolUseID,toolName:K?.name??"unknown",argsPreview:q&&q.length===200?q+"...":q,reason:V.run.reason}})}function PF(J,Q){return Array.from(J).map((Y)=>{let X=v8.get(Y)?.thread,G=JY8(Q[Y]),V=X&&G==="waiting"?XY8(X):void 0;return{threadID:Y,status:G,title:X?.title,initialPromptPreview:X?QY8(X):void 0,latestPromptPreview:X?YY8(X):void 0,lastAssistantPreview:X?ZY8(X):void 0,blockedTools:V&&V.length>0?V:void 0}})}async function $Y8(J,Q,Y,Z,X,G){let V=oJ.getInstance(),K=RF.getInstance();if(J.start(async(H)=>{V.logDispatch(H);try{let z=await x96(H.payload,Q,Y);V.logResult(H.id,z);let F=v96(H.payload);if(z.success){if(H.payload instanceof a2&&"threadID"in z){let U=z.threadID;X.add(U),J.updateActiveThreads(PF(X,{}))}if(F&&H.payload instanceof o2)X.add(F),J.updateActiveThreads(PF(X,{}));if(F&&H.payload instanceof n2)X.delete(F),J.updateActiveThreads(PF(X,{}))}return z}catch(z){let F=z instanceof Error?z.message:String(z);R.error("Command execution failed",{commandId:H.id,error:z});let U={success:!1,error:F};return V.logResult(H.id,U),U}}),await J.waitForConnection(),J.socketId)K.setOwnSocketId(J.socketId);let q=await J.listClients();K.setClients(q),J.onClientConnected((H)=>{K.handleClientConnected(H)}),J.onClientDisconnected(({socketId:H})=>{K.handleClientDisconnected(H)});let W=v8.statuses.subscribe((H)=>{J.updateActiveThreads(PF(X,H))});await dw(new WC1({isConnected:J.isConnected,socketId:J.socketId,sessionsType:Z,onQuit:async()=>{W.unsubscribe(),await G(),d6.instance.stop()}}))}async function GY8(J,Q,Y,Z,X){J.start(async(V)=>{let K=v96(V.payload);jF(`COMMAND id=${V.id} type=${V.type}${K?` thread=${K}`:""}`);try{let q=await x96(V.payload,Q,Y);if(q.success){if(V.payload instanceof a2&&"threadID"in q){let W=q.threadID;Z.add(W),J.updateActiveThreads(PF(Z,{})),jF(`RESULT id=${V.id} success=true threadID=${W}`)}else jF(`RESULT id=${V.id} success=true`);if(K&&V.payload instanceof o2)Z.add(K),J.updateActiveThreads(PF(Z,{}));if(K&&V.payload instanceof n2)Z.delete(K),J.updateActiveThreads(PF(Z,{}))}else jF(`RESULT id=${V.id} success=false error=${q.error}`);return q}catch(q){let W=q instanceof Error?q.message:String(q);return R.error("Command execution failed",{commandId:V.id,error:q}),jF(`RESULT id=${V.id} success=false error=${W}`),{success:!1,error:W}}}),await J.waitForConnection(),jF(`CONNECTED socket=${J.socketId}`);let G=v8.statuses.subscribe((V)=>{J.updateActiveThreads(PF(Z,V))});await new Promise((V)=>{let K=setInterval(()=>{if(X.value)G.unsubscribe(),clearInterval(K),V()},100)})}async function Q61(J){let{ampURL:Q,apiKey:Y,version:Z,workerDeps:X}=J,{sessions:G,type:V}=J.sessions?{sessions:J.sessions,type:"subprocess"}:await IT1(),K=new Set,q=await eQ8(),W=new LT1({ampURL:Q,apiKey:Y,clientName:"CLI (headless)",version:Z,hostname:oQ8.hostname(),workingDirectory:rq.cwd(),processID:rq.pid,repository:q}),H={value:!1},z=async()=>{if(H.value)return;if(H.value=!0,!rq.stdout.isTTY)jF("SHUTDOWN starting");if(W.stop(),await G.terminateAll(),await v8.disposeAll(),!rq.stdout.isTTY)jF("SHUTDOWN complete")};if(SR(()=>{R.info("Received signal, shutting down headless mode"),z().then(()=>rq.exit(0)).catch((D)=>{R.error("Error during shutdown",{error:D}),rq.exit(1)})}).install(),rq.stdout.isTTY)await $Y8(W,X,G,V,K,z);else await GY8(W,X,G,K,H)}import{stderr as R$,stdin as VY8,stdout as KY8}from"node:process";import{createInterface as qY8}from"node:readline";var Y61=[],HC1=null;function zC1(J){if(HC1=J,J&&Y61.length>0){for(let Q of Y61)J(Q);Y61=[]}}function b96(J){return async(Q,Y)=>{return new Promise((Z,X)=>{let G={serverName:J,authorizationUrl:Q,redirectUrl:Y,resolve:Z,reject:X};if(HC1)HC1(G);else Y61.push(G)})}}function f96(){return async(J,Q)=>{return R$.write(`
|
|
4063
4063
|
`),R$.write(Z0.yellow.bold(`OAuth Authorization Required
|
|
4064
4064
|
`)),R$.write(Z0.dim("─".repeat(60)+`
|
|
@@ -4185,11 +4185,11 @@ Actual: ${X}`)}async function AZ8(J,Q,Y){let Z=EV(Q,"package.tgz");R.debug("Do
|
|
|
4185
4185
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
|
|
4186
4186
|
|
|
4187
4187
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4188
|
-
npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function W61(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=PZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return R.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return R.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function PZ8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}K0();function H61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await tz(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=aw(),W=await W61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await q61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Fh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await tz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}un();import{stderr as RV}from"node:process";function y56(J){let Q=new F$().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Z)=>{await OC1(Z.force||!1,Z.verbose||!1,"0.0.
|
|
4188
|
+
npm install -g @sourcegraph/amp`;K(Error(D))}},error:(F)=>{if(!H)H=!0,K(Error(`Failed to spawn ${X}: ${F.message}`))},complete:()=>{if(!H)H=!0,V()}})})}v1();v1();async function W61(J,Q){let Z=Q||"https://registry.npmjs.org";try{let X=new AbortController,G=setTimeout(()=>X.abort(),5000),V=await fetch(`${Z}/@sourcegraph/amp`,{signal:X.signal});if(clearTimeout(G),!V.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await V.json(),q=K["dist-tags"]?.latest;if(!q)return{hasUpdate:!1,currentVersion:J,source:"npm"};let W=PZ8(J,q),H=W<0,z,F;if(K.time){let U=K.time[J],D=K.time[q],B=Date.now();if(U)z=Math.floor((B-new Date(U).getTime())/3600000);if(D)F=Math.floor((B-new Date(D).getTime())/3600000)}return R.info("NPM version comparison",{currentVersion:J,latestVersion:q,compareResult:W,hasUpdate:H,currentVersionAge:z,latestVersionAge:F}),{hasUpdate:H,latestVersion:q,currentVersion:J,currentVersionAge:z,latestVersionAge:F,source:"npm"}}catch(X){return R.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function PZ8(J,Q){let Y=(V)=>{let[K,q]=V.split("-");return{parts:K?.split(".").map(Number)||[],label:q}},Z=Y(J),X=Y(Q),G=Math.max(Z.parts.length,X.parts.length);for(let V=0;V<G;V++){let K=Z.parts[V]||0,q=X.parts[V]||0;if(K<q)return-1;if(K>q)return 1}if(Z.label===X.label)return 0;if(!Z.label&&X.label)return 1;if(Z.label&&!X.label)return-1;if(Z.label&&X.label)return Z.label<X.label?-1:1;return 0}K0();function H61(J,Q){let Y=new E6,Z=Y.pipe($4({shouldCountRefs:!1}));return setImmediate(async()=>{let X=new $G().scoped("update"),G=Z.subscribe({next:(V)=>{X.debug("emit new state",V)}});try{let V=process.env.AMP_TEST_UPDATE_STATUS;if(V){X.debug("using fake update status for testing",{status:V}),await tz(500),Y.next(V);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){X.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let K=await Q.get("updates.mode");if(K==="disabled"){X.debug("checking disabled");return}X.debug("checking",{currentVersion:J,mode:K});let q=aw(),W=await W61(J,q);if(!(W.latestVersion&&W.hasUpdate)){X.debug("no update available");return}let H=()=>{if(W.currentVersionAge!==void 0&&W.latestVersionAge!==void 0){let F=W.currentVersionAge-W.latestVersionAge,U=0.5;if(Math.abs(F)<0.5)return X.debug("versions too close together, suppressing update warning",{currentVersionAge:W.currentVersionAge,latestVersionAge:W.latestVersionAge,ageDifferenceHours:F}),!0}return!1},z=await q61();if(!K)K=z==="pnpm"?"warn":"auto",X.debug("no configured update mode; selected default based on package manager",{packageManager:z,mode:K});if(K==="warn"){if(!H())Y.next("update-available");return}if(!z){if(X.debug("auto-update not supported, falling back to warn mode"),!H())Y.next("update-available");return}if(z==="binary"&&process.platform==="win32"){if(X.debug("binary auto-update not supported on Windows, falling back to warn mode"),!H())Y.next("update-available");return}try{await Fh(W.latestVersion,z);let F=await CF(W.latestVersion),U={from:W.currentVersion,to:W.latestVersion,...F};if(F.status==="same")X.info("success",U),Y.next("updated");else X.warn("success with warning",U),Y.next("updated-with-warning")}catch(F){Y.next("update-error")}}catch(V){X.debug("check failed",{error:V})}finally{await tz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:Z}}un();import{stderr as RV}from"node:process";function y56(J){let Q=new F$().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(Z)=>{await OC1(Z.force||!1,Z.verbose||!1,"0.0.1768305708-gbd5551"),process.exit()});J.addCommand(Q,{hidden:!0});let Y=new F$("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Z)=>{await TZ8(Z.targetVersion)});J.addCommand(Y)}async function TZ8(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")RV.write(Z0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4189
4189
|
|
|
4190
4190
|
`));try{if(!J){RV.write(Z0.blue(`Checking for updates...
|
|
4191
|
-
`));let Y=aw(),{hasUpdate:Z,latestVersion:X}=await W61("0.0.
|
|
4192
|
-
`));let V=await CF("0.0.
|
|
4191
|
+
`));let Y=aw(),{hasUpdate:Z,latestVersion:X}=await W61("0.0.1768305708-gbd5551",Y);if(!Z){RV.write(Z0.green(`✓ Amp CLI is already up to date: ${"0.0.1768305708-gbd5551"} (${"released"} ${"2026-01-13T12:06:10.736Z"}${`, ${cA(new Date("2026-01-13T12:06:10.736Z"))} ago`})
|
|
4192
|
+
`));let V=await CF("0.0.1768305708-gbd5551");if(V.warning)RV.write(`
|
|
4193
4193
|
`+Z0.yellow(V.warning)+`
|
|
4194
4194
|
`);process.exit(0)}if(!X)RV.write(Z0.yellow("[WARN] could not find latest version")),process.exit(0);J=X}RV.write(Z0.blue(`Updating to version ${J}...
|
|
4195
4195
|
`)),await Fh(J,void 0,(Y)=>{RV.write(Z0.dim(`Running: ${Y}
|
|
@@ -4984,7 +4984,7 @@ exit code: ${G}`,new f({color:Z.foreground,dim:!0,italic:!0})));if(V)K.push(new
|
|
|
4984
4984
|
`));let q=K.startsWith("file://")?Q0.parse(K):Q0.file(K),W=W7(q,X??void 0);G.push(new S(` • ${W}`,new f({color:Z.foreground,dim:!0})))}return new e({text:new S("",void 0,G)})}class B$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=Q.length>0,X=[new e({text:new S(Y?"This will delete this message and any subsequent messages in the thread, and will restore the following files:":"This will delete this message and any subsequent messages in the thread.",new f({color:a.yellow,bold:!0}))}),new A1({height:1})],G=D$6(J,Q);if(G)X.push(G),X.push(new A1({height:1}));let V=[{value:"confirm",label:Y?"Delete and restore":"Delete"},{value:"cancel",label:"Cancel"}];return X.push(new L5({options:V,onSelect:(K)=>{if(K==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:X})}}class N$6 extends S0{props;constructor(J){super();this.props=J}build(J){let Q=this.props.affectedFiles,Y=[],Z=D$6(J,Q);if(Z)Y.push(new e({text:new S("This will restore the following files:",new f({color:a.yellow,bold:!0}))})),Y.push(new A1({height:1})),Y.push(Z),Y.push(new A1({height:1}));let X=[{value:"confirm",label:"Confirm edit"},{value:"cancel",label:"Cancel"}];return Y.push(new L5({options:X,onSelect:(G)=>{if(G==="confirm")this.props.onConfirm();else this.props.onCancel()},padding:j1.all(0),showDismissalMessage:!1,enableMouseInteraction:!1,showBorder:!1})),new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:Y})}}class p81 extends d1{initialText;onSubmitted;message;completionBuilder;autocompleteHandle;onShowImagePreview;constructor(J){super();this.initialText=J.initialText,this.onSubmitted=J.onSubmitted,this.message=J.message,this.completionBuilder=J.completionBuilder,this.autocompleteHandle=J.autocompleteHandle,this.onShowImagePreview=J.onShowImagePreview}createState(){return new w$6}}class w$6 extends u1{controller=new Q7;currentShellModeStatus;imageAttachments=[];initState(){this.controller.text=this.widget.initialText,this.controller.addListener(this.textChangeListener);let J=xF(this.widget.initialText);if(this.currentShellModeStatus=J?.visibility,this.widget.message){let Q=this.widget.message.content.filter((Y)=>Y.type==="image");this.imageAttachments=Q}}dispose(){this.controller.removeListener(this.textChangeListener),this.controller.dispose(),super.dispose()}textChangeListener=()=>{let J=this.controller.text,Y=xF(J)?.visibility;if(Y!==this.currentShellModeStatus)this.currentShellModeStatus=Y,this.setState(()=>{})};handleSubmit=(J)=>{this.widget.onSubmitted(J,this.imageAttachments)};handleInsertImage=(J)=>{let Q=SF(J);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q]}),!1;return!1};handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1)})};handleImageClick=(J)=>{let Q=this.imageAttachments[J];if(Q)this.widget.onShowImagePreview(Q,J,()=>{this.setState(()=>{this.imageAttachments=this.imageAttachments.filter((Y,Z)=>Z!==J)})})};build(J){let Q=q0.of(J),Y=Q.colors,Z=Q.app,X=this.currentShellModeStatus?n56(Q,this.currentShellModeStatus):z$6,G=null,V=this.widget.message&&ml(this.widget.message);if(V)G=ny1(J,V);let K=new ew({controller:this.controller,triggers:[new PV],completionBuilder:this.widget.completionBuilder,ampURL:"",onSubmitted:this.handleSubmit,theme:Y,placeholder:"",enabled:!0,autofocus:!0,shellPromptRules:Yj(Q),imageAttachments:this.imageAttachments,onInsertImage:this.handleInsertImage,popImage:this.handlePopImage,onImageClick:this.handleImageClick,minLines:1,textColor:X,autocompleteHandle:this.widget.autocompleteHandle,autoOverlayPosition:!0}),q=[];if(q.push(K),G)q.push(new A1({height:1})),q.push(G);let W;if(q.length===1)W=q[0];else W=new k1({mainAxisSize:"min",crossAxisAlignment:"start",children:q});let H=[];if(this.currentShellModeStatus===yF)H.push(new S("shell mode (incognito)",new f({color:Q.app.shellModeHidden})));else if(this.currentShellModeStatus===L61)H.push(new S("shell mode",new f({color:Q.app.shellMode})));else H.push(new S("esc",new f({color:Z.keybind})),new S(" to cancel",new f({color:Y.foreground,dim:!0})));return new Yh({child:new zY({decoration:{border:x0.all(new j0(X,2,"solid"))},padding:j1.only({left:1,right:1}),overlays:[{child:new e({text:new S("",void 0,H)}),position:"bottom",alignment:"left"}],child:W})})}}class d81 extends x8{}class c81 extends x8{}class ay1 extends x8{}class oy1 extends x8{}class ry1 extends x8{}class sy1 extends x8{}class ty1 extends x8{}class ey1 extends x8{}function ZN8(J,Q,Y){let X=q0.maybeOf(J)?.colors??k0.of(J).colorScheme,V=Q.trimStart().startsWith("You're absolutely right"),K=new u8(`${Y}-text`),q=[];if(V)q.push(new Ry1({key:K,markdown:Q,defaultColor:X.foreground}));else q.push(new t8({key:K,markdown:Q}));if(q.length===1)return q[0];return new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q})}function XN8(J,Q){let Z=k0.of(J).colorScheme;if(Q.summary.type!=="message")return new p1;return new k1({crossAxisAlignment:"start",children:[new e({text:new S("Summary:",new f({color:Z.foreground,dim:!0,bold:!0,italic:!0})),selectable:!0}),new A1({height:1}),new t8({markdown:Q.summary.summary,styleScheme:{text:new f({color:Z.foreground,dim:!0,italic:!0}),inlineCode:new f({color:Z.foreground,dim:!0,italic:!0}),codeBlock:new f({color:Z.foreground,dim:!0,italic:!0}),tableBorder:Z.foreground,link:new f({color:Z.foreground,dim:!0,italic:!0}),syntaxHighlight:{keyword:Z.foreground,string:Z.foreground,number:Z.foreground,comment:Z.foreground,function:Z.foreground,variable:Z.foreground,type:Z.foreground,operator:Z.foreground}}})]})}class l81 extends d1{items;subagentToolsByParentID;controller;autofocus;onNewMessage;showScrollbar;onCopy;onMessageEditSubmit;onShellCommandSubmit;onMessageRestoreSubmit;onMessageForkSubmit;getAffectedFiles;thread;focusNode;onDismissFocus;isInSelectionMode=!1;isInHandoffMode=!1;completionBuilder;onShowImagePreview;onSelectionChanged;get userMessageIndices(){let J=[];for(let Q=0;Q<this.items.length;Q++){let Y=this.items[Q];if(Y?.type==="message"){if(Y.message.role==="user"||dO(Y.message))J.push(Q)}}return J}constructor({key:J,items:Q,subagentToolsByParentID:Y={},controller:Z,autofocus:X=!1,onNewMessage:G,showScrollbar:V=!0,onCopy:K,onMessageEditSubmit:q,onMessageRestoreSubmit:W,onMessageForkSubmit:H,getAffectedFiles:z,thread:F,focusNode:U,onDismissFocus:D,isInSelectionMode:B=!1,isInHandoffMode:N=!1,completionBuilder:w,onShowImagePreview:M,onSelectionChanged:L}){super(J?{key:J}:{});this.items=Q,this.subagentToolsByParentID=Y,this.controller=Z,this.autofocus=X,this.onNewMessage=G,this.showScrollbar=V,this.onCopy=K,this.onMessageEditSubmit=q,this.onMessageRestoreSubmit=W,this.onMessageForkSubmit=H,this.getAffectedFiles=z,this.thread=F,this.focusNode=U,this.onDismissFocus=D,this.isInSelectionMode=B,this.isInHandoffMode=N,this.completionBuilder=w,this.onShowImagePreview=M,this.onSelectionChanged=L}createState(){return new M$6}}class M$6 extends u1{_controller=null;_isDisposed=!1;_thinkingBlockStates=new Map;_globalToggleListener;_streamingIndexes=new Set;_viewportHeight=25;_widgetCache=new Map;_lastCostDisplayState=null;_selectedUserMessageOrdinal=null;_editingMessageOrdinal=null;_isShowingRestoreConfirmation=!1;_isShowingEditConfirmation=!1;_pendingEditText=null;_pendingEditImageAttachments=[];_affectedFiles=[];_autocompleteHandle={dismiss:()=>{}};_scrollListener=null;get controller(){return this._controller}dismiss(){Y4.instance.addPostFrameCallback(()=>{this.widget.focusNode?.unfocus()}),this.widget.onDismissFocus?.()}_navigateUp(J,Q){if(Q<=0)return null;if(J===null)return Q-1;if(J<=0)return 0;return J-1}_navigateDown(J,Q){if(Q<=0)return null;if(J===null)return null;if(J>=Q-1)return null;return J+1}_ordinalToIndex(J,Q){if(Q===null)return null;if(Q<0||Q>=J.length)return null;return J[Q]??null}_getUserCount(){return this.widget.userMessageIndices.length}_clearSelectedUserMessage(){let J=this._selectedUserMessageOrdinal,Q=J!==null?this.getUserMessageIndexFromOrdinal(J):null;this.setState(()=>{if(Q!=null)this._widgetCache.delete(Q);this._selectedUserMessageOrdinal=null})}_selectUserMessageByOrdinal(J){let Q=this._selectedUserMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=this.getUserMessageIndexFromOrdinal(Y);if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);if(this.setState(()=>{this._selectedUserMessageOrdinal=Y}),X!==null)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(X,{animated:!0,edge:"top",duration:200})})}_selectEditingUserMessageByOrdinal(J){let Q=this._editingMessageOrdinal,Y=J,Z=Q!==null?this.getUserMessageIndexFromOrdinal(Q):null,X=Y!==null?this.getUserMessageIndexFromOrdinal(Y):null;if(Z!==null)this._widgetCache.delete(Z);if(X!==null)this._widgetCache.delete(X);this.setState(()=>{this._editingMessageOrdinal=Y})}getUserMessageIndexFromOrdinal(J){return this.widget.userMessageIndices[J]??null}getOrdinalFromUserMessageIndex(J){let Y=this.widget.userMessageIndices.indexOf(J);return Y>=0?Y:null}getLatestUserMessageOrdinal(){let J=this.widget.userMessageIndices;return J.length>0?J.length-1:null}navigateToUserMessage(J){let Q=this._getUserCount(),Y=J==="up"?this._navigateUp(this._selectedUserMessageOrdinal,Q):this._navigateDown(this._selectedUserMessageOrdinal,Q);if(Y===null&&J==="down"){this._controller?.animateToBottom(100),this._clearSelectedUserMessage(),this.dismiss();return}if(Y!==null)this._selectUserMessageByOrdinal(Y)}handleNavigateUserMessageUp=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("up"),"handled"};handleNavigateUserMessageDown=()=>{if(this._editingMessageOrdinal!==null)return"ignored";return this.navigateToUserMessage("down"),"handled"};handleEscape=()=>{if(this._editingMessageOrdinal!==null)return this.setState(()=>{let J=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(J!=null)this._widgetCache.delete(J);this._editingMessageOrdinal=null}),"handled";else if(this._selectedUserMessageOrdinal!==null)return this._clearSelectedUserMessage(),this.setState(()=>{this._editingMessageOrdinal=null}),this.dismiss(),this._controller?.animateToBottom(100),"handled";return"ignored"};handleScrollDown=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollDown(1),"handled";return"ignored"};handleScrollUp=()=>{if(this._selectedUserMessageOrdinal!==null)return this._controller?.scrollUp(1),"handled";return"ignored"};handleEditMessage=()=>{if(this._selectedUserMessageOrdinal!==null)return this._selectEditingUserMessageByOrdinal(this._selectedUserMessageOrdinal),"handled";return"ignored"};handleRestoreMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||dO(Q.message)))this.showRestoreConfirmation(Q.message,J)}return"handled"}return"ignored"};async showRestoreConfirmation(J,Q){let Y=[];if(this.widget.getAffectedFiles)try{Y=await this.widget.getAffectedFiles(J)}catch{Y=[]}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!0,this._affectedFiles=Y}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Q)})}handleRestoreConfirm=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(J===0)return"ignored";let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageRestoreSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.dismiss()}return"handled"}return"ignored"};handleRestoreCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingRestoreConfirmation=!1,this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}return"handled"};handleForkMessage=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||dO(Q.message))){if(J===0)return"ignored";this.widget.onMessageForkSubmit?.(Q.message),this._clearSelectedUserMessage(),this.setState(()=>{}),this.dismiss()}}return"handled"}return"ignored"};handleEditConfirmationRequest=async(J,Q)=>{if(J.trim()===""&&Q.length===0)return;if(this._editingMessageOrdinal!==null){let Y=this._ordinalToIndex(this.widget.userMessageIndices,this._editingMessageOrdinal);if(Y!=null){let Z=this.widget.items[Y],X=[];if(this.widget.getAffectedFiles&&Z?.type==="message")try{X=await this.widget.getAffectedFiles(Z.message)}catch{X=[]}if(X.length===0&&Z?.type==="message"&&(Z.message.role==="user"||Z.message.role==="info")){this.widget.onMessageEditSubmit?.(Z.message,J,Q),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._editingMessageOrdinal=null}),this.dismiss(),this.controller.animateToBottom(100);return}if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!0,this._pendingEditText=J,this._pendingEditImageAttachments=Q,this._affectedFiles=X,this._editingMessageOrdinal=null}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(Y)})}}};handleEditConfirm=()=>{if(this._selectedUserMessageOrdinal!==null&&this._pendingEditText!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){let Q=this.widget.items[J];if(Q?.type==="message"&&(Q.message.role==="user"||Q.message.role==="info"))this.widget.onMessageEditSubmit?.(Q.message,this._pendingEditText,this._pendingEditImageAttachments),this._clearSelectedUserMessage(),this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.dismiss(),this.controller.animateToBottom(100)}}};handleEditCancel=()=>{if(this._selectedUserMessageOrdinal!==null){let J=this._ordinalToIndex(this.widget.userMessageIndices,this._selectedUserMessageOrdinal);if(J!=null){if(this.setState(()=>{this._widgetCache.clear(),this._isShowingEditConfirmation=!1,this._pendingEditText=null,this._pendingEditImageAttachments=[],this._affectedFiles=[]}),this.controller.atBottom)Y4.instance.addPostFrameCallback(()=>{this.scrollToMessage(J)})}}};_signatureFor(J){if(J.type==="message"){let Q=J.message;if(Q.role==="user"){let Y=K7(Q.content),Z=Q.content.filter((X)=>X.type==="image").length;return`${J.id}|user|${Q.interrupted?1:0}|${Z}|${Y}`}else if(Q.role==="assistant"){let Y=K7(Q.content),Z=Q.state?.type??"none",X=Q.content.filter((q)=>q.type==="thinking"),G=Q.content.filter((q)=>q.type==="tool_use"),V=Q.usage,K=V?`${V.credits??""}|${V.inputTokens}|${V.outputTokens}|${V.cacheCreationInputTokens??""}|${V.cacheReadInputTokens??""}|${V.model??""}`:"no-usage";return`${J.id}|assistant|${Z}|${X.length}|${G.length}|${Y}|${K}`}else{let Z=Q.content.map((X)=>X.type).join(",");return`${J.id}|info|${Z}`}}else{let Y=J.toolResult.run.status;return`${J.id}|tool|${Y}|${J.toolUse.id}`}}getThinkingBlockExpanded(J,Q){let Y=`${J}-${Q}`;return this._thinkingBlockStates.get(Y)??Y7.instance.allExpanded}toggleThinkingBlock=(J,Q)=>{return(Y)=>{let Z=`${J}-${Q}`;this.setState(()=>{this._thinkingBlockStates.set(Z,Y),this._widgetCache.delete(J)})}};buildThinkingBlock(J,Q,Y,Z,X){let G=Y===X,V=Z.state?.type==="streaming"&&G,K=Z.state?.type==="cancelled"&&G;return new RM({key:new u8(`thinking-${Q}-${Y}`),thinkingBlock:J,expanded:this.getThinkingBlockExpanded(Q,Y),onToggle:this.toggleThinkingBlock(Q,Y),isStreaming:V,isCancelled:K})}buildAssistantMessageWidget(J,Q,Y,Z){let X=Q.content.map((U,D)=>({block:U,index:D})).filter((U)=>U.block.type==="thinking"&&Ug(U.block.thinking).length>0),G=X.length>0,V=X.length>0?X.at(-1).index:-1,K=Q.content.filter((U)=>U.type==="text"),q=[];if(q.push(...X.map(({block:U,index:D})=>this.buildThinkingBlock(U,Y,D,Q,V))),G&&K.length>0)q.push(new A1({height:1}));let W=K7(K);if(W.trim())q.push(ZN8(J,W,Z));let H=Ey1(J),z=Q.usage!=null&&(Q.usage.inputTokens>0||Q.usage.outputTokens>0);if(H&&z){let D=q0.maybeOf(J)?.colors??k0.of(J).colorScheme,B=IX6(Q.usage);q.push(new J0({padding:j1.only({top:1}),child:new e({text:new S(B,new f({color:D.foreground,dim:!0}))})}))}let F;if(q.length===0)F=new p1;else if(q.length===1)F=q[0];else F=new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:q});return F}buildThreadItemWidget(J,Q,Y){let Z=new u8(`thread-item-${Q.id}`);if(Q.type==="message"){let X=Q.message;if(X.role==="user"){let G,V=(K,q)=>{this.widget.onShowImagePreview(K,q,()=>{})};if(!this.widget.isInSelectionMode)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else{let K=this.getOrdinalFromUserMessageIndex(Y);if(K===null)G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V});else if(this._editingMessageOrdinal===K)G=new p81({initialText:K7(X.content),message:X,onSubmitted:(q,W)=>{this.handleEditConfirmationRequest(q,W)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview});else if(this._selectedUserMessageOrdinal===K)G=new u81({message:X,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:V});else G=new lj({message:X,isFirstMessage:Y>0,onShowImagePreview:V})}return G}else if(X.role==="assistant"){let G=this.buildAssistantMessageWidget(J,X,Y,Q.id);return new p1({key:Z,child:G})}else{let G=X,V=[],K=this.getOrdinalFromUserMessageIndex(Y),q=this.widget.isInSelectionMode&&K!==null&&this._selectedUserMessageOrdinal===K,W=(H,z)=>{this.widget.onShowImagePreview(H,z,()=>{})};for(let H of G.content)if(H.type==="manual_bash_invocation")if(this._editingMessageOrdinal===K){let F=`${O61(H.hidden??!1)}${H.args.cmd}`;V.push(new p81({initialText:F,message:G,onSubmitted:(U,D)=>{this.handleEditConfirmationRequest(U,D)},completionBuilder:this.widget.completionBuilder,autocompleteHandle:this._autocompleteHandle,onShowImagePreview:this.widget.onShowImagePreview}))}else if(!this.widget.isInSelectionMode||!q)V.push(new lj({message:G,isFirstMessage:Y>0,onShowImagePreview:W}));else V.push(new u81({message:G,isFirstMessage:Y>0,isShowingRestoreConfirmation:this._isShowingRestoreConfirmation,isShowingEditConfirmation:this._isShowingEditConfirmation,affectedFiles:this._affectedFiles,pendingEditText:this._pendingEditText??void 0,onRestoreConfirm:()=>{this.handleRestoreConfirm()},onRestoreCancel:()=>{this.handleRestoreCancel()},onEditConfirm:()=>{this.handleEditConfirm()},onEditCancel:()=>{this.handleEditCancel()},onShowImagePreview:W}));else if(H.type==="summary"&&H.summary.type==="message")V.push(XN8(J,H));if(V.length===0)return new p1;if(V.length===1)return V[0];return new k1({crossAxisAlignment:"stretch",children:V})}}else{let X=new WW({toolUse:Q.toolUse,toolRun:Q.toolResult.run,subagentTools:this.widget.subagentToolsByParentID[Q.toolUse.id],thread:this.widget.thread});return new p1({key:Z,child:X})}}initState(){if(super.initState(),this._controller=this.widget.controller||new o4,this._scrollListener=()=>{this._autocompleteHandle.dismiss()},this._controller.addListener(this._scrollListener),this._globalToggleListener=()=>{this.setState(()=>{this._thinkingBlockStates.clear(),this._widgetCache.clear()})},Y7.instance.addListener(this._globalToggleListener),this.widget.items.length>0)Y4.instance.requestFrame()}didUpdateWidget(J){if(super.didUpdateWidget(J),!J.isInSelectionMode&&this.widget.isInSelectionMode){this.widget.focusNode?.requestFocus();let Y=this.getLatestUserMessageOrdinal();if(Y!==null)this._selectUserMessageByOrdinal(Y)}if(J.items===this.widget.items)return;let Q=Math.min(J.items.length,this.widget.items.length);for(let Y=0;Y<Q;Y++){let Z=J.items[Y],X=this.widget.items[Y];if(Z&&X){if(Z.type!==X.type){this._widgetCache.delete(Y);continue}if(Z.type==="toolResult"&&X.type==="toolResult"){let G=Z.toolResult.run,V=X.toolResult.run;if(G.status!==V.status||"result"in G!=="result"in V||"error"in G!=="error"in V)this._widgetCache.delete(Y)}if(Z.type==="message"&&X.type==="message"){let G=Z.message,V=X.message;if(G.content!==V.content)this._widgetCache.delete(Y)}}}if(this.widget.items.length<J.items.length)this._cleanupOrphanedCacheEntries();this._updateStreamingIndexes();for(let Y of this._streamingIndexes)if(Y>=this.widget.items.length)this._streamingIndexes.delete(Y)}_cleanupOrphanedCacheEntries(){for(let J of this._widgetCache.keys())if(J>=this.widget.items.length)this._widgetCache.delete(J)}_isMessageStreaming(J){if(J.type!=="message")return!1;let Q=J.message;if(Q.role!=="assistant")return!1;if(Q.state.type==="streaming")return!0;return Q.content.at(-1)?.type==="thinking"}_updateStreamingIndexes(){for(let J of this._streamingIndexes)if(J>=this.widget.items.length)this._streamingIndexes.delete(J);for(let J=0;J<this.widget.items.length;J++){let Q=this.widget.items[J];if(!Q)continue;let Y=this._isMessageStreaming(Q);if(Y&&!this._streamingIndexes.has(J))this._streamingIndexes.add(J);else if(!Y&&this._streamingIndexes.has(J))this._streamingIndexes.delete(J)}}_getViewportHeight(){let J=this.context.findRenderObject();if(J&&"size"in J){let Q=J.size;if(typeof Q.height==="number"&&Q.height>0)return this._viewportHeight=Q.height,Q.height}return this._viewportHeight}dispose(){if(this._isDisposed=!0,this._widgetCache.clear(),this._scrollListener&&this._controller)this._controller.removeListener(this._scrollListener),this._scrollListener=null;if(this._globalToggleListener)Y7.instance.removeListener(this._globalToggleListener);if(!this.widget.controller)this._controller?.dispose();this.widget.focusNode?.dispose(),super.dispose()}build(J){let Q=q0.of(J),Y=Ey1(J);if(this._lastCostDisplayState!==null&&this._lastCostDisplayState!==Y)this._widgetCache.clear();this._lastCostDisplayState=Y;let Z=this._getTotalItemCount(J),X=[];for(let F=0;F<Z;F++)if(X.push(this._buildItemAtIndex(J,F)),F<Z-1)X.push(new A1({height:1}));let G=new q4({controller:this._controller,autofocus:this.widget.autofocus,position:"bottom",child:new k1({key:new u8("message-list-column"),crossAxisAlignment:"start",children:X})}),K=[new J0({padding:j1.only({left:2,right:this.widget.showScrollbar?3:2,bottom:1}),child:G})];if(this.widget.showScrollbar&&this._controller){let F=new C9({controller:this._controller,getScrollInfo:()=>this._getScrollbarInfo(),thickness:1,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack});K.push(new f4({right:1,top:0,bottom:0,child:new A1({width:1,child:F})}))}let q=new O4({children:K}),W=new j$({child:q,onCopy:this.widget.onCopy,onSelectionChanged:this.widget.onSelectionChanged}),H=new Map([[d81,new h6(this.handleNavigateUserMessageUp)],[c81,new h6(this.handleNavigateUserMessageDown)],[ay1,new h6(this.handleEscape)],[oy1,new h6(this.handleScrollDown)],[ry1,new h6(this.handleScrollUp)],[sy1,new h6(this.handleEditMessage)],[ty1,new h6(this.handleRestoreMessage)],[ey1,new h6(this.handleForkMessage)]]),z=new Map([[p0.key("Tab"),new d81],[p0.shift("Tab"),new c81],[p0.key("Escape"),new ay1],[p0.key("j"),new oy1],[p0.key("k"),new ry1],[p0.key("e"),new sy1],[p0.key("r"),new ty1],[p0.key("f"),new ey1]]);if(!J7())z.set(p0.key("ArrowUp"),new d81),z.set(p0.key("ArrowDown"),new c81);if(this.widget.focusNode)return new A6({focusNode:this.widget.focusNode,child:new b5({actions:H,child:new T3({shortcuts:z,focusNode:this.widget.focusNode,child:W})})});return W}_getTotalItemCount(J){return this.widget.items.length}_shouldDimItem(J){if(this.widget.isInHandoffMode)return!0;if(this._isShowingRestoreConfirmation||this._isShowingEditConfirmation){let Q=this._selectedUserMessageOrdinal;if(Q===null)return!1;let Y=this.getUserMessageIndexFromOrdinal(Q);if(Y===null)return!1;return J>Y}if(this._editingMessageOrdinal!==null){let Q=this.getUserMessageIndexFromOrdinal(this._editingMessageOrdinal);if(Q===null)return!1;return J>Q}return!1}_buildItemAtIndex(J,Q){let Y=this.widget.items[Q];if(!Y)return new p1;let Z=Y.type==="message"&&this._isMessageStreaming(Y),X=Y.type==="toolResult"&&(Y.toolResult.run.status==="queued"||Y.toolResult.run.status==="in-progress")&&!("result"in Y.toolResult.run)&&!("error"in Y.toolResult.run),G=this._shouldDimItem(Q);if(!Z&&!X){let q=`${this._signatureFor(Y)}|dim:${G?1:0}`,W=this._widgetCache.get(Q);if(W&&W.sig===q)return W.widget;let H=this.buildThreadItemWidget(J,Y,Q),z=G?new HY({forceDim:!0,child:H}):H;return this._widgetCache.set(Q,{sig:q,widget:z}),z}let K=this.buildThreadItemWidget(J,Y,Q);return G?new HY({forceDim:!0,child:K}):K}onNewMessage(){if(this._isDisposed)return;this.widget.onNewMessage?.()}scrollToTop(){if(this._isDisposed||!this._controller)return;this._controller.scrollToTop()}scrollToMessage(J,{animated:Q=!1,offsetPercent:Y=0.25,edge:Z="top",duration:X}={}){if(this._isDisposed||!this._controller)return!1;let G=this._getMessageRelativeOffset(J,Z);if(G===null)return!1;let V=this._getViewportHeight(),K=Math.floor(V*Y),q=G-K;if(Q)this._controller.animateTo(q,X);else this._controller.jumpTo(q);return!0}_getColumnElement(){let J=this.context.element;if(!J)return null;let Q=new u8("message-list-column"),Y=(Z)=>{if(Z.widget.key?.equals(Q))return Z;for(let X of Z.children){let G=Y(X);if(G)return G}return null};return Y(J)}_getMessageRelativeOffset(J,Q){let Y=this._getColumnElement();if(!Y)return null;let Z=J*2,X=Y.children[Z];if(!X?.renderObject)return null;let G=X.renderObject,V=Y.renderObject;if(!V)return null;let K=G.localToGlobal({x:0,y:0}),q=V.localToGlobal({x:0,y:0}),W=0;if(Q==="bottom")W=G.size.height;return K.y+W-q.y}_getScrollbarInfo(){let J=this._controller?.maxScrollExtent??0,Q=this._getViewportHeight(),Y=this._controller?.offset??0,Z=J+Q;return{totalContentHeight:Math.max(Z,0),viewportHeight:Math.max(Q,1),scrollOffset:Math.max(Y,0)}}}l6();T6();l6();K0();class Jx1{threadService;workers=new Map;threadsMap=new Map;mainThreadSubs=new Map;workerStatusSubs=new Map;mainThreadObservable;workerStatusObservable;emitMainThread=null;emitWorkerStatus=null;constructor(J){this.threadService=J;this.mainThreadObservable=new T1((Q)=>{return this.emitMainThread=(Y)=>Q.next(Y),()=>{this.emitMainThread=null}}),this.workerStatusObservable=new T1((Q)=>{return this.emitWorkerStatus=(Y)=>Q.next(Y),()=>{this.emitWorkerStatus=null}})}registerWorker(J){let Q=J.thread.id;if(this.workers.has(Q))this.unregisterWorker(Q);this.threadsMap.set(Q,J.thread),this.workers.set(Q,{state:"initial"});let Y=this.threadService.observePatches(Q).pipe(pl()).subscribe((X)=>{this.threadsMap.set(Q,X);let G=this.workers.get(Q)||{state:"initial"};if(this.emitMainThread)this.emitMainThread({threadID:Q,mainThread:X,workerStatus:G})});this.mainThreadSubs.set(Q,Y);let Z=J.status.subscribe((X)=>{if(this.workers.set(Q,X),this.emitWorkerStatus)this.emitWorkerStatus({threadID:Q,status:X})});this.workerStatusSubs.set(Q,Z)}unregisterWorker(J){let Q=this.mainThreadSubs.get(J);if(Q)Q.unsubscribe(),this.mainThreadSubs.delete(J);let Y=this.workerStatusSubs.get(J);if(Y)Y.unsubscribe(),this.workerStatusSubs.delete(J);this.workers.delete(J),this.threadsMap.delete(J)}observeThread(J){return{mainThread:new T1((Q)=>{return this.mainThreadObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})}),workerStatus:new T1((Q)=>{return this.workerStatusObservable.subscribe((Y)=>{if(Y.threadID===J)Q.next(Y)})})}}get threadViewStates(){let J={};for(let[Q,Y]of this.threadsMap){let Z=this.workers.get(Q);if(Z)J[Q]=Xw(Y,Z)}return J}dispose(){for(let J of this.mainThreadSubs.values())J.unsubscribe();for(let J of this.workerStatusSubs.values())J.unsubscribe();this.mainThreadSubs.clear(),this.workerStatusSubs.clear(),this.workers.clear(),this.threadsMap.clear()}}function $N8(J,Q){switch(Q.type){case"main-thread-patch":{let{thread:Y,workerStatus:Z}=Q,{items:X}=i81(Y),G=Xw(Y,Z),V=WH({messages:Y.messages}),K=Array.isArray(V)?V:[];return{...J,items:X,viewState:G,todosList:K,mainThread:Y}}case"worker-status-change":{if(!J.mainThread)return J;let Y=Xw(J.mainThread,Q.workerStatus);if(Y===J.viewState)return J;return{...J,viewState:Y}}default:return J}}function i81(J){let Q=[],Y=new Map,Z=new Set;for(let[X,G]of J.messages.entries()){let V=`${G.role}-${X}`;switch(G.role){case"assistant":{let K=G.state.type==="streaming";for(let W of G.content)if(W.type==="tool_use"){if(Y.set(W.id,W),K)Z.add(W.id)}if(G.content.some((W)=>W.type==="text"&&W.text.trim()||W.type==="thinking"))Q.push({type:"message",id:V,message:G});for(let W of G.content)if(W.type==="tool_use"){let H=!1;for(let z=X+1;z<J.messages.length;z++){let F=J.messages[z];if(F){for(let U of F.content)if(U.type==="tool_result"&&U.toolUseID===W.id){H=!0;break}}if(H)break}if(!H)Q.push({type:"toolResult",id:W.id,toolUse:W,toolResult:{type:"tool_result",toolUseID:W.id,run:{status:K?"in-progress":"queued"}}})}break}case"info":{if(G.content.some((q)=>q.type==="manual_bash_invocation"||q.type==="summary"&&q.summary.type==="message"))Q.push({type:"message",id:V,message:G});break}case"user":{let K=G.content.some((q)=>q.type==="text"&&q.text.trim()||q.type==="image");for(let q of G.content)if(q.type==="tool_result"){let W=Y.get(q.toolUseID)??j2(J,q.toolUseID);if(!W)throw Error(`(bug) tool use ${q.toolUseID} not found`);Q.push({type:"toolResult",id:q.toolUseID,toolUse:W,toolResult:q})}if(K)Q.push({type:"message",id:V,message:G});break}}}return{items:Q}}class Qx1 extends d1{props;constructor(J){super();this.props=J}createState(){return new L$6}}class L$6 extends u1{state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null};workerController;subscriptions=[];recentThreadIDs=[];currentWorker;constructor(){super();this.workerController=null,this.currentWorker=null}addToRecentThreads(J){this.setState(()=>{let Q=this.recentThreadIDs.indexOf(J);if(Q!==-1)this.recentThreadIDs.splice(Q,1);if(this.recentThreadIDs.unshift(J),this.recentThreadIDs.length>50)this.recentThreadIDs.pop()})}initState(){let{threadService:J,worker:Q}=this.widget.props;this.workerController=new Jx1(J),this.currentWorker=Q,this.setupSubscriptions(Q),this.addToRecentThreads(Q.thread.id)}dispose(){this.cleanup()}didUpdateWidget(J){if(J.props.threadService!==this.widget.props.threadService||J.props.worker!==this.widget.props.worker)this.cleanup(),this.setupSubscriptions(this.widget.props.worker)}setupSubscriptions(J){this.workerController.registerWorker(J);let Q=this.workerController.observeThread(J.thread.id),Y=Q.mainThread.subscribe((X)=>{this.dispatch({type:"main-thread-patch",thread:X.mainThread,workerStatus:X.workerStatus})});this.subscriptions.push(Y);let Z=Q.workerStatus.subscribe((X)=>{this.dispatch({type:"worker-status-change",workerStatus:X.status})});this.subscriptions.push(Z)}cleanup(){this.subscriptions.forEach((J)=>J.unsubscribe()),this.subscriptions=[]}switchWorker(J){this.cleanup(),this.setState(()=>{this.currentWorker=J}),this.setState(()=>{this.state={items:[],viewState:{state:"initial",interactionState:!1,toolState:{running:0,blocked:0}},todosList:[],mainThread:null}}),this.setupSubscriptions(J),this.addToRecentThreads(J.thread.id)}dispatch(J){this.setState(()=>{this.state=$N8(this.state,J)})}getThreadData(){let J=(X)=>X===y9||X===C8||X===qG||X===L2,Q=new Map;for(let X of this.state.items)if(X.type==="toolResult"&&J(X.toolUse.name))Q.set(X.toolUse.id,{toolUseId:X.toolUse.id,toolName:X.toolUse.name,toolRun:X.toolResult.run});let Y=Array.from(Q.values()),Z={};for(let{toolUseId:X,toolRun:G}of Y){let V=[],K;if(G.status==="in-progress"||G.status==="done"||G.status==="error"||G.status==="cancelled")K=G.progress;if(K){let q=0;for(let W of K)if(W.tool_uses)for(let H of W.tool_uses){let z=`${X}:progress:${q++}`,F=H.status==="done"&&H.result!==void 0?{status:"done",result:H.result}:{status:H.status};V.push({toolUse:pO(H.tool_name,H.input,z),toolRun:F})}}Z[X]=V}return{...this.state,subagentToolsByParentID:Z}}build(J){let Q=this.getThreadData();return this.widget.props.builder(J,Q,this.workerController,(Y)=>this.switchWorker(Y),()=>this.currentWorker,this.recentThreadIDs)}}class Yx1 extends d1{props;constructor(J){super({key:J.key});this.props=J}createState(){return new O$6}}class O$6 extends u1{build(J){let Y=q0.of(J).colors,{todos:Z,title:X="TODOs"}=this.widget.props;if(!Array.isArray(Z)||Z.length===0)return new A1({width:0,height:0});let G=Z.map((V)=>this.buildTodoItem(V,Y));return new p1({child:new J0({padding:j1.symmetric(1,0),child:new k1({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new e({text:new S(X,new f({bold:!0,color:Y.foreground}))}),...G]})})})}buildTodoItem(J,Q){let Y=this.getStatusIcon(J.status),Z=J.status==="completed",X=new f({bold:J.status==="in-progress",color:Q.foreground,dim:Z}),G=new f({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Q.foreground,dim:Z});return new X0({crossAxisAlignment:"start",children:[new e({text:new S(Y,X)}),new A1({width:1}),new A0({child:new e({text:new S(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Zx1 extends d1{ad;onDismiss;onButtonClick;onImpression;onAdInfoClick;constructor({key:J,ad:Q,onDismiss:Y,onButtonClick:Z,onImpression:X,onAdInfoClick:G}){super({key:J});this.ad=Q,this.onDismiss=Y,this.onButtonClick=Z,this.onImpression=X,this.onAdInfoClick=G}createState(){return new A$6}}class A$6 extends u1{lastTrackedAdId=null;initState(){super.initState(),this.fireImpressionIfNeeded()}didUpdateWidget(J){super.didUpdateWidget(J),this.fireImpressionIfNeeded()}fireImpressionIfNeeded(){let J=this.widget.ad;if(J.id!==this.lastTrackedAdId)this.lastTrackedAdId=J.id,this.widget.onImpression?.(J)}build(J){let Q=q0.of(J),Y=Q.colors.primary,Z=Q.colors.foreground,X=this.widget.ad;return new p1({decoration:new N6(void 0,new x0(new j0(Y,1,"rounded"),new j0(Y,1,"rounded"),void 0,new j0(Y,1,"rounded"))),child:new J0({padding:j1.horizontal(1),child:new k1({children:[new X0({crossAxisAlignment:"start",children:[new A0({child:new e({text:new S(X.content,new f({color:Z}))})}),new A1({width:4}),new H6({onClick:()=>this.widget.onAdInfoClick?.(),cursor:"pointer",child:new e({text:new S("Ad",new f({color:Z,dim:!0}))})})]}),new X0({crossAxisAlignment:"start",children:[new hC1({text:X.buttonLabel,onPressed:()=>this.widget.onButtonClick?.(),padding:j1.horizontal(1),color:Y,reverse:!0}),new A1({width:2}),new e({text:new S(X.destinationUrlHostname,new f({color:Z,dim:!0}))})]})]})})})}}class Xx1 extends d1{props;constructor(J){super();this.props=J}createState(){return new I$6(this.props.autofocus??!0)}}class I$6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(K)=>{if(K.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(K.ctrlKey&&K.key==="c"||K.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Y=c0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(this.widget.props.title)G.push(new e({text:new S(this.widget.props.title,new f({bold:!0,color:a.blue}))}),new A1({height:1}));if(this.widget.props.message)G.push(new e({text:new S(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)G.push(new A1({height:1}));let V=[];if(this.widget.props.showCopyOption)V.push(new e({text:new S("Enter to copy",new f({dim:!0}))}));return V.push(new e({text:new S("Escape to close",new f({dim:!0}))})),G.push(new X0({children:V.flatMap((K,q)=>q<V.length-1?[K,new A1({width:1}),new e({text:new S("•",new f({dim:!0}))}),new A1({width:1})]:[K]),mainAxisSize:"min"})),new v0({child:new p1({constraints:new O0(Z,Z,0,X),decoration:new N6(a.default(),new x0(new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}class $x1 extends d1{props;constructor(J){super();this.props=J}createState(){return new E$6(this.props.autofocus??!0)}}class E$6 extends u1{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(V)=>{if(V.key==="Enter"||V.key==="Escape"||V.ctrlKey&&V.key==="c")return this.widget.props.onClose(),"handled";return"ignored"},Y=c0.sizeOf(J),Z=Math.min(60,Y.width-4),X=Y.height-4,G=[];if(G.push(new e({text:new S("Ads make Amp Free possible",new f({bold:!0}))})),this.widget.props.provider)G.push(new A1({height:1}),new e({text:new S(`Ad source: ${this.widget.props.provider}`,new f({dim:!0}))}));return G.push(new A1({height:1}),new e({text:new S("Escape to close",new f({dim:!0}))})),new v0({child:new p1({constraints:new O0(Z,Z,0,X),decoration:new N6(a.default(),new x0(new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"),new j0(a.blue,1,"rounded"))),padding:new j1(2,2,2,2),child:new A6({autofocus:this.autofocus,onKey:Q,child:new k1({children:G,mainAxisSize:"min"})})})})}}function Gx1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Y)=>{if(Y.startsWith('"')&&Y.endsWith('"')||Y.startsWith("'")&&Y.endsWith("'"))return Y.slice(1,-1);return Y})}PX();v1();import{spawn as GN8}from"node:child_process";import{promises as VN8}from"node:fs";function R$6(J){return J.kind==="executable"}function j$6(J){return J.kind==="markdown"}var HW=50000,P$6=300000;async function Vx1(J,Q,Y,Z={}){let{timeoutMs:X=P$6,signal:G,source:V}=Z;try{let K=await Y.getCommand(J,V);if(!K)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Y.isCommandAvailable(J,V))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(R.debug("Executing command",{commandName:J,filePath:K.filePath,args:Q}),j$6(K))return await KN8(K,Q);else if(R$6(K))return await qN8(K,Q,X,G);else return{success:!1,output:"",error:"Unsupported command type"}}catch(K){return R.error("Failed to execute command",{commandName:J,error:K}),{success:!1,output:"",error:K instanceof Error?K.message:"Unknown error occurred"}}}async function KN8(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Y=await VN8.readFile(J.filePath,"utf8");return{success:!0,output:(Y.length>HW?Y.slice(0,HW)+`
|
|
4985
4985
|
... (output truncated at ${HW} characters)`:Y).trim(),exitCode:0}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:"Failed to read markdown file"}}}async function qN8(J,Q,Y=P$6,Z){return new Promise((X)=>{let[G,V]=WN8(J,Q);R.debug("Spawning command",{spawnCommand:G,spawnArgs:V.slice(0,10),filePath:J.filePath,timeoutMs:Y});let K=g_(Z),q=!1,W=setTimeout(()=>{q=!0,K.abort(),R.warn("Command execution timed out",{commandName:J.name,timeoutMs:Y})},Y),H=GN8(G,V,{stdio:["pipe","pipe","pipe"],signal:K.signal,detached:!0}),z=[],F=[],U=0;H.stdout?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=HW)z.push(B);else{let N=HW-(U-B.length);if(N>0)z.push(B.slice(0,N))}}),H.stderr?.on("data",(D)=>{let B=D.toString();if(U+=B.length,U<=HW)F.push(B);else{let N=HW-(U-B.length);if(N>0)F.push(B.slice(0,N))}}),H.on("close",(D)=>{if(clearTimeout(W),q){X({success:!1,output:z.join(""),error:`Command timed out after ${Y}ms`,exitCode:void 0});return}if(K.signal.aborted){X({success:!1,output:z.join(""),error:"The command was aborted",exitCode:D??void 0});return}let B=D===0||D===1,N=z.join(""),w=F.join(""),M=N;if(!B&&!N.trim()&&w.trim())M=w;else if(w.trim())M+=N?`
|
|
4986
4986
|
${w}`:w;if(U>HW)M+=`
|
|
4987
|
-
... (output truncated at ${HW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function WN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return zN8(Y,Z?[...Z]:null,X,Q);else return HN8(Y,Z?[...Z]:null,X,Q)}function HN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function zN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}v1();tO();OJ();f9();K3();LO();wG();N3();CQ();qH();BZ();l6();Db();t9();LC();K0();var VG6=H0(lH(),1);import{writeFile as YG6}from"fs/promises";import ZG6 from"path";v1();N3();class Kx1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1768291296-g18aa0d"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ga(Q,this.configService)}catch(Q){R.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ZU extends d1{props;constructor(J){super();this.props=J}createState(){return new T$6}}class T$6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class C$6 extends u1{controller=new Q7;focusNode=new s6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=q0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=x0.all(new j0(Y.foreground,1,"solid")),q=new e2({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:a.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new p1({decoration:{border:K,color:a.default()},padding:j1.all(1),child:new k1({children:[H,new A1({height:1}),W,new O8,F]})})}}class Lg extends d1{props;constructor(J){super();this.props=J}createState(){return new C$6}}import{isDeepStrictEqual as BN8}from"node:util";var FN8=/[\\/_ +.#"@[({&]/,UN8=/[\\/_ +.#"@[({&]/g,DN8=/[\s-]/,_$6=/[\s-]/g;function a81(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=a81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(DN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(_$6),D&&X>0)z*=0.999**D.length}else if(FN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match(UN8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(F=a81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function n81(J){return J.toLowerCase().replace(_$6," ")}function S$6(J,Q){let Y=a81(J,Q,n81(J),n81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=a81(J,K,n81(J),n81(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class ij{}class nj{}class o81{}class r81{}class k$6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new y$6}}class y$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function NN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=S$6(Q,J);return{matches:Y>0.15,score:Y}}class j7 extends d1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new x$6}}class x$6 extends u1{controller=new Q7;focusNode;scrollController=new o4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new s6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!BN8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof o81){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof r81)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...NN8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=q0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=x0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new e2({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new T3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new o81],[new p0("Escape"),new r81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[o81,new h6(this.invoke)],[r81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new A1({height:10,child:new v0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new v0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?a.yellow:void 0,I=M?a.black:Y.foreground;O=new p1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new k$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new p1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:a.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new A1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new p1({padding:j1.vertical(1),child:new v0({child:N})}));else F.push(new A1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new p1({decoration:{border:X,color:a.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function v$6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class qx1 extends S0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>v$6(X.pubDate).length));return new j7({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=q0.of(K),{colors:W}=q,H=G?a.yellow:void 0,z=G?a.black:W.foreground,F=a.index(8),U=(D,B)=>new A1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new p1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new A1({width:2}),U(v$6(X.pubDate),Y)]})})}})}}class Wx1 extends d1{createState(){return new b$6}}class b$6 extends u1{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new e({text:new S("●",new f({color:this.isGreen?a.green:a.index(8),bold:!0})),maxLines:1})}}function wN8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return OY.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function Hx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function MN8(J,Q,Y,Z){return[Hx1("+",J,Z.success),O8.horizontal(1),Hx1("~",Q,Z.warning),O8.horizontal(1),Hx1("-",Y,Z.destructive)]}class s81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=wN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=q0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new v0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:a.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new j7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(z,F,U,D)=>{let B=q0.of(D),{colors:N}=B,w=F?a.yellow:void 0,M=F?a.black:N.foreground,L=a.index(8),O=(u,v)=>new A1({width:v,child:X0.end([new e({text:new S(u,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new I81;if(z.depth>0){let u=[],v=z.ancestorsAreLast.slice(1);for(let c of v)u.push(new S(C.getAncestorPrefix(c),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,m=C.getConnectorText(x);u.push(new S(m,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,u)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:a.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Wx1),y.push(new A1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let u=b.match(/^Forked\((\d+)\): /);if(u)b=b.slice(u[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:a.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:a.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new A1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let u=F?{success:L,warning:L,destructive:L}:N;y.push(...MN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,u)),y.push(new A1({width:2}))}return y.push(O(z.description.timeAgo,K)),new p1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class h$6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new g$6}}class g$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var f$6=30,LN8=30;class aj{}class oj{}class t81{}class e81{}class zx1 extends d1{props;constructor(J){super();this.props=J}createState(){return new m$6}}class m$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new o4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof t81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof e81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=q0.of(J),{colors:Z}=Y,V=c0.of(J).size.width>=LN8+f$6,K=x0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:a.yellow,bold:!0}))})}),H=new e2({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new T3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new t81],[new p0("Escape"),new e81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[t81,new h6(this.invoke)],[e81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?a.yellow:void 0,y=I?a.black:a.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?a.black:a.green})));return new h$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new p1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new p1({padding:j1.all(1),child:new jM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new A1({width:f$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new p1({decoration:{border:K,color:a.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new A1({height:1}),new A0({child:L})]})})}}class Fx1 extends S0{props;constructor(J){super();this.props=J}build(){return new v0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
|
|
4987
|
+
... (output truncated at ${HW} characters)`;X({success:B,output:M.trim(),error:!B?w.trim()||"Command failed":void 0,exitCode:D??void 0})}),H.on("error",(D)=>{clearTimeout(W);let B=D.message;if(q)B=`Command timed out after ${Y}ms`;else if(D.message.includes("operation was aborted")||D.name==="AbortError")B="The command was aborted";X({success:!1,output:z.join(""),error:B})})})}function WN8(J,Q){let{filePath:Y,interpreter:Z,extension:X}=J;if(process.platform==="win32")return zN8(Y,Z?[...Z]:null,X,Q);else return HN8(Y,Z?[...Z]:null,X,Q)}function HN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];else return[J,Z]}function zN8(J,Q,Y,Z){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...Z]];switch(Y.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...Z]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...Z]];case".exe":return[J,Z];default:return[J,Z]}}v1();tO();OJ();f9();K3();LO();wG();N3();CQ();qH();BZ();l6();Db();t9();LC();K0();var VG6=H0(lH(),1);import{writeFile as YG6}from"fs/promises";import ZG6 from"path";v1();N3();class Kx1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Y])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1768305708-gbd5551"},parameters:{metadata:{count:Y}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Ga(Q,this.configService)}catch(Q){R.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class ZU extends d1{props;constructor(J){super();this.props=J}createState(){return new T$6}}class T$6 extends u1{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Q=(Y)=>{this.setState(()=>{this._state=Y(this._state)})};return this.widget.props.builder(J,Q,this._state)}}class C$6 extends u1{controller=new Q7;focusNode=new s6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Q=q0.of(J),{colors:Y,app:Z}=Q,X=this.widget.props.isRequiredArg??!0,G=this.controller.text.trim().length>0,V=!X||G,K=x0.all(new j0(Y.foreground,1,"solid")),q=new e2({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Y.foreground,border:null},maxLines:1}),W=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]}),H=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,[new S("Command: ",new f({color:Y.foreground})),new S(this.widget.props.commandName,new f({color:a.yellow,bold:!0}))])})}),z=[];if(V)z.push(new S("Enter",new f({color:Z.keybind}))),z.push(new S(" to submit, ",new f({color:Y.foreground,dim:!0})));z.push(new S("Esc",new f({color:Z.keybind}))),z.push(new S(" to cancel",new f({color:Y.foreground,dim:!0})));let F=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("",void 0,z)})});return new p1({decoration:{border:K,color:a.default()},padding:j1.all(1),child:new k1({children:[H,new A1({height:1}),W,new O8,F]})})}}class Lg extends d1{props;constructor(J){super();this.props=J}createState(){return new C$6}}import{isDeepStrictEqual as BN8}from"node:util";var FN8=/[\\/_ +.#"@[({&]/,UN8=/[\\/_ +.#"@[({&]/g,DN8=/[\s-]/,_$6=/[\s-]/g;function a81(J,Q,Y,Z,X,G,V){if(G===Q.length){if(X===J.length)return 1;return 0.99}let K=`${X},${G}`;if(V[K]!==void 0)return V[K];let q=Z.charAt(G),W=Y.indexOf(q,X),H=0,z,F,U,D;while(W>=0){if(z=a81(J,Q,Y,Z,W+1,G+1,V),z>H){if(W===X)z*=1;else if(DN8.test(J.charAt(W-1))){if(z*=0.9,D=J.slice(X,W-1).match(_$6),D&&X>0)z*=0.999**D.length}else if(FN8.test(J.charAt(W-1))){if(z*=0.8,U=J.slice(X,W-1).match(UN8),U&&X>0)z*=0.999**U.length}else if(z*=0.3,X>0)z*=0.999**(W-X);if(J.charAt(W)!==Q.charAt(G))z*=0.9999}if(z<0.1&&(Y.charAt(W-1)===Z.charAt(G+1)||Z.charAt(G+1)===Z.charAt(G)&&Y.charAt(W-1)!==Z.charAt(G))){if(F=a81(J,Q,Y,Z,W+1,G+2,V),F*0.1>z)z=F*0.1}if(z>H)H=z;W=Y.indexOf(q,W+1)}return V[K]=H,H}function n81(J){return J.toLowerCase().replace(_$6," ")}function S$6(J,Q){let Y=a81(J,Q,n81(J),n81(Q),0,0,{}),Z=Q.trim().split(/\s+/);if(Z.length>1){let X=0,G=0;for(let K of Z){let q=a81(J,K,n81(J),n81(K),0,0,{});if(q===0)return Y;X+=q,G+=K.length}let V=X/Z.length*0.95;return Math.max(Y,V)}return Y}class ij{}class nj{}class o81{}class r81{}class k$6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new y$6}}class y$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}function NN8(J,Q){if(J==="")return{matches:!0,score:1};let Y=S$6(Q,J);return{matches:Y>0.15,score:Y}}class j7 extends d1{props;debugLabel="FuzzyPicker";constructor(J){super();this.props=J}createState(){return new x$6}}class x$6 extends u1{controller=new Q7;focusNode;scrollController=new o4;selectedIndex=0;itemContexts=[];cachedQuery="";cachedItemsRef=null;cachedFiltered=[];initState(){this.scrollController.disableFollowMode(),this.focusNode=new s6({debugLabel:this.widget.debugLabel}),this.controller.addListener(()=>{this.selectedIndex=0,this.recomputeFilteredItems(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[0]??null)}),this.recomputeFilteredItems();let J=this.cachedFiltered;this.widget.props.onSelectionChange?.(J[0]??null),this.ensureSelectedItemVisible()}didUpdateWidget(J){if(!BN8(J.props.items,this.widget.props.items)){this.recomputeFilteredItems(),this.ensureSelectedItemVisible();let Q=this.cachedFiltered;this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)}}dispose(){this.widget.props.onSelectionChange?.(null),this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}invoke=(J)=>{if(J instanceof ij){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length-1)this.selectedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof nj){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex>0)this.selectedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null);return"handled"}if(J instanceof o81){let Q=this.getFilteredItems();if(Q.length>0&&this.selectedIndex<Q.length){let Y=Q[this.selectedIndex];if(Y){if(!(this.widget.props.isItemDisabled?.(Y)??!1))this.widget.props.onAccept(Y)}}return"handled"}if(J instanceof r81)return this.widget.props.onDismiss?.(),"handled";return"ignored"};recomputeFilteredItems(){let J=this.controller.text,Q=this.widget.props.items,Y=Q.filter((Z)=>!this.widget.props.filterItem||this.widget.props.filterItem(Z,J)).map((Z)=>({item:Z,...NN8(J,this.widget.props.getLabel(Z))})).filter((Z)=>Z.matches).sort(this.widget.props.sortItems?(Z,X)=>this.widget.props.sortItems(Z,X,J):(Z,X)=>X.score-Z.score).map((Z)=>Z.item);this.cachedQuery=J,this.cachedItemsRef=Q,this.cachedFiltered=this.widget.props.maxRenderItems?Y.slice(0,this.widget.props.maxRenderItems):Y}getFilteredItems(){let J=this.controller.text,Q=this.widget.props.items;if(this.cachedQuery===J&&this.cachedItemsRef===Q)return this.cachedFiltered;return this.recomputeFilteredItems(),this.cachedFiltered}ensureSelectedItemVisible(){let J=this.itemContexts[this.selectedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}handleScroll=(J)=>{let Q=this.getFilteredItems();if(Q.length===0)return;if(J.direction==="down")if(this.selectedIndex<Q.length-1)this.selectedIndex++;else return;else if(this.selectedIndex>0)this.selectedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()}),this.widget.props.onSelectionChange?.(Q[this.selectedIndex]??null)};handleItemClick=(J,Q)=>{let Y=this.getFilteredItems();if(J>=0&&J<Y.length){let Z=Y[J],X=Z?this.widget.props.isItemDisabled?.(Z)??!1:!1;if(Q===1)this.selectedIndex=J,this.setState(),this.widget.props.onSelectionChange?.(Y[this.selectedIndex]??null);else if(Q===2&&!X){if(Z)this.widget.props.onAccept(Z)}}};build(J){let Q=q0.of(J),{colors:Y}=Q,Z=this.getFilteredItems(),X=x0.all(new j0(Y.foreground,1,"solid")),G=this.widget.props.enabled??!0,V=new e2({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:G,style:{textColor:Y.foreground,border:null},maxLines:1}),K=new T3({shortcuts:new Map([[new p0("ArrowDown"),new ij],[new p0("ArrowUp"),new nj],[new p0("Tab"),new ij],[new p0("Tab",{shift:!0}),new nj],[new p0("n",{ctrl:!0}),new ij],[new p0("p",{ctrl:!0}),new nj],[new p0("Enter"),new o81],[new p0("Escape"),new r81]]),focusNode:this.focusNode,child:V}),q=new b5({actions:new Map([[ij,new h6(this.invoke)],[nj,new h6(this.invoke)],[o81,new h6(this.invoke)],[r81,new h6(this.invoke)]]),child:K}),W=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Y.foreground}))})}),new A0({child:q})]});this.itemContexts=[];let H;if(this.widget.props.isLoading){let B=this.widget.props.loadingText??"Loading...";H=new A1({height:10,child:new v0({child:new e({text:new S(B,new f({color:Y.foreground}))})})})}else if(Z.length===0&&this.widget.props.emptyStateText)H=new A0({child:new v0({child:new e({text:new S(this.widget.props.emptyStateText,new f({color:Y.foreground,dim:!0}))})})});else{let B=Z.map((N,w)=>{let M=w===this.selectedIndex,L=this.widget.props.isItemDisabled?.(N)??!1,O;if(this.widget.props.renderItem)O=this.widget.props.renderItem(N,M,L,J);else{let A=M?a.yellow:void 0,I=M?a.black:Y.foreground;O=new p1({decoration:A?{color:A}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(this.widget.props.getLabel(N),new f({color:I,dim:L}))})})}return new k$6(new H6({onClick:(A)=>this.handleItemClick(w,A.clickCount),child:O}),(A)=>{this.itemContexts[w]=A})});H=new k1({children:B,crossAxisAlignment:"start"})}let z=new A0({child:new H6({onScroll:this.handleScroll,opaque:!1,child:new q4({controller:this.scrollController,autofocus:!1,child:H})})}),F=[];if(this.widget.props.title){let B=new p1({padding:j1.symmetric(1,0),child:new e({text:new S(this.widget.props.title,new f({color:a.yellow,bold:!0}))})});F.push(B)}if(F.push(W,new A1({height:1}),z),this.controller.text!==""){let B=Z.length>0?Z[this.selectedIndex]:void 0,N=B&&this.widget.props.buildDisabledReasonWidget?.(B);if(N)F.push(new p1({padding:j1.vertical(1),child:new v0({child:N})}));else F.push(new A1({height:3}))}if(this.widget.props.footer)F.push(this.widget.props.footer);return new p1({decoration:{border:X,color:a.default()},padding:j1.symmetric(1,0),child:new k1({children:F})})}}function v$6(J){let Y=new Date().getTime()-J.getTime(),Z=Math.floor(Y/60000),X=Math.floor(Y/3600000),G=Math.floor(Y/86400000);if(Z<1)return"just now";if(Z<60)return`${Z}m ago`;if(X<24)return`${X}h ago`;if(G<7)return`${G}d ago`;return J.toLocaleDateString()}class qx1 extends S0{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Q=[...this.props.entries].sort((X,G)=>G.pubDate.getTime()-X.pubDate.getTime()),Y=Math.max(0,...Q.map((X)=>v$6(X.pubDate).length));return new j7({items:Q,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,G,V,K)=>{let q=q0.of(K),{colors:W}=q,H=G?a.yellow:void 0,z=G?a.black:W.foreground,F=a.index(8),U=(D,B)=>new A1({width:B,child:X0.end([new e({text:new S(D,new f({color:F}))})])});return new p1({decoration:H?{color:H}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[new A0({child:new e({text:new S(X.title,new f({color:z})),overflow:"ellipsis",maxLines:1})}),new A1({width:2}),U(v$6(X.pubDate),Y)]})})}})}}class Wx1 extends d1{createState(){return new b$6}}class b$6 extends u1{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){return new e({text:new S("●",new f({color:this.isGreen?a.green:a.index(8),bold:!0})),maxLines:1})}}function wN8(J){let Q=new Map,Y=new Map,Z=new Map,X=[];for(let V of J)Q.set(V.id,V);for(let V of J){let K=V.parentRelationships.find((q)=>q.role==="child"&&Q.has(q.threadID)&&(q.type==="fork"||q.type==="handoff"));if(K){Z.set(V.id,K.type);let q=K.threadID,W=Y.get(q)||[];W.push(V),Y.set(q,W)}else X.push(V)}return OY.flatten(X,(V)=>Y.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Z.get(V.item.id)}))}function Hx1(J,Q,Y){return new e({text:new S(`${J}${Q}`,new f({color:Y})),maxLines:1})}function MN8(J,Q,Y,Z){return[Hx1("+",J,Z.success),O8.horizontal(1),Hx1("~",Q,Z.warning),O8.horizontal(1),Hx1("-",Y,Z.destructive)]}class s81 extends S0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}build(J){let Q=this.props.filterByWorkspace&&this.props.currentWorkspaceURI?this.props.threads.filter((z)=>z.workspaceURI===this.props.currentWorkspaceURI):this.props.threads;if(this.props.excludeCurrentThread&&this.props.currentThreadID)Q=Q.filter((z)=>z.id!==this.props.currentThreadID);let Y=this.props.recentThreadIDs||[],Z=new Set(Y),X=this.props.currentThreadID,G=[...Q].sort((z,F)=>{if(X){if(z.id===X)return-1;if(F.id===X)return 1}let U=Y.indexOf(z.id),D=Y.indexOf(F.id);if(U!==-1&&D!==-1)return U-D;if(U!==-1)return-1;if(D!==-1)return 1;return 0}),V=wN8(G),K=Math.max(0,...V.map((z)=>z.description.timeAgo.length)),q=q0.of(J),W=new J0({padding:j1.symmetric(0,1),child:new v0({child:new e({text:new S("",new f({color:q.colors.foreground,dim:!0}),[new S("Ctrl+T",new f({color:a.blue,dim:!0})),new S(this.props.filterByWorkspace?" for all workspaces":" to filter by workspace",new f({color:q.colors.foreground,dim:!0}))])})})});return new j7({items:V,getLabel:(z)=>z.title,onAccept:(z)=>this.props.onSelect?.(z.id),onDismiss:this.props.onDismiss,onSelectionChange:(z)=>{if(this.props.previewController){if(z)this.props.previewController.select(z.id)}},title:this.props.title,isLoading:this.props.isLoading,loadingText:"Loading threads...",emptyStateText:"No threads match your filter",maxRenderItems:200,footer:this.props.isLoading?void 0:W,renderItem:(z,F,U,D)=>{let B=q0.of(D),{colors:N}=B,w=F?a.yellow:void 0,M=F?a.black:N.foreground,L=a.index(8),O=(u,v)=>new A1({width:v,child:X0.end([new e({text:new S(u,new f({color:L}))})])}),A=this.props.threadViewStates[z.id],I=[],j=z.relationshipType==="handoff",C=new I81;if(z.depth>0){let u=[],v=z.ancestorsAreLast.slice(1);for(let c of v)u.push(new S(C.getAncestorPrefix(c),new f({color:C.connectorColor,dim:C.connectorDim})));let x=z.isLast?C.elbow:C.tee,m=C.getConnectorText(x);u.push(new S(m,new f({color:C.connectorColor,dim:C.connectorDim}))),I.push(new e({text:new S("",void 0,u)}))}let y=[],k=X===z.id?new S("(current) ",new f({color:a.green})):Z.has(z.id)?new S("(visited) ",new f({color:N.foreground,dim:!0})):null;if(k)y.push(new e({text:k}));if(A){if(A.state==="active"&&(A.interactionState==="tool-running"||A.interactionState==="handoff"||A.inferenceState==="running"))y.push(new Wx1),y.push(new A1({width:1}))}let b=z.title;if(z.relationshipType==="fork"){let u=b.match(/^Forked\((\d+)\): /);if(u)b=b.slice(u[0].length);else while(b.startsWith("Forked: "))b=b.slice(8);y.push(new e({text:new S("[fork] ",new f({color:a.blue}))}))}else if(j)y.push(new e({text:new S("[handoff] ",new f({color:a.index(208)}))}));if(y.push(new A0({child:new e({text:new S(b,new f({color:M})),overflow:"ellipsis",maxLines:1})})),y.push(new A1({width:2})),z.diffStats&&(z.diffStats.added>0||z.diffStats.changed>0||z.diffStats.deleted>0)){let u=F?{success:L,warning:L,destructive:L}:N;y.push(...MN8(z.diffStats.added,z.diffStats.changed,z.diffStats.deleted,u)),y.push(new A1({width:2}))}return y.push(O(z.description.timeAgo,K)),new p1({decoration:w?{color:w}:void 0,padding:j1.symmetric(2,0),child:new X0({children:[...I,...y]})})}})}}class h$6 extends d1{child;onContext;constructor(J,Q){super();this.child=J;this.onContext=Q}createState(){return new g$6}}class g$6 extends u1{build(J){return this.widget.onContext(J),this.widget.child}}var f$6=30,LN8=30;class aj{}class oj{}class t81{}class e81{}class zx1 extends d1{props;constructor(J){super();this.props=J}createState(){return new m$6}}class m$6 extends u1{highlightedIndex=0;controller=new Q7;focusNode;scrollController=new o4;filteredClusters=[];itemContexts=[];initState(){this.focusNode=new s6({debugLabel:"ClusterPicker"}),this.scrollController.disableFollowMode(),this.recomputeFiltered(),this.controller.addListener(()=>{this.highlightedIndex=0,this.recomputeFiltered(),this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})})}didUpdateWidget(J){if(J.props.clusters!==this.widget.props.clusters){if(this.recomputeFiltered(),this.highlightedIndex>=this.filteredClusters.length)this.highlightedIndex=Math.max(0,this.filteredClusters.length-1)}}ensureSelectedItemVisible(){let J=this.itemContexts[this.highlightedIndex];if(!J)return;let Q=J.findRenderObject();if(!Q)return;let Y=0,Z=Q.size.height;nR(J,{top:Y,bottom:Z},{padding:1})}dispose(){this.controller.dispose(),this.focusNode.dispose(),this.scrollController.dispose()}recomputeFiltered(){let J=this.controller.text.toLowerCase(),{clusters:Q}=this.widget.props;if(!J)this.filteredClusters=[...Q];else this.filteredClusters=Q.filter((Y)=>Y.label.toLowerCase().includes(J))}invoke=(J)=>{if(J instanceof aj){if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof oj){if(this.highlightedIndex>0)this.highlightedIndex--,this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()});return"handled"}if(J instanceof t81){let Q=this.filteredClusters[this.highlightedIndex];if(Q)this.widget.props.onAccept(Q);return"handled"}if(J instanceof e81)return this.widget.props.onDismiss(),"handled";return"ignored"};handleItemClick=(J,Q)=>{if(J>=0&&J<this.filteredClusters.length){if(Q===1)this.highlightedIndex=J,this.setState();else if(Q===2){let Y=this.filteredClusters[J];if(Y)this.widget.props.onAccept(Y)}}};handleScroll=(J)=>{if(this.filteredClusters.length===0)return;if(J.direction==="down")if(this.highlightedIndex<this.filteredClusters.length-1)this.highlightedIndex++;else return;else if(this.highlightedIndex>0)this.highlightedIndex--;else return;this.setState(),Y4.instance.addPostFrameCallback(()=>{this.ensureSelectedItemVisible()})};build(J){let{currentThreadID:Q}=this.widget.props,Y=q0.of(J),{colors:Z}=Y,V=c0.of(J).size.width>=LN8+f$6,K=x0.all(new j0(Z.foreground,1,"solid")),q=this.filteredClusters[this.highlightedIndex]??null,W=new p1({padding:j1.symmetric(1,0),child:new e({text:new S("Select a cluster",new f({color:a.yellow,bold:!0}))})}),H=new e2({controller:this.controller,focusNode:this.focusNode,autofocus:!0,enabled:!0,style:{textColor:Z.foreground,border:null},maxLines:1}),z=new T3({shortcuts:new Map([[new p0("ArrowDown"),new aj],[new p0("ArrowUp"),new oj],[new p0("Tab"),new aj],[new p0("Tab",{shift:!0}),new oj],[new p0("n",{ctrl:!0}),new aj],[new p0("p",{ctrl:!0}),new oj],[new p0("Enter"),new t81],[new p0("Escape"),new e81]]),focusNode:this.focusNode,child:H}),F=new b5({actions:new Map([[aj,new h6(this.invoke)],[oj,new h6(this.invoke)],[t81,new h6(this.invoke)],[e81,new h6(this.invoke)]]),child:z}),U=new X0({children:[new p1({decoration:{color:a.default()},child:new e({text:new S(">",new f({color:Z.foreground}))})}),new A0({child:F})]});this.itemContexts=[];let D=this.filteredClusters.map((O,A)=>{let I=A===this.highlightedIndex,j=Q?O.threads.some((b)=>b.id===Q):!1,C=I?a.yellow:void 0,y=I?a.black:a.default(),k=[new S(O.label,new f({color:y})),new S(` (${O.threads.length})`,new f({color:y,dim:!0}))];if(j)k.push(new S(" (current)",new f({color:I?a.black:a.green})));return new h$6(new H6({onClick:(b)=>this.handleItemClick(A,b.clickCount),child:new p1({decoration:C?{color:C}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,k)})})}),(b)=>{this.itemContexts[A]=b})}),B=new k1({children:D,crossAxisAlignment:"start"}),N=new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})}),w=q?q.threads.map((O)=>({id:O.id,title:O.title,parentID:O.parentID,updatedAt:O.updatedAt})):[],M=q?new p1({padding:j1.all(1),child:new jM({threads:w,autofocus:!1,offsetY:2})}):null,L;if(V){let O=M?new A0({child:M}):new A1({width:f$6});L=new X0({crossAxisAlignment:"stretch",mainAxisAlignment:"start",children:[N,O]})}else{let O=[new A0({child:new H6({onScroll:this.handleScroll,child:new q4({controller:this.scrollController,autofocus:!1,child:B})})})];if(M)O.push(new A0({child:M}));L=new k1({crossAxisAlignment:"stretch",children:O})}return new p1({decoration:{border:K,color:a.default()},padding:j1.symmetric(1,0),child:new k1({children:[W,U,new A1({height:1}),new A0({child:L})]})})}}class Fx1 extends S0{props;constructor(J){super();this.props=J}build(){return new v0({child:new e({text:new S("",void 0,[new S(`Forked to new thread:
|
|
4988
4988
|
|
|
4989
4989
|
`,new f({color:a.white,dim:!0})),new S(`"${this.props.newThreadTitle||"Untitled"}"`,new f({color:a.white}))]),textAlign:"center"})})}}v1();class u$6 extends u1{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let J=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!J.ok){R.error("Failed to load labels",J.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=J.result,this.isLoading=!1,this.setState()}catch(J){R.error("Failed to load labels",J),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(J){if(J.length===0)return null;if(J.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(J))return"Label must be lowercase alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(J){return this.getValidationError(J)===null&&J.length>0}getAvailableLabels(){let J=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!J.includes(Q.name))}shouldShowCreateMarker(J){if(J.length===0||this.isLoading)return!1;let Q=J.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let Y=this.widget.props.currentLabels||[],Z=this.labels.some((G)=>G.name===Q),X=Y.includes(Q);return!Z&&!X}build(J){let Q=q0.of(J),{colors:Y}=Q,Z=this.currentQuery.trim().toLowerCase(),X=Z.length>0?this.getValidationError(Z):null,G=this.getAvailableLabels(),K=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...G];return new j7({title:"Add Label",items:K,getLabel:(q)=>{if("__isCreateMarker"in q)return this.currentQuery.trim().toLowerCase();return q.name},onAccept:(q)=>{if("__isCreateMarker"in q)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(q.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:X||"Type to create a new label",renderItem:(q,W,H,z)=>{let F=W?a.yellow:void 0,U=W?a.black:Y.foreground;if("__isCreateMarker"in q&&q.__isCreateMarker){let B=this.currentQuery.trim().toLowerCase();return new p1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S("",void 0,[new S("Create new label: ",new f({color:U})),new S(B,new f({color:U,bold:!0}))])})})}return new p1({decoration:F?{color:F}:void 0,padding:j1.symmetric(2,0),child:new e({text:new S(q.name,new f({color:U}))})})},filterItem:(q,W)=>{if(this.currentQuery!==W)this.currentQuery=W,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in q&&q.__isCreateMarker)return this.shouldShowCreateMarker(W);let z=W.trim().toLowerCase();return z.length===0||q.name.includes(z)},sortItems:(q,W,H)=>{let z="__isCreateMarker"in q.item&&q.item.__isCreateMarker,F="__isCreateMarker"in W.item&&W.item.__isCreateMarker;if(z&&!F)return-1;if(!z&&F)return 1;return W.score-q.score}})}}class Ux1 extends d1{props;constructor(J){super();this.props=J}createState(){return new u$6}}class XU extends d1{props;constructor(J){super();this.props=J}createState(){return new p$6}}class p$6 extends u1{_spinner=new ZJ;animationInterval=null;initState(){super.initState(),this.animationInterval=setInterval(()=>{this._spinner.step(),this.setState(()=>{})},100)}dispose(){if(this.animationInterval)clearInterval(this.animationInterval),this.animationInterval=null;super.dispose()}build(J){let Q=q0.of(J),{colors:Y}=Q,Z=x0.all(new j0(Y.foreground,1,"solid")),X=this._spinner.toBraille(),G=new e({textAlign:"center",text:new S("",void 0,[new S(X,new f({color:a.yellow})),new S(" ",void 0),new S(this.widget.props.message,new f({color:Y.foreground}))])}),K=[new A0({child:new k1({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[G]})})];if(this.widget.props.onAbort)K.push(new A1({height:2,child:new p1({padding:j1.symmetric(2,0),child:new e({text:new S("",new f({dim:!0}),[new S("Press ",new f({color:Y.foreground})),new S("Esc",new f({color:Y.info})),new S(" to cancel",new f({color:Y.foreground}))])})})}));let q=new p1({decoration:new N6(a.default(),Z),child:new A1({width:60,height:7,child:new k1({mainAxisAlignment:"start",children:K})})});if(this.widget.props.onAbort)return new A6({debugLabel:"LoadingDialog",autofocus:!0,onKey:(W)=>{if(W.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:q});return q}}class PM extends d1{props;constructor(J){super();this.props=J}createState(){return new d$6}}class d$6 extends u1{scrollController=new o4;scrollAreaKey=new o7("message-dialog-scroll-area");viewportHeight=20;initState(){super.initState(),this.scrollController.followMode=!1,this.scrollController.addListener(()=>{this.setState()})}dispose(){this.scrollController.dispose(),super.dispose()}isWidgetMessage(J){return J instanceof LY}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let Y=Q.size;if(typeof Y.height==="number"&&Y.height>0)return this.viewportHeight=Y.height,Y.height}return this.viewportHeight}build(J){let Q=q0.of(J),Y=this.widget.props.message,Z=(()=>{if(this.isWidgetMessage(Y))return{title:Y.title,type:Y.type};if(Y instanceof Error&&Y.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:Y.message};if(Y instanceof Error&&Y.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:Y.message};let H=A81(Y);return{title:H.title,type:H.type,description:H.description}})(),X=Z.type==="error"?a.red:a.yellow,G=x0.all(new j0(a.default(),1,"solid")),V=new p1({padding:j1.symmetric(1,0),child:new e({text:new S(Z.title,new f({color:X,bold:!0}))})}),K=this.isWidgetMessage(Y)?Y.widget:new e({text:new S(Z.description,new f({color:a.default()})),selectable:!0}),q=new A0({child:new j$({child:new p1({padding:j1.symmetric(1,0),child:new X0({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new A0({child:new q4({controller:this.scrollController,autofocus:!0,child:K})}),new C9({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let H=this.scrollController.maxScrollExtent,z=this.scrollController.offset,F=this.getViewportHeight(),U=H+F;return{totalContentHeight:Math.max(U,0),viewportHeight:Math.max(F,1),scrollOffset:Math.max(z,0)}}})]})})})}),W=new p1({padding:j1.symmetric(1,0),child:new e({text:this.widget.props.onRetry?new S("",void 0,[new S("Press ",new f({color:a.default(),dim:!0})),new S("R",new f({color:a.yellow})),new S(" to retry, ",new f({color:a.default(),dim:!0})),new S("Esc",new f({color:a.yellow})),new S(" to cancel",new f({color:a.default(),dim:!0}))]):new S("Press any key to close",new f({color:a.default(),dim:!0,italic:!0}))})});return new A6({onKey:(H)=>{if(this.widget.props.onRetry&&H.key==="r")return this.widget.props.onRetry(),"handled";if(H.key==="Escape")return this.widget.props.onDismiss(),"handled";if(!this.widget.props.onRetry)return this.widget.props.onDismiss(),"handled";return"ignored"},autofocus:!1,child:new p1({decoration:{border:G,color:a.default()},padding:j1.all(1),child:new k1({mainAxisAlignment:"center",children:[V,new A1({height:1}),q,W]})})})}}class Dx1 extends S0{build(){return new v0({child:new e({text:new S("",void 0,[new S(`✓ Thread Shared
|
|
4990
4990
|
|
|
@@ -5093,7 +5093,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
5093
5093
|
|
|
5094
5094
|
To use Sonnet 4.5, use large mode instead: amp --mode large
|
|
5095
5095
|
Learn more: https://ampcode.com/news/large-mode
|
|
5096
|
-
`),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")NG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")NG("experimental.agentMode",Q.mode)}async function B51(J){try{await WI8(F51.dirname(mb1),{recursive:!0}),await HI8(mb1,J,"utf-8")}catch(Q){R.debug("Failed to save last thread ID",Q)}}async function UI8(){try{return(await dW6(mb1,"utf-8")).trim()}catch(J){return null}}function DI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var mW6=[{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??uZ,description:`Custom settings file path (overrides the default location ${uZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${_w})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:J7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:BO.SMART.key,description:`Set the agent mode (${LJ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:LJ().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],uW6=(J)=>("deprecated"in J)&&J.deprecated===!0,BI8=(J)=>("hidden"in J)&&J.hidden===!0,NI8=(J)=>("default"in J),wI8=(J)=>("default"in J)?J.default:void 0;function MI8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new o6(fZ.unknownCommand(Y),1,V)}}var cW6=null;function gb5(){return cW6}async function DP(J){let Q=await J.configService.getLatest(),Y=iT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:OE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new BI(J.fileSystem),generateThreadTitle:yi0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_Q(J.configService),internalHooks:nT0(Y)}}var U51=Q0.file(zI8.homedir()),ub1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(U51,".config");async function h3(J,Q){UD0("0.0.
|
|
5096
|
+
`),process.exit(1);if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")NG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")NG("experimental.agentMode",Q.mode)}async function B51(J){try{await WI8(F51.dirname(mb1),{recursive:!0}),await HI8(mb1,J,"utf-8")}catch(Q){R.debug("Failed to save last thread ID",Q)}}async function UI8(){try{return(await dW6(mb1,"utf-8")).trim()}catch(J){return null}}function DI8(J){return!!(J&&(J.endsWith("@sourcegraph.com")||J.endsWith("@ampcode.com")||J==="auth-bypass-user@example.com"))}var mW6=[{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??uZ,description:`Custom settings file path (overrides the default location ${uZ})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(R).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${_w})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:J7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"useSonnet",long:"use-sonnet",type:"flag",description:(J)=>J?"Use Claude Sonnet 4.5 instead of Claude Opus 4.5":"Use default model (Claude Opus 4.5)",hidden:!0},{name:"mode",long:"mode",short:"m",type:"option",default:BO.SMART.key,description:`Set the agent mode (${LJ().map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:LJ().map((J)=>J.mode).concat("large")},{name:"jmap",long:"jmap",type:"switch",default:!1,description:"Use experimental JMAP TUI (connects to server instead of running locally)",hidden:!0}],uW6=(J)=>("deprecated"in J)&&J.deprecated===!0,BI8=(J)=>("hidden"in J)&&J.hidden===!0,NI8=(J)=>("default"in J),wI8=(J)=>("default"in J)?J.default:void 0;function MI8(J,Q){let Y=Q.args[0],Z=Q.commands.map((G)=>G.name());if(Y&&!Y.includes(" ")&&Y.length<30&&!/[./\\]/.test(Y)){let G=Z.filter((K)=>Y.includes(K)||K.includes(Y)),V="Run amp --help for a list of available commands.";if(G.length>0)V=`Did you mean: ${G.join(", ")}? Or run amp --help for all commands.`;throw new o6(fZ.unknownCommand(Y),1,V)}}var cW6=null;function gb5(){return cW6}async function DP(J){let Q=await J.configService.getLatest(),Y=iT0(Q.settings["experimental.autoHandoff"]);return{...J,getThreadEnvironment:MR,vfs:OE0({os:J.fileSystem},J.configService.config),skillService:J.skillService,fileChangeTrackerStorage:new BI(J.fileSystem),generateThreadTitle:yi0,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>_Q(J.configService),internalHooks:nT0(Y)}}var U51=Q0.file(zI8.homedir()),ub1=process.env.XDG_CONFIG_HOME?Q0.file(process.env.XDG_CONFIG_HOME):s1.joinPath(U51,".config");async function h3(J,Q){UD0("0.0.1768305708-gbd5551");let Y=sl({storage:J.settings,secretStorage:J.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:U51,userConfigDir:ub1}),Z=I0(_Q(Y).pipe(u4((m)=>m!=="pending"))),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (A91(),O91));X(Y);let G=await Y.getLatest();R.debug("Global configuration initialized",{settingsKeys:Object.keys(G.settings)});let{toolService:V,dispose:K}=nr0({configService:Y}),q=new Map,W=()=>q.clear(),H=new JU1(Y,J.settings.getWorkspaceRootPath()),z=fT0({configService:Y,filesystem:l4}),F=eI0({configService:Y,trustStore:H,skillMCPServers:z.skillMCPServers,createOAuthProvider:async(m,c,h)=>{let i=`${m}:${c}`,g=q.get(i);if(g)return R.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:c}),g;R.debug("Creating OAuth provider for server",{serverName:m,serverUrl:c});let V1=(async()=>{let O1=new AB(J.secrets),n=await O1.getClientInfo(m,c),w1=h?.scopes??n?.scopes,M1=h96();R.info("OAuth headless mode check",{useHeadless:M1,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:T8.isTTY});let S1;if(M1)S1=J.executeMode?f96():b96(m);let B1=new rF1({storage:O1,serverName:m,serverUrl:c,clientId:h?.clientId??n?.clientId,clientSecret:h?.clientSecret??n?.clientSecret,authUrl:h?.authUrl??n?.authUrl,tokenUrl:h?.tokenUrl??n?.tokenUrl,scopes:w1,headlessAuthHandler:S1});return R.debug("OAuth provider created",{serverName:m,serverUrl:c,hasManualClientId:!!(h?.clientId??n?.clientId),willUseDCR:!(h?.clientId??n?.clientId),scopes:w1,headlessMode:M1,executeMode:J.executeMode}),B1})();return q.set(i,V1),V1}}),U=Pb({configService:Y,filesystem:l4,spawn:XF}),{initializeToolProviders:D,startToolProviders:B}=await Promise.resolve().then(() => (gW6(),hW6)),N;if(J.executeMode){let m=await D({toolService:V,providers:[F,U],initialTimeout:15000});N=m.registrations;for(let[c,h]of m.initErrors)R.warn(`${c} provider initialization slow or failed:`,h)}else N=B({toolService:V,providers:[F,U]});if(Q.jetbrains)oO("JetBrains");else if(Q.ide&&w86())oO("VS Code");else if(Q.ide&&M86())oO("Neovim");if(J.executeMode)DD0(!0);let w,M=h9.status.pipe(W0((m)=>Boolean(m.connected&&m.authenticated)),q6()).subscribe((m)=>{if(m){if(!w)w=V.registerTool(ua0)}else w?.dispose(),w=void 0}),L;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];L=new D01(process.cwd(),{alwaysIncludePaths:m},!0)}else L=new class extends D01{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(T8.write(`No API key found. Starting login flow...
|
|
5097
5097
|
`),!await LI8(J))await Sw(),process.exit(1)}let O=await dT0({isDevelopment:!1}),A=await Z,I=D9(A)&&A.features.some((m)=>m.name===_X.LIVE_SYNC&&m.enabled),j=new CE1(O,Y,I),C=new NE1(O,{lazy:!0}),y=Q.notifications!==void 0?Q.notifications:!J.executeMode,k=er0({playNotificationSound:async(m)=>{if(y){tr0(m);let c=s01(),h=cT1();if((!c||h)&&G.settings["notifications.system.enabled"]!==!1){if(m==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(m==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(s01()),threadService:j,configService:Y});R.info("Starting Amp background services");let b=gi0({threadService:j,threadHistoryService:C,configService:Y,isExtensionDevelopment:!1,liveSyncEnabled:I,fileChangeTrackerStorage:new BI(l4),fileSystem:l4,getServerStatus:()=>_Q(Y)}),d;h9.status.subscribe((m)=>{d=m});let u=new tq1({workspaceRoots:[Q0.file(process.cwd())],getCurrentFile:()=>{if(!d?.openFile)return;try{return Q0.parse(d.openFile)}catch(m){R.warn("Failed to parse current file URI",{uri:d.openFile,error:m});return}},getOpenFiles:()=>{if(!d?.visibleFiles?.length)return[];let m=d.openFile;return d.visibleFiles.filter((c)=>c!==m).map((c)=>{try{return Q0.parse(c)}catch(h){return R.warn("Failed to parse visible file URI",{uri:c,error:h}),null}}).filter((c)=>c!==null)}}),v=new Sk1,x={codebaseContextService:u,configService:Y,toolService:V,mcpService:F,skillService:z,toolboxService:U,trustStore:H,threadService:j,threadHistoryService:C,threadSyncService:b,threadStorage:O,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:L,notificationService:k,fileSystem:Q.jetbrains||Q.ide?wE0:l4,terminal:v,serverStatus:A};return{...x,async asyncDispose(){if(x.mcpService.hasAuthenticatingClients())R.info("Waiting for OAuth authentication to complete before exit..."),await x.mcpService.waitForAuthentication();for(let m of N.values())m.dispose();await x.mcpService.dispose(),W(),await x.threadService.asyncDispose(),await x.threadSyncService.flushFileChanges(),x.configService.unsubscribe(),K(),x.fuzzyServer.dispose(),x.threadSyncService.dispose(),x.settingsStorage[Symbol.dispose](),M.unsubscribe(),w?.dispose()}}}async function LI8(J){if(!J.executeMode){if(!await Pk1("Would you like to log in to Amp? [(y)es, (n)o]: "))return T8.write(`Login cancelled. Run the command again to retry.
|
|
5098
5098
|
`),!1}return await lW6(J)}async function lW6(J){let Q=qI8(32).toString("hex"),Y=await jk1(J.ampURL,Q),Z=new AbortController;try{await HH(Y,Z.signal)}catch(G){R.error("Error opening browser",{error:G})}let X=await jk1(J.ampURL,Q,!1);T8.write(`If your browser does not open automatically, visit:
|
|
5099
5099
|
|
|
@@ -5101,7 +5101,7 @@ ${Z0.blue.bold(X)}
|
|
|
5101
5101
|
|
|
5102
5102
|
`);try{return await eQ6(J.ampURL,Q,J.secrets,Z),T8.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(G){return R.error("Login failed",{error:G}),Y3.write(`
|
|
5103
5103
|
Login failed: ${G instanceof Error?G.message:String(G)}
|
|
5104
|
-
`),!1}}function OI8(){let J=new F$().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)_R(),process.exit(0);let z=H.originalError??H;r06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${cA(new Date("2026-01-
|
|
5104
|
+
`),!1}}function OI8(){let J=new F$().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)_R(),process.exit(0);let z=H.originalError??H;r06(z)}),J.option("-V, --version","Print the version number and exit",()=>{let z;try{z=`, ${cA(new Date("2026-01-13T12:06:10.736Z"))} ago`}catch{}T8.write(`0.0.1768305708-gbd5551 (released 2026-01-13T12:06:10.736Z${z??""})
|
|
5105
5105
|
`),process.exit(0)}),J.addHelpText("after",F56()),J.configureHelp({formatHelp:U56}),J.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await I5(F);await RI8(U)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await I5(F);await EI8(U,await UC1(F,U.settings))});let Q=async(H,z,F)=>{sl({storage:z.settings,secretStorage:z.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:z.ampURL,homeDir:U51,userConfigDir:ub1});let U={...z,executeMode:!1};await D51(U,{...H,openThreadSwitcher:!0},F)},Y=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await I5(F);await pW6(F,U,z)});if(Y.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await I5(F);await xI8(F,U,z)}),Y.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);if(z.pick)Y3.write(`${Z0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
5106
5106
|
`);if(z.last||H||D.executeMode)await yI8(U,D,H,F);else await Q(U,D,F)}),Y.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await SI8(U,D,H,F)}),Y.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(H,z)=>{let F=z.optsWithGlobals(),U=await I5(F);await pW6(F,U,z)}),Y.command("search <query>").alias("find").summary("Search threads").description(`Search for threads using a query DSL.
|
|
5107
5107
|
|
|
@@ -5120,13 +5120,13 @@ Examples:
|
|
|
5120
5120
|
amp threads handoff T-xxx --goal "Continue working on the auth feature"
|
|
5121
5121
|
amp threads handoff --goal "Fix the remaining tests" # Uses last thread
|
|
5122
5122
|
|
|
5123
|
-
By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await kI8(U,D,H??null,z.goal,!z.print,F)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await TI8(U,D,H,F)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await CI8(U,D,H,z,F)}),xs0(Y,I5,z2,h3,og,MU,g3),fY6(J,async(H,z)=>{let F=await I5(z);z2(H,z);let U=await h3(F,z);return{context:F,mcpService:U.mcpService,toolService:U.toolService,toolServices:U.toolService,configService:U.configService,cleanupTerminal:_R,asyncDispose:U.asyncDispose.bind(U)}}),IY6(J,async(H)=>{let z=H.optsWithGlobals(),F=await I5(z);z2(H,z);let U=await h3(F,z);return{settings:F.settings,configService:U.configService,skillService:U.skillService,asyncDispose:U.asyncDispose.bind(U)}}),FY6(J,async(H)=>{let z=H.optsWithGlobals();return await I5(z)}),$Y6(J,async(H)=>{let z=await I5(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(F)=>{z2(F,H);let U=await h3(z,H);return{mcpService:U.mcpService,settings:z.settings,asyncDispose:U.asyncDispose.bind(U)}}}}),process.env.AMP_EXPERIMENTAL_REMOTE==="1")DY6(J,async(H,z)=>{let F=await I5(z);z2(H,z);let U=sl({storage:F.settings,secretStorage:F.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:U51,userConfigDir:ub1}),D=await I0(_Q(U).pipe(u4((N)=>N!=="pending"))),B=D9(D)?D.features:[];return{ampURL:F.ampURL,secretStorage:F.secrets,features:B,asyncDispose:async()=>{}}},async(H,z)=>{let F=await I5(z);z2(H,z);let U=await h3(F,z),D=await DP(U),{serverStatus:B}=U,N=D9(B)?B.features:[],w=await U.secretStorage.get("apiKey",F.ampURL);if(!w)throw new o6("API key required for worker mode. Please run `amp login` first.",1);return{ampURL:F.ampURL,apiKey:w,version:"0.0.
|
|
5123
|
+
By default, opens the new thread in the TUI. Use --print to just print the thread ID.`).option("-g, --goal <goal>","Goal/prompt for the handoff (alternative to stdin)").option("-p, --print","Print the thread ID instead of opening the TUI").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await kI8(U,D,H??null,z.goal,!z.print,F)}),Y.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await TI8(U,D,H,F)}),Y.command("replay <threadId>").alias("p").summary("Replay a thread").description("Replay a thread by downloading it and playing through all interactions. User messages are simulated with variable typing speed.").option("--wpm <wpm>","Typing speed in words per minute (default: 120)","120").option("--no-typing","Disable typing simulation and display messages instantly").option("--message-delay <ms>","Delay between messages in milliseconds (default: 1000)","1000").option("--tool-progress-delay <ms>","Delay to show tool in-progress state in milliseconds (default: 800)","800").option("--exit-delay <seconds>","Delay in seconds before exiting after replay completes (default: 3)","3").option("--no-indicator","Hide the replay progress indicator").action(async(H,z,F)=>{let U=F.optsWithGlobals(),D=await I5(U);await CI8(U,D,H,z,F)}),xs0(Y,I5,z2,h3,og,MU,g3),fY6(J,async(H,z)=>{let F=await I5(z);z2(H,z);let U=await h3(F,z);return{context:F,mcpService:U.mcpService,toolService:U.toolService,toolServices:U.toolService,configService:U.configService,cleanupTerminal:_R,asyncDispose:U.asyncDispose.bind(U)}}),IY6(J,async(H)=>{let z=H.optsWithGlobals(),F=await I5(z);z2(H,z);let U=await h3(F,z);return{settings:F.settings,configService:U.configService,skillService:U.skillService,asyncDispose:U.asyncDispose.bind(U)}}),FY6(J,async(H)=>{let z=H.optsWithGlobals();return await I5(z)}),$Y6(J,async(H)=>{let z=await I5(H);return{settings:z.settings,secretStorage:z.secrets,getThreadDeps:async(F)=>{z2(F,H);let U=await h3(z,H);return{mcpService:U.mcpService,settings:z.settings,asyncDispose:U.asyncDispose.bind(U)}}}}),process.env.AMP_EXPERIMENTAL_REMOTE==="1")DY6(J,async(H,z)=>{let F=await I5(z);z2(H,z);let U=sl({storage:F.settings,secretStorage:F.secrets,workspaceRoots:T1.of([Q0.file(process.cwd())]),defaultAmpURL:F.ampURL,homeDir:U51,userConfigDir:ub1}),D=await I0(_Q(U).pipe(u4((N)=>N!=="pending"))),B=D9(D)?D.features:[];return{ampURL:F.ampURL,secretStorage:F.secrets,features:B,asyncDispose:async()=>{}}},async(H,z)=>{let F=await I5(z);z2(H,z);let U=await h3(F,z),D=await DP(U),{serverStatus:B}=U,N=D9(B)?B.features:[],w=await U.secretStorage.get("apiKey",F.ampURL);if(!w)throw new o6("API key required for worker mode. Please run `amp login` first.",1);return{ampURL:F.ampURL,apiKey:w,version:"0.0.1768305708-gbd5551",dependencies:U,workerDeps:D,features:N,asyncDispose:U.asyncDispose.bind(U)}});function X(H,z,F){let D=typeof H.description==="string"?H.description:F===void 0?H.description(!0):H.description(F),B=new hq(z,D),N=wI8(H);if(N)B.default(N);if(B.hidden=BI8(H)||uW6(H),"choices"in H)B.choices([...H.choices]);return B}for(let H of mW6)switch(H.type){case"flag":{J.addOption(X(H,`--${H.long}`)),J.addOption(X(H,`--no-${H.long}`,!1));break}case"switch":{J.addOption(X(H,`--${H.long}`,!0));break}default:{J.addOption(X(H,`${"short"in H?`-${H.short}, `:""}--${H.long} <value>`));break}}let G=new hq("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(G);let V=new hq("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(V);let K=new hq("--stream-json","When used with --execute, output in Claude Code-compatible stream JSON format instead of plain text.").default(!1);J.addOption(K);let q=new hq("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let W=new hq("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(W),process.env.AMP_EXPERIMENTAL_REMOTE==="1"){let H=new hq("--headless","Run in headless mode: listen for remote commands without showing TUI").default(!1);J.addOption(H)}if(process.env.AMP_CONNECT==="1"){let H=new hq("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(H)}return J.action(async(H,z)=>{let F=H,U=await I5(F);if(Object.keys(F).forEach((D)=>{let B=mW6.find((N)=>N.name===D);if(B&&uW6(B)&&!NI8(B))Y3.write(Z0.yellow(`Warning: '--${D}' flag is deprecated
|
|
5124
5124
|
`))}),z.args.length>0)MI8(U,z);await D51(U,F,z)}),y56(J),J}async function z51(J,Q){let{thread:Y,visibility:Z}=Q,X=Y?.id??PJ(),G=await DP(J);if(Y)await J.threadStorage.set(X,Y);let V=await v8.getOrCreateForThread(G,X),K=await J.threadStorage.get(X);if(Q.agentMode&&!K?.agentMode&&(!K||q7(K)===0))await V.handle({type:"agent-mode",mode:Q.agentMode});if(Z)await J.threadSyncService.updateThreadMeta(X,x41(Z));let q=J.threadService.observe(X).subscribe(async(W)=>{if(W5(W,"assistant"))await B51(X),q.unsubscribe()});return await V.resume(),V}async function D51(J,Q,Y){let Z=y41(Q);if(Z instanceof Error)g3(Z.message);let X,G=null;if(Q.streamJsonInput)X="";else if(typeof Q.execute==="string"){X=Q.execute;let u=(await f41()).trimEnd();if(u)G=u}else X=(await f41()).trimEnd();if(Q.remote&&!J.executeMode)throw new o6("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new o6("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new o6("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new o6("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new o6("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 o6("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&X===""&&!Q.streamJsonInput&&!Q.jmap)throw new o6("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"
|
|
5125
|
-
Or pipe via stdin: echo "your message" | amp --execute`);z2(Y,Q);let V=await h3(J,Q);cW6=V;let K=await DP(V),{serverStatus:q}=V,W=D9(q)?q.user.email:void 0,H=D9(q)?q.features:[],z=D9(q)?q.workspace:null,F=DI8(W);if((J.executeMode||Q.streamJson)&&U9(Q.mode)&&!F)throw new o6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(Y3.write(Z0.yellow("Warning: --headless is deprecated. Use `amp remote worker` instead.\n")),!H.some((x)=>x.name===_X.AMP_CONNECT&&x.enabled))throw new o6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new o6("API key required for headless mode. Please run `amp login` first.",1);await Q61({ampURL:J.ampURL,apiKey:v,version:"0.0.
|
|
5125
|
+
Or pipe via stdin: echo "your message" | amp --execute`);z2(Y,Q);let V=await h3(J,Q);cW6=V;let K=await DP(V),{serverStatus:q}=V,W=D9(q)?q.user.email:void 0,H=D9(q)?q.features:[],z=D9(q)?q.workspace:null,F=DI8(W);if((J.executeMode||Q.streamJson)&&U9(Q.mode)&&!F)throw new o6(`Execute mode is not permitted with --mode '${Q.mode}'`,1);if(Q.headless){if(Y3.write(Z0.yellow("Warning: --headless is deprecated. Use `amp remote worker` instead.\n")),!H.some((x)=>x.name===_X.AMP_CONNECT&&x.enabled))throw new o6("Remote control features require the amp-connect feature flag. Contact support to enable.",1);let v=await V.secretStorage.get("apiKey",J.ampURL);if(!v)throw new o6("API key required for headless mode. Please run `amp login` first.",1);await Q61({ampURL:J.ampURL,apiKey:v,version:"0.0.1768305708-gbd5551",dependencies:V,workerDeps:K}),await V.asyncDispose(),process.exit(0)}if(Q.jmap)throw new o6("JMAP mode is only available in development builds",1);let U=async(u)=>{let v=await dW6(u,"utf-8"),x=JSON.parse(v);if(!H3(x.id))throw new o6(fZ.invalidThreadId);return z51(V,{visibility:Z,agentMode:Q.mode,thread:x})},D=async(u)=>{if(!H3(u))throw new o6(fZ.invalidThreadId);try{let[x,m]=await Promise.all([k4.getThreadLinkInfo({thread:u},{config:V.configService}),k4.getUserInfo({},{config:V.configService})]);if(x.ok&&m.ok){let c=x.result.creatorUserID,h=m.result.id;if(c&&c!==h&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new o6(`Cannot resume thread created by another user.
|
|
5126
5126
|
|
|
5127
5127
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}catch(x){if(x instanceof o6)throw x;R.warn("Failed to validate thread ownership in CLI, allowing to open",{error:x})}let v=await V.threadService.get(u)??void 0;return R.info(`[fetchAndStartThread] Loaded thread ${u}, agentMode: ${v?.agentMode??"undefined"}`),z51(V,{visibility:Z,agentMode:v?void 0:Q.mode,thread:v})},B=async()=>{try{if(Q.threadId)return D(Q.threadId);else return z51(V,{visibility:Z,agentMode:Q.mode})}catch(u){if(u instanceof o6)throw u;throw await qf(u,Q.threadId),Error("handleError should have called process.exit()")}},N=async()=>{return z51(V,{visibility:Z,agentMode:Q.mode})};if(Q.format==="jsonl")Y3.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
5128
|
-
`),await Sw(),process.exit(1);if(J.executeMode&&Q.remote)await UY6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)qY6(V.mcpService,J.settings),await $66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await jD0();let u=JA({jetbrainsOnly:Q.jetbrains});if(u.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(u.length===1){let v=u[0];if(v)h9.selectConfig(v)}else O=!0}let A=H61("0.0.
|
|
5129
|
-
`);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await s96({...J,workspaceTrust:{current:!0,changes:AC},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 VY6(J.mcpConfig);X=KY6(X,K)}let G=F51.dirname(X.getSettingsFilePath());sr0(Vh,G);let V=await X.get("url","global");if(!V)V=l3;if(!zH(V))R.info("Targeting custom Amp server",{ampURL:V});return X=VD0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:wY6(await UC1(J,X))}}function AI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function II8(){let J=AI8(process.argv);if(i06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),FI8(R),R.info("Starting Amp CLI.",{version:"0.0.
|
|
5128
|
+
`),await Sw(),process.exit(1);if(J.executeMode&&Q.remote)await UY6(X,G,V.configService),await V.asyncDispose(),process.exit(0);let w=await B();if(J.executeMode)qY6(V.mcpService,J.settings),await $66(w,w.threadID,X,G,V,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL,F,Q.mode),await V.asyncDispose(),process.exit(0);let M=!1,L=!1,O=!1;if(Q.jetbrains||Q.ide){await jD0();let u=JA({jetbrainsOnly:Q.jetbrains});if(u.length===0){if(Q.jetbrains)L=!await V.configService.get("jetbrains.skipInstall")}else if(u.length===1){let v=u[0];if(v)h9.selectConfig(v)}else O=!0}let A=H61("0.0.1768305708-gbd5551",V.settingsStorage),I=new ye(V.threadStorage),j=T1.of([Q0.file(process.cwd())]),C=eq1(void 0,j),y=new k41(V.mcpService,J.settings.getWorkspaceRootPath());if(X)w.handle({type:"user:message",message:{content:[{type:"text",text:X}]}});let b=await(async()=>{try{let u=await k4.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(5000)});if(u.ok)return R.info("User free tier status:",u),u.result}catch(u){throw R.error("Failed to fetch free tier status:",u),u}})(),d=await OY6();R.info("Loaded session state:",d),await zv1({codebaseContextService:V.codebaseContextService,stdout:process.stdout,history:new K01,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,threadHistoryService:V.threadHistoryService,threadSyncService:V.threadSyncService,threadID:w.threadID,threadFuzzyIndexer:I,worker:w,workerDeps:K,skillService:K.skillService,configService:V.configService,internalAPIClient:k4,ampURL:J.ampURL,startNewThread:N,switchToThread:D,ideClient:h9,commandRegistry:C,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:y,showJetBrainsInstaller:L,showIdePicker:M,showIdePickerHint:O,openThreadSwitcher:Q.openThreadSwitcher,updateService:A,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:d,freeTierStatus:b,workspace:z??null,features:H,isDogfooding:F,threadDependencies:V,initialAgentMode:Y.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0}),await V.asyncDispose(),process.exit(0)}async function I5(J){if(J.interactive)Y3.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
5129
|
+
`);let Y=!J.headless&&(!!J.execute||!process.stdout.isTTY&&!J.streamJson),Z=process.stdout.isTTY&&process.stderr.isTTY,X=await s96({...J,workspaceTrust:{current:!0,changes:AC},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 VY6(J.mcpConfig);X=KY6(X,K)}let G=F51.dirname(X.getSettingsFilePath());sr0(Vh,G);let V=await X.get("url","global");if(!V)V=l3;if(!zH(V))R.info("Targeting custom Amp server",{ampURL:V});return X=VD0(X),{executeMode:Y,isTTY:Z,ampURL:V,settings:X,secrets:wY6(await UC1(J,X))}}function AI8(J){let Q={};for(let Y=0;Y<J.length;Y++){let Z=J[Y];if(Z?.startsWith("--")){let G=Z.slice(2).replace(/-([a-z])/g,(K,q)=>q.toUpperCase()),V=J[Y+1];if(V&&!V.startsWith("--"))Q[G]=V,Y++}}return Q}async function II8(){let J=AI8(process.argv);if(i06({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),FI8(R),R.info("Starting Amp CLI.",{version:"0.0.1768305708-gbd5551",buildTimestamp:"2026-01-13T12:06:10.736Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new o6(fZ.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await OI8().parseAsync(process.argv)}or0().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await II8().catch(qf)});async function EI8(J,Q){let Y=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Y)await J.settings.set("url",process.env.AMP_URL,"global"),T8.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
5130
5130
|
`);else if(!zH(J.ampURL))T8.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
5131
5131
|
`);let Z=process.env.AMP_API_KEY;if(Z)T8.write(`API key found in environment variable, storing...
|
|
5132
5132
|
`),await Q.set("apiKey",Z,J.ampURL),T8.write(`API key successfully stored.
|
|
@@ -5140,7 +5140,7 @@ This thread belongs to a different user and cannot be continued for security rea
|
|
|
5140
5140
|
`);process.exit(0)}async function jI8(J,Q,Y,Z,X){z2(X,J);let G=await h3(Q,J);try{let V=rg(Y);if(!V)sg(Y);let K=V,q=Z.trim();if(q.length===0)g3("Thread name cannot be empty");if(q.length>256)g3("Thread name cannot exceed 256 characters");if(!(await MU(K,G)).messages.length)g3("Cannot rename an empty thread.");let H=await DP(G);await(await v8.getOrCreateForThread(H,K)).handle({type:"title",value:q}),R.info("GOT HERE"),await G.threadSyncService.sync(),R.info("GOT THERE"),T8.write(Z0.green(`✓ Thread ${K} renamed to "${q}"
|
|
5141
5141
|
`)),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose();let K=`Failed to rename thread: ${V instanceof Error?V.message:String(V)}`;g3(K)}}async function PI8(J,Q,Y,Z){let X=await h3(Q,J);try{let G=rg(Y);if(!G)sg(Y);let V=await k4.archiveThread({thread:G,archived:Z},{config:X.configService});if(!V.ok)g3(`Failed to ${Z?"archive":"unarchive"} thread: ${V.error.message??V.error.code}`);T8.write(Z0.green(`✓ Thread ${Z?"archived":"unarchived"} successfully
|
|
5142
5142
|
`)),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose(),g3(`Failed to ${Z?"archive":"unarchive"} thread: ${G instanceof Error?G.message:String(G)}`)}}async function TI8(J,Q,Y,Z){z2(Z,J);let X=await h3(Q,J);try{let G=rg(Y);if(!G)sg(Y);let K=await MU(G,X),q=GR(K);T8.write(q+`
|
|
5143
|
-
`),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;g3(V)}}async function CI8(J,Q,Y,Z,X){z2(X,J);let G=await h3(Q,J);try{let V=await og(Y),K=await MU(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await DP(G),B=K.id;await G.threadStorage.set(B,K);let N=await v8.getOrCreateForThread(D,B);await N.resume();let w=ke.fromWorker(N),M=new ye(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=eq1(void 0,L),A=new k41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=H61("0.0.
|
|
5143
|
+
`),await X.asyncDispose(),process.exit(0)}catch(G){await X.asyncDispose();let V=`Failed to render thread as markdown: ${G instanceof Error?G.message:String(G)}`;g3(V)}}async function CI8(J,Q,Y,Z,X){z2(X,J);let G=await h3(Q,J);try{let V=await og(Y),K=await MU(V,G),q=Z.typing!==!1,W=parseInt(Z.wpm||"120",10),H=parseInt(Z.messageDelay||"1000",10),z=parseInt(Z.toolProgressDelay||"800",10),F=parseInt(Z.exitDelay||"3",10)*1000,U=Z.indicator!==!1,D=await DP(G),B=K.id;await G.threadStorage.set(B,K);let N=await v8.getOrCreateForThread(D,B);await N.resume();let w=ke.fromWorker(N),M=new ye(G.threadStorage),L=T1.of([Q0.file(process.cwd())]),O=eq1(void 0,L),A=new k41(G.mcpService,Q.settings.getWorkspaceRootPath()),I=H61("0.0.1768305708-gbd5551",G.settingsStorage),j=Pb({configService:G.configService,filesystem:l4,spawn:XF});await zv1({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new K01,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadHistoryService:G.threadHistoryService,threadSyncService:G.threadSyncService,threadID:B,threadFuzzyIndexer:M,worker:w,workerDeps:D,skillService:D.skillService,configService:G.configService,internalAPIClient:k4,ampURL:Q.ampURL,startNewThread:async()=>w,switchToThread:async()=>w,ideClient:h9,commandRegistry:O,mcpService:G.mcpService,toolboxService:j,mcpTrustHandler:A,showJetBrainsInstaller:!1,updateService:I,isDogfooding:!1,replayMode:{thread:K,typingEnabled:q,baseWpm:W,messageDelayMs:H,toolProgressDelayMs:z,exitDelayMs:F,showIndicator:U},freeTierStatus:{canUseAmpFree:!0,isDailyGrantEnabled:!1},features:[]}),await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),await qf(V,Y)}}async function _I8(J,Q,Y,Z,X){z2(Z,J);let G=await h3(Q,J);try{let V=rg(Y);if(!V)sg(Y);let K=V,q=await k4.getUserInfo({},{config:G.configService}),W=q.ok?q.result:null,H=y41(J,W);if(!H&&!X)g3("Must specify either --visibility or --support");if(H&&X)g3("Cannot specify both --visibility and --support at the same time");if(H instanceof Error)g3(H.message);if(H)await G.threadSyncService.updateThreadMeta(K,x41(H)),T8.write(Z0.green("✓ ")+`Thread ${K} visibility changed to ${H}.
|
|
5144
5144
|
`);if(X){await MU(K,G);let z=typeof X==="string"?X:void 0;await aR0(G.threadService,K,G.configService,z),T8.write(Z0.green("✓ ")+`Thread ${K} has been shared with Amp support. These thread reports will be aggregated and analysed.
|
|
5145
5145
|
`)}await G.asyncDispose(),process.exit(0)}catch(V){await G.asyncDispose(),g3(`Failed to update thread: ${V instanceof Error?V.message:String(V)}`)}}async function SI8(J,Q,Y,Z){z2(Z,J);let X=await h3(Q,J),G=await DP(X);try{let V=await og(Y),q=(await MU(V,X)).messages.length-1,W=await v8.getOrCreateForThread(G,V),H=await qR(W,X.threadSyncService,q);await Promise.all([X.threadSyncService.uploadThread(V),X.threadSyncService.uploadThread(H)]),await B51(H),T8.write(`${H}
|
|
5146
5146
|
`),await X.asyncDispose(),process.exit(0)}catch(V){Y3.write(`Error forking thread: ${V instanceof Error?V.message:String(V)}
|