@sourcegraph/amp 0.0.1778070211-gdd8fb4 → 0.0.1778070540-gc7ef03

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/main.js +11 -11
  2. package/package.json +1 -1
package/dist/main.js CHANGED
@@ -4694,7 +4694,7 @@ ${Dg4("\t",n??"(unknown)")}
4694
4694
  `)}else if(n)process.stdout.write(n+`
4695
4695
  `);await b()}}})})}function Xg4(A){return A.filter((Q)=>Q.role==="assistant"&&Q.state.type!=="streaming").length}function Fg4(A){if(A instanceof Error)if(Ty(A))return"Unauthorized. Check your access token.";else if(QU(A))return"Context window limit reached.";else if(RO(A))return"Model provider overloaded. Try again in a few seconds.";else if(PO(A))return"Model stream timed out. Try again in a few seconds.";else if(_y(A))return"Insufficient credit balance.";else return A.message;if(typeof A==="object"&&A&&"message"in A&&typeof A.message==="string")return A.message;return String(A)}function Dg4(A,Q){if(!Q)return Q;return A+Q.split(`
4696
4696
  `).join(`
4697
- `+A)}l0();import{randomUUID as oP5}from"node:crypto";k4();R1();class RF0 extends Error{constructor(A){super(A);this.name="ThreadClientError"}}class w8 extends RF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="NetworkError"}}class S2 extends RF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="ThreadClientConnectionError"}}J4();bz();M3();T5();k4();sz();l0();k4();var XM5=0,Vg4=0,ke0=0,ox=new Map,Ug4=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry(({boundaryRef:A,threadID:Q})=>{if(ox.get(Q)?.boundaryRef===A)ox.delete(Q)});function Hg4(A,Q,B,$){let J=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_PERF_LOG!==void 0,Y=++XM5,Z=J?performance.now():0,X=J?Kg4():void 0,F=!1,D=A.length,G=0,{threadID:V,...U}=Q,K=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_CACHE==="0",E={activityGroups:Q.activityGroups,aggman:Q.aggman,compactionCutMessageIDs:Q.compactionCutMessageIDs,isWorking:!1},W;if(K)W=B(A,E);else{let z=JSON.stringify({activityGroups:E.activityGroups??!0,aggman:E.aggman??!1,compactionCutMessageIDs:Array.from(new Set(E.compactionCutMessageIDs??[])).sort()}),q=GM5(A);if(q===-1)ke0+=1,W=B(A,E);else{let N=A[q],I=DM5(V,A,q,z);if(I){F=!0,Vg4+=1,G=I.cachedPrefix.messageCount,D=A.length-I.cachedPrefix.messageCount;let w=q+1,C=I.cachedPrefix.entries.concat(B(A.slice(I.cachedPrefix.messageCount,w),E));if(w!==I.cachedPrefix.messageCount)Eg4(V,N,z,{messageCount:w,entries:C});W=C.concat(B(A.slice(w),E))}else{ke0+=1;let w=q+1,C=B(A.slice(0,w),E);Eg4(V,N,z,{messageCount:w,entries:C}),G=w,W=C.concat(B(A.slice(w),E))}}}let H=$(W,U);if(J){let z=Kg4(),q=FM5(X,z);j.debug("buildTranscript completed",{callCount:Y,durationUs:Math.round((performance.now()-Z)*1000),threadID:V,messageCount:A.length,cachedPrefixMessageCount:G,cachePartialHit:F&&D>0,cacheProcessedMessageCount:D,cacheHit:F,cacheDisabled:K,cacheHits:Vg4,cacheMisses:ke0,memoryUsageAvailable:q!==void 0,heapUsedBeforeBytes:X?.heapUsedBytes,heapUsedAfterBytes:z?.heapUsedBytes,heapUsedDeltaBytes:q?.heapUsedBytes,heapTotalDeltaBytes:q?.heapTotalBytes,rssDeltaBytes:q?.rssBytes,externalDeltaBytes:q?.externalBytes,arrayBuffersDeltaBytes:q?.arrayBuffersBytes})}return H}function Kg4(){if(typeof process>"u"||typeof process.memoryUsage!=="function")return;let A=process.memoryUsage();return{arrayBuffersBytes:A.arrayBuffers,externalBytes:A.external,heapTotalBytes:A.heapTotal,heapUsedBytes:A.heapUsed,rssBytes:A.rss}}function FM5(A,Q){if(!A||!Q)return;return{arrayBuffersBytes:Q.arrayBuffersBytes-A.arrayBuffersBytes,externalBytes:Q.externalBytes-A.externalBytes,heapTotalBytes:Q.heapTotalBytes-A.heapTotalBytes,heapUsedBytes:Q.heapUsedBytes-A.heapUsedBytes,rssBytes:Q.rssBytes-A.rssBytes}}function DM5(A,Q,B,$){let J=ox.get(A);if(!J)return;if(J.cacheKey!==$)return;let Y=J.boundaryRef.deref();if(!Y){ox.delete(A);return}let Z=J.messageCount-1;if(Z>B)return;if(Q[Z]!==Y)return;return{cachedPrefix:J}}function Eg4(A,Q,B,$){let J=ox.get(A);if(J)Ug4?.unregister(J.boundaryRef);let Y=new WeakRef(Q);ox.set(A,{...$,boundaryRef:Y,cacheKey:B}),Ug4?.register(Q,{boundaryRef:Y,threadID:A},Y)}function GM5(A){let Q=-1,B=new Set,$=new Set;for(let[J,Y]of A.entries()){if(Y.role==="assistant"){for(let Z of Y.content){if(Z.type!=="tool_use")continue;if(Z.name!==void 0&&H80(Z.name)){if(Z.id!==void 0)$.add(Z.id);continue}if(Z.id!==void 0)B.add(Z.id)}if(Wg4(Y)&&VM5(Y,J,A.length))Q=J;continue}if(Y.role==="user"){for(let Z of Y.content){if(Z.type!=="tool_result"||Z.toolUseID===void 0)continue;if($.has(Z.toolUseID))continue;B.delete(Z.toolUseID)}if(Wg4(Y)){Q=J;continue}if(B.size===0&&UM5(A,J))Q=J}}return Q}function VM5(A,Q,B){if(A.state===void 0)return Q<B-1;return A.state.type==="complete"||A.state.type==="cancelled"||A.state.type==="error"}function Wg4(A){return A.content.length===1&&zg4(A.content[0])}function UM5(A,Q){let B=A[Q+1];if(B?.role!=="assistant")return!1;let $=B.content.find((J)=>J.type!=="thinking"&&J.type!=="redacted_thinking");return $!==void 0&&zg4($)}function zg4(A){return A?.type==="text"&&!A.hidden&&(A.text??"").trim()!==""}function _F0(A){return A.type==="compaction"||A.parentToolUseID===void 0}function ge0(A){let Q=new Map;for(let B of A){if(B.type==="compaction"||B.parentToolUseID===void 0)continue;let $=be0(B.parentToolUseID),J=Q.get($)??[];J.push(B),Q.set($,J)}return Q}function me0(A,Q){if(A===void 0)return[];return Q.get(A)??[]}function TF0(A,Q){switch(A.type){case"message":return A.role==="assistant"&&A.text.trim()!=="";case"tool":return!0;case"activity-group":return A.actions.length>0||A.label!==void 0||A.detail!==void 0||A.error!==void 0||Q(A.rowID).some((B)=>TF0(B,Q));case"compaction":case"thinking":return!1}}function Ng4(A,Q){if(A.label!==void 0||A.detail!==void 0||A.error!==void 0||A.actions.length===0)return!1;return!Q(A.rowID).some((B)=>TF0(B,Q))}function KM5(A){let Q=[...A];for(let B=0;B<A.length;B++){let $=ge0(Q),J=!1,Y=Q.map((Z)=>{let X=EM5(Z,$);if(X!==Z)J=!0;return X});if(!J)return Y;Q=Y}return Q}function EM5(A,Q){if(A.type!=="activity-group"||A.rowID===void 0)return A;let B=me0(A.rowID,Q);if(B.some(Ig4))return A.hasInProgress?A:{...A,hasInProgress:!0};if(!A.hasInProgress)return A;if(!WM5(B))return A;let $={...A,hasInProgress:!1};if($.status!==void 0&&$r($.status))$.status="done";return $}function WM5(A){return!A.some(Ig4)&&A.some(HM5)}function Ig4(A){if(A.type==="activity-group")return A.hasInProgress;if(wg4(A))return!0;return A.type==="tool"&&$r(A.tool.status)}function HM5(A){return A.type==="message"&&A.role==="assistant"&&A.text.trim()!==""&&!wg4(A)}function wg4(A){return A.type==="message"&&A.role==="assistant"&&A.isStreaming===!0}function zM5(A){if(A.isStreaming===!0)return!0;if(A.state?.type==="streaming")return!0;return A.state?.type==="complete"&&"stopReason"in A.state&&A.state.stopReason===null}function Cg4(A){return{activityGroups:!qM5.has(A)}}var qM5=new Set(["smart","rush","large"]);function be0(A,Q){return Q===void 0?`tool:${A}`:`tool:${A}:${Q}`}function NM5(A,Q){return`manual-bash:${A}:${Q}`}function ve0(A){return A==="done"||A==="in-progress"||A==="queued"||A==="blocked-on-user"||A==="cancellation-requested"||A==="error"||A==="cancelled"||A==="rejected-by-user"}function IM5(A){if(A.message.content.length===0&&A.message.images.length===0)return;let{message:Q}=A,$={type:"message",text:Q.content.map((J)=>(J.text??"").trim()).join(`
4697
+ `+A)}l0();import{randomUUID as oP5}from"node:crypto";k4();R1();class RF0 extends Error{constructor(A){super(A);this.name="ThreadClientError"}}class w8 extends RF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="NetworkError"}}class S2 extends RF0{cause;constructor(A,Q){super(A);this.cause=Q;this.name="ThreadClientConnectionError"}}J4();bz();M3();T5();k4();sz();l0();k4();var XM5=0,Vg4=0,ke0=0,ox=new Map,Ug4=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry(({boundaryRef:A,threadID:Q})=>{if(ox.get(Q)?.boundaryRef===A)ox.delete(Q)});function Hg4(A,Q,B,$){let J=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_PERF_LOG!==void 0,Y=++XM5,Z=J?performance.now():0,X=J?Kg4():void 0,F=!1,D=A.length,G=0,{threadID:V,...U}=Q,K=typeof process<"u"&&process.env.AMP_BUILD_TRANSCRIPT_CACHE==="0",E={activityGroups:Q.activityGroups,aggman:Q.aggman,compactionCutMessageIDs:Q.compactionCutMessageIDs,isWorking:!1},W;if(K)W=B(A,E);else{let z=JSON.stringify({activityGroups:E.activityGroups??!0,aggman:E.aggman??!1,compactionCutMessageIDs:Array.from(new Set(E.compactionCutMessageIDs??[])).sort()}),q=GM5(A);if(q===-1)ke0+=1,W=B(A,E);else{let N=A[q],I=DM5(V,A,q,z);if(I){F=!0,Vg4+=1,G=I.cachedPrefix.messageCount,D=A.length-I.cachedPrefix.messageCount;let w=q+1,C=I.cachedPrefix.entries.concat(B(A.slice(I.cachedPrefix.messageCount,w),E));if(w!==I.cachedPrefix.messageCount)Eg4(V,N,z,{messageCount:w,entries:C});W=C.concat(B(A.slice(w),E))}else{ke0+=1;let w=q+1,C=B(A.slice(0,w),E);Eg4(V,N,z,{messageCount:w,entries:C}),G=w,W=C.concat(B(A.slice(w),E))}}}let H=$(W,U);if(J){let z=Kg4(),q=FM5(X,z);j.debug("buildTranscript completed",{callCount:Y,durationUs:Math.round((performance.now()-Z)*1000),threadID:V,messageCount:A.length,cachedPrefixMessageCount:G,cachePartialHit:F&&D>0,cacheProcessedMessageCount:D,cacheHit:F,cacheDisabled:K,cacheHits:Vg4,cacheMisses:ke0,memoryUsageAvailable:q!==void 0,heapUsedBeforeBytes:X?.heapUsedBytes,heapUsedAfterBytes:z?.heapUsedBytes,heapUsedDeltaBytes:q?.heapUsedBytes,heapTotalDeltaBytes:q?.heapTotalBytes,rssDeltaBytes:q?.rssBytes,externalDeltaBytes:q?.externalBytes,arrayBuffersDeltaBytes:q?.arrayBuffersBytes})}return H}function Kg4(){if(typeof process>"u"||typeof process.memoryUsage!=="function")return;let A=process.memoryUsage();return{arrayBuffersBytes:A.arrayBuffers,externalBytes:A.external,heapTotalBytes:A.heapTotal,heapUsedBytes:A.heapUsed,rssBytes:A.rss}}function FM5(A,Q){if(!A||!Q)return;return{arrayBuffersBytes:Q.arrayBuffersBytes-A.arrayBuffersBytes,externalBytes:Q.externalBytes-A.externalBytes,heapTotalBytes:Q.heapTotalBytes-A.heapTotalBytes,heapUsedBytes:Q.heapUsedBytes-A.heapUsedBytes,rssBytes:Q.rssBytes-A.rssBytes}}function DM5(A,Q,B,$){let J=ox.get(A);if(!J)return;if(J.cacheKey!==$)return;let Y=J.boundaryRef.deref();if(!Y){ox.delete(A);return}let Z=J.messageCount-1;if(Z>B)return;if(Q[Z]!==Y)return;return{cachedPrefix:J}}function Eg4(A,Q,B,$){let J=ox.get(A);if(J)Ug4?.unregister(J.boundaryRef);let Y=new WeakRef(Q);ox.set(A,{...$,boundaryRef:Y,cacheKey:B}),Ug4?.register(Q,{boundaryRef:Y,threadID:A},Y)}function GM5(A){let Q=-1,B=new Set,$=new Set;for(let[J,Y]of A.entries()){if(Y.role==="assistant"){for(let Z of Y.content){if(Z.type!=="tool_use")continue;if(Z.name!==void 0&&H80(Z.name)){if(Z.id!==void 0)$.add(Z.id);continue}if(Z.id!==void 0)B.add(Z.id)}if(Wg4(Y)&&VM5(Y,J,A.length))Q=J;continue}if(Y.role==="user"){for(let Z of Y.content){if(Z.type!=="tool_result"||Z.toolUseID===void 0)continue;if($.has(Z.toolUseID))continue;B.delete(Z.toolUseID)}if(Wg4(Y)){Q=J;continue}if(B.size===0&&UM5(A,J))Q=J}}return Q}function VM5(A,Q,B){if(A.state===void 0)return Q<B-1;return A.state.type==="complete"||A.state.type==="cancelled"||A.state.type==="error"}function Wg4(A){return A.content.length===1&&zg4(A.content[0])}function UM5(A,Q){let B=A[Q+1];if(B?.role!=="assistant")return!1;let $=B.content.find((J)=>J.type!=="thinking"&&J.type!=="redacted_thinking");return $!==void 0&&zg4($)}function zg4(A){return A?.type==="text"&&!A.hidden&&(A.text??"").trim()!==""}function _F0(A){return A.type==="compaction"||A.parentToolUseID===void 0}function ge0(A){let Q=new Map;for(let B of A){if(B.type==="compaction"||B.parentToolUseID===void 0)continue;let $=be0(B.parentToolUseID),J=Q.get($)??[];J.push(B),Q.set($,J)}return Q}function me0(A,Q){if(A===void 0)return[];return Q.get(A)??[]}function TF0(A,Q){switch(A.type){case"message":return A.role==="assistant"&&A.text.trim()!=="";case"tool":return!0;case"activity-group":return A.actions.length>0||A.label!==void 0||A.detail!==void 0||A.error!==void 0||Q(A.rowID).some((B)=>TF0(B,Q));case"compaction":case"thinking":return!1}}function Ng4(A,Q){if(A.label!==void 0||A.detail!==void 0||A.error!==void 0||A.actions.length===0)return!1;return!Q(A.rowID).some((B)=>TF0(B,Q))}function KM5(A){let Q=[...A];for(let B=0;B<A.length;B++){let $=ge0(Q),J=!1,Y=Q.map((Z)=>{let X=EM5(Z,$);if(X!==Z)J=!0;return X});if(!J)return Y;Q=Y}return Q}function EM5(A,Q){if(A.type!=="activity-group"||A.rowID===void 0)return A;let B=me0(A.rowID,Q);if(B.some(Ig4))return A.hasInProgress?A:{...A,hasInProgress:!0};if(!A.hasInProgress)return A;if(!WM5(B))return A;let $={...A,hasInProgress:!1};if($.status!==void 0&&$r($.status))$.status="done";return $}function WM5(A){return!A.some(Ig4)&&A.some(HM5)}function Ig4(A){if(A.type==="activity-group")return A.hasInProgress;if(wg4(A))return!0;return A.type==="tool"&&$r(A.tool.status)}function HM5(A){return A.type==="message"&&A.role==="assistant"&&A.text.trim()!==""&&!wg4(A)}function wg4(A){return A.type==="message"&&A.role==="assistant"&&A.isStreaming===!0}function zM5(A){if(A.isStreaming===!0)return!0;if(A.state?.type==="streaming")return!0;return A.state?.type==="complete"&&"stopReason"in A.state&&A.state.stopReason===null}function Cg4(A){return{activityGroups:!qM5.has(A)}}var qM5=new Set(["rush","large"]);function be0(A,Q){return Q===void 0?`tool:${A}`:`tool:${A}:${Q}`}function NM5(A,Q){return`manual-bash:${A}:${Q}`}function ve0(A){return A==="done"||A==="in-progress"||A==="queued"||A==="blocked-on-user"||A==="cancellation-requested"||A==="error"||A==="cancelled"||A==="rejected-by-user"}function IM5(A){if(A.message.content.length===0&&A.message.images.length===0)return;let{message:Q}=A,$={type:"message",text:Q.content.map((J)=>(J.text??"").trim()).join(`
4698
4698
 
4699
4699
  `),images:Q.images,timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,role:Q.role};if(A.sourceMessageID!==void 0)$.sourceMessageID=A.sourceMessageID;if(Q.role==="user")$.fromAggman=Q.fromAggman,$.fromExecutorThreadID=Q.fromExecutorThreadID;else if(Q.isStreaming)$.isStreaming=!0;return $}function wM5(A){let Q=A.manualBashInvocation.toolRun;return{type:"tool",timestampLookupID:A.timestampLookupID,parentToolUseID:A.parentToolUseID,tool:{kind:"bash",rowID:A.rowID,command:A.manualBashInvocation.args.cmd,status:Q.status,output:de0(Q),exitCode:xg4(Q),error:Q8(Q)}}}function CM5(A,Q={}){return hM5(bM5(A,Q.compactionCutMessageIDs),Q).filter(OM5)}function Mg4(A,Q){return Hg4(A,Q,CM5,MM5)}function MM5(A,Q){let B=KM5(A);if(!Q.isWorking)return B;return LM5(B)}function LM5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!_F0(B))continue;if(B.type==="activity-group"){let $=A.slice();return $[Q]={...B,hasInProgress:!0},$}break}return A}function OM5(A){if(A.type==="thinking")return!1;if(A.type==="message"&&A.text===""&&A.images.length===0)return!1;return!0}function jM5(A){if(A.protocolMessageID!==void 0)return A.protocolMessageID;if(typeof A.messageId==="string"&&A.messageId.startsWith("M-"))return A.messageId;return}function Lg4(A,Q){return{kind:"bash",command:A,status:Q.status,output:de0(Q),exitCode:xg4(Q),error:Q8(Q)}}function Og4(A,Q){let B=VI(A.path);if(B===void 0)return;let $=Q.status==="done"&&typeof Q.result==="object"&&Q.result&&"diff"in Q.result?Q.result.diff:void 0,J=Q.status==="done"?WV(A.old_str,A.new_str):{added:0,deleted:0,changed:0};return{kind:"edit",uri:B,status:Q.status,diff:$,linesAdded:J.added,linesDeleted:J.deleted,error:Q8(Q)}}function VI(A){return typeof A==="string"&&A.trim()!==""?g1(t0.file(A)):void 0}function jg4(A,Q){let B=VI(A.path);if(B===void 0)return;let $=typeof A.content==="string"?A.content:void 0,J=HV($);return{kind:"create-file",uri:B,status:Q.status,content:$,linesAdded:J.added,error:Q8(Q)}}function RM5(A,Q){let B=VI(A.path);if(B===void 0)return;let $=A.read_range,J=Array.isArray($)&&$.length===2&&typeof $[0]==="number"&&typeof $[1]==="number"?[$[0],$[1]]:void 0,Y={kind:"read",uri:B,status:Q.status,error:Q8(Q)};if(J)return{...Y,readRange:J};return Y}function Rg4(A,Q){let B=VI(A.path);if(B===void 0)return;let $=typeof A.objective==="string"&&A.objective.trim()!==""?A.objective.trim():void 0,J=typeof A.context==="string"&&A.context.trim()!==""?A.context.trim():void 0,Y=Array.isArray(A.referenceFiles)?A.referenceFiles.filter((X)=>typeof X==="string"):[],Z={kind:"look-at",uri:B,referenceFiles:Y,status:Q.status,error:Q8(Q)};if($)Z.objective=$;if(J)Z.context=J;return Z}function PM5(A,Q){let B=typeof A.threadID==="string"&&A.threadID.trim()!==""?A.threadID.trim():void 0,$=typeof A.goal==="string"&&A.goal.trim()!==""?A.goal.trim():void 0,J=Q.status==="done"&&typeof Q.result==="string"&&Q.result.length>0?Q.result:void 0,Z=(Q.status==="in-progress"?Q.progress:void 0)?.statusMessage,X={kind:"read-thread",status:Q.status,error:Q8(Q)};if(B)X.threadID=B;if($)X.goal=$;if(J)X.markdownResult=J;if(Z)X.statusMessage=Z;return X}function Pg4(A,Q){return{kind:"edit",uri:A.uri,status:Q.status,diff:A.diff||void 0,linesAdded:A.additions,linesDeleted:A.deletions,error:Q8(Q)}}function _g4(A,Q){return{kind:"read-web-page",url:hg4(A),status:Q.status,error:Q8(Q)}}function _M5(A,Q){let B=xM5(Q);return{kind:"find-thread",query:(typeof A.query==="string"?A.query.trim():void 0)||void 0,status:Q.status,threads:B?.threads??[],hasMore:B?.hasMore??!1,error:Q8(Q)}}function Tg4(A,Q,B){let $=typeof Q.prompt==="string"?Q.prompt.trim():void 0,J=dM5(B);return{kind:"painter",title:A==="render_agg_man"?"Render Agg Man":void 0,prompt:$,status:B.status,images:J?.images??[],error:Q8(B)}}function TM5(A,Q,B){if(pe0(A)){let J=vg4(Q);if(J)return Lg4(J,B)}if(A==="edit_file")return Og4(Q,B);if(A==="create_file")return jg4(Q,B);if(A==="Read")return RM5(Q,B);if(A==="look_at")return Rg4(Q,B);if(A==="read_thread")return PM5(Q,B);if(A==="apply_patch"){if(B.status==="error")return{kind:"generic",name:A,detail:aX(Q),status:B.status,error:Q8(B)};let J=fg4(B);if(J&&J.length>0)return Pg4(J[0],B);let Y=bg4(Q),Z=Y?ug4(Y):[],X=VI(Z[0]?.path);if(X===void 0)return;let F={kind:"edit",uri:X,status:B.status,diff:Z[0]?.diff,linesAdded:Z[0]?.additions??0,linesDeleted:Z[0]?.deletions??0,error:Q8(B)};if(Z[0]?.path)F.displayPath=Z[0].path;return F}if(A==="read_web_page")return _g4(Q,B);if(A==="find_thread")return _M5(Q,B);if(A==="painter"||A==="render_agg_man")return Tg4(A,Q,B);let $=kg4(B);return{kind:"generic",name:A,detail:aX(Q),status:B.status,error:Q8(B),...$.length>0?{images:$}:{}}}function Sg4(A){switch(A.kind){case"bash":return{action:EV("Bash"),detail:A.command};case"edit":return{action:ye0(A.status,"Edited","Editing"),detail:A.displayPath??t0.parse(A.uri).fsPath};case"create-file":return{action:ye0(A.status,"Created","Creating"),detail:t0.parse(A.uri).fsPath};case"read":return{action:EV("Read"),detail:t0.parse(A.uri).fsPath};case"look-at":return{action:EV("look_at"),detail:t0.parse(A.uri).fsPath};case"read-thread":return{action:EV("read_thread"),detail:A.threadID};case"painter":return{action:A.title??EV("painter"),detail:A.prompt};case"read-web-page":return{action:EV("Read"),detail:A.url};case"find-thread":return{action:EV("find_thread"),detail:A.query};case"generic":if(kM5(A))return{action:ye0(A.status,"Ran tool","Running tool"),detail:A.name};return{action:A.name,detail:A.detail}}}function ye0(A,Q,B){switch(A){case"in-progress":case"queued":case"blocked-on-user":case"cancellation-requested":return B;case"done":case"error":case"cancelled":case"rejected-by-user":return Q}}function SM5(A){return A.kind==="generic"&&vM5.has(A.name)}function kM5(A){return A.kind==="generic"&&!SM5(A)&&typeof A.markdownResponse!=="string"&&!yM5.has(A.name)}var vM5=new Set(["Web Search"]),yM5=new Set(["Slack"]);function kg4(A){if(A.status!=="done"||!Array.isArray(A.result))return[];return A.result.filter(wB0).filter((Q)=>Q.type==="image").map((Q)=>({mimeType:Q.mimeType,data:Q.data}))}function xM5(A){if(A.status!=="done"||!NJ(A.result))return;return{threads:Array.isArray(A.result.threads)?A.result.threads.filter(fM5):[],hasMore:A.result.hasMore===!0}}function fM5(A){return NJ(A)&&typeof A.id==="string"&&typeof A.creatorUserID==="string"&&typeof A.created==="number"&&typeof A.updatedAt==="string"&&typeof A.messageCount==="number"&&(A.title===void 0||typeof A.title==="string")&&(A.matchedSearchText===void 0||typeof A.matchedSearchText==="string")}function pe0(A){return A==="Bash"||A==="shell_command"||A==="run_terminal_command"}function bM5(A,Q){let B=[],$=new Map,J=new Set,Y=new Set(Q??[]),Z=[];for(let[X,F]of A.entries()){let D=F.parentToolUseId,G=jM5(F);if(G!==void 0&&Y.has(G))Z.push({cutMessageID:G,messageIndex:X});if(F.role==="assistant"){let V=zM5(F),U=F.content.filter((E)=>E.type==="text"&&!E.hidden&&(E.text??"").trim()!==""),K=F.content.some((E)=>E.type!=="thinking"&&E.type!=="redacted_thinking");for(let E of F.content)if(E.type==="thinking"&&E.thinking.trim()!=="")B.push({type:"thinking",parentToolUseID:D,startMessageIndex:X,endMessageIndex:X,timestampLookupID:F.messageId,text:E.thinking,isStreaming:!K});if(U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:X,endMessageIndex:X,sourceMessageID:F.messageId,timestampLookupID:F.messageId,message:{role:"assistant",content:U,images:[],isStreaming:V}});for(let E of F.content)if(E.type==="tool_use"){if(H80(E.name)){J.add(E.id);continue}if(!E.complete&&pe0(E.normalizedName??E.name)){J.add(E.id);continue}let W=B.push({type:"toolResult",parentToolUseID:D,startMessageIndex:X,endMessageIndex:X,timestampLookupID:F.messageId,toolUse:E})-1;$.set(E.id,{itemIndex:W,messageIndex:X,isStreaming:V,parentToolUseID:D})}}else if(F.role==="user"){for(let W of F.content)if(W.type==="tool_result"){if(J.has(W.toolUseID))continue;let H=$.get(W.toolUseID);if(H){let z=B[H.itemIndex];if(z?.type==="toolResult")z.toolResult=W,z.endMessageIndex=X;$.delete(W.toolUseID)}}let V=F.content.filter((W)=>W.type==="text"&&!W.hidden&&(W.text??"").trim()!==""),U=F.content.filter((W)=>W.type==="image"),K=F.meta?.fromAggman===!0,E=F.meta?.fromExecutorThreadID;if(V.length>0||U.length>0)B.push({type:"message",parentToolUseID:D,startMessageIndex:X,endMessageIndex:X,sourceMessageID:F.messageId,timestampLookupID:F.messageId,message:{role:"user",content:V,images:U,...K?{fromAggman:!0}:{},...E?{fromExecutorThreadID:E}:{}}})}else if(F.role==="info"){for(let[V,U]of F.content.entries())if(U.type==="manual_bash_invocation")B.push({type:"manualBashInvocation",parentToolUseID:D,startMessageIndex:X,endMessageIndex:X,rowID:NM5(F.messageId,V),manualBashInvocation:U})}}for(let[X,F]of $){let D=B[F.itemIndex];if(D?.type!=="toolResult")continue;let V=A.slice(F.messageIndex+1).some((K)=>{if(K.parentToolUseId!==F.parentToolUseID)return!1;if(K.role==="assistant")return!0;return K.content.some((E)=>E.type!=="tool_result")})?"cancelled":F.isStreaming?"in-progress":"queued",U={type:"tool_result",toolUseID:X,run:{status:V}};D.toolResult=U}if(Z.length===0)return B;return uM5(B,Z)}function uM5(A,Q){let B=[],$=[...Q].sort((Y,Z)=>Y.messageIndex-Z.messageIndex),J=0;for(let[Y,Z]of A.entries()){while(J<$.length){let F=$[J];if(F.messageIndex<Z.startMessageIndex){B.push({type:"compaction",cutMessageID:F.cutMessageID}),J++;continue}break}B.push(Z);let X=A[Y+1];while(J<$.length){let F=$[J];if(F.messageIndex<=Z.endMessageIndex&&(X===void 0||F.messageIndex<X.startMessageIndex)){B.push({type:"compaction",cutMessageID:F.cutMessageID}),J++;continue}break}}for(;J<$.length;J++)B.push({type:"compaction",cutMessageID:$[J].cutMessageID});return B}function hM5(A,Q){let B=[],$=Q.activityGroups??!0,J=Q.aggman??!1,Y=[],Z,X=new Set,F=!1,D,G,V=(N,I,w,C,O)=>{if(Y.length>0&&G!==O)z();if(Y.length===0)G=O;if(Y.push(N),C!==void 0&&Z===void 0)Z=C;if(w!==void 0&&D===void 0)D=w;if(I==="in-progress"||I==="queued")F=!0},U=(N,I,w,C)=>{for(let O of mg4(N)){let _=`${O.kind}:${O.title}`;if(X.has(_))continue;X.add(_),V(O,N.status,I,w,C)}},K=(N,I,w,C,O)=>{V(N,I.status,w,C,O),U(I,w,C,O)},E=(N,I,w)=>{B.push({type:"tool",tool:N,timestampLookupID:I,parentToolUseID:w})},W=(N)=>{B.push({type:"thinking",text:N.text,isStreaming:N.isStreaming,timestampLookupID:N.timestampLookupID,parentToolUseID:N.parentToolUseID})},H=(N,I,w)=>{if(N.actions.length===0&&N.label===void 0&&N.detail===void 0&&N.error===void 0)return;B.push({type:"activity-group",...N,timestampLookupID:I,parentToolUseID:w})},z=()=>{if(Y.length===0)return;let N={rowID:Z,actions:Y,summary:he0(Y),hasInProgress:F};if(J)N.aggman=!0;H(N,D,G),Y=[],Z=void 0,X=new Set,F=!1,D=void 0,G=void 0};for(let N of A){if(N.type==="compaction"){z(),B.push(N);continue}if(N.type==="message"){let I=IM5(N);if(I)z(),B.push(I);continue}if(N.type==="manualBashInvocation"){z(),B.push(wM5(N));continue}if(N.type==="thinking"){if($)continue;else z(),W(N);continue}if(N.type==="toolResult"&&N.toolResult){let I=N.toolUse.normalizedName??N.toolUse.name,w=cM5(N.toolUse),C=N.toolResult.run,O=N.timestampLookupID,_=be0(N.toolUse.id),T=(x,v)=>{if(x===void 0)return;E({...x,rowID:be0(N.toolUse.id,v?.index)},v?.timestampLookupID??O,N.parentToolUseID)},S=()=>{T(TM5(I,w,C))};if($){let x=oM5(I,w);if(x){K(x,C,O,_,N.parentToolUseID);continue}}if(pe0(I)){let x=vg4(w);if(x){let v=sa0(x),u=v[0]??Zj(x),m=v.some((g)=>g.kind==="command");if(v.length===1&&u.isWriteLike&&(u.program==="sed"||u.program==="perl")){if(!ve0(C.status))continue;let g=VI(u.path??x);if(g===void 0)continue;z(),T({kind:"edit",uri:g,status:C.status,linesAdded:0,linesDeleted:0,error:Q8(C)});continue}let d=v.filter((g)=>g.kind!=="command");if(d.length>0&&!m){if(!$){z(),S();continue}let g=de0(C),n=!1;for(let[c,$0]of d.entries()){let E0=FL5($0);if(!E0)continue;K({kind:$0.kind,title:E0,...c===d.length-1&&g?{detail:g}:{}},C,O,_,N.parentToolUseID),n=!0}if(n)continue}z(),T(Lg4(x,C));continue}}if(I==="edit_file"){if(!ve0(C.status))continue;z(),T(Og4(w,C));continue}if(I==="create_file"){z(),T(jg4(w,C));continue}if(I==="apply_patch"){if(!ve0(C.status))continue;if(z(),C.status==="error"){S();continue}let x=fg4(C);if(x&&x.length>0)for(let[v,u]of x.entries())T(Pg4(u,C),{index:v});else{let v=bg4(w),u=v?ug4(v):[];for(let[m,d]of u.entries()){let g=VI(d.path);if(g===void 0)continue;T({kind:"edit",uri:g,displayPath:d.path,status:C.status,diff:d.diff,linesAdded:d.additions,linesDeleted:d.deletions,error:Q8(C)},{index:m})}}continue}if(I==="Read"){if(VI(w.path)===void 0)continue;if(!$){z(),S();continue}let x=PF0(I,w);K({kind:"read",title:x},C,O,_,N.parentToolUseID);continue}if(I==="file_tree"){if(!$){z(),S();continue}let x=PF0(I,w);K({kind:"list",title:x},C,O,_,N.parentToolUseID);continue}if(I==="glob"||I==="Grep"){if(!$){z(),S();continue}let x=PF0(I,w);K({kind:"search",title:x},C,O,_,N.parentToolUseID);continue}if(I==="finder"){z();let x=typeof w.query==="string"?w.query.trim():void 0,v=ce0([],C),u={rowID:_,label:{active:"Searching codebase",complete:"Searched codebase"},actions:v,summary:he0(v),hasInProgress:$r(C.status),status:C.status};if(x!==void 0)u.detail=x;let m=Q8(C);if(m!==void 0)u.error=m;H(u,O,N.parentToolUseID);continue}let b=YL5(I,w,C);if(b){z(),H({rowID:_,...b},O,N.parentToolUseID);continue}if(I==="web_search"){z();let x=gg4(w);T({kind:"generic",name:"Web Search",detail:x,status:C.status,error:Q8(C)});continue}if(I==="read_web_page"){z(),T(_g4(w,C));continue}if(I==="read_thread"){if(!$){z(),S();continue}let x=typeof w.threadID==="string"?w.threadID.trim():void 0,v=typeof w.goal==="string"?w.goal.trim():void 0,u=v?`Read thread: ${v}`:x?`Read thread ${x}`:"Read thread";K({kind:"thread",title:u,icon:"threads"},C,O,_,N.parentToolUseID);continue}if(I==="find_thread"){if(!$){z(),S();continue}let x=typeof w.query==="string"?w.query.trim():void 0,v=x?`Searched threads: ${x}`:"Searched threads";K({kind:"search",title:v},C,O,_,N.parentToolUseID);continue}if(I==="skill"){if(!$){z(),S();continue}let x=w.name;K({kind:"read",title:`Read skill ${x}`},C,O,_,N.parentToolUseID);continue}if(I==="get_diagnostics"){if(!$){z(),S();continue}let x=PF0(I,w);K({kind:"read",title:x},C,O,_,N.parentToolUseID);continue}if(I==="look_at"){z(),T(Rg4(w,C));continue}if(I==="task_list"){z();let x=typeof w.action==="string"?w.action.trim():void 0,v=typeof w.title==="string"?w.title.trim():void 0,u=x&&v?`Task list: ${x} "${v}"`:x?`Task list: ${x}`:"Task list";T({kind:"generic",name:"task_list",detail:u,status:C.status,error:Q8(C)});continue}if(I==="painter"||I==="render_agg_man"){z(),T(Tg4(I,w,C));continue}if(I==="slack_write"){z();let x=C.status==="done"?"sent message":"sending message…";T({kind:"generic",name:"Slack",detail:x,status:C.status,error:Q8(C)});continue}if(I==="slack_read"){z();let x=typeof w.type==="string"?w.type:void 0,v;if(x==="channels")v="searched channels";else if(x==="users")v="searched users";else if(x==="thread")v="read thread";else v="read";T({kind:"generic",name:"Slack",detail:v,status:C.status,error:Q8(C)});continue}z();let h=kg4(C);T({kind:"generic",name:I,detail:aX(w),args:$L5(w),status:C.status,error:Q8(C),...h.length>0?{images:h}:{}})}}z();let q=mM5(B);if(Q.isWorking)gM5(q);return q}function gM5(A){for(let Q=A.length-1;Q>=0;Q--){let B=A[Q];if(B.type==="thinking"||!_F0(B))continue;if(B.type==="activity-group")B.hasInProgress=!0;break}}function mM5(A){let Q=[];for(let B of A){let $=Q[Q.length-1];if($&&$.type==="tool"&&B.type==="tool"&&$.parentToolUseID===B.parentToolUseID){let J=$.tool,Y=B.tool,Z=$.timestampLookupID??B.timestampLookupID;if(J.kind==="edit"&&Y.kind==="edit"&&J.uri===Y.uri&&xe0(J.status)&&xe0(Y.status)){let X=J.diff&&Y.diff?`${J.diff}
4700
4700
  ${Y.diff}`:Y.diff??J.diff,F=Y.status==="error"?0:J.linesAdded+Y.linesAdded,D=Y.status==="error"?0:J.linesDeleted+Y.linesDeleted;Q[Q.length-1]={type:"tool",tool:{kind:"edit",rowID:J.rowID??Y.rowID,uri:J.uri,displayPath:J.displayPath??Y.displayPath??t0.parse(J.uri).fsPath,status:Y.status,diff:X,linesAdded:F,linesDeleted:D,error:Y.error??J.error},timestampLookupID:Z,parentToolUseID:$.parentToolUseID};continue}if(J.kind==="create-file"&&Y.kind==="create-file"&&J.uri===Y.uri){Q[Q.length-1]={type:"tool",tool:{...Y,rowID:J.rowID??Y.rowID},timestampLookupID:Z,parentToolUseID:$.parentToolUseID};continue}if(J.kind==="create-file"&&Y.kind==="edit"&&J.uri===Y.uri&&xe0(Y.status)){let X=t0.parse(J.uri).fsPath,F=J.content&&Y.diff?`${ue0(J.content,Br(X))}
@@ -4885,12 +4885,12 @@ ${E}`))}},error:(K)=>{if(!U)U=!0,F(Error(`Failed to spawn brew: ${K.message}`))}
4885
4885
  ${E}`;if(Y==="pnpm"&&E.includes("Unable to find the global bin directory"))W+=`
4886
4886
 
4887
4887
  Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
4888
- npm install -g @sourcegraph/amp`;F(Error(W))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}l0();l0();LN();async function HD0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=vr(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var mS5="https://static.ampcode.com/cli/cli-version.txt";async function zD0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${mS5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=vr(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var pS5=604800000;function Gc4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>pS5)return{ageMs:B};return null}function vr(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function K11(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?AU(B):void 0;return{sha:$,age:J}}catch{return null}}R1();l0();import{readFile as dS5,realpath as cS5}from"node:fs/promises";import{homedir as lS5}from"node:os";import{dirname as Vc4,join as E11}from"node:path";async function Uc4(A){switch(A){case"binary":case"brew":return iS5(_r());case"npm":case"pnpm":case"yarn":case"bun":return nS5();case"bootstrap":return aS5()}}async function iS5(A){let Q=await dD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function nS5(){try{let A=process.argv[1];if(!A)return null;let Q=await cS5(A),B=Vc4(Vc4(Q));return await Kc4(E11(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function aS5(){try{let A=process.env.AMP_HOME??E11(lS5(),".amp");return await Kc4(E11(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Kc4(A){let Q=await dS5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var oS5=3600000,rS5=5000;function W11(A,Q,B={}){let $=new h4,J=$.pipe(nA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??oS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new f$().with({name:"update"});if(Y>0){if(await eV(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await sS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(rS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await eV(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function sS5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await Ef(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await zD0(A);else{let V=await rj();F=await HD0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Uc4(Z);if(V&&vr(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,vr(A,V)<0){let U=await mW(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==_r()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await kr(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await mW(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}LN();import{stderr as cD}from"node:process";function Ec4(A){let Q=new rN().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($)=>{await Q11($.force||!1,$.verbose||!1,"0.0.1778070211-gdd8fb4"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new rN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await eS5($.targetVersion)});A.addCommand(B)}function tS5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4888
+ npm install -g @sourcegraph/amp`;F(Error(W))}},error:(K)=>{if(!V)V=!0,F(Error(`Failed to spawn ${Y}: ${K.message}`))},complete:()=>{if(!V)V=!0,X()}})})}l0();l0();LN();async function HD0(A,Q){let J=`${Q||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,Y=new AbortController,Z=setTimeout(()=>Y.abort(),5000);try{let X=await fetch(J,{signal:Y.signal});if(!X.ok)return{hasUpdate:!1,currentVersion:A,source:"npm"};let F=await X.json(),D=F.version??F["dist-tags"]?.latest;if(!D)return{hasUpdate:!1,currentVersion:A,source:"npm"};let G=vr(A,D),V=G<0,U,K;if(F.time){let E=F.time[A],W=F.time[D],H=Date.now();if(E)U=Math.floor((H-new Date(E).getTime())/3600000);if(W)K=Math.floor((H-new Date(W).getTime())/3600000)}return j.info("NPM version comparison",{currentVersion:A,latestVersion:D,compareResult:G,hasUpdate:V,currentVersionAge:U,latestVersionAge:K}),{hasUpdate:V,latestVersion:D,currentVersion:A,currentVersionAge:U,latestVersionAge:K,source:"npm"}}catch(X){return j.debug("Error checking npm version",{error:X}),{hasUpdate:!1,currentVersion:A,source:"npm"}}finally{clearTimeout(Z)}}var mS5="https://static.ampcode.com/cli/cli-version.txt";async function zD0(A){let Q=new AbortController,B=setTimeout(()=>Q.abort(),5000);try{let $=await fetch(`${mS5}?t=${Date.now()}`,{signal:Q.signal,cache:"no-store"});if(!$.ok)return{hasUpdate:!1,currentVersion:A,source:"bin"};let J=(await $.text()).trim();if(!J||!/^\d+\.\d+\.\d+/.test(J))return{hasUpdate:!1,currentVersion:A,source:"bin"};let Y=vr(A,J),Z=Y<0;return j.info("Bin version comparison",{currentVersion:A,latestVersion:J,compareResult:Y,hasUpdate:Z}),{hasUpdate:Z,latestVersion:J,currentVersion:A,source:"bin"}}catch($){return j.debug("Error checking bin version",{error:$}),{hasUpdate:!1,currentVersion:A,source:"bin"}}finally{clearTimeout(B)}}var pS5=604800000;function Gc4(A){if(!A)return null;let Q=typeof A==="number"?A:new Date(A).getTime();if(isNaN(Q))return null;let B=Date.now()-Q;if(B>pS5)return{ageMs:B};return null}function vr(A,Q){let B=(Z)=>{let[X,F]=Z.split("-");return{parts:X?.split(".").map(Number)||[],label:F}},$=B(A),J=B(Q),Y=Math.max($.parts.length,J.parts.length);for(let Z=0;Z<Y;Z++){let X=$.parts[Z]||0,F=J.parts[Z]||0;if(X<F)return-1;if(X>F)return 1}if($.label===J.label)return 0;if(!$.label&&J.label)return 1;if($.label&&!J.label)return-1;if($.label&&J.label)return $.label<J.label?-1:1;return 0}function K11(A){try{let Q=A.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Q)return null;let B=parseInt(Q[1],10)*1000,$=Q[2],J=B!==0?AU(B):void 0;return{sha:$,age:J}}catch{return null}}R1();l0();import{readFile as dS5,realpath as cS5}from"node:fs/promises";import{homedir as lS5}from"node:os";import{dirname as Vc4,join as E11}from"node:path";async function Uc4(A){switch(A){case"binary":case"brew":return iS5(_r());case"npm":case"pnpm":case"yarn":case"bun":return nS5();case"bootstrap":return aS5()}}async function iS5(A){let Q=await dD(A,["--version"],5000);if(Q.reason!=="success")return j.debug("failed to read version from binary",{binaryPath:A,result:Q}),null;return Q.output.trim().split(/\s+/)[0]||null}async function nS5(){try{let A=process.argv[1];if(!A)return null;let Q=await cS5(A),B=Vc4(Vc4(Q));return await Kc4(E11(B,"package.json"))}catch(A){return j.debug("failed to read installed version from package.json",{error:A}),null}}async function aS5(){try{let A=process.env.AMP_HOME??E11(lS5(),".amp");return await Kc4(E11(A,"package","package.json"))}catch(A){return j.debug("failed to read installed version from bootstrap package.json",{error:A}),null}}async function Kc4(A){let Q=await dS5(A,"utf8"),B=JSON.parse(Q);if(B.name!=="@sourcegraph/amp")return j.debug("package.json name mismatch",{pkgJsonPath:A,name:B.name}),null;return B.version||null}var oS5=3600000,rS5=5000;function W11(A,Q,B={}){let $=new h4,J=$.pipe(nA({shouldCountRefs:!1})),Y=B.startDelayMs??0,Z=B.checkIntervalMs??oS5,X=!1,F=()=>{X=!0};return setImmediate(async()=>{let D=new f$().with({name:"update"});if(Y>0){if(await eV(Y),X)return}let G=J.subscribe({next:(U)=>{D.debug("emit new state",U)}}),V=A;try{while(!X){let U=await sS5(V,Q,D,$);if(U.stop)return;if(U.updatedTo)V=U.updatedTo;if(U.emittedVisibleState){if(await eV(rS5),X)return;$.next("hidden")}if(Z<=0)return;let K=1000,E=Z;while(E>0&&!X){let W=Math.min(K,E);await eV(W),E-=W}}}finally{G.unsubscribe(),$.complete()}}),{state:J,dispose:F}}async function sS5(A,Q,B,$){let J={stop:!1,emittedVisibleState:!1};try{if(process.env.AMP_SKIP_UPDATE_CHECK==="1")return B.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable"),J.stop=!0,J;let Y=await Q.get("updates.mode");if(Y==="disabled")return B.debug("checking disabled"),J.stop=!0,J;let Z=await Ef(),X=Z==="binary"||Z==="brew";B.debug("checking",{currentVersion:A,mode:Y,packageManager:Z,isBinaryDistribution:X});let F;if(X)F=await zD0(A);else{let V=await rj();F=await HD0(A,V)}if(!(F.latestVersion&&F.hasUpdate))return B.debug("no update available"),J;let D=(V)=>{$.next(V),J.emittedVisibleState=!0};if(Z){let V=await Uc4(Z);if(V&&vr(V,F.latestVersion)>=0){if(B.debug("on-disk version already up to date",{currentVersion:A,installedVersion:V,latestVersion:F.latestVersion}),J.updatedTo=V,vr(A,V)<0){let U=await mW(V),K={from:A,to:V,externallyUpdated:!0,...U};if(U.status==="same")B.info("on-disk already updated by another instance",K),D("updated");else B.warn("on-disk already updated by another instance, with PATH warning",K),D("updated-with-warning")}return J}}let G=()=>{if(F.currentVersionAge!==void 0&&F.latestVersionAge!==void 0){let V=F.currentVersionAge-F.latestVersionAge,U=0.5;if(Math.abs(V)<0.5)return B.debug("versions too close together, suppressing update warning",{currentVersionAge:F.currentVersionAge,latestVersionAge:F.latestVersionAge,ageDifferenceHours:V}),!0}return!1};if(!Y)Y=Z==="pnpm"?"warn":"auto",B.debug("no configured update mode; selected default based on package manager",{packageManager:Z,mode:Y});if(Z==="brew"){if(!G())D("update-available-brew");return J}if(Z==="binary"&&process.execPath!==_r()){if(B.debug("non-standard binary path, showing warning"),!G())D("update-available-unrecognized-path");return J}if(Y==="warn"){if(!G())D("update-available");return J}if(!Z){if(B.debug("auto-update not supported, falling back to warn mode"),!G())D("update-available");return J}if(Z==="binary"&&process.platform==="win32"){if(B.debug("binary auto-update not supported on Windows, falling back to warn mode"),!G())D("update-available");return J}try{await kr(F.latestVersion,Z),J.updatedTo=F.latestVersion;let V=await mW(F.latestVersion),U={from:F.currentVersion,to:F.latestVersion,...V};if(V.status==="same")B.info("success",U),D("updated");else B.warn("success with warning",U),D("updated-with-warning")}catch(V){D("update-error")}return J}catch(Y){return B.debug("check failed",{error:Y}),J}}LN();import{stderr as cD}from"node:process";function Ec4(A){let Q=new rN().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($)=>{await Q11($.force||!1,$.verbose||!1,"0.0.1778070540-gc7ef03"),process.exit()});A.addCommand(Q,{hidden:!0});let B=new rN("update").alias("up").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async($)=>{await eS5($.targetVersion)});A.addCommand(B)}function tS5(A){let Q=Boolean(A.isTTY),B=0,$=!1;function J(){if(!Q||!$)return;A.write(`
4889
4889
  `),$=!1,B=0}function Y(Z){if(!Q)return;let X=Z.padEnd(B," ");A.write(`\r${X}`),$=!0,B=X.length}return{flushProgressLine:J,renderProgress:Y}}async function eS5(A){let B=process.platform==="win32"&&oj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:$,renderProgress:J}=tS5(cD);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cD.write(o0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
4890
4890
 
4891
4891
  `));try{if(!A){cD.write(o0.blue(`Checking for updates...
4892
- `));let X=!1,F;if(oj()){let D=await zD0("0.0.1778070211-gdd8fb4");X=D.hasUpdate,F=D.latestVersion}else{let D=await rj(),G=await HD0("0.0.1778070211-gdd8fb4",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=K11("0.0.1778070211-gdd8fb4"),G=D?.age?`released ${D.age} ago`:`built ${AU(new Date("2026-05-06T12:27:20.020Z"))} ago`;cD.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1778070211-gdd8fb4"} (${G})
4893
- `));let V=await mW("0.0.1778070211-gdd8fb4",B);if(V.warning)cD.write(`
4892
+ `));let X=!1,F;if(oj()){let D=await zD0("0.0.1778070540-gc7ef03");X=D.hasUpdate,F=D.latestVersion}else{let D=await rj(),G=await HD0("0.0.1778070540-gc7ef03",D);X=G.hasUpdate,F=G.latestVersion}if(!X){let D=K11("0.0.1778070540-gc7ef03"),G=D?.age?`released ${D.age} ago`:`built ${AU(new Date("2026-05-06T12:32:43.933Z"))} ago`;cD.write(o0.green(`✓ Amp is already up to date on version ${"0.0.1778070540-gc7ef03"} (${G})
4893
+ `));let V=await mW("0.0.1778070540-gc7ef03",B);if(V.warning)cD.write(`
4894
4894
  `+o0.yellow(V.warning)+`
4895
4895
  `);process.exit(0)}if(!F)cD.write(o0.yellow("[WARN] could not find latest version")),process.exit(0);A=F}cD.write(o0.blue(`Updating to version ${A}...
4896
4896
  `)),await kr(A,void 0,(X)=>{$(),cD.write(o0.dim(`Running: ${X}
@@ -5327,7 +5327,7 @@ ${$}`).join(`
5327
5327
  `)}function Gn5(A){return A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}function P51(A){return A.replace(/\[(image(?:\s+\d+)?)\]/gi,"").trim()}function Vn5(A){let Q=rI.extname(A.sourcePath).toLowerCase();if(Q.length>0)return Q;if(A.source.type==="base64")switch(A.source.mediaType){case"image/jpeg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp"}return".png"}async function Un5(A,Q){let B=[];for(let[$,J]of Q.entries()){if(J.source.type!=="base64"){j.warn("Skipping non-base64 debug package issue image",{index:$,sourceType:J.source.type});continue}let Y=`issue-image-${$+1}${Vn5(J)}`,Z=rI.join(A,Y);try{await Fb(Z,Buffer.from(J.source.data,"base64")),B.push(Y)}catch(X){j.warn("Failed to write debug package issue image",{index:$,fileName:Y,error:X})}}return B}function Kn5(A,Q,B=[]){let $=["# Bug Report","","## Issue Description","",A,""];if(B.length>0){for(let[J,Y]of B.entries())$.push(`![Issue image ${J+1}](./${Y})`);$.push("")}if($.push("## Included Files","","- `cli-logs.json` — CLI logs filtered for this session PID","- `thread.yaml` — Full thread data (messages, metadata, agent mode, etc.)"),B.length>0)$.push("- `issue-image-*.*` — Images attached to the issue description");if(Db(Q.thread))$.push("- `thread.sqlite` — DTW Durable Object SQLite dump","- `cloudflare-logs.json` — Worker logs from Cloudflare (if CLOUDFLARE_API_TOKEN was set)");if($.push("","## Debug Instructions","","To investigate, start with the issue description above, then:","","1. Review `cli-logs.json` for errors, warnings, and the sequence of events"),Db(Q.thread))$.push("2. Open `thread.sqlite` and inspect the `messages` and `thread_events` tables:"," ```sh"," sqlite3 -json thread.sqlite 'SELECT * FROM messages ORDER BY created_at, rowid'"," sqlite3 -json thread.sqlite 'SELECT * FROM thread_events ORDER BY seq'"," ```","3. Review `cloudflare-logs.json` (if present) for server-side worker errors","4. Check Cloudflare dashboards for more detail:",` - Logs: <${j51(Q.thread.id)}>`,` - Data Studio: <${O51(Q.thread.id)}>`);return $.push("",yV0(Q)),$.join(`
5328
5328
  `)}function _51(A){let Q=A.activeThreadHandle.getInitialTreeURI();return{thread:A.thread,ampURL:A.ampURL,effectiveAgentMode:A.getEffectiveAgentMode(),isProcessing:A.isProcessing,threadPoolIsDTW:A.threadPool.isDTWMode?.()===!0,transportState:A.threadPool.getTransportConnectionState?.(),transportRole:A.threadPool.getTransportConnectionRole?.(),threadViewState:A.threadViewStates[A.thread.id],initialTreePath:Q?W5(F8(Q)):void 0,currentWorkspacePath:W5(F8(A.currentWorkspace)),clientId:A.clientId,logFile:A.logFile,pid:process.pid}}async function Ee4(A){try{let Q=rI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.json`),B=JSON.stringify(A.thread,null,2);await Fb(Q,B,"utf-8"),await LJ(Q),j.info("Thread JSON written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread JSON or open editor",Q),Error("Failed to write thread JSON or open editor",{cause:Q})}}async function We4(A){try{let Q=rI.join("/tmp",`amp-thread-${A.thread.id}-${Date.now()}.yaml`),B=L51.default.stringify(A.thread);await Fb(Q,B,"utf-8"),await LJ(Q),j.info("Thread YAML written and opened in editor",{file:Q});return}catch(Q){return j.error("Failed to write thread YAML or open editor",Q),Error("Failed to write thread YAML or open editor",{cause:Q})}}async function He4(A,Q){if(typeof Q!=="string")return Error("Select a log option from the picker");switch(Q){case"cli-open":{let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $="less -R +G",J=vV0(process.pid,B,$);try{try{L4.instance.tuiInstance.suspend(),Bt(J,{stdio:"inherit"})}finally{process.stdout.write("\x1B[?25l"),L4.instance.tuiInstance.resume()}j.info("Opened filtered CLI logs",{command:J,pid:process.pid,logFile:$t(B),outputCommand:$??null});return}catch(Y){return j.error("Failed to open filtered CLI logs",{error:Y,command:J}),Error("Failed to open filtered CLI logs",{cause:Y})}}case"cloudflare-logs":{await lA(A.context??A.contextFallback,j51(A.thread.id));return}case"cloudflare-data-studio":{await lA(A.context??A.contextFallback,O51(A.thread.id));return}default:return Error(`Unknown log option: ${Q}`)}}async function ze4(A){let Q=_51(A),B=Ke4(Q),$=!1;try{await L4.instance.tuiInstance.clipboard.writeText(B),$=!0}catch(J){j.error("Failed to copy debug prompt",{error:J})}return new y2(new PA({child:new S6({markdown:[$?"**Copied Markdown debug prompt to clipboard.**":"**Clipboard copy failed. Select and copy manually.**","",B].join(`
5329
5329
  `)})}),"Debug Prompt","info","help",{width:100,height:28})}function En5(A){return typeof A==="object"&&A!==null&&"label"in A&&typeof A.label==="string"&&"command"in A&&typeof A.command==="string"}async function qe4(A,Q){if(!En5(Q))return Error("Select a command from the picker");try{await L4.instance.tuiInstance.clipboard.writeText(Q.command),A.showToast(`Copied: ${Q.label}`,"success")}catch(B){j.error("Failed to copy DTW debug command",{error:B})}}async function Ne4(A){return new y2(new PA({child:new S6({markdown:yV0(_51(A))})}),"Thread Diagnostics","info","help",{width:100,height:26})}async function Ie4(A,Q){let B=A.logFile;if(!B)return Error("CLI log file is unavailable for this session");let $=P51(Q.description);if($.trim().length===0)return Error("Description is required");let J=Q.images,Y=$t(B),Z=process.pid,X=Gn5($)||"debug-package",F=Yn5.tmpdir(),D=rI.join(F,`amp-${X}`),G=`${D}.zip`;A.showStatusMessage("Building debug package...");try{Bt(`mkdir -p ${D}`);let V=`select(.pid == ${Z})`,U=Bt(`cat ${Y} | jq -c '${V}'`,{encoding:"utf-8",maxBuffer:52428800});await Fb(rI.join(D,"cli-logs.json"),U,"utf-8"),await Fb(rI.join(D,"thread.yaml"),L51.default.stringify(A.thread),"utf-8");let K=await Un5(D,J),E=Kn5($,_51(A),K);await Fb(rI.join(D,"agent-read-this.md"),E,"utf-8"),Bt(`zip -j ${G} ${D}/*`),Bt(`osascript -e 'set the clipboard to POSIX file "${G}"'`),A.showToast("Debug package copied to clipboard — paste into Slack","success"),j.info("Packaged debug bundle to clipboard",{zipPath:G,packageDir:D,pid:Z,threadId:A.thread.id});return}catch(V){return j.error("Failed to package debug bundle",{error:V}),Error("Failed to package debug bundle",{cause:V})}}E8();var Wn5=80,Hn5=20,we4=4,zn5=42,je4=420,Re4=640,qn5=Math.max(32,cU),Ce4="░▒▓█▁▂▃▄▅▆▇∿∾∽≋≈∼",xV0=["▁","▂","▃","▄","▅","▆","▇","█"],Nn5=["▏","▎","▍","▌","▋","▊","▉","█"],In5=["▕","▐","▉","▊","▋","▌","▍","▎"],wn5=z0.symmetric(1,0),Cn5=z0.all(1),Mn5=z0.all(1),Ln5={primary:{r:102,g:102,b:102},secondary:{r:255,g:255,b:255}},On5={primary:{r:77,g:0,b:10},secondary:{r:255,g:77,b:95}};function jn5(A){return{borderShape:A?.borderShape??"notched",borderAnimation:A?.borderAnimation??"subtle",titleAnimation:A?.titleAnimation??"none",timeMs:A?.timeMs,animate:A?.animate,seed:A?.seed??zn5}}function Pe4(A){switch(A){case"notched":return Cn5;case"classic":return wn5}}class _A extends w1{props;constructor(A){super();this.props=A}build(A){let Q=T0.of(A),B=e1.of(A),$=this.props.tone??"default",J=jn5(this.props.visualStyle),Y=this.props.bodyFit??{kind:"shrink"},Z=yn5(this.props,Y,B,J.borderShape),X=un5($,Q),F=n1.all(new a1(X.border,1,"rounded")),D=S51(this.props.header,J.borderShape),G=k51(this.props.footer,J.borderShape),V=hn5(D===void 0?this.props.header:void 0,X.header,J),U=dn5(this.props.child,Y),K=G===void 0?cn5(this.props.footer,Q):new W0({height:0}),E=Y.kind==="fill"?"max":"min",W=typeof this.props.header==="string"?`NeoModal:${this.props.header}`:"NeoModal",H=this.props.autofocus??!0,z=this.props.chromePadding??Pe4(J.borderShape),q=D===void 0&&typeof this.props.header==="string"?1:0,N=G===void 0?le4(this.props.footer):0,I=new c4({autofocus:H,canRequestFocus:!0,debugLabel:W,onKey:(_)=>{if(_.key==="Escape")return this.props.onDismiss(),"handled";return"ignored"},child:new f0({mainAxisSize:E,crossAxisAlignment:"stretch",children:[V,new W0({height:q}),U,new W0({height:N}),K]})}),C=!(J.borderShape==="notched"||J.borderAnimation!=="none")?new p0({constraints:Z,decoration:new x4(Q.colors.background,F),padding:z,child:I}):_n5({borderShape:J.borderShape,borderAnimation:J.borderAnimation,child:I,constraints:Z,background:Q.colors.background,borderColor:X.border,tone:$,headerColor:X.header,footerKeyColor:Q.app.keybind,footerHintColor:Q.colors.foreground,padding:z,title:D,footer:G,titleAnimation:J.titleAnimation,seed:J.seed,timeMs:J.timeMs,animate:J.animate}),O=new p0({decoration:new x4(Q.colors.background),padding:Mn5,child:C});return new t4({fit:"expand",children:[new _e4,new f1({onClick:()=>{},opaque:this.props.barrierOpaque??!0,child:W0.expand()}),new B4({child:O})]})}}class _e4 extends $8{createRenderObject(){return new Te4}}class Te4 extends Z4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Number.isFinite(A.maxWidth)?A.maxWidth:A.minWidth,B=Number.isFinite(A.maxHeight)?A.maxHeight:A.minHeight;this.setSize(Q,B)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=A.getSize(),Z=Math.max(0,$),X=Math.max(0,J),F=Math.min(Y.width,$+this.size.width),D=Math.min(Y.height,J+this.size.height);for(let G=X;G<D;G++)for(let V=Z;V<F;V++){let U=A.getCell(V,G);if(!U||Rn5(U))continue;let K={char:U.char,style:{...U.style,dim:!0},width:U.width};if(U.hyperlink!==void 0)K.hyperlink=U.hyperlink;A.setCell(V,G,K)}}}function Rn5(A){return A.char===" "&&A.width===1&&A.hyperlink===void 0&&Pn5(A.style)}function Pn5(A){return A.fg===void 0&&A.bg===void 0&&A.bold===void 0&&A.italic===void 0&&A.underline===void 0&&A.strikethrough===void 0&&A.reverse===void 0&&A.dim===void 0}function S51(A,Q){return Q==="notched"&&typeof A==="string"?A:void 0}function k51(A,Q){if(Q!=="notched")return;if(A===void 0)return[{keys:["Esc"],label:"close"}];if(!fV0(A)||A.length===0)return;return A}function _n5(A){if(A.timeMs!==void 0)return Me4(A,A.timeMs);if(!(A.animate??Tn5(A)))return Me4(A,0);return new Se4({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,initialTimeMs:0})}function Me4(A,Q){return new v51({borderShape:A.borderShape,borderAnimation:A.borderAnimation,child:A.child,constraints:A.constraints,background:A.background,borderColor:A.borderColor,tone:A.tone,headerColor:A.headerColor,footerKeyColor:A.footerKeyColor,footerHintColor:A.footerHintColor,padding:A.padding,title:A.title,footer:A.footer,titleAnimation:A.titleAnimation,seed:A.seed,timeMs:Q})}function Tn5(A){return A.titleAnimation!=="none"||A.borderAnimation!=="none"}class Se4 extends v0{props;constructor(A){super();this.props=A}createState(){return new ke4}}class ke4 extends k0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.borderShape!==this.widget.props.borderShape||A.props.borderAnimation!==this.widget.props.borderAnimation||A.props.seed!==this.widget.props.seed||A.props.title!==this.widget.props.title||A.props.titleAnimation!==this.widget.props.titleAnimation)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},cU),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){if(this.widget.props.borderAnimation!=="none")return!1;if(this.widget.props.titleAnimation!=="none")return Date.now()-this.startedAt>=me4(this.widget.props.titleAnimation);return!0}build(A){return new v51({borderShape:this.widget.props.borderShape,borderAnimation:this.widget.props.borderAnimation,child:this.widget.props.child,constraints:this.widget.props.constraints,background:this.widget.props.background,borderColor:this.widget.props.borderColor,tone:this.widget.props.tone,headerColor:this.widget.props.headerColor,footerKeyColor:this.widget.props.footerKeyColor,footerHintColor:this.widget.props.footerHintColor,padding:this.widget.props.padding,title:this.widget.props.title,footer:this.widget.props.footer,titleAnimation:this.widget.props.titleAnimation,seed:this.widget.props.seed,timeMs:Date.now()-this.startedAt+this.widget.props.initialTimeMs})}}class v51 extends q5{props;constructor(A){super({child:A.child});this.props=A}createRenderObject(){return new T51(this.props)}updateRenderObject(A){N4(A instanceof T51,"unexpected modal surface"),A.update(this.props)}}class T51 extends Z4{props;glow;constructor(A){super();this.props=A;this.glow=new T9(A.seed)}update(A){let Q=!this.props.constraints.equals(A.constraints)||this.props.padding!==A.padding;if(A.seed!==this.props.seed)this.glow=new T9(A.seed);if(this.props=A,Q)this.markNeedsLayout();this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.enforce(this.props.constraints),B=2+this.props.padding.horizontal,$=2+this.props.padding.vertical,J=new O1(Math.max(0,Q.minWidth-B),Math.max(0,Q.maxWidth-B),Math.max(0,Q.minHeight-$),Math.max(0,Q.maxHeight-$)),Y=this.children[0];if(Y)Y.layout(J),Y.setOffset(1+this.props.padding.left,1+this.props.padding.top);let Z=(Y?.size.width??0)+B,X=(Y?.size.height??0)+$,F=Q.constrain(Z,X);this.setSize(F.width,F.height)}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height);if(Y<=0||Z<=0)return;A.fill($,J,Y,Z," ",{bg:this.props.background}),this.paintBorder(A,$,J,Y,Z),super.paint(A,Q,B)}paintBorder(A,Q,B,$,J){if($<2||J<2)return;for(let Y=1;Y<$-1;Y++)this.paintBorderCell(A,Q+Y,B,Y,0,$,J,"top"),this.paintBorderCell(A,Q+Y,B+J-1,Y,J-1,$,J,"bottom");for(let Y=1;Y<J-1;Y++)this.paintBorderCell(A,Q,B+Y,0,Y,$,J,"left"),this.paintBorderCell(A,Q+$-1,B+Y,$-1,Y,$,J,"right");if(this.paintCorner(A,Q,B,0,0,$,J,"top-left"),this.paintCorner(A,Q+$-1,B,$-1,0,$,J,"top-right"),this.paintCorner(A,Q,B+J-1,0,J-1,$,J,"bottom-left"),this.paintCorner(A,Q+$-1,B+J-1,$-1,J-1,$,J,"bottom-right"),this.props.borderShape==="notched")this.paintNotchedLabels(A,Q,B,$,J)}paintBorderCell(A,Q,B,$,J,Y,Z,X){let F=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.borderGlyph(X,F),this.borderStyle(F),1)}paintCorner(A,Q,B,$,J,Y,Z,X){let F=this.sampleBorderIntensity($,J,Y,Z);A.setChar(Q,B,this.cornerGlyph(X,F),this.borderStyle(F),1)}paintNotchedLabels(A,Q,B,$,J){let Y=this.props.title;if(Y){let G=mn5(Y,this.props.titleAnimation,this.props.timeMs);this.paintBorderText(A,Q+2,B,` ${G} `,$-4,{fg:this.props.headerColor,bg:this.props.background,bold:!0})}let Z=this.props.footer;if(!Z||J<2)return;let X=ve4(Z,{fg:this.props.footerKeyColor,bg:this.props.background},{fg:this.props.footerHintColor,bg:this.props.background,dim:!0}),F=ye4(X),D=Math.max(2,$-F-2);this.paintStyledBorderText(A,Q+D,B+J-1,X,Math.max(0,$-D-2))}paintBorderText(A,Q,B,$,J,Y){this.paintStyledBorderText(A,Q,B,[{text:$,style:Y}],J)}paintStyledBorderText(A,Q,B,$,J){let Y=Q,Z=kn5($,J);for(let X of Z)A.setChar(Y,B,X.grapheme,X.style,X.width),Y+=X.width}borderGlyph(A,Q){switch(this.props.borderAnimation){case"mysterious-message":return this.mysteriousMessageBorderGlyph(A,Q);case"none":case"subtle":return A==="left"||A==="right"?"│":"─"}}mysteriousMessageBorderGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="left")return Nn5[B]??"▏";if(A==="right")return In5[B]??"▕";return xV0[B]??"▁"}mysteriousMessageBorderIndex(A){return Math.max(0,Math.min(xV0.length-1,Math.floor(A*xV0.length)))}mysteriousMessageCornerGlyph(A,Q){let B=this.mysteriousMessageBorderIndex(Q);if(A==="top-left"||A==="top-right")return xV0[B]??"▁";return"█"}cornerGlyph(A,Q){if(this.props.borderAnimation==="mysterious-message")return this.mysteriousMessageCornerGlyph(A,Q);switch(A){case"top-left":return"╭";case"top-right":return"╮";case"bottom-left":return"╰";case"bottom-right":return"╯"}}borderStyle(A){let Q={fg:this.borderColor(A),bg:this.props.background};if(this.props.borderAnimation==="mysterious-message"&&A>0.72)Q.bold=!0;return Q}borderColor(A){switch(this.props.borderAnimation){case"none":return this.props.borderColor;case"subtle":case"mysterious-message":return this.animatedBorderColor(A)}}animatedBorderColor(A){let Q=0.18+Jt(A)*0.82;switch(this.props.tone){case"default":return tQ(Q,void 0,Ln5);case"warning":return tQ(Q,sM);case"success":return tQ(Q,void 0);case"error":return tQ(Q,void 0,On5)}}sampleBorderIntensity(A,Q,B,$){let J=Math.max(1,B*2+$*2-4),Y=Sn5(A,Q,B,$),Z=Y/J,X=this.props.timeMs/1000,F=this.glow.sample(A*1.3+Y*0.07,Q*1.1-X*5,X,1.2),D=(Z-X*0.18%1+1)%1,G=Math.min(D,1-D),V=Math.max(0,1-G/0.085)**2;return Jt(F*0.58+V*0.54)}}function Sn5(A,Q,B,$){if(Q<=0)return Math.max(0,A);if(A>=B-1)return B-1+Math.max(0,Q);if(Q>=$-1)return B+$-2+Math.max(0,B-1-A);return B*2+$-3+Math.max(0,$-1-Q)}function ve4(A,Q,B){let $=[{text:" ",style:B}];return A.forEach((J,Y)=>{if(Y>0)$.push({text:" · ",style:B});J.keys.forEach((Z,X)=>{if(X>0)$.push({text:"/",style:B});$.push({text:Z,style:Q})}),$.push({text:` ${J.label}`,style:B})}),$.push({text:" ",style:B}),$}function ye4(A){return xe4(A).reduce((Q,B)=>Q+B.width,0)}function kn5(A,Q){if(Q<=0)return[];let B=[],$=0;for(let J of xe4(A)){if($+J.width>Q)return vn5(B,$,Q,J.style);B.push(J),$+=J.width}return B}function xe4(A){let Q=[];for(let B of A)for(let $ of f4(B.text))Q.push({grapheme:$,style:B.style,width:m6($)});return Q}function vn5(A,Q,B,$){let Y=m6("…");if(Y>B)return A;let Z=Q;while(A.length>0&&Z+Y>B){let X=A.pop();if(X)Z-=X.width}if(Z+Y<=B)A.push({grapheme:"…",style:$,width:Y});return A}function Jt(A){return Math.max(0,Math.min(1,A))}function yn5(A,Q,B,$){let J=Math.max(0,B.size.width-we4),Y=Math.max(0,B.size.height-we4),Z=Math.max(A.minWidth??0,xn5(A,$)),X=Math.max(0,Math.min(A.maxWidth??Wn5,J));if(Q.kind==="fill"){let G=fn5(A,$),V=Math.max(Q.modalRows,G),U=Math.max(0,Math.min(V,Y));return new O1(Math.min(Z,X),X,U,U)}let F=Math.max(0,Math.min(A.maxHeight??Hn5,Y)),D=Math.min(A.minHeight??0,F);return new O1(Math.min(Z,X),X,D,F)}function xn5(A,Q){if(Q!=="notched")return 0;let B=0,$=S51(A.header,Q);if($)B=Math.max(B,4+a4(` ${$} `));let J=k51(A.footer,Q);if(J)B=Math.max(B,4+ye4(ve4(J,{},{})));return B}function fn5(A,Q){let B=A.chromePadding??Pe4(Q),$=S51(A.header,Q),J=k51(A.footer,Q),Y=2,Z=A.header===void 0||$!==void 0?0:1,X=$===void 0&&typeof A.header==="string"?1:0,F=J===void 0?bn5(A.footer):0,D=J===void 0?le4(A.footer):0,G=1;return 2+B.top+B.bottom+Z+X+1+D+F}function bn5(A){if(A===void 0)return 1;if(A==="none")return 0;if(fV0(A))return A.length===0?0:1;return 1}function un5(A,Q){switch(A){case"default":return{border:Q.colors.border,header:Q.app.command};case"warning":return{border:Q.colors.warning,header:Q.colors.warning};case"success":return{border:Q.app.toolSuccess,header:Q.app.toolSuccess};case"error":return{border:Q.app.toolError,header:Q.app.toolError}}}function hn5(A,Q,B){if(A===void 0)return new W0({height:0});if(typeof A==="string")return new p0({padding:z0.symmetric(1,0),child:new B4({child:gn5(A,Q,B)})});return A}function gn5(A,Q,B){if(B.titleAnimation==="none")return new l({text:new M(A,new y({color:Q,bold:!0}))});let $=B.timeMs??(B.animate===!1?0:void 0);if($!==void 0)return new l({text:ue4(A,Q,B.titleAnimation,$)});return new fe4({title:A,color:Q,animation:B.titleAnimation})}class fe4 extends v0{props;constructor(A){super();this.props=A}createState(){return new be4}}class be4 extends k0{startedAt=Date.now();timer=null;initState(){this.startTimer()}didUpdateWidget(A){if(A.props.title!==this.widget.props.title||A.props.animation!==this.widget.props.animation||A.props.color!==this.widget.props.color)this.startedAt=Date.now();this.startTimer()}dispose(){this.stopTimer(),super.dispose()}startTimer(){if(this.timer||this.widget.props.animation==="none"||this.animationComplete())return;this.timer=setInterval(()=>{if(!this.mounted)return;if(this.setState(()=>{}),this.animationComplete())this.stopTimer()},qn5),this.timer.unref()}stopTimer(){if(!this.timer)return;clearInterval(this.timer),this.timer=null}animationComplete(){return Date.now()-this.startedAt>=me4(this.widget.props.animation)}build(A){return new l({text:ue4(this.widget.props.title,this.widget.props.color,this.widget.props.animation,Date.now()-this.startedAt)})}}function ue4(A,Q,B,$){let J=f4(A),Y=new y({color:Q,bold:!0}),Z=new y({color:Q,bold:!0,dim:!0});switch(B){case"none":return new M(A,Y);case"wipe":return new M("",void 0,Le4(J,he4(J,$),Y,Z));case"scramble":return new M("",void 0,Le4(J,ge4(J,$),Y,Z))}}function mn5(A,Q,B){let $=f4(A);switch(Q){case"none":return A;case"wipe":return he4($,B).join("");case"scramble":return ge4($,B).join("")}}function Le4(A,Q,B,$){return Q.map((J,Y)=>{let Z=J===A[Y]?B:$;return new M(J,Z)})}function he4(A,Q){let B=pe4(Jt(Q/je4)),$=Math.floor(B*(A.length+1));return A.map((J,Y)=>{if(Y<$)return J;if(Y===$)return"▒";return" "})}function ge4(A,Q){let $=pe4(Jt(Q/Re4))*(A.length+5),J=Math.floor(Q/45);return A.map((Y,Z)=>{if(Jt(($-Z)/5)>=1)return Y;return pn5(Z,J)})}function pn5(A,Q){return Ce4[(A*7+Q*11)%Ce4.length]??"░"}function me4(A){if(A==="scramble")return Re4;return je4}function pe4(A){return 1-(1-A)**3}function dn5(A,Q){let B=Q.kind==="fill"?"tight":"loose";return new k2({fit:B,child:new de4({child:A})})}class de4 extends q5{constructor({child:A}){super({child:A})}createRenderObject(){return new ce4}}class ce4 extends Z4{performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(Q)Q.layout(A.loosen()),Q.setOffset(0,0);let B=Q?.size.width??0,$=Q?.size.height??0,J=A.constrain(A.hasTightWidth?A.maxWidth:B,A.hasTightHeight?A.maxHeight:$);this.setSize(J.width,J.height)}}function cn5(A,Q){if(A===void 0)return Oe4([{keys:["Esc"],label:"close"}],Q);if(fV0(A))return A.length===0?new W0({height:0}):Oe4(A,Q);if(A==="none")return new W0({height:0});return A}function fV0(A){return Array.isArray(A)}function le4(A){return A===void 0||fV0(A)&&A.length>0?1:0}function Oe4(A,Q){let B=new y({color:Q.app.keybind}),$=new y({color:Q.colors.foreground,dim:!0}),J=[];return A.forEach((Y,Z)=>{if(Z>0)J.push(new M(" · ",$));Y.keys.forEach((X,F)=>{if(F>0)J.push(new M("/",$));J.push(new M(X,B))}),J.push(new M(` ${Y.label}`,$))}),new B4({child:l.spans(J)})}function in5(A){return[{label:"cli: copy tail logs",command:sI("tail",process.pid,{path:A})},{label:"cli: copy logs snapshot",command:sI("snapshot",process.pid,{path:A})},{label:"cli: htop",command:`htop -p ${process.pid}`}]}async function nn5(A,Q){try{await L4.instance.tuiInstance.clipboard.writeText(A.command)}catch(B){j.error("Failed to copy debug command from Neo command palette",{error:B})}finally{Q()}}function an5(A,Q){let B=vV0(process.pid,{path:A},"less -R +G");Q();try{L4.instance.tuiInstance.suspend(),ln5(B,{stdio:"inherit"})}catch($){j.error("Failed to open filtered CLI logs in pager",{error:$,command:B})}finally{process.stdout.write("\x1B[?25l"),L4.instance.tuiInstance.resume()}}function ie4(A){return[{noun:"debug",verb:"page logs",description:"View CLI logs in pager",status:{type:"enabled"},run:(Q,B,$)=>{an5(A,$)}},{noun:"debug",verb:"copy command",description:"Copy debug command to clipboard",status:{type:"enabled"},run:(Q,B,$)=>{Q.pushWithDismiss((J)=>new _A({header:"Debug: Copy Command",minWidth:80,maxWidth:80,autofocus:!1,footer:"none",onDismiss:J,child:new p6({items:in5(A),getLabel:(Y)=>Y.label,showBorder:!1,onAccept:(Y)=>{nn5(Y,$)},onDismiss:J})}))}}]}var Gb="exit-app-key-pressed",Vb="cancel-key-pressed",tI="loading-thread",Ub="previous-thread-reference",Kb="double-enter-steer";class Zt extends d4{}class bV0 extends d4{}class uV0 extends d4{}class Xt extends d4{visualIndex;constructor(A){super();this.visualIndex=A}}class Ft extends d4{}class hV0 extends d4{}class Dt extends d4{}class Eb extends d4{}class Wb extends d4{}class Gt extends d4{}class Vt extends d4{}class Ut extends d4{}class Hb extends d4{}class J$ extends d4{text;successMessage;failureMessage;constructor(A="",Q="Selection copied to clipboard",B="Failed to copy selection"){super();this.text=A;this.successMessage=Q;this.failureMessage=B}}class gV0 extends d4{}class Kt extends d4{}class mV0 extends d4{}class pV0 extends d4{}class Et extends d4{}class Wt extends d4{}class Ht extends d4{}class dV0 extends d4{}class cV0 extends d4{}class lV0 extends d4{}class bR extends d4{}class zt extends d4{}class y51 extends d4{mode;constructor(A){super();this.mode=A}}M3();var ne4=process.platform==="win32"?" ":"█",ae4=process.platform==="win32"?"░":"█";class D2 extends v0{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=ne4,thumbChar:Y=ae4,showTrack:Z=!0,thumbColor:X,trackColor:F}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=X,this.trackColor=F}createState(){return new oe4}}class oe4 extends k0{_dragStartY=null;_dragStartOffset=null;_isOverThumb=!1;_isPositionOverThumb(A){let{totalContentHeight:Q,viewportHeight:B}=this.widget.getScrollInfo(),J=this.context.findRenderObject()?.size.height??0;if(J===0||Q<=B)return!1;let Y=this.widget.getScrollInfo(),Z=Math.min(1,B/Q),X=Math.max(1,J*Z),F=Math.max(0,Math.min(1,Y.scrollOffset/(Q-B))),D=J-X,G=Math.max(0,D*F),V=G+X;return A>=G&&A<=V}_handleHover=(A)=>{let Q=this._isOverThumb;if(this._isOverThumb=this._isPositionOverThumb(A.localPosition.y),Q!==this._isOverThumb)this.setState()};_handleDrag=(A)=>{let{totalContentHeight:Q,viewportHeight:B,scrollOffset:$}=this.widget.getScrollInfo(),Y=this.context.findRenderObject()?.size.height??0;if(Y===0||Q<=B)return;if(this._dragStartY===null)this._dragStartY=A.localPosition.y,this._dragStartOffset=$;let Z=A.localPosition.y-this._dragStartY,X=Math.min(1,B/Q),F=Math.max(1,Y*X),D=Y-F;if(D<=0)return;let G=Q-B,V=D/G,U=Z/V,K=Math.max(0,Math.min(G,this._dragStartOffset+U));this.widget.controller.jumpTo(K)};_handleRelease=()=>{this._dragStartY=null,this._dragStartOffset=null};_handleClick=(A)=>{if(A.button!=="left")return;let Q=A.localPosition.y,{totalContentHeight:B,viewportHeight:$,scrollOffset:J}=this.widget.getScrollInfo(),Z=this.context.findRenderObject()?.size.height??0;if(Z===0||B<=$)return;let X=Math.min(1,$/B),F=Math.max(1,Z*X),D=B-$,G=Z-F,V=Math.max(0,Math.min(1,J/(B-$))),U=Math.max(0,G*V),K=U+F;if(Q>=U&&Q<=K)return;if(Q<U)this.widget.controller.animateTo(Math.max(0,J-$));else this.widget.controller.animateTo(Math.min(D,J+$))};build(A){return new f1({onClick:this._handleClick,onHover:this._handleHover,onDrag:this._handleDrag,onRelease:this._handleRelease,cursor:this._isOverThumb?r6.POINTER:r6.DEFAULT,child:new re4({controller:this.widget.controller,getScrollInfo:this.widget.getScrollInfo,thickness:this.widget.thickness,trackChar:this.widget.trackChar,thumbChar:this.widget.thumbChar,showTrack:this.widget.showTrack,thumbColor:this.widget.thumbColor,trackColor:this.widget.trackColor})})}}class re4 extends LI{controller;getScrollInfo;thickness;trackChar;thumbChar;showTrack;thumbColor;trackColor;constructor({key:A,controller:Q,getScrollInfo:B,thickness:$=1,trackChar:J=ne4,thumbChar:Y=ae4,showTrack:Z=!0,thumbColor:X,trackColor:F}){super(A?{key:A}:{});this.controller=Q,this.getScrollInfo=B,this.thickness=$,this.trackChar=J,this.thumbChar=Y,this.showTrack=Z,this.thumbColor=X,this.trackColor=F}createRenderObject(){return new se4(this)}updateRenderObject(A){A.updateWidget(this)}}class se4 extends Z4{_widget;constructor(A){super();this._widget=A}updateWidget(A){this._widget=A,this.markNeedsLayout()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=Math.min(A.maxWidth,this._widget.thickness),B=A.maxHeight;this.setSize(Q,B),super.performLayout()}getMinIntrinsicWidth(A){return this._widget.thickness}getMaxIntrinsicWidth(A){return this._widget.thickness}getMinIntrinsicHeight(A){return 0}getMaxIntrinsicHeight(A){return 0}paint(A,Q,B){let{thumbStartFloat:$,thumbSizeFloat:J,showScrollbar:Y}=this._calculateScrollbarMetrics();if(!Y)return;let Z=this._widget.trackColor,X=this._widget.thumbColor,F=process.platform==="win32",D=$,G=$+J;if(!F){let V=["▁","▂","▃","▄","▅","▆","▇","█"];for(let U=0;U<this.size.height;U++){let K="█",E=!0;if(U===Math.floor(D)){let W=1-(D-U),H=Math.floor(W*8);K=V[H]||"█",E=!1}else if(U===Math.floor(G)){let W=1-(G-U),H=Math.floor(W*8);K=V[H]||"█"}else if(U>D&&U<G)E=!1;A.setChar(Q,B+U,K,{fg:X,bg:Z,reverse:E},1)}return}for(let V=0;V<this.size.height;V++){let U=V+0.5,K=U>=D&&U<G,E=K?this._widget.thumbChar:this._widget.trackChar;A.setChar(Q,B+V,E,{fg:K?X:Z,bg:Z,reverse:!1},1)}}_calculateScrollbarMetrics(){let{totalContentHeight:A,viewportHeight:Q,scrollOffset:B}=this._widget.getScrollInfo(),$=this.size.height;if(A<=Q||$<=0)return{thumbStartFloat:0,thumbSizeFloat:0,showScrollbar:!1};let J=Math.max(0,Math.min(1,B/(A-Q))),Y=Math.min(1,Q/A),Z=Math.max(1,$*Y),X=$-Z;return{thumbStartFloat:Math.max(0,X*J),thumbSizeFloat:Z,showScrollbar:!0}}}var te4=1;class JZ extends v0{props;constructor(A){super();this.props=A}createState(){return new ee4}}class ee4 extends k0{ownership;viewportHeight=0;initState(){let A=this.widget.props.controller;if(A)this.ownership={controller:A,owned:!1};else{let Q=new rA;Q.followMode=!1,Q.jumpTo(0),this.ownership={controller:Q,owned:!0}}}didUpdateWidget(A){N4(A.props.controller===this.widget.props.controller,"NeoModalScrollArea.controller identity must be stable across rebuilds")}dispose(){if(this.ownership.owned)this.ownership.controller.dispose()}getScrollInfo=()=>{let{controller:A}=this.ownership,Q=this.viewportHeight;return{totalContentHeight:Math.max(A.maxScrollExtent+Q,0),viewportHeight:Q,scrollOffset:Math.max(A.offset,0)}};setMeasuredHeight=(A)=>{this.viewportHeight=A};build(A){let Q=T0.of(A),{controller:B}=this.ownership;return new A0A({thickness:te4,onMeasured:this.setMeasuredHeight,scrollable:new PA({controller:B,autofocus:this.widget.props.autofocus??!0,keyboardScrolling:!0,child:this.widget.props.child}),scrollbar:new D2({controller:B,thickness:te4,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:this.getScrollInfo})})}__testing={isOwned:()=>this.ownership.owned,controller:()=>this.ownership.controller}}class A0A extends _9{thickness;onMeasured;constructor({scrollable:A,scrollbar:Q,thickness:B,onMeasured:$}){super({children:[A,Q]});this.thickness=B,this.onMeasured=$}createRenderObject(){return new Q0A(this.thickness,this.onMeasured)}}class Q0A extends Z4{thickness;onMeasured;constructor(A,Q){super();this.thickness=A;this.onMeasured=Q}performLayout(){let A=this._lastConstraints;N4(!!A,"ScrollAreaLayoutRenderObject.performLayout called without constraints");let Q=A.maxWidth,B=Math.max(0,Math.min(this.thickness,Q)),$=Q-B,[J,Y]=this.children;N4(J!==void 0&&Y!==void 0,"ScrollAreaLayout requires scrollable and scrollbar children"),J.layout(new O1($,$,0,A.maxHeight)),J.setOffset(0,0);let Z=J.size.height;this.onMeasured(Z),Y.layout(new O1(B,B,Z,Z)),Y.setOffset($,0),this.setSize(Q,Z)}}var B0A=10;class x51 extends v0{pluginService;workspaceRoot;logFilePath;onDismiss;constructor(A){super();this.pluginService=A.pluginService,this.workspaceRoot=A.workspaceRoot,this.logFilePath=A.logFilePath,this.onDismiss=A.onDismiss}createState(){return new $0A}}class $0A extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.pluginService.plugins.subscribe((A)=>{this.setState(()=>{this.plugins=A})})}didUpdateWidget(A){if(A.pluginService===this.widget.pluginService)return;this.subscription?.unsubscribe(),this.subscription=this.widget.pluginService.plugins.subscribe((Q)=>{this.setState(()=>{this.plugins=Q})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}relativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.workspaceRoot.replace(/\/$/,"");return Q.startsWith(`${B}/`)?Q.slice(B.length+1):Q}detailPrefix(A){if(A.length===0)return` ${" ".repeat(B0A)}`;return` ${`${A}:`.padEnd(B0A," ")}`}pluginRows(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=new y({color:$.foreground,dim:!0}),Y=new y({color:B.link}),Z=new y({color:B.link,underline:!0});if(this.plugins.length===0)return[new b0({padding:z0.symmetric(1,1),child:new l({text:new M("No plugins found.",J)})})];return this.plugins.map((X)=>{let F=X.uri.toString(),D=F.startsWith("file://"),G=()=>{lA(A,F)},V=X.status==="active"?new y({color:B.toolSuccess}):X.status==="error"?new y({color:B.toolError}):new y({color:$.warning}),U=new l({text:new M(this.relativePath(F),D?Z:new y({color:B.command}),void 0,D?CI(F):void 0,D?G:void 0),maxLines:1,overflow:"ellipsis"}),K=D?new f1({cursor:"pointer",onClick:G,child:U}):U,E=[new Q1({children:[new l({text:new M(X.status,V,[new M(" ",J)]),maxLines:1,overflow:"clip"}),new k2({fit:"loose",child:K})]})];if(X.errorMessage)E.push(new l({text:new M(this.detailPrefix("Error"),J,[new M(`see logs: ${this.widget.logFilePath}`,new y({color:B.toolError}))]),maxLines:1,overflow:"ellipsis"}));if(X.registeredEvents.length>0)E.push(new l({text:new M(this.detailPrefix("Events"),J,[new M(X.registeredEvents.join(", "),Y)]),maxLines:1,overflow:"ellipsis"}));for(let[W,H]of X.registeredCommands.entries())E.push(new l({text:new M(W===0?this.detailPrefix("Commands"):this.detailPrefix(""),J,[new M(`${H.category}: ${H.title}`,Y)]),maxLines:1,overflow:"ellipsis"}));for(let[W,H]of X.registeredTools.entries())E.push(new l({text:new M(W===0?this.detailPrefix("Tools"):this.detailPrefix(""),J,[new M(H.name,Y)]),maxLines:1,overflow:"ellipsis"}));return new b0({padding:z0.only({left:1,right:1,bottom:1}),child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:E})})})}build(A){let Q=this.plugins.filter((Y)=>Y.status==="active").length,B=this.plugins.reduce((Y,Z)=>Y+Z.registeredCommands.length,0),$=this.plugins.reduce((Y,Z)=>Y+Z.registeredTools.length,0),J=`${Q}/${this.plugins.length} ${H4(this.plugins.length,"plugin")} active (${B} ${H4(B,"command")}, ${$} ${H4($,"tool")})`;return new _A({header:"Plugins",autofocus:!1,maxWidth:90,maxHeight:30,footer:[{keys:["Esc"],label:"close"},{keys:["↑↓","j/k"],label:"scroll"}],onDismiss:this.widget.onDismiss,child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new b0({padding:z0.only({left:1,right:1,bottom:1}),child:new l({text:new M(J,new y({bold:!0}))})}),new k2({fit:"loose",child:new JZ({child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:this.pluginRows(A)})})})]})})}}function J0A(A){return[{noun:"plugins",verb:"list",description:"List all loaded plugins",keywords:["extensions","tools","commands"],status:{type:"enabled"},run:(Q,B,$)=>{Q.push(new x51({pluginService:A.pluginService,workspaceRoot:A.workspaceRoot,logFilePath:A.logFilePath,onDismiss:$}))}},{noun:"plugins",verb:"reload",description:"Reload all plugins",keywords:["refresh","restart","extensions"],status:{type:"enabled"},run:(Q,B,$)=>{A.pluginService.reload(),A.toastController.show("Reloading plugins..."),$()}}]}l0();class qt extends d4{}class zb extends d4{}class f51 extends v0{props;constructor(A){super();this.props=A}createState(){return new Y0A}}class Y0A extends k0{build(A){let{options:Q,onConfirm:B,onCancel:$}=this.widget.props,{colors:J}=T0.of(A),Y=Q.message?new l({text:new M(Q.message,new y({color:J.foreground}))}):new W0({height:1});return new _A({header:Q.title,minWidth:64,maxWidth:80,footer:[{keys:["Y"],label:Q.confirmButtonText??"yes"},{keys:["N","Esc"],label:"cancel"},{keys:["↑↓","j/k"],label:"scroll"}],autofocus:!1,onDismiss:$,child:new BA({actions:new Map([[qt,new K4(()=>B())],[zb,new K4(()=>$())]]),child:new d5({debugLabel:"NeoConfirmDialogShortcuts",shortcuts:on5(),child:new JZ({child:Y})})})})}}function on5(){return new Map([[v1.key("y"),new qt],[v1.shift("Y"),new qt],[v1.shift("y"),new qt],[v1.key("n"),new zb],[v1.shift("N"),new zb],[v1.shift("n"),new zb],[v1.key("Escape"),new zb]])}class Nt extends v0{props;constructor(A){super();this.props=A}createState(){return new Z0A}}class Z0A extends k0{controller=new L8;onTextChanged=()=>{this.setState()};initState(){this.controller.text=this.widget.props.initialValue??"",this.controller.addListener(this.onTextChanged)}dispose(){this.controller.removeListener(this.onTextChanged),this.controller.dispose(),super.dispose()}handleSubmit(){let A=this.controller.text.trim();if((this.widget.props.isRequired??!0)&&A.length===0)return;this.widget.props.onSubmit(A)}build(A){let{colors:Q,app:B}=T0.of(A),Y=!(this.widget.props.isRequired??!0)||this.controller.text.trim().length>0?[{keys:["Enter"],label:"submit"},{keys:["Esc"],label:"cancel"}]:[{keys:["Esc"],label:"cancel"}],Z=[];if(this.widget.props.helpText)Z.push(new l({text:new M(this.widget.props.helpText,new y({color:Q.foreground}))})),Z.push(new W0({height:1}));return Z.push(new Q1({children:[new l({text:new M("> ",new y({color:B.command}))}),new k1({child:new eB({controller:this.controller,placeholder:this.widget.props.placeholder??"",autofocus:!0,maxLines:1,style:{textColor:Q.foreground,border:null},onSubmitted:()=>this.handleSubmit()})})]})),new _A({header:this.widget.props.header,minWidth:80,maxWidth:80,footer:Y,autofocus:!1,bodyFit:this.widget.props.bodyFit,onDismiss:this.widget.props.onDismiss,child:new f0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:Z})})}}class b51 extends w1{props;constructor(A){super();this.props=A}build(A){return new _A({header:this.props.options.title,minWidth:64,maxWidth:80,footer:[{keys:["↑/↓","j/k"],label:"move"},{keys:["Enter"],label:"select"},{keys:["Esc"],label:"cancel"}],autofocus:!1,onDismiss:this.props.onCancel,child:rn5(this.props)})}}function rn5(A){let Q=A.options.options.map((B)=>({value:B,label:B}));return new F9({options:Q,body:A.options.message,onSelect:(B)=>{if(B===null){A.onCancel();return}A.onSelect(B)},padding:z0.all(0),showBorder:!1,showDismissalMessage:!1,enableMouseInteraction:!1})}class u51{options;unregisterPluginCommands=null;pluginCommandSubscriptions=[];pluginErrorToastKeys=new Set;pendingInputDialog=null;pendingConfirmDialog=null;pendingSelectDialog=null;constructor(A){this.options=A}init(){this.configurePluginPlatform(),this.subscribePluginCommands()}dispose(){this.unregisterPluginCommands?.(),this.unregisterPluginCommands=null;for(let A of this.pluginCommandSubscriptions)A.unsubscribe();this.pluginCommandSubscriptions=[]}hasBlockingDialog(){return this.pendingInputDialog!==null||this.pendingConfirmDialog!==null||this.pendingSelectDialog!==null}buildDialogLayers(){let A=[];if(this.pendingInputDialog)A.push(new Nt({header:this.pendingInputDialog.options.title??"Input",helpText:this.pendingInputDialog.options.helpText,initialValue:this.pendingInputDialog.options.initialValue,isRequired:!1,onSubmit:this.resolveInputDialog,onDismiss:this.cancelInputDialog}));if(this.pendingConfirmDialog)A.push(new f51({options:this.pendingConfirmDialog.options,onConfirm:this.resolveConfirmDialog,onCancel:this.cancelConfirmDialog}));if(this.pendingSelectDialog)A.push(new b51({options:this.pendingSelectDialog.options,onSelect:this.resolveSelectDialog,onCancel:this.cancelSelectDialog}));return A}configurePluginPlatform(){let A=this.options.neoContext.pluginPlatform;if(!A)return;A.showToast=(Q)=>this.options.toastController.show(Q,"success"),A.showOpenedURLToast=(Q)=>{this.options.toastController.show(`Opened URL: ${Q}`,"success",8000)},A.appendToThreadHandler=this.options.neoContext.observerOnly?async()=>{throw Error("thread.append is only available from an executor-owned plugin runtime")}:this.options.appendToThread,A.showInputDialog=this.showInputDialog,A.showConfirmDialog=this.showConfirmDialog,A.showSelectDialog=this.showSelectDialog}subscribePluginCommands(){let A=this.options.neoContext.pluginService;if(!A)return;this.refreshPluginCommands(A.commands.list()),this.pluginCommandSubscriptions=[A.plugins.subscribe((Q)=>{this.showNewPluginErrorToasts(Q),this.refreshPluginCommands(A.commands.list())}),A.commands.changed.subscribe(()=>{this.refreshPluginCommands(A.commands.list())})]}refreshPluginCommands(A){this.unregisterPluginCommands?.();let B=A.map(($)=>this.createPluginCommand($)).map(($)=>this.options.commandRegistry.register($));this.unregisterPluginCommands=()=>{for(let $ of B)$()}}showNewPluginErrorToasts(A){let Q=new Set;for(let B of A){if(B.status!=="error")continue;let $=`${B.uri.toString()}
5330
- ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingInputDialog={options:A,resolve:Q}})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(!1);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingConfirmDialog={options:A,resolve:Q}})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingSelectDialog={options:A,resolve:Q}})})};resolveInputDialog=(A)=>{let Q=this.pendingInputDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),Q.resolve(A)};cancelInputDialog=()=>{let A=this.pendingInputDialog;if(!A)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),A.resolve(void 0)};resolveConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!0)};cancelConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!1)};resolveSelectDialog=(A)=>{let Q=this.pendingSelectDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),Q.resolve(A)};cancelSelectDialog=()=>{let A=this.pendingSelectDialog;if(!A)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),A.resolve(void 0)};clearDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}el();C2();import{readFile as sn5}from"node:fs/promises";import h51 from"node:os";async function X0A(A,Q){try{return{path:Q,contents:mg0(await sn5(A,"utf8"))}}catch{return null}}async function F0A(A,Q){let B=[],$=await YA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(JJ(J),null,2)});let Y=await X0A(nx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await X0A(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Ef()??"unknown",F=await YA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778070211-gdd8fb4",clientOS:`${h51.platform()} ${h51.release()} ${h51.arch()}`,installMethod:X}},{config:A.configService});if(!F.ok)throw Error(`Failed to submit report: ${F.error.message}`);return F.result.reportID}class g51{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}l0();o9();C2();async function D0A(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await YA.setThreadMeta({thread:Q,meta:QZ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=PB(new URL(A.ampURL),Q).toString();try{await L4.instance.tuiInstance.clipboard.writeText(X),Y=!0}catch(F){j.error("Failed to copy thread URL after visibility update",{error:F})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new eQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class iV0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new m51(this.offstage)}updateRenderObject(A){if(A instanceof m51)A.offstage=this.offstage}}class m51 extends Z4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class p51{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class d51 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new G0A}}class G0A extends k0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new BR,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new BR,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new iV0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new iV0({key:$.key,offstage:!J,child:Y}))}return new t4({fit:"expand",children:Q})}}class l51 extends w1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=tn5(Q);return new _A({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:z0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new p6({items:Q,showBorder:!1,getLabel:($)=>{let J=c51($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=wR($.item.verb.toLowerCase(),Y),X=wR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=wR(c51($.item),Y),D=wR(c51(J.item),Y);if(F!==D)return D-F;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=T0.of(J);return new l({text:new M($.status.reason,new y({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new V0A({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class V0A extends w1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=T0.of(Y),{colors:X,app:F}=Z,D=B?F.selectionBackground:void 0,G=B?F.selectionForeground:X.foreground,V=B?G:X.mutedForeground,U=new l({text:new M(Q.noun?.toLowerCase()??"",new y({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new y({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new y({color:G,dim:!0})));let E=l.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:en5(Q.shortcut,Z,$)});return new U0A({columns:W,padding:z0.horizontal(1),backgroundColor:D})}}function c51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function tn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,a4(B.noun)):Q},0)}function en5(A,Q,B){let{colors:$,app:J}=Q,Y=new y({color:$.mutedForeground,dim:B}),Z=[];for(let X of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(X,new y({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new y({color:J.keybind,bold:!0,dim:B}))),l.spans(Z)}class U0A extends w1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let X=0;X<Q.length;X++){let F=Q[X];if(X>0&&B>0)Y.push(new W0({width:B}));if(F.fixedWidth!==void 0)Y.push(new W0({width:F.fixedWidth,child:F.child}));else if(F.expanded)Y.push(new k1({child:F.child}));else Y.push(F.child)}let Z=new Q1({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new p0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class i51{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class YZ extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=YZ.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(YZ)?.commandRegistry??null}}class n51 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new K0A}}class K0A extends k0{modalStack=new p51;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=YZ.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=YZ.of(A).commands,B=new l51({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new d51({root:B,controller:this.modalStack})}}var a51=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],o51=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class nV0 extends w1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=e1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[X,F]=this.renderRow(Z),D;if(J)D=new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[X,new b0({padding:z0.only({left:4}),child:F})]});else D=new Q1({crossAxisAlignment:"start",children:[new k1({flex:1,child:X}),new W0({width:1}),new k1({flex:1,child:F})]});Y.push(new b0({padding:z0.horizontal(6),child:D}))}return new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class r51 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new E0A}}class E0A extends k0{scrollController;initState(){this.scrollController=new rA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=T1.of(A).colorScheme,J=T0.of(A).app,Y=e1.of(A),Z=new y({color:B.primary,bold:!0}),X=new y({color:B.secondary,bold:!0}),F=new y({color:J.keybind}),D=new y({color:J.command}),G=new y({color:B.foreground}),V=new y({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,H=Math.max(40,Math.min(80,E)),z=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!z.has(O.id)})].sort((O,_)=>{let T=(O.noun??"").toLowerCase(),S=(_.noun??"").toLowerCase(),b=T.localeCompare(S);if(b!==0)return b;let h=O.verb.toLowerCase(),x=_.verb.toLowerCase(),v=h.localeCompare(x);if(v!==0)return v;return O.id.localeCompare(_.id)}),I=new PA({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new O1(H,H,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new B4({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
5330
+ ${B.errorMessage??""}`;if(Q.add($),this.pluginErrorToastKeys.has($))continue;this.options.toastController.show(this.formatPluginErrorToast(B),"error",8000)}this.pluginErrorToastKeys=Q}formatPluginErrorToast(A){let Q=A.uri.toString();return`Plugin failed: ${Q.split("/").pop()??Q}. See logs: ${this.options.neoContext.logFilePath}`}createPluginCommand(A){return{noun:A.category,verb:A.title,description:A.description??`Run plugin command ${A.category}: ${A.title}`,keywords:["plugin",A.pluginName,A.id],status:{type:"enabled"},run:async(Q,B,$)=>{$();try{await this.options.neoContext.pluginService?.commands.execute(A.pluginName,A.id,{threadID:this.options.getActiveThreadID()})}catch(J){j.error("Neo plugin command failed",{error:J,command:A}),this.options.toastController.show(J instanceof Error?J.message:String(J),"error",5000)}}}}showInputDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingInputDialog={options:A,resolve:Q}})})};showConfirmDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(!1);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingConfirmDialog={options:A,resolve:Q}})})};showSelectDialog=(A)=>{return new Promise((Q)=>{if(!this.options.state.mounted){Q(void 0);return}this.options.state.setState(()=>{this.options.commandPalette.disable(),this.pendingSelectDialog={options:A,resolve:Q}})})};resolveInputDialog=(A)=>{let Q=this.pendingInputDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),Q.resolve(A)};cancelInputDialog=()=>{let A=this.pendingInputDialog;if(!A)return;this.clearDialogState(()=>{this.pendingInputDialog=null}),A.resolve(void 0)};resolveConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!0)};cancelConfirmDialog=()=>{let A=this.pendingConfirmDialog;if(!A)return;this.clearDialogState(()=>{this.pendingConfirmDialog=null}),A.resolve(!1)};resolveSelectDialog=(A)=>{let Q=this.pendingSelectDialog;if(!Q)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),Q.resolve(A)};cancelSelectDialog=()=>{let A=this.pendingSelectDialog;if(!A)return;this.clearDialogState(()=>{this.pendingSelectDialog=null}),A.resolve(void 0)};clearDialogState(A){if(this.options.state.mounted)this.options.state.setState(A);else A()}}el();C2();import{readFile as sn5}from"node:fs/promises";import h51 from"node:os";async function X0A(A,Q){try{return{path:Q,contents:mg0(await sn5(A,"utf8"))}}catch{return null}}async function F0A(A,Q){let B=[],$=await YA.getThread({thread:Q},{config:A.configService}),J=$.ok?$.result.thread.data:null;B.push({path:"thread.json",contents:JSON.stringify(JJ(J),null,2)});let Y=await X0A(nx(Q),`logs/${Q}.log`);if(Y)B.push(Y);let Z=await X0A(A.settingsFilePath,"settings/global.json");if(Z)B.push(Z);let X=await Ef()??"unknown",F=await YA.sendReport({threadID:Q,files:B,metadata:{clientVersion:"0.0.1778070540-gc7ef03",clientOS:`${h51.platform()} ${h51.release()} ${h51.arch()}`,installMethod:X}},{config:A.configService});if(!F.ok)throw Error(`Failed to submit report: ${F.error.message}`);return F.result.reportID}class g51{backStack=[];forwardStack=[];canNavigateBack(){return this.backStack.length>0}canNavigateForward(){return this.forwardStack.length>0}recordNavigation(A){if(!A)return;this.backStack.push(A),this.forwardStack.length=0}startBackNavigation(A){let Q=this.backStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.forwardStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.forwardStack.pop();this.backStack.push(Q)}}}startForwardNavigation(A){let Q=this.forwardStack.pop();if(!Q)return null;let B=Boolean(A);if(A)this.backStack.push(A);return{targetThreadID:Q,rollback:()=>{if(B)this.backStack.pop();this.forwardStack.push(Q)}}}}l0();o9();C2();async function D0A(A,Q,B){let $;switch(B){case"private":$="This thread's visibility has been updated to private";break;case"workspace":$="This thread's visibility has been updated to workspace";break;case"group":$="This thread's visibility has been updated to group";break;case"unlisted":$="This thread's visibility has been updated to unlisted. Anyone on the Internet with the link can view it.";break;case"public":$="This thread's visibility has been updated to public. Anyone on the Internet can see it on your public profile, and it is publicly searchable.";break}try{let J=await YA.setThreadMeta({thread:Q,meta:QZ(B)},{config:A.configService});if(!J.ok)throw Error(J.error.message);let Y=!1;if(B!=="private"){let X=PB(new URL(A.ampURL),Q).toString();try{await L4.instance.tuiInstance.clipboard.writeText(X),Y=!0}catch(F){j.error("Failed to copy thread URL after visibility update",{error:F})}}let Z=Y?`${$} Link copied to clipboard.`:$;return new eQ(Z)}catch(J){let Y=J instanceof Error?J.message:String(J);if(Y.includes("no-workspace"))return Error("You are not a member of any workspace.");if(Y.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(Y.includes("no-groups"))return Error("You are not a member of any groups.");return j.error("Unexpected failure to update thread visibility",{error:J}),Error(`Failed to update thread visibility for ${Q}`)}}class iV0 extends q5{offstage;constructor({key:A,offstage:Q=!0,child:B}){super({key:A,child:B});this.offstage=Q}createRenderObject(){return new m51(this.offstage)}updateRenderObject(A){if(A instanceof m51)A.offstage=this.offstage}}class m51 extends Z4{_offstage;constructor(A){super();this._offstage=A}get offstage(){return this._offstage}set offstage(A){if(A===this._offstage)return;this._offstage=A,this.markNeedsLayout()}getMinIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicWidth(A)??0}getMaxIntrinsicWidth(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicWidth(A)??0}getMinIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMinIntrinsicHeight(A)??0}getMaxIntrinsicHeight(A){if(this._offstage)return 0;return this.children[0]?.getMaxIntrinsicHeight(A)??0}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=this.children[0];if(this._offstage){if(this.setSize(0,0),Q)Q.layout(A),Q.setOffset(0,0)}else if(Q){Q.layout(A);let B=A.constrain(Q.size.width,Q.size.height);this.setSize(B.width,B.height),Q.setOffset(0,0)}else{let B=A.smallest;this.setSize(B.width,B.height)}super.performLayout()}paint(A,Q,B){if(this._offstage)return;super.paint(A,Q,B)}hitTest(A,Q,B,$){if(this._offstage)return!1;return super.hitTest(A,Q,B,$)}}class p51{_state=null;_attach(A){this._state=A}_detach(){this._state=null}push(A){this._state?.push(A)}pushWithDismiss(A){this._state?.pushWithDismiss(A)}pop(){return this._state?.pop()??!1}get canPop(){return this._state?.canPop??!1}}class d51 extends v0{root;controller;constructor(A){super();this.root=A.root,this.controller=A.controller}createState(){return new G0A}}class G0A extends k0{entries=[];initState(){this.widget.controller._attach(this)}didUpdateWidget(A){if(A.controller!==this.widget.controller)A.controller._detach(),this.widget.controller._attach(this)}dispose(){this.widget.controller._detach(),super.dispose()}push(A){let Q=new BR,B=this.makeScopedDismiss(Q);this.setState(()=>{this.entries.push({key:Q,widget:A,dismiss:B})})}pushWithDismiss(A){let Q=new BR,B=this.makeScopedDismiss(Q),$=A(B);this.setState(()=>{this.entries.push({key:Q,widget:$,dismiss:B})})}pop(){if(this.entries.length===0)return!1;return this.setState(()=>{this.entries.pop()}),!0}get canPop(){return this.entries.length>0}makeScopedDismiss(A){return()=>{if(!this.mounted)return;let Q=this.entries[this.entries.length-1];if(!Q||Q.key!==A)return;this.setState(()=>{this.entries.pop()})}}build(A){let Q=[];Q.push(new iV0({offstage:this.entries.length>0,child:this.widget.root}));for(let B=0;B<this.entries.length;B++){let $=this.entries[B],J=B===this.entries.length-1,Y=J?new c4({autofocus:!0,debugLabel:`ModalStackEntry[${B}]`,onKey:(Z)=>{if(Z.key!=="Escape")return"ignored";return $.dismiss(),"handled"},child:$.widget}):$.widget;Q.push(new iV0({key:$.key,offstage:!J,child:Y}))}return new t4({fit:"expand",children:Q})}}class l51 extends w1{props;constructor(A){super();this.props=A}build(A){let Q=this.props.commands.filter(($)=>$.status.type!=="hidden"),B=tn5(Q);return new _A({header:"Command Palette",autofocus:!1,barrierOpaque:!1,chromePadding:z0.only({left:1,top:1,right:1}),footer:"none",onDismiss:this.props.onDismiss,child:new p6({items:Q,showBorder:!1,getLabel:($)=>{let J=c51($);return $.keywords&&$.keywords.length>0?`${J} ${$.keywords.join(" ").toLowerCase()}`:J},sortItems:($,J,Y)=>{if(Y===""){let G=$.item.status.type==="disabled"?1:0,V=J.item.status.type==="disabled"?1:0;if(G!==V)return G-V;let U=$.item.sortBoost??0,K=J.item.sortBoost??0;if(U!==K)return K-U;let E=$.item.noun?.toLowerCase()??"",W=J.item.noun?.toLowerCase()??"";if(E!==W)return E<W?-1:1;return 0}let Z=wR($.item.verb.toLowerCase(),Y),X=wR(J.item.verb.toLowerCase(),Y);if(Z!==X)return X-Z;let F=wR(c51($.item),Y),D=wR(c51(J.item),Y);if(F!==D)return D-F;return J.score-$.score},isItemDisabled:($)=>$.status.type==="disabled",buildDisabledReasonWidget:($,J)=>{if($.status.type!=="disabled")return;let{colors:Y}=T0.of(J);return new l({text:new M($.status.reason,new y({color:Y.mutedForeground,dim:!0})),textAlign:"center"})},renderItem:($,J,Y,Z)=>new V0A({command:$,isSelected:J,isDisabled:Y,categoryWidth:B,buildContext:Z}),onAccept:($)=>{this.props.onAccept($)},onDismiss:this.props.onDismiss})})}}class V0A extends w1{props;constructor(A){super();this.props=A}build(A){let{command:Q,isSelected:B,isDisabled:$,categoryWidth:J,buildContext:Y}=this.props,Z=T0.of(Y),{colors:X,app:F}=Z,D=B?F.selectionBackground:void 0,G=B?F.selectionForeground:X.foreground,V=B?G:X.mutedForeground,U=new l({text:new M(Q.noun?.toLowerCase()??"",new y({color:V,dim:$||!B})),textAlign:"right"}),K=[new M(Q.verb.toLowerCase(),new y({color:G,bold:!0,dim:$}))];if($)K.push(new M(" (unavailable)",new y({color:G,dim:!0})));let E=l.spans(K),W=[{child:U,fixedWidth:J},{child:E,expanded:!0}];if(Q.shortcut)W.push({child:en5(Q.shortcut,Z,$)});return new U0A({columns:W,padding:z0.horizontal(1),backgroundColor:D})}}function c51(A){return A.noun?`${A.noun.toLowerCase()} ${A.verb.toLowerCase()}`:A.verb.toLowerCase()}function tn5(A){return A.reduce((Q,B)=>{return B.noun?Math.max(Q,a4(B.noun)):Q},0)}function en5(A,Q,B){let{colors:$,app:J}=Q,Y=new y({color:$.mutedForeground,dim:B}),Z=[];for(let X of A.modifiers()){if(Z.length>0)Z.push(new M(" ",Y));Z.push(new M(X,new y({color:J.keybind,bold:!0,dim:B})))}if(Z.length>0)Z.push(new M(" ",Y));return Z.push(new M(A.key,new y({color:J.keybind,bold:!0,dim:B}))),l.spans(Z)}class U0A extends w1{props;constructor(A){super();this.props=A}build(A){let{columns:Q,gap:B=2,padding:$,backgroundColor:J}=this.props,Y=[];for(let X=0;X<Q.length;X++){let F=Q[X];if(X>0&&B>0)Y.push(new W0({width:B}));if(F.fixedWidth!==void 0)Y.push(new W0({width:F.fixedWidth,child:F.child}));else if(F.expanded)Y.push(new k1({child:F.child}));else Y.push(F.child)}let Z=new Q1({crossAxisAlignment:"start",children:Y});if(!$&&!J)return Z;return new p0({decoration:J?{color:J}:void 0,padding:$,child:Z})}}class i51{#A=[];#Q=new Set;get commands(){return this.#A}register(A){return this.#A.push(A),this.#B(),()=>{let Q=this.#A.indexOf(A);if(Q===-1)return;this.#A.splice(Q,1),this.#B()}}addListener(A){this.#Q.add(A)}removeListener(A){this.#Q.delete(A)}#B(){for(let A of this.#Q)A()}}class YZ extends q6{commandRegistry;constructor({commandRegistry:A,child:Q}){super({child:Q});this.commandRegistry=A}updateShouldNotify(A){return!1}static of(A){let Q=YZ.maybeOf(A);if(!Q)throw Error("No NeoCommandRegistryProvider found in widget tree");return Q}static maybeOf(A){return A.dependOnInheritedWidgetOfExactType(YZ)?.commandRegistry??null}}class n51 extends v0{onDismiss;constructor(A){super();this.onDismiss=A.onDismiss}createState(){return new K0A}}class K0A extends k0{modalStack=new p51;commandRegistry=null;initState(){super.initState(),queueMicrotask(()=>{if(!this.mounted)return;let A=YZ.of(this.context);this.commandRegistry=A,A.addListener(this.onCommandsChanged)})}dispose(){this.commandRegistry?.removeListener(this.onCommandsChanged),this.commandRegistry=null,super.dispose()}onCommandsChanged=()=>{this.setState()};build(A){let Q=YZ.of(A).commands,B=new l51({commands:Q,onAccept:($)=>{$.run(this.modalStack,A,this.widget.onDismiss)},onDismiss:()=>{if(this.modalStack.canPop)this.modalStack.pop();else this.widget.onDismiss()}});return new d51({root:B,controller:this.modalStack})}}var a51=[{description:"Move cursor up/down",methods:[{keys:["↑"]},{keys:["↓"]}]},{description:"Move cursor left/right",methods:[{keys:["←"]},{keys:["→"]},{input:"B",keys:["Ctrl"]},{input:"F",keys:["Ctrl"]}]},{description:"Insert newline",methods:[{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!0},{description:"Insert newline",methods:[{keys:["Enter"]},{keys:["Shift","Enter"]},{keys:["Alt","Enter"]},{input:"J",keys:["Ctrl"]}],submitOnEnterOnly:!1},{description:"Submit message",methods:[{keys:["Enter"]}],submitOnEnterOnly:!0},{description:"Submit message",methods:[{keys:["Ctrl/Cmd","Enter"]}],submitOnEnterOnly:!1},{description:"Clear input",methods:[{keys:["Escape"]}]},{description:"Edit prompt in $EDITOR",methods:[{input:"G",keys:["Ctrl"]}]},{description:"Navigate history (previous/next)",methods:[{input:"P",keys:["Ctrl"]},{input:"N",keys:["Ctrl"]}]},{description:"Jump to start of line",methods:[{keys:["Cmd","←"]},{input:"A",keys:["Ctrl"]}]},{description:"Jump to end of line",methods:[{keys:["Cmd","→"]},{input:"E",keys:["Ctrl"]}]},{description:"Jump to previous word",methods:[{keys:["Alt","←"]},{keys:["Ctrl","←"]},{input:"B",keys:["Alt"]}]},{description:"Jump to next word",methods:[{keys:["Alt","→"]},{keys:["Ctrl","→"]},{input:"F",keys:["Alt"]}]},{description:"Delete character backward",methods:[{keys:["Backspace"]},{input:"H",keys:["Ctrl"]}]},{description:"Delete word backward",methods:[{keys:["Alt","Backspace"]},{input:"W",keys:["Ctrl"]}]},{description:"Delete character forward",methods:[{keys:["Delete"]},{input:"D",keys:["Ctrl"]}]},{description:"Delete to start of line",methods:[{keys:["Cmd","Backspace"]},{input:"U",keys:["Ctrl"]}]},{description:"Delete to end of line",methods:[{input:"K",keys:["Ctrl"]}]},{description:"Yank (paste deleted text)",methods:[{input:"Y",keys:["Ctrl"]}]},{description:"Paste image from clipboard",methods:[{input:"V",keys:["Ctrl"]}]},{description:"Switch agent mode",methods:[{input:"S",keys:["Ctrl"]},{input:"S",keys:["Alt"]}]},{description:"Toggle reasoning effort",methods:[{input:"D",keys:["Alt"]}]},{description:"Open command palette",methods:[{input:"O",keys:["Ctrl"]}]},{description:"Mention files",methods:[{keys:["@"]}]},{description:"Mention threads",methods:[{keys:["@@"]}]},{description:"Show prompt history",methods:[{input:"R",keys:["Ctrl"]}]},{description:"Toggle inline shortcuts help",methods:[{keys:["?"]}]},{description:"Toggle thinking/dense view",methods:[{input:"T",keys:["Alt"]}]}],o51=[{description:"Page scroll",methods:[{keys:["Pg Up"]},{keys:["Pg Down"]}]},{description:"Half-page scroll",methods:[{input:"K",keys:["Alt"]},{input:"J",keys:["Alt"]}]},{description:"Mouse wheel scroll",methods:[{keys:["Mouse Wheel"]}]},{description:"Jump to first message",methods:[{keys:["Home"]}]},{description:"Jump to bottom of screen",methods:[{keys:["End"]}]},{description:"Navigate to previous messages",methods:[{keys:["Tab"]},{keys:["Shift","Tab"]}]}];class nV0 extends w1{items;renderRow;constructor({items:A,renderRow:Q}){super();this.items=A,this.renderRow=Q}build(A){let B=e1.of(A).size.width,$=50,J=B<50,Y=[];for(let Z of this.items){let[X,F]=this.renderRow(Z),D;if(J)D=new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[X,new b0({padding:z0.only({left:4}),child:F})]});else D=new Q1({crossAxisAlignment:"start",children:[new k1({flex:1,child:X}),new W0({width:1}),new k1({flex:1,child:F})]});Y.push(new b0({padding:z0.horizontal(6),child:D}))}return new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:Y})}}class r51 extends v0{commands;submitOnEnter;constructor({key:A,commands:Q,submitOnEnter:B}){super(A?{key:A}:{});this.commands=Q,this.submitOnEnter=B??!0}createState(){return new E0A}}class E0A extends k0{scrollController;initState(){this.scrollController=new rA,this.scrollController.disableFollowMode(),this.scrollController.jumpTo(0)}dispose(){}build(A){let B=T1.of(A).colorScheme,J=T0.of(A).app,Y=e1.of(A),Z=new y({color:B.primary,bold:!0}),X=new y({color:B.secondary,bold:!0}),F=new y({color:J.keybind}),D=new y({color:J.command}),G=new y({color:B.foreground}),V=new y({color:B.foreground}),U=Y.size.width,K=Y.size.height,E=U-4,W=K-4,H=Math.max(40,Math.min(80,E)),z=new Set(["permissions-disable"]),N=[...this.widget.commands.filter((O)=>{let _=O.noun?.toLowerCase();return _!=="dev"&&_!=="debug"&&!O.id.startsWith("debug-")&&!z.has(O.id)})].sort((O,_)=>{let T=(O.noun??"").toLowerCase(),S=(_.noun??"").toLowerCase(),b=T.localeCompare(S);if(b!==0)return b;let h=O.verb.toLowerCase(),x=_.verb.toLowerCase(),v=h.localeCompare(x);if(v!==0)return v;return O.id.localeCompare(_.id)}),I=new PA({autofocus:!0,controller:this.scrollController,child:new p0({constraints:new O1(H,H,0,Number.POSITIVE_INFINITY),child:new f0({crossAxisAlignment:"start",mainAxisSize:"min",children:[new B4({child:new l({text:new M(`Amp CLI - Help & Keyboard Shortcuts
5331
5331
  `,Z)})}),new W0({height:1}),new b0({padding:z0.horizontal(2),child:new l({text:new M(`Editor Shortcuts
5332
5332
  `,X)})}),new nV0({items:a51.filter((O)=>O.submitOnEnterOnly===void 0||O.submitOnEnterOnly===this.widget.submitOnEnter),renderRow:(O)=>{let _=[];for(let S of O.methods){let b=this.buildCleanKeyCombination(S);_.push(b)}let T=_.join(", ");return[new l({text:new M(T,F)}),new l({text:new M(O.description,G)})]}}),new W0({height:1}),new b0({padding:z0.horizontal(2),child:new l({text:new M(`Scrolling & Navigation
5333
5333
  `,X)})}),new nV0({items:o51,renderRow:(O)=>{let _=[];for(let S of O.methods){let b=this.buildCleanKeyCombination(S);_.push(b)}let T=_.join(", ");return[new l({text:new M(T,F)}),new l({text:new M(O.description,G)})]}}),new W0({height:1}),new b0({padding:z0.horizontal(2),child:new l({text:new M(`Command Palette Commands
@@ -5428,7 +5428,7 @@ Ctrl-X, Y, Z to unlock`;if(E){let i=G.text.replace(/`([^`]+)`/g,"$1")+`
5428
5428
  `))}function at5(A,Q){let{colors:B,app:$}=Q;switch(A){case"pending":return{icon:"◌",color:B.warning};case"registered":return{icon:"•",color:B.mutedForeground};case"failed":return{icon:"✗",color:$.toolError};case"duplicate":return{icon:"◇",color:B.warning};default:return{icon:"?",color:B.foreground}}}function fAA(A,Q){let B=A.replace(/\s+/g," ").trim();if(a4(B)<=Q)return B;let $="...",J=a4($);if(Q<=J)return sX($,Q);return`${sX(B,Q-J,!0,"")}${$}`}var gAA="https://ampcode.com/news/neo",k81=[{title:"Meet the new Amp CLI",body:[]},{title:"Rebuilt From The Ground Up",body:["Same close-up terminal workflow. Completely different underneath."]},{title:"Just Keep Typing",body:["Context is summarized automatically at ~90%.","No handoff flow. No context percentage to babysit."]},{title:"Queueing and Steering",body:["Sending a message now queues by default instead of cancelling tools.","Use steering when you want the agent to see something sooner."]},{title:"Remote Control",body:["Start a thread in the CLI, then keep going from ampcode.com.","Watch live updates and queue follow-ups from any device."]},{title:"Customize Amp with Amp",body:["Amp now has a complete plugin API.",{text:"Add tools, commands, control UI, and hook into ",linkText:"events",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:"Permissions",body:[{text:"By default (when no ",highlightText:"amp.permissions",textAfterHighlight:" setting is present), Amp no longer asks for confirmation before running any tools and commands. And you can now implement your own custom permission logic with ",linkText:"plugins",href:"https://ampcode.com/manual/plugin-api",textAfter:"."}]},{title:null,body:["Check out the full news post for more:",{text:gAA,href:gAA},"","",{text:"Need old Amp for a bit? Use ",keybind:"amp --take-me-back"}]}],Rb=50,dR=40,T81=1000,ot5=420,rt5=760,st5=-250,tt5=1100,OU0=33,mAA=0.999,et5=2.1,ZH=k81.length,Ae5=ZH-2,Qe5=720,Be5=420,oAA="Meet the new",rAA="Amp",sAA="CLI",v81=f4(oAA).length,$e5=f4(rAA).length,Je5=f4(sAA).length,jU0={primary:{r:140,g:38,b:0},secondary:{r:255,g:225,b:102}},pAA={primary:{r:10,g:42,b:18},secondary:{r:200,g:230,b:68}},dAA={primary:{r:18,g:0,b:107},secondary:{r:103,g:255,b:168}},cAA=[jU0,pAA,dAA,jU0,pAA,dAA,jU0],Ye5=jU0;class y81 extends v0{onDismiss;animationProgress;constructor(A){super();this.onDismiss=A.onDismiss,this.animationProgress=A.animationProgress}createState(){return new tAA}}class tAA extends k0{startedAt=performance.now();animationTimer=null;stageTransitionTimer=null;firstStageTitleTimer=null;firstStageHintTimer=null;firstStageRevealTimer=null;firstStageTitleRevealStartedAt=null;firstStageHintRevealStartedAt=null;stageTransitionStartedAt=performance.now();animationStartProgress=0;animationTargetProgress=1;animationDurationMs=T81;onAnimationComplete=null;animationProgress=0;introStage=0;previousIntroStage=null;stageTransitionProgress=1;stageTransitionDirection=1;firstStageTitleVisible=!1;firstStageHintVisible=!1;firstStageTitleRevealProgress=0;firstStageHintRevealProgress=0;dismissTimer=null;dismissStartedAt=performance.now();dismissProgress=0;isDismissing=!1;splashOrbGlow=new T9(42);initState(){super.initState(),this.startAnimationIfNeeded()}didUpdateWidget(A){if(super.didUpdateWidget(A),A.animationProgress!==this.widget.animationProgress)this.startAnimationIfNeeded()}dispose(){this.stopAnimation(),this.stopStageTransitionTimer(),this.stopFirstStageRevealTimers(),this.stopDismissAnimation(),super.dispose()}startAnimationIfNeeded(){if(this.stopAnimation(),this.stopFirstStageRevealTimers(),this.widget.animationProgress!==void 0){this.animationProgress=ZZ(this.widget.animationProgress),this.firstStageTitleVisible=this.animationProgress>=mAA,this.firstStageHintVisible=this.animationProgress>=mAA,this.firstStageTitleRevealProgress=this.firstStageTitleVisible?1:0,this.firstStageHintRevealProgress=this.firstStageHintVisible?1:0;return}this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0,this.startProgressAnimation({from:0,to:1,durationMs:T81,onComplete:()=>{}}),this.startFirstStageRevealSequence()}startDismissAnimation(){if(this.isDismissing)return;this.stopFirstStageRevealTimers(),this.stopStageTransitionTimer(),this.dismissStartedAt=performance.now(),this.setState(()=>{this.isDismissing=!0,this.dismissProgress=0}),this.dismissTimer=setInterval(()=>{let A=performance.now()-this.dismissStartedAt,Q=ZZ(A/rt5);if(this.setState(()=>{this.dismissProgress=Q}),Q>=1)this.stopDismissAnimation(),this.widget.onDismiss()},OU0)}canNavigateIntroStage(){if(this.isDismissing)return!1;if(!this.firstStageHintVisible)return!1;if(this.introStage===0&&this.firstStageHintRevealProgress<1)return!1;return!0}advanceIntroStage(){if(!this.canNavigateIntroStage())return;if(this.introStage>=ZH-1){this.startDismissAnimation();return}this.moveIntroStage(1)}dismissFromFinalIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<ZH-1)return!1;return this.startDismissAnimation(),!0}nextIntroStage(){if(!this.canNavigateIntroStage()||this.introStage>=ZH-1)return;this.moveIntroStage(1)}goToPreviousIntroStage(){if(!this.canNavigateIntroStage()||this.introStage<=0)return;this.moveIntroStage(-1)}moveIntroStage(A){let Q=this.introStage+A;if(this.stopStageTransitionTimer(),this.stageTransitionStartedAt=performance.now(),this.setState(()=>{this.previousIntroStage=this.introStage,this.introStage=Q,this.stageTransitionDirection=A}),this.widget.animationProgress!==void 0){this.setState(()=>{this.previousIntroStage=null,this.stageTransitionProgress=1});return}this.setState(()=>{this.stageTransitionProgress=0}),this.stageTransitionTimer=setInterval(()=>{let B=performance.now()-this.stageTransitionStartedAt,$=ZZ(B/ot5);if(this.setState(()=>{if(this.stageTransitionProgress=$,$>=1)this.previousIntroStage=null}),$>=1)this.stopStageTransitionTimer()},OU0)}startProgressAnimation({from:A,to:Q,durationMs:B,onComplete:$}){this.stopAnimation(),this.startedAt=performance.now(),this.animationStartProgress=A,this.animationTargetProgress=Q,this.animationDurationMs=B,this.onAnimationComplete=$,this.animationProgress=A,this.animationTimer=setInterval(()=>{let J=performance.now()-this.startedAt,Y=ZZ(J/this.animationDurationMs),Z=this.animationStartProgress+(this.animationTargetProgress-this.animationStartProgress)*Pb(Y);if(this.setState(()=>{this.animationProgress=Z}),Y>=1)this.stopAnimation(),this.onAnimationComplete?.(),this.onAnimationComplete=null},OU0)}stopAnimation(){if(this.animationTimer)clearInterval(this.animationTimer),this.animationTimer=null}stopStageTransitionTimer(){if(this.stageTransitionTimer)clearInterval(this.stageTransitionTimer),this.stageTransitionTimer=null}startFirstStageRevealSequence(){this.stopFirstStageRevealTimers(),this.setState(()=>{this.firstStageTitleVisible=!1,this.firstStageHintVisible=!1,this.firstStageTitleRevealProgress=0,this.firstStageHintRevealProgress=0});let A=Math.max(0,T81+st5),Q=A+tt5;this.firstStageTitleTimer=setTimeout(()=>{this.firstStageTitleRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageTitleVisible=!0,this.firstStageTitleRevealProgress=0}),this.startFirstStageRevealTimer()},A),this.firstStageHintTimer=setTimeout(()=>{this.firstStageHintRevealStartedAt=performance.now(),this.setState(()=>{this.firstStageHintVisible=!0,this.firstStageHintRevealProgress=0}),this.startFirstStageRevealTimer()},Q)}startFirstStageRevealTimer(){if(this.firstStageRevealTimer)return;this.firstStageRevealTimer=setInterval(()=>{let A=performance.now(),Q=this.firstStageTitleRevealStartedAt?ZZ((A-this.firstStageTitleRevealStartedAt)/Qe5):this.firstStageTitleRevealProgress,B=this.firstStageHintRevealStartedAt?ZZ((A-this.firstStageHintRevealStartedAt)/Be5):this.firstStageHintRevealProgress;if(this.setState(()=>{this.firstStageTitleRevealProgress=Q,this.firstStageHintRevealProgress=B}),Q>=1&&B>=1)this.stopFirstStageRevealTimer()},OU0)}stopFirstStageRevealTimers(){if(this.stopFirstStageRevealTimer(),this.firstStageTitleRevealStartedAt=null,this.firstStageHintRevealStartedAt=null,this.firstStageTitleTimer)clearTimeout(this.firstStageTitleTimer),this.firstStageTitleTimer=null;if(this.firstStageHintTimer)clearTimeout(this.firstStageHintTimer),this.firstStageHintTimer=null}stopFirstStageRevealTimer(){if(this.firstStageRevealTimer)clearInterval(this.firstStageRevealTimer),this.firstStageRevealTimer=null}stopDismissAnimation(){if(this.dismissTimer)clearInterval(this.dismissTimer),this.dismissTimer=null}currentOrbPalette(){let A=lAA(this.introStage),Q=this.previousIntroStage===null||this.stageTransitionProgress>=1?A:iAA(lAA(this.previousIntroStage),A,Pb(this.stageTransitionProgress));return this.dismissProgress>0?iAA(Q,Ye5,Pb(this.dismissProgress)):Q}build(A){let Q=T1.of(A).colorScheme,B=T0.of(A),$=this.currentOrbPalette(),J=tQ(1,"frontier",$),Y=e1.of(A).size,X=this.widget.animationProgress??this.animationProgress,F=Math.max(Y.width/Rb,Y.height/dR)*et5,D=F+(1-F)*X,G=Pb(this.dismissProgress),V=Math.max(Rb,Math.round(Rb*D)),U=Math.max(dR,Math.round(dR*D)),K=Math.round((Y.width-V)/2),E=Math.round((Y.height-U)/2),W=Math.max(0,Math.floor((Y.width-Rb)/2)),H=-Math.floor(dR/2),z=Math.round(K+(W-K)*X),q=Math.round(E+(H-E)*X),N=z+V/2,I=q+U/2,w=Ze5({dismissProgress:this.dismissProgress,easedDismissProgress:G,introOrbScale:D,normalOrbCenterX:N,normalOrbCenterY:I,size:Y}),C=Math.max(Rb,Math.round(Rb*w.orbScale)),O=Math.max(dR,Math.round(dR*w.orbScale)),_=w.orbCenterX,T=w.orbCenterY,S=Math.round(_-C/2),b=Math.round(T-O/2),h=Math.max(3,Math.min(Y.height-5,Math.floor(dR/2)+2)),x=Math.max(h+3,Y.height-3),v=w.textDissolveProgress,u=this.introStage>=ZH-1?w.backdropDissolveProgress:0,m=this.firstStageTitleVisible&&v<1,d=m&&this.firstStageHintVisible,g=d&&this.introStage>0&&this.introStage<ZH-1,n=this.introStage===0?this.firstStageTitleRevealProgress:1,c=this.introStage===0?this.firstStageHintRevealProgress:1,$0=Math.max(24,Math.min(74,Y.width-4)),E0=Math.min(12,Math.max(8,Y.height-h-6)),i=Math.max(0,Math.floor((Y.width-$0)/2)),J0=Math.max(0,Math.min(Y.height-E0,Math.floor(Y.height*0.55-E0/2))),I0=this.widget.animationProgress!==void 0?new Nf({width:C,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,seed:42,fps:0,onClick:()=>{}}):new Nf({width:C,height:O,agentMode:"frontier",visualStyle:"neo",neoGlyphSet:"dotField",backgroundColor:Q.background,primaryColor:$.primary,secondaryColor:$.secondary,glow:this.splashOrbGlow,onClick:()=>{}});return new c4({autofocus:!0,canRequestFocus:!0,debugLabel:"NeoWelcomeTakeover",onKey:(A0)=>{if(A0.key==="Enter")return this.advanceIntroStage(),"handled";if((A0.key===" "||A0.key==="Space")&&this.introStage<ZH-1)return this.advanceIntroStage(),"handled";if(A0.key==="Escape"||A0.key==="Esc")return this.dismissFromFinalIntroStage()?"handled":"ignored";if(A0.key==="ArrowRight")return this.nextIntroStage(),"handled";if(A0.key==="ArrowLeft")return this.goToPreviousIntroStage(),"handled";return"ignored"},child:new t4({fit:"expand",children:[new eAA({color:Q.background,dissolveProgress:u}),new t4({fit:"expand",children:[new f1({onClick:()=>{},child:W0.expand()}),new EA({left:S,top:b,width:C,height:O,child:I0}),...m?[new EA({left:i,top:J0,width:$0,height:E0,child:Fe5({stage:this.introStage,previousStage:this.previousIntroStage,progress:this.stageTransitionProgress,direction:this.stageTransitionDirection,width:$0,height:E0,foreground:Q.foreground,mutedForeground:Q.mutedForeground,accent:J,link:B.app.link,keybind:B.app.keybind,titleRevealProgress:n,dissolveProgress:v,context:A})})]:[],...d?[...g?[new EA({left:i,top:Math.max(0,x-1),width:$0,height:1,child:new l({text:Ee5({stage:this.introStage,foreground:Q.mutedForeground,dissolveProgress:v}),textAlign:"center"})})]:[],new EA({left:i,top:x,width:$0,height:1,child:new l({text:We5({stage:this.introStage,foreground:Q.mutedForeground,keybind:B.app.keybind,revealProgress:c,dissolveProgress:v}),textAlign:"center"})})]:[]]})]})})}}class eAA extends $8{color;dissolveProgress;constructor({color:A,dissolveProgress:Q}){super();this.color=A,this.dissolveProgress=Q}createRenderObject(){return new A6A(this.color,this.dissolveProgress)}updateRenderObject(A){A.update(this.color,this.dissolveProgress)}}class A6A extends Z4{color;dissolveProgress;constructor(A,Q){super();this.color=A,this.dissolveProgress=Q}update(A,Q){this.color=A,this.dissolveProgress=Q,this.markNeedsPaint()}performLayout(){let A=this._lastConstraints;N4(!!A,"performLayout called without constraints");let Q=A.constrain(A.biggest.width,A.biggest.height);this.setSize(Q.width,Q.height),super.performLayout()}paint(A,Q=0,B=0){let $=Math.floor(Q+this.offset.x),J=Math.floor(B+this.offset.y),Y=Math.floor(this.size.width),Z=Math.floor(this.size.height),X={bg:this.color},F=ZZ(this.dissolveProgress);if(F<=0){A.fill($,J,Y,Z," ",X);return}if(F>=1)return;for(let D=0;D<Z;D++)for(let G=0;G<Y;G++)if(!Xe5(G,D,Y,Z,F))A.fill($+G,J+D,1,1," ",X)}}function ZZ(A){return Math.min(1,Math.max(0,A))}function Pb(A){return 1-(1-A)**3}function lAA(A){return cAA[A]??cAA[0]}function iAA(A,Q,B){return{primary:$R(A.primary,Q.primary,B),secondary:$R(A.secondary,Q.secondary,B)}}function Ze5({dismissProgress:A,easedDismissProgress:Q,introOrbScale:B,normalOrbCenterX:$,normalOrbCenterY:J,size:Y}){return{orbScale:B+(B*0.86-B)*Q,orbCenterX:$+(Y.width*0.54-$)*Q,orbCenterY:J-Y.height*0.44*Q,textDissolveProgress:ZZ(A/0.52),backdropDissolveProgress:Pb(ZZ((A-0.12)/0.88))}}function Xe5(A,Q,B,$,J){let Y=$<=1?0:Q/($-1),Z=Q6A(A+Q*Math.max(1,B));return(1-Y)*0.72+Z*0.28<J}function Fe5({stage:A,previousStage:Q,progress:B,direction:$,width:J,height:Y,foreground:Z,mutedForeground:X,accent:F,link:D,keybind:G,titleRevealProgress:V,dissolveProgress:U,context:K}){if(Q===null||B>=1)return S81({stage:A,foreground:Z,mutedForeground:X,accent:F,link:D,keybind:G,titleRevealProgress:V,dissolveProgress:U,context:K});let E=Pb(B),W=$*Math.round((1-E)*J),H=-$*Math.round(E*J);return new iW(new t4({fit:"expand",children:[new EA({left:H,top:0,width:J,height:Y,child:S81({stage:Q,foreground:Z,mutedForeground:X,accent:F,link:D,keybind:G,titleRevealProgress:Q===0?1:V,dissolveProgress:U,context:K})}),new EA({left:W,top:0,width:J,height:Y,child:S81({stage:A,foreground:Z,mutedForeground:X,accent:F,link:D,keybind:G,titleRevealProgress:V,dissolveProgress:U,context:K})})]}))}function S81({stage:A,foreground:Q,mutedForeground:B,accent:$,link:J,keybind:Y,titleRevealProgress:Z,dissolveProgress:X,context:F}){let D=k81[A]??k81[0],G=new y({color:$,bold:!0}),V=new y({color:Q}),U=[...D.title===null?[]:[new l({text:A===0?RU0(Ve5({progress:Z,foreground:$,pulseColor:$}),X):new M(XH(D.title,X),G),textAlign:"center"})],...D.body.length>0?[De5()]:[],...D.body.map((K)=>Ge5(K,V,B,J,Y,X,F))];return new B4({child:new b0({padding:z0.horizontal(1),child:new f0({crossAxisAlignment:"stretch",mainAxisAlignment:"center",mainAxisSize:"min",children:U})})})}function De5(){return W0.height(1)}function Ge5(A,Q,B,$,J,Y,Z){if(typeof A==="string")return new l({text:new M(XH(A,Y),Q),textAlign:"center"});if("keybind"in A)return new l({text:new M("",void 0,[new M(XH(A.text,Y),new y({color:B,dim:!0})),new M(XH(A.keybind,Y,f4(A.text).length),new y({color:J}))]),textAlign:"center"});if("highlightText"in A){let X=zA.createSpan(A.href,A.linkText,new y({color:$,underline:!0})),F=BG.of(Z),D=new M("",void 0,[new M(A.text,Q),new M(A.highlightText,new y({color:J})),new M(A.textAfterHighlight,Q),new M(X.text,X.style,X.children,X.hyperlink,()=>{lA(Z,A.href,{forceExternal:!1,onShowImagePreview:F})}),new M(A.textAfter,Q)]);return new l({text:RU0(D,Y),textAlign:"center"})}if("linkText"in A){let X=zA.createSpan(A.href,A.linkText,new y({color:$,underline:!0})),F=BG.of(Z),D=new M("",void 0,[new M(A.text,Q),new M(X.text,X.style,X.children,X.hyperlink,()=>{lA(Z,A.href,{forceExternal:!1,onShowImagePreview:F})}),new M(A.textAfter,Q)]);return new l({text:RU0(D,Y),textAlign:"center"})}if(Y>0)return new l({text:new M(XH(A.text,Y),new y({color:$,underline:!0})),textAlign:"center"});return new B4({child:zA.createWidget(Z,A.href,A.text,new y({color:$,underline:!0}))})}function Ve5({progress:A,foreground:Q,pulseColor:B}){let $=new y({color:Q,bold:!0}),J=new y({color:Ke5({progress:A,foreground:Q,pulseColor:B}),bold:!0});return new M("",void 0,[new M(Ue5(A).padEnd(v81," "),$),new M(" ",$),new M(nAA(rAA,$e5,A,0.72),$),new M(" ",$),new M(nAA(sAA,Je5,A,0.88),J)])}function Ue5(A){let Q=f4(oAA),B=Math.min(v81,Math.ceil(ZZ(A/0.62)*v81));return Q.slice(0,B).join("")}function nAA(A,Q,B,$){return B>=$?A:"".padEnd(Q," ")}function Ke5({progress:A,foreground:Q,pulseColor:B}){if(A<0.88||A>=1)return Q;let $=ZZ((A-0.88)/0.12);return Math.cos($*Math.PI*4)*(1-$)>0.12?B:Q}function Ee5({stage:A,foreground:Q,dissolveProgress:B}){return new M(XH(`${A}/${Ae5}`,B),new y({color:Q,dim:!0}))}function We5({stage:A,foreground:Q,keybind:B,revealProgress:$,dissolveProgress:J}){let Y=new y({color:B}),Z=new y({color:Q,dim:!0}),X=A>=ZH-1?"Enter":"Space",F=A>=ZH-1?" to get started":" to continue",D=aAA(X,$),G=aAA(F,ZZ(($*(f4(X).length+f4(F).length)-f4(X).length)/f4(F).length));return new M("",void 0,[new M(XH(D,J),Y),new M(XH(G,J),Z)])}function aAA(A,Q){let B=f4(A),$=Math.min(B.length,Math.ceil(ZZ(Q)*B.length));return B.slice(0,$).join("").padEnd(B.length," ")}function RU0(A,Q,B=0){if(Q<=0)return A;let $=B+f4(A.text??"").length,J=A.children?.map((Y)=>{let Z=RU0(Y,Q,$);return $+=f4(Y.toPlainText()).length,Z});return new M(A.text?XH(A.text,Q,B):A.text,A.style,J,A.hyperlink,A.onClick)}function XH(A,Q,B=0){if(Q<=0)return A;return f4(A).map((J,Y)=>{if(J.trim()==="")return J;return Q6A(B+Y)<Q?" ":J}).join("")}function Q6A(A){let Q=Math.sin((A+1)*12.9898)*43758.5453;return Q-Math.floor(Q)}l0();C2();function Dw(A,Q){let{colors:B,dim:$}=Q,J=[];if(A.totalCostUSD===null)return J;let Y=A.costBreakdown,Z=Y?.freeUSD??0,X=Y?.paidUSD??0;if(Z===0&&X===0)return J;let D={decimalPlaces:"more-if-tiny",intent:"cost"};if(X===0)J.push(new M(YK(Z,D),new y({color:B.foreground,dim:$}))),J.push(new M(" (free)",new y({color:B.foreground,dim:$})));else if(Z>0)J.push(new M(YK(Z,D),new y({color:B.foreground,dim:$}))),J.push(new M(" (free)",new y({color:B.foreground,dim:$}))),J.push(new M(" + ",new y({color:B.foreground,dim:$}))),J.push(new M(YK(X,D),new y({color:B.foreground,dim:$,bold:!$})));else J.push(new M(YK(X,D),new y({color:B.foreground,dim:$,bold:!$})));return J}class x81 extends d4{}class f81 extends d4{}function He5(A,Q){if(Q.code==="auth-required")return"You must be logged in to view thread usage. Run `amp login` first.";if(Q.code==="thread-not-found")return`Thread ${A} not found.`;return`Failed to load thread usage: ${Q.message??Q.code}`}function ze5(A,Q){let B=T0.of(Q),{colors:$}=B,J=Dw(A,{colors:{foreground:$.foreground}}),Y=[];if(J.length>0)Y.push(new M("Total: ",new y({color:$.mutedForeground}))),Y.push(...J);else if(A.totalCostUSD===null)Y.push(new M("Usage information is currently unavailable."));else Y.push(new M("No usage recorded for this thread yet."));if(A.costBreakdownURL)Y.push(new M(`
5429
5429
 
5430
5430
  `)),Y.push(new M("Details: ",new y({color:$.mutedForeground}))),Y.push(new M(A.costBreakdownURL,new y({color:B.app.link})));return new l({text:new M("",void 0,Y)})}function qe5(A,Q,B){let $=ze5(A,Q);if(!A.costBreakdownURL)return new _A({header:"Thread Cost",minWidth:80,maxWidth:100,onDismiss:B,child:$});let J=A.costBreakdownURL,Y=new K4(()=>{return BA.maybeInvoke(Q,new J$(J,"Cost breakdown URL copied to clipboard","Failed to copy cost breakdown URL")),"handled"}),Z=new K4(()=>{return lA(Q,J),"handled"});return new _A({header:"Thread Cost",minWidth:80,maxWidth:100,autofocus:!1,footer:[{keys:["Esc"],label:"close"},{keys:["o"],label:"open in browser"},{keys:["y"],label:"copy url"}],onDismiss:B,child:new BA({actions:new Map([[x81,Y],[f81,Z]]),child:new d5({debugLabel:"ThreadCostShortcuts",shortcuts:new Map([[v1.key("o"),new f81],[v1.key("y"),new x81]]),child:new m4({autofocus:!0,debugLabel:"ThreadCostBody",child:$})})})})}function B6A(A){return{noun:"thread",verb:"show cost",description:"Show usage cost for the active thread",keywords:["usage","credits","billing","spend"],get status(){return A.getActiveThreadID()?{type:"enabled"}:{type:"disabled",reason:"No active thread"}},run:async(Q,B,$)=>{let J=A.getActiveThreadID();if(!J)return;try{let Y=await YA.threadDisplayCostInfo({threadID:J},{config:A.configService});if(!Y.ok){A.toastController.show(He5(J,Y.error),"error",5000),$();return}Q.push(qe5(Y.result,B,$))}catch(Y){j.error("Failed to load Neo thread cost",{error:Y,threadID:J}),A.toastController.show(`Failed to show thread cost: ${Y instanceof Error?Y.message:String(Y)}`,"error",5000),$()}}}}var Ne5=250,Ie5=2000;function we5({ampURL:A,threadID:Q,logPath:B}){return[`Debug thread ${PB(new URL(A),Q).toString()} (cli log: ${B}). Start with the CLI log, actor logs, and Rivet DB/inspector as sources of truth. Read thread-actors/docs/debugging-actors.md and thread-actors/scripts/README.md. For dev, actor logs are in .amp/in/thread-actors.json.log; for staging/prod, logs are in gcloud.`,"","Problem: "].join(`
5431
- `)}class b81 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new J6A}}class J6A extends k0{editorController=new L8;commandPalette=new Ks(this);commandRegistry=new i51;toastController=new R41;exitHintTimer=new bf(this,1000);ideStatus=new h8(this,{});threadNavigationHistory=new g51;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new z6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>F0A({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return D0A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await Gr4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Vr4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Ur4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(O80(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new u51({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=L4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},Ne5),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<Ie5)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?J0A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>o31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},B6A({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new F31({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new _81({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await lA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{LJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new Z31({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new s51({commands:YZ.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new _A({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(I41({version:"0.0.1778070211-gdd8fb4",buildTimestamp:"2026-05-06T12:27:20.020Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:v1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{BA.maybeInvoke(Y,new Hb)}},...Q,...ie4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new P81({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=e1.of(A),Z=[new p0({constraints:O1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new n51({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(o31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new y81({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new J31({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:mt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new Y31);return new T3({neoContext:this.widget.neoContext,child:new YZ({commandRegistry:this.commandRegistry,child:new eI({completionBuilder:this.widget.completionBuilder,child:new f5({controller:this.toastController,child:new BA({actions:this.buildActions(),child:new d5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[v1.ctrl("c"),new hV0],[v1.ctrl("o"),new gV0],[v1.alt("i"),new pV0],[v1.alt("p"),new kI],[v1.ctrl("t"),new dV0]]),child:new m4({debugLabel:"AppShellFocus",child:new P41({controller:this.toastController,child:new t4({children:Z})})})})})})})})})}buildActions(){let A=new K4(()=>{if(MJ.hasAnyCopyableSelection())return MJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new K4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new K4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new K4(()=>{return this.startNewDraftThread(),"handled"}),J=new K4(()=>{return L4.instance.stop(),"handled"}),Y=new K4((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new K4(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),X=new K4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new K4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=nx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new K4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new K4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new K4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[Gt,$],[Hb,J],[J$,Y],[Kt,B],[gV0,Q],[pV0,X],[Et,F],[Wt,D],[Ht,G],[kI,Z],[dV0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:we5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:nx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await jf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=tB(Q),J=rD0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return oD0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=$6A(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=$6A(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(tI);if(this.exitHintTimer.isActive())A.add(Gb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((X)=>X.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,mt.cwd()),this.widget.history.reset();let Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?QZ(B):void 0);this.sendUserMessage(Z,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=tB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};CJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=EZ0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=$31(Q);if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=mt.cwd().replace(mt.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,mt.stdout.write(MI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;if(this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function $6A(A,Q,B){let $={...A};for(let J of Ce5(Q,B)){if(!iZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Ce5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Y6A(A,Q,B,$){let J=jS(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new T9(42),E=new jI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(O1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let _=0;_<V;_++)if(W[_].some((T)=>T.char!==" ")){H=_;break}let z=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((T)=>T.char!==" ")){z=_;break}function q(_,T){if(!_)return"";if(_.type==="rgb"){let{r:S,g:b,b:h}=_.value;if(B.getColorDepth()>=24)return`\x1B[${T?38:48};2;${S};${b};${h}m`;let x=AR(S,b,h);return`\x1B[${T?38:48};5;${x}m`}return""}let N=[];if(z>=H)for(let _=H;_<=z;_++){let T="";for(let S=0;S<G;S++){let b=W[_][S],h=b.char,x=q(b.style.fg,!0);T+=x+h+"\x1B[0m"}N.push(T)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let _=0;_<w;_++){let T=" ".repeat(G);if(_>=C&&_<C+I)T=N[_-C];let S=" ",b="";if(_>=O&&_<O+D.length)b=D[_-O];B.write(T+S+b+`
5431
+ `)}class b81 extends v0{analyzeContextForThread;listSkillsForThread;clientPool;completionBuilder;history;ideManager;configService;initialThreadID;showNeoWelcome;onNeoWelcomeDismissed;notificationService;onThreadArchived;initialUserInput;openThreadPickerOnStart;neoContext;constructor(A){super();this.analyzeContextForThread=A.analyzeContextForThread,this.listSkillsForThread=A.listSkillsForThread,this.clientPool=A.clientPool,this.completionBuilder=A.completionBuilder,this.history=A.history,this.ideManager=A.ideManager,this.configService=A.configService,this.initialThreadID=A.initialThreadID,this.showNeoWelcome=A.showNeoWelcome??!1,this.onNeoWelcomeDismissed=A.onNeoWelcomeDismissed,this.notificationService=A.notificationService,this.onThreadArchived=A.onThreadArchived,this.initialUserInput=A.initialUserInput,this.openThreadPickerOnStart=A.openThreadPickerOnStart??!1,this.neoContext=A.neoContext}createState(){return new J6A}}class J6A extends k0{editorController=new L8;commandPalette=new Ks(this);commandRegistry=new i51;toastController=new R41;exitHintTimer=new bf(this,1000);ideStatus=new h8(this,{});threadNavigationHistory=new g51;draftThreadSettings={};draftThreadSettingsSeed={};hasDraftThreadSettingsSeed=!1;draftThreadSettingsInitPromise=null;activeThreadContext=null;titleSubscription=null;agentStateSubscription=null;currentTitleText=void 0;currentAgentBusy=!1;currentTerminalTitle=void 0;terminalTitleSpinner=new z6;terminalTitleSpinnerTimer=null;connectionErrorsSubscription=null;configSubscription=null;connectingToThreadID=null;switchThreadPickerVisible=!1;neoWelcomeVisible=!1;debugOverlayVisible=!1;focusDebugVisible=!1;unregisterCommands=null;pluginIntegration=null;configReloadSubscription=null;configReloadToastTimer=null;pendingConfigReloadToastType=null;lastConfigReloadToast=null;loadThreads=async()=>{return this.widget.neoContext.listThreads()};onSwitchThread=(A)=>{this.connectToExistingThread(A,{recordNavigation:!0})};sendFeedbackReport=async(A)=>F0A({configService:this.widget.configService,settingsFilePath:this.widget.neoContext.settingsFilePath},A);setThreadVisibility=(A,Q)=>{return D0A({ampURL:this.widget.neoContext.ampURL,configService:this.widget.configService},A,Q)};archiveThread=async(A)=>{let Q=await Gr4({configService:this.widget.configService},A);if(Q===null)this.widget.onThreadArchived?.(A);return Q};addThreadLabel=async(A,Q)=>{let B=await Vr4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};removeThreadLabel=async(A,Q)=>{let B=await Ur4({configService:this.widget.configService},A,Q);if(B instanceof Error)return B;return this.toastController.show(B.message,B.type,2000),null};initState(){if(sB.getInstance().interceptConsole(),this.widget.showNeoWelcome)this.neoWelcomeVisible=!0;if(this.connectionErrorsSubscription=this.widget.clientPool.connectionErrors$.subscribe(({threadID:Q,error:B})=>{if(j.error("Neo failed to connect to thread",{threadID:Q,error:B}),!Q)this.toastController.show(`Connection failed: ${B.message}`,"error",4000)}),this.configReloadSubscription=this.widget.configService.configReloadEvents.subscribe((Q)=>this.scheduleConfigReloadToast(Q)),this.configSubscription=this.widget.configService.config.subscribe((Q)=>{this.applyDraftThreadSettingsSeed(this.applySessionDefaultsToThreadSettings(O80(Q.settings)))}),this.ideStatus.subscribe(this.widget.ideManager.status),this.widget.openThreadPickerOnStart)this.switchThreadPickerVisible=!0;this.ensureDraftThreadSettingsInitialized();let A=this.widget.initialUserInput;if(this.widget.initialThreadID){let Q={};if(A)Q.initialUserInput=A;this.connectToExistingThread(this.widget.initialThreadID,Q)}else if(A)this.onNewThread([{type:"text",text:A}],this.widget.neoContext.sessionAgentMode);this.pluginIntegration=new u51({state:this,commandPalette:this.commandPalette,commandRegistry:this.commandRegistry,toastController:this.toastController,neoContext:this.widget.neoContext,getActiveThreadID:this.getActiveThreadID,appendToThread:this.appendPluginMessagesToThread}),this.pluginIntegration.init(),this.unregisterCommands=this.registerAppCommands(),queueMicrotask(()=>{if(!this.mounted)return;this.replayEarlyInputToEditor()})}replayEarlyInputToEditor(){let A=L4.instance.tuiInstance.getEarlyInputText();if(!A)return;this.editorController.insertText(A)}scheduleConfigReloadToast(A){if(this.pendingConfigReloadToastType=this.pendingConfigReloadToastType==="failed"||A.type==="failed"?"failed":"succeeded",this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer);this.configReloadToastTimer=setTimeout(()=>{this.flushConfigReloadToast()},Ne5),this.configReloadToastTimer.unref()}flushConfigReloadToast(){let A=this.pendingConfigReloadToastType;if(this.pendingConfigReloadToastType=null,this.configReloadToastTimer=null,!A)return;let Q=Date.now();if(this.lastConfigReloadToast?.type===A&&Q-this.lastConfigReloadToast.shownAt<Ie5)return;switch(this.lastConfigReloadToast={type:A,shownAt:Q},A){case"succeeded":this.toastController.show("Config reloaded","success",1500);break;case"failed":this.toastController.show("Config reload failed","error",5000);break}}registerAppCommands(){let A=this,Q=this.widget.neoContext.pluginService?J0A({pluginService:this.widget.neoContext.pluginService,workspaceRoot:this.widget.neoContext.workspaceRoot,logFilePath:this.widget.neoContext.logFilePath,toastController:this.toastController}):[],$=[{noun:"thread",verb:"switch",description:"Switch to existing thread",keywords:["recent","history","open","resume","change"],status:{type:"enabled"},sortBoost:100,run:(J,Y,Z)=>{J.pushWithDismiss((X)=>o31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:X,onThreadSelected:Z}))}},{noun:"thread",verb:"switch to previous",description:"Switch to previous thread",keywords:["back"],get status(){return A.threadNavigationHistory.canNavigateBack()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to previous with no previous thread"}},run:(J,Y,Z)=>{A.navigateBack(),Z()}},B6A({configService:this.widget.configService,getActiveThreadID:()=>this.activeThreadContext?.client.getThreadId()??void 0,toastController:this.toastController}),{noun:"thread",verb:"switch to next",description:"Switch to next thread",keywords:["forward"],get status(){return A.threadNavigationHistory.canNavigateForward()?{type:"enabled"}:{type:"disabled",reason:"Cannot use thread: switch to next with no next thread"}},run:(J,Y,Z)=>{A.navigateForward(),Z()}},{noun:"mcp",verb:"info",description:"Show MCP servers and tools",keywords:["servers","tools","plugins","integrations"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new F31({mcpServers:this.widget.neoContext.mcpServers,onDismiss:Z}))}},{noun:"toolbox",verb:"list",description:"List all toolboxes and their tools",keywords:["tools","toolbox"],status:{type:"enabled"},run:(J)=>{J.pushWithDismiss((Y)=>new _81({toolboxes:this.widget.neoContext.toolboxes,onDismiss:Y}))}},{noun:"news",verb:"open",description:"Open Amp Chronicle in browser",keywords:["chronicle","updates","blog","announcements"],status:{type:"enabled"},run:async(J,Y,Z)=>{try{await lA(Y,"https://ampcode.com/chronicle")}finally{Z()}}},{noun:"settings",verb:"open in editor",description:"Open CLI settings in $EDITOR",keywords:["config","preferences","edit"],status:{type:"enabled"},run:()=>{LJ(this.widget.neoContext.settingsFilePath).catch((J)=>{j.error("Failed to open settings file in editor",{error:J})})}},{noun:"IDE",verb:"connect",description:"Connect to an IDE",keywords:["vscode","cursor","jetbrains","editor","attach"],status:{type:"enabled"},run:(J,Y,Z)=>{J.pushWithDismiss((X)=>new Z31({onCancel:X,onSelect:(F)=>{this.handleIdeSelection(F),Z()}}))}},{noun:"amp",verb:"help",description:"Show help & keyboard shortcuts",keywords:["shortcuts","keybindings","docs","manual","?"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new s51({commands:YZ.of(Y).commands,onDismiss:Z}))}},{noun:"amp",verb:"show welcome",description:"Show the welcome message again",keywords:["intro","onboarding","getting started"],status:{type:"enabled"},run:(J,Y,Z)=>{Z(),A.showNeoWelcome()}},{noun:"amp",verb:"show version",description:"Show current Amp version",keywords:["about","release","build"],status:{type:"enabled"},run:(J,Y,Z)=>{J.push(new _A({header:"Amp Version",maxWidth:72,onDismiss:Z,child:new l({text:new M(I41({version:"0.0.1778070540-gc7ef03",buildTimestamp:"2026-05-06T12:32:43.933Z",buildType:"'release'"}))})}))}},{noun:"amp",verb:"reconnect",description:"Disconnect and reconnect the active thread",keywords:["connection","disconnect","socket","debug"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: reconnect with no active thread"}},run:(J,Y,Z)=>{A.reconnectActiveThread(),Z()}},{noun:"amp",verb:"disconnect",description:"Disconnect the active thread without reconnecting",keywords:["connection","socket","debug","dev"],get status(){return A.activeThreadContext?.client.getThreadId()?{type:"enabled"}:{type:"disabled",reason:"Cannot use amp: disconnect with no active thread"}},run:(J,Y,Z)=>{A.disconnectActiveThread(),Z()}},{noun:"amp",verb:"quit",description:"Exit application",keywords:["exit","close","leave","bye"],shortcut:v1.ctrl("c"),status:{type:"enabled"},run:(J,Y)=>{BA.maybeInvoke(Y,new Hb)}},...Q,...ie4(this.widget.neoContext.logFilePath)].map((J)=>this.commandRegistry.register(J));return()=>{for(let J of $)J()}}build(A){let Q=this.buildHints(),B=this.ideStatus.getValue(),$=new P81({initialAgentMode:this.widget.neoContext.sessionAgentMode,analyzeContextForThread:this.widget.analyzeContextForThread,listSkillsForThread:this.widget.listSkillsForThread,threadContext:this.activeThreadContext,draftThreadSettings:this.draftThreadSettings,editorController:this.editorController,history:this.widget.history,updateDraftThreadSettings:this.updateDraftThreadSettings,onNewThread:this.onNewThread,sendFeedbackReport:this.sendFeedbackReport,setThreadVisibility:this.setThreadVisibility,archiveThread:this.archiveThread,addThreadLabel:this.addThreadLabel,removeThreadLabel:this.removeThreadLabel,configService:this.widget.configService,hints:Q,ideStatus:B}),J=e1.of(A),Z=[new p0({constraints:O1.tight(J.size.width,J.size.height),child:$})];if(this.commandPalette.isEnabled())Z.push(new c4({debugLabel:"CommandPaletteOverlay",onFocusChange:this.closeCommandPaletteOnFocusLoss,child:new n51({onDismiss:this.commandPalette.disable})}));if(this.switchThreadPickerVisible&&!this.neoWelcomeVisible)Z.push(o31({activeThreadID:this.activeThreadContext?.client.getThreadId()??null,loadThreads:this.loadThreads,onSelectThread:this.onSwitchThread,onDismiss:this.closeSwitchThreadPicker,onThreadSelected:this.closeSwitchThreadPicker}));if(this.neoWelcomeVisible)Z.push(new c4({debugLabel:"NeoWelcomeDialogOverlay",child:new y81({onDismiss:this.dismissNeoWelcome})}));if(Z.push(...this.pluginIntegration?.buildDialogLayers()??[]),this.widget.neoContext.isInternalUser)Z.push(new J31({top:this.focusDebugVisible?33:1,visible:this.debugOverlayVisible,pid:mt.pid,activeThreadID:this.activeThreadContext?.client.getThreadId()??null,connectionInfo$:this.activeThreadContext?.observer.connectionInfo()??null}));if(this.focusDebugVisible)Z.push(new Y31);return new T3({neoContext:this.widget.neoContext,child:new YZ({commandRegistry:this.commandRegistry,child:new eI({completionBuilder:this.widget.completionBuilder,child:new f5({controller:this.toastController,child:new BA({actions:this.buildActions(),child:new d5({debugLabel:"NeoAppShortcuts",shortcuts:new Map([[v1.ctrl("c"),new hV0],[v1.ctrl("o"),new gV0],[v1.alt("i"),new pV0],[v1.alt("p"),new kI],[v1.ctrl("t"),new dV0]]),child:new m4({debugLabel:"AppShellFocus",child:new P41({controller:this.toastController,child:new t4({children:Z})})})})})})})})})}buildActions(){let A=new K4(()=>{if(MJ.hasAnyCopyableSelection())return MJ.tryCopyAnyActiveSelection(),"handled";return this.onExitPressed(),"handled"}),Q=new K4(()=>{if(!this.commandPalette.isEnabled()&&this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.toggle(),"handled"}),B=new K4(()=>{if(this.commandPalette.isEnabled()||this.hasBlockingTopLevelModal())return"ignored";return this.commandPalette.enable(),"handled"}),$=new K4(()=>{return this.startNewDraftThread(),"handled"}),J=new K4(()=>{return L4.instance.stop(),"handled"}),Y=new K4((U)=>{if(!U.text)return"ignored";return L4.instance.tuiInstance.clipboard.writeText(U.text).then(()=>{this.toastController.show(U.successMessage,"success",2000)}).catch((K)=>{j.error("Failed to copy Neo text to clipboard",{error:K}),this.toastController.show(U.failureMessage,"error",2000)}),"handled"}),Z=new K4(()=>{return L4.instance.toggleFrameStatsOverlay(),"handled"}),X=new K4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";return this.setState(()=>{this.debugOverlayVisible=!this.debugOverlayVisible}),"handled"}),F=new K4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";let K=nx(U);return L4.instance.tuiInstance.clipboard.writeText(K).then(()=>{this.toastController.show("Copied log path to clipboard","success",2000)}).catch((E)=>{j.error("Failed to copy thread log path",{error:E,threadID:U,logPath:K}),this.toastController.show("Failed to copy log path","error",2000)}),"handled"}),D=new K4(()=>{if(!this.widget.neoContext.isInternalUser)return"ignored";let U=this.activeThreadContext?.client.getThreadId();if(!U)return"handled";return this.prepareThreadIssueInvestigation(U),"handled"}),G=new K4(()=>{let U=this.activeThreadContext?.client.getThreadId();if(!U)return this.toastController.show("No active thread","error",2000),"handled";return this.toastController.show("Sending report...","success",2000),this.sendFeedbackReport(U).then(async(K)=>{try{await L4.instance.tuiInstance.clipboard.writeText(K),this.toastController.show("Sent report and copied report ID","success",3000)}catch(E){j.warn("Failed to copy report ID to clipboard",{error:E,reportID:K}),this.toastController.show(`Sent report ${K}`,"success",3000)}}).catch((K)=>{j.error("Failed to send report from debug overlay",{error:K,threadID:U}),this.toastController.show("Failed to send report","error",3000)}),"handled"}),V=new K4(()=>{return this.setState(()=>{this.focusDebugVisible=!this.focusDebugVisible}),"handled"});return new Map([[hV0,A],[Gt,$],[Hb,J],[J$,Y],[Kt,B],[gV0,Q],[pV0,X],[Et,F],[Wt,D],[Ht,G],[kI,Z],[dV0,V]])}startNewDraftThread(A={}){let Q=this.activeThreadContext?.client.getThreadId();if(this.commandPalette.disable(),this.threadNavigationHistory.recordNavigation(Q),this.setState(()=>{if(this.titleSubscription?.unsubscribe(),this.titleSubscription=null,this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.currentAgentBusy=!1,this.syncTerminalTitleSpinner(),this.clearTerminalTitle(),this.activeThreadContext=null,this.connectingToThreadID=null,A.hideDebugOverlay)this.debugOverlayVisible=!1}),A.prompt!==void 0)this.editorController.text=A.prompt}prepareThreadIssueInvestigation(A){try{this.startNewDraftThread({prompt:we5({ampURL:this.widget.neoContext.ampURL,threadID:A,logPath:nx(A)}),hideDebugOverlay:!0})}catch(Q){j.error("Failed to prepare thread issue investigation",{error:Q,threadID:A})}}closeCommandPaletteOnFocusLoss=(A)=>{if(A||!this.commandPalette.isEnabled())return;this.commandPalette.disable()};ensureDraftThreadSettingsInitialized(){if(this.hasDraftThreadSettingsSeed)return Promise.resolve();if(!this.draftThreadSettingsInitPromise)this.draftThreadSettingsInitPromise=this.initDraftThreadSettings();return this.draftThreadSettingsInitPromise}async initDraftThreadSettings(){try{let A=this.applySessionDefaultsToThreadSettings(await jf(this.widget.configService));this.applyDraftThreadSettingsSeed(A)}catch(A){j.warn("Failed to initialize Neo draft thread settings",{error:A instanceof Error?A.message:String(A)})}}applySessionDefaultsToThreadSettings(A){let Q=this.widget.neoContext.sessionAgentMode,B=A,$=tB(Q),J=rD0(this.widget.neoContext,Q);if($!==void 0&&J!==void 0)B={...B,[$]:J};return oD0(B,{agentMode:Q,explicitEffort:this.widget.neoContext.explicitReasoningEffort,sessionState:this.widget.neoContext})}applyDraftThreadSettingsSeed(A){if(!this.mounted)return;if(!this.hasDraftThreadSettingsSeed){this.setState(()=>{this.hasDraftThreadSettingsSeed=!0,this.draftThreadSettings=$6A(this.draftThreadSettings,{},A),this.draftThreadSettingsSeed={...A}});return}if(iZ(this.draftThreadSettingsSeed,A))return;this.setState(()=>{this.draftThreadSettings=$6A(this.draftThreadSettings,this.draftThreadSettingsSeed,A),this.draftThreadSettingsSeed={...A}})}buildHints(){let A=new Set;if(this.connectingToThreadID)A.add(tI);if(this.exitHintTimer.isActive())A.add(Gb);return A}onExitPressed=()=>{if(this.exitHintTimer.isActive())this.exitHintTimer.clear(),L4.instance.stop();else this.exitHintTimer.activate()};dismissNeoWelcome=()=>{if(!this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!1}),this.widget.onNeoWelcomeDismissed?.()};showNeoWelcome=()=>{if(this.neoWelcomeVisible)return;this.setState(()=>{this.neoWelcomeVisible=!0})};closeSwitchThreadPicker=()=>{if(!this.switchThreadPickerVisible)return;this.setState(()=>{this.switchThreadPickerVisible=!1})};updateDraftThreadSettings=(A)=>{this.setState(()=>{this.draftThreadSettings=A(this.draftThreadSettings)})};onNewThread=async(A,Q,B=null,$)=>{await this.ensureDraftThreadSettingsInitialized();let J=this.activeThreadContext?.client.getThreadId(),Y=A.find((X)=>X.type==="text");if(Y&&Y.type==="text")this.widget.history.add(Y.text,mt.cwd()),this.widget.history.reset();let Z=this.widget.clientPool.createNewThread(Q,this.draftThreadSettings,B?QZ(B):void 0);this.sendUserMessage(Z,A,Q,$),this.rememberSessionDefaultsForNewMessage(Q,this.draftThreadSettings),this.threadNavigationHistory.recordNavigation(J),this.setActiveClient(Z)};rememberSessionDefaultsForNewMessage(A,Q){this.widget.neoContext.sessionAgentMode=A;let B=Q["reasoning.effort"];if(B!==void 0)this.widget.neoContext.lastReasoningEffortByMode={...this.widget.neoContext.lastReasoningEffortByMode??{},[A]:B};let $=tB(A),J=$?Q[$]:void 0;if(J!==void 0)this.widget.neoContext.lastSpeedByMode={...this.widget.neoContext.lastSpeedByMode??{},[A]:J};CJ((Y)=>{let Z={...Y,agentMode:A};if(B!==void 0)Z={...Z,lastReasoningEffortByMode:{...Z.lastReasoningEffortByMode??{},[A]:B}};if(J!==void 0)Z={...Z,lastSpeedByMode:{...Z.lastSpeedByMode??{},[A]:J}};return Z}).catch((Y)=>{j.warn("Failed to persist Neo session defaults for new message",{error:Y instanceof Error?Y.message:String(Y)})})}sendUserMessage(A,Q,B,$){let J=EZ0(this.ideStatus.getValue());if($===void 0){A.client.sendUserMessage(Q,B,{userState:J});return}A.client.sendUserMessage(Q,B,{reasoningEffort:$,userState:J})}getActiveThreadID=()=>{return this.activeThreadContext?.client.getThreadId()??void 0};appendPluginMessagesToThread=async(A,Q)=>{let B=this.activeThreadContext;if(!B)throw Error("appendToThread is not available - no active thread");let $=B.client.getThreadId();if(Q&&$!==Q)throw Error("thread.append is only available for the active executor thread");for(let J of A)this.sendUserMessage(B,[{type:"text",text:J.content}])};async connectToExistingThread(A,Q={}){let B=this.activeThreadContext?.client.getThreadId();this.setState(()=>{this.connectingToThreadID=A});try{let $=await this.widget.clientPool.connectToThread(A,{observerOnly:this.widget.neoContext.observerOnly});if(this.setActiveClient($),Q.recordNavigation&&B!==A)this.threadNavigationHistory.recordNavigation(B);if(Q.initialUserInput)this.sendUserMessage($,[{type:"text",text:Q.initialUserInput}])}catch($){if(j.error("Failed to load thread",{error:$,threadID:A}),this.toastController.show(`Failed to load ${A}: ${$ instanceof Error?$.message:String($)}`,"error",4000),Q.rethrowError)throw $}finally{this.setState(()=>{this.connectingToThreadID=null})}}async navigateBack(){let A=this.threadNavigationHistory.startBackNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateForward(){let A=this.threadNavigationHistory.startForwardNavigation(this.activeThreadContext?.client.getThreadId());if(!A)return;await this.navigateToThread(A)}async navigateToThread(A){try{await this.connectToExistingThread(A.targetThreadID,{rethrowError:!0})}catch{A.rollback()}}async reconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to reconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Reconnecting ${Q}...`:"Reconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.reconnectClient(A.client);this.toastController.update(B,`Reconnected ${$}`,"success",2000)}catch($){j.error("Failed to reconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Reconnect failed: ${J}`,"error",4000)}}async disconnectActiveThread(){let A=this.activeThreadContext;if(!A){this.toastController.show("No active thread to disconnect","error",2000);return}let Q=A.client.getThreadId(),B=this.toastController.show(Q?`Disconnecting ${Q}...`:"Disconnecting thread...","warning",60000);try{let $=await this.widget.clientPool.disconnectClient(A.client);this.toastController.update(B,`Disconnected ${$}`,"success",2000)}catch($){j.error("Failed to disconnect thread",{error:$,threadID:Q});let J=$ instanceof Error?$.message:String($);this.toastController.update(B,`Disconnect failed: ${J}`,"error",4000)}}setActiveClient({client:A,observer:Q}){this.setState(()=>{this.activeThreadContext={client:A,observer:Q},this.subscribeTitleUpdates(Q),this.subscribeNotifications(Q)})}subscribeTitleUpdates(A){this.titleSubscription?.unsubscribe(),this.titleSubscription=A.title().subscribe({next:(Q)=>{this.currentTitleText=Q,this.updateTerminalTitle()}}),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=A.agentState().subscribe({next:(Q)=>{let B=$31(Q);if(B===this.currentAgentBusy)return;this.currentAgentBusy=B,this.syncTerminalTitleSpinner(),this.updateTerminalTitle()}})}subscribeNotifications(A){this.widget.notificationService.attach(A.agentState())}clearTerminalTitle(){this.currentTitleText=void 0,this.updateTerminalTitle()}updateTerminalTitle(){let A=mt.cwd().replace(mt.env.HOME||"","~"),Q=this.currentAgentBusy?`${this.terminalTitleSpinner.toBraille()} `:"",B=this.currentTitleText?`${Q}amp - ${this.currentTitleText} - ${A}`:this.currentAgentBusy?`${Q}amp - ${A}`:"";if(B===this.currentTerminalTitle)return;this.currentTerminalTitle=B,mt.stdout.write(MI(B))}syncTerminalTitleSpinner(){if(this.currentAgentBusy){if(this.terminalTitleSpinnerTimer)return;this.terminalTitleSpinnerTimer=setInterval(()=>{this.terminalTitleSpinner.step(),this.updateTerminalTitle()},200);return}if(this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null}handleIdeSelection=async(A)=>{try{await this.widget.ideManager.connect(A)}catch(Q){j.error("Failed to connect to IDE",{error:Q});let B=Q instanceof Error?Q.message:String(Q);this.toastController.show(`IDE connection failed: ${B}`,"error",4000)}};dispose(){if(this.unregisterCommands?.(),this.unregisterCommands=null,this.pluginIntegration?.dispose(),this.pluginIntegration=null,this.titleSubscription?.unsubscribe(),this.agentStateSubscription?.unsubscribe(),this.agentStateSubscription=null,this.terminalTitleSpinnerTimer)clearInterval(this.terminalTitleSpinnerTimer),this.terminalTitleSpinnerTimer=null;if(this.connectionErrorsSubscription?.unsubscribe(),this.configSubscription?.unsubscribe(),this.configSubscription=null,this.configReloadSubscription?.unsubscribe(),this.configReloadSubscription=null,this.configReloadToastTimer)clearTimeout(this.configReloadToastTimer),this.configReloadToastTimer=null;this.pendingConfigReloadToastType=null,this.widget.notificationService.detach(),this.toastController.dispose(),super.dispose()}hasBlockingTopLevelModal(){return this.switchThreadPickerVisible||this.neoWelcomeVisible||(this.pluginIntegration?.hasBlockingDialog()??!1)}}function $6A(A,Q,B){let $={...A};for(let J of Ce5(Q,B)){if(!iZ(A[J],Q[J]))continue;let Y=B[J];if(Y===void 0)delete $[J];else $[J]=Y}return $}function Ce5(...A){return Array.from(new Set(A.flatMap((Q)=>Object.keys(Q))))}i4();function Y6A(A,Q,B,$){let J=jS(A),Y="\x1B[0m",Z="\x1B[34m",X="\x1B[90m",F="\x1B[2m",D=[];if(A.archived)D.push("\x1B[90m\x1B[2mArchived\x1B[0m");D.push(`${J}`),D.push(`\x1B[34m${Q}\x1B[0m`),D.push(`\x1B[90mamp threads continue ${A.id}\x1B[0m`);let G=14,V=7,U=new rY(G,V),K=new T9(42),E=new jI(G,V,G,V,G,V,0,A.agentMode??"smart","intensity","classic","braille",void 0,void 0,H0.default(),K);E.layout(O1.tight(G,V)),E.paint(U,0,0);let W=U.getBuffer().getCells(),H=0;for(let _=0;_<V;_++)if(W[_].some((T)=>T.char!==" ")){H=_;break}let z=V-1;for(let _=V-1;_>=0;_--)if(W[_].some((T)=>T.char!==" ")){z=_;break}function q(_,T){if(!_)return"";if(_.type==="rgb"){let{r:S,g:b,b:h}=_.value;if(B.getColorDepth()>=24)return`\x1B[${T?38:48};2;${S};${b};${h}m`;let x=AR(S,b,h);return`\x1B[${T?38:48};5;${x}m`}return""}let N=[];if(z>=H)for(let _=H;_<=z;_++){let T="";for(let S=0;S<G;S++){let b=W[_][S],h=b.char,x=q(b.style.fg,!0);T+=x+h+"\x1B[0m"}N.push(T)}let I=N.length,w=Math.max(I,D.length),C=Math.floor((w-I)/2),O=Math.floor((w-D.length)/2);for(let _=0;_<w;_++){let T=" ".repeat(G);if(_>=C&&_<C+I)T=N[_-C];let S=" ",b="";if(_>=O&&_<O+D.length)b=D[_-O];B.write(T+S+b+`
5432
5432
  `)}if($)B.write(`
5433
5433
  \x1B[90m${$}\x1B[0m
5434
5434
  `)}l0();YG0();var Me5=2000;function Z6A(A){let Q=!0,B=!0,$=A.configService.config.subscribe((V)=>{Q=V.settings["notifications.enabled"]??!0,B=V.settings["notifications.system.enabled"]!==!1}),J=0,Y=(V)=>{if(!Q)return;let U=Date.now();if(U-J<Me5)return;if(J=U,XR())return;if(ZD0())XD0();else eZ0(V)},Z=(V)=>{if(!Q||!B)return;if(XR()&&!Ys()&&!zf())return;process.stdout.write(iD(`\x1B]777;notify;Amp;${V}\x1B\\`))},X=null,F=null,D=()=>{X?.unsubscribe(),X=null,F=null};return{attach:(V)=>{D(),X=V.subscribe({next:(U)=>{try{let K=F!==null&&oB(F),E=F==="awaiting_approval";if(U==="awaiting_approval"&&!E)Y("requires-user-input"),Z("Waiting for approval");else if((U==="idle"||U==="error")&&(K||E))Y("idle"),Z("Agent is ready")}catch(K){j.debug("Neo notification handling failed",{error:K})}finally{F=U}},error:(U)=>{j.debug("Neo notification agent state stream errored",{error:U})}})},detach:D,unsubscribe(){D(),$.unsubscribe()}}}function Le5({initialUserInput:A,showNeoWelcome:Q,neoWelcomeDismissed:B}){if(Q)return{show:!0,markDismissedOnDismiss:!0};let $=!A&&!B;return{show:$,markDismissedOnDismiss:$}}async function Oe5(A){await CJ((Q)=>tD0(Q,A,"interactive"))}async function X6A(A,Q={}){let{initialThreadID:B,initialUserInput:$,openThreadPickerOnStart:J=!1,observerOnly:Y=!1,initialAgentMode:Z,initialReasoningEffort:X,showNeoWelcome:F=!1}=Q,D=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)return null;return pF0(w)},G=async(I)=>{let w=await A.getThreadFromServer(I);if(!w)throw Error(`Thread ${I} not found`);let C=await nY(I,A.configService,A.apiKey,{usesThreadActors:!0}),T=await _U({endpoint:A.rivetEndpoint}).threadActor.getOrCreate([I],{params:{wsToken:C.wsToken},createWithInput:{threadId:C.threadId,threadVersion:C.threadVersion,ownerUserId:C.ownerUserId,...C.agentMode?{agentMode:C.agentMode}:{}}}).fetch("/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({thread:Sm4(w)}),skipReadyWait:!0});if(T.ok||T.status===409)return;throw Error(`Thread import failed (${T.status}): ${await T.text()}`)},V=new e11(A.rivetEndpoint,A.apiKey,A.configService,{clientID:UI.parse(`neo-${crypto.randomUUID()}`),toolService:A.toolService,skillService:A.skillService,requestPluginToolCall:(I)=>A.pluginService.event.toolCall(I),requestPluginToolResult:(I)=>A.pluginService.event.toolResult(I),pluginService:A.pluginService,invokeTool:async(I,w)=>{let C=typeof w.args==="object"&&w.args!==null?w.args:{},O=await WI({toolName:w.toolName,configService:A.configService,toolService:A.toolService,mcpService:A.mcpService,skillService:A.skillService,toolUseID:w.toolCallId,threadID:I});return A.toolService.invokeTool(w.toolName,{args:C},O)},persistLastThreadID:Oe5,readFileSystemDirectory:A.readFileSystemDirectory},D,G),U=await TI(),K=Le5({initialUserInput:$,showNeoWelcome:F,neoWelcomeDismissed:U.neoWelcomeDismissed}),E={ampURL:A.ampURL,configService:A.configService,getThreadMarkdown:async(I)=>{let w=await A.getThreadFromServer(I);return w?xV(w):null},isInternalUser:A.isInternalUser,listThreads:A.listThreads,logFilePath:Qr,mcpServers:A.mcpService.servers,pluginPlatform:A.pluginPlatform,pluginService:A.pluginService,toolboxes:A.toolboxes,observerOnly:Y,sessionAgentMode:Z??U.agentMode,explicitReasoningEffort:X,lastReasoningEffortByMode:U.lastReasoningEffortByMode,lastSpeedByMode:U.lastSpeedByMode,settingsFilePath:A.settingsFilePath,splashOrbVisualStyle:Q.splashOrbVisualStyle??"neo",workspaceRoot:A.workspaceRoot},W=(I,w)=>{return xx({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},H=(I,w)=>{return Ui4({ampURL:A.ampURL,configService:A.configService,threadID:I,signal:w})},z=new N41,q=Z6A({configService:A.configService}),N=new Set;try{await Zs(new b81({clientPool:V,analyzeContextForThread:W,listSkillsForThread:H,completionBuilder:A.completionBuilder,history:new Er,ideManager:z,configService:A.configService,initialThreadID:B,notificationService:q,initialUserInput:$,openThreadPickerOnStart:J,neoContext:E,showNeoWelcome:K.show,onNeoWelcomeDismissed:K.markDismissedOnDismiss?()=>{CJ(Hi4).catch((w)=>{j.warn("Failed to mark Neo welcome as dismissed",{error:w})})}:void 0,onThreadArchived:(w)=>{N.add(w)}}));let I=V.lastActiveObservingClient;if(I){let{client:w,observer:C}=I,O=w.getThreadId();if(O){let _={id:O,title:C.title().getValue(),agentMode:C.agentMode,archived:N.has(O)},T=`${A.ampURL.replace(/\/$/,"")}/threads/${O}`;Y6A(_,T,process.stdout)}}}finally{process.stdout.write(MI("")),q.unsubscribe(),V.dispose(),await A.dispose?.()}process.exit(0)}Od();DE();async function je5(A,Q,B){let $=V20(A);if(!$.success)throw Error(`Invalid permission format: ${$.error.message}`);if($.data.length===0)throw Error("No permission entry provided");let J=cz($.data);if(!J.success){let F=J.error.issues.map((D)=>D.message).join(", ");throw Error(`Invalid permission entry: ${F}`)}let Y=await Q.get("permissions",B)??[],X=[$.data[0],...Y];await Q.set("permissions",X,B)}async function F6A(A){try{let Q=A.args.map((B)=>{if(/[\s/\\*?[\]{}()"]/.test(B))return`"${B}"`;return B}).join(" ");await je5(Q,A.settings,A.scope),A.exit(0)}catch(Q){let B=Q instanceof Error?Q.message:"Unknown error";A.stderr.write(`Error: ${B}
@@ -7099,7 +7099,7 @@ ${J}`,Q);this.line=B,this.column=$,this.codeblock=J}}/*!
7099
7099
  `),Y=[];for(let Z=0;Z<J.length;Z++){let D=J[Z].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let G of D)if(G.startsWith("\x00")&&G.endsWith("\x01"))Y.push(new M(G.slice(1,-1),new y({color:$.app.keybind,bold:!0})));else Y.push(new M(G,new y({color:B.colorScheme.foreground})));if(Z<J.length-1)Y.push(new M(`
7100
7100
  `))}return new p0({decoration:{color:B.colorScheme.background,border:n1.all(new a1($.app.keybind,1,"rounded"))},child:new b0({padding:z0.symmetric(0,1),child:new l({text:new M(void 0,void 0,Y)})})})}}class d21 extends $8{chartData;highlightIndex;showAxes;colors;constructor({key:A,chartData:Q,highlightIndex:B=null,showAxes:$=!0,colors:J=bK0}){super(A?{key:A}:{});this.chartData=Q,this.highlightIndex=B,this.showAxes=$,this.colors=J}createRenderObject(){return new m21({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(A){let Q=A;Q.chartData=this.chartData,Q.highlightIndex=this.highlightIndex,Q.showAxes=this.showAxes,Q.colors=this.colors,Q.markNeedsLayout()}}function O8A(A,Q,B,$,J,Y,Z){if(Y<=0)return null;switch(A){case"horizontal-bar":{let X=B;return X>=0&&X<Y?X:null}case"bar":case"stacked-bar":{let X=Z?p8:0,F=$-X;if(F<=0)return null;let D=Q-X;if(D<0||D>=F)return null;let G=Math.max(1,Math.floor(F/Y)),V=Math.floor(D/G);return V>=0&&V<Y?V:null}case"line":case"sparkline":case"stacked-area":{let X=Z?p8:0,F=$-X;if(F<=0)return null;let D=Math.max(0,Math.min(F-1,Q-X));if(Y===1)return 0;let G=F/(Y-1),V=Math.round(D/G);return Math.max(0,Math.min(Y-1,V))}default:return null}}function y53(A,Q,B,$,J,Y,Z,X){if(J<=0||Q<0||Q>=J)return null;let F=2;switch(A){case"horizontal-bar":return{x:Math.floor(B/2),y:Q};case"bar":case"stacked-bar":{let D=Y?p8:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=Math.max(1,Math.floor(G/J)),K=D+Q*U+Math.floor(U/2),E=X>0?Z/X:0,W=Math.round((1-E)*(V-1));return{x:K,y:W}}case"line":case"sparkline":case"stacked-area":{let D=Y?p8:0,G=B-D,V=$-(Y?F:0);if(G<=0||V<=0)return null;let U=J>1?D+Math.round(Q/(J-1)*(G-1)):D+Math.floor(G/2),K=X>0?Z/X:0,E=Math.round((1-K)*(V-1));return{x:U,y:E}}default:return null}}function x53(A){let Q=0;for(let B of A)for(let $ of B.points)if($.value>Q)Q=$.value;return Q||1}function f53(A,Q,B,$,J){if(B.length<=1){let X=$(A.value),F=A.meta?` (${A.meta})`:"";return A.label.length+2+X.length+F.length}let Y=A.label.length,Z=0;for(let X of B){let F=X.points[Q];if(!F)continue;Z+=F.value;let D=2+X.name.length+2+$(F.value).length;Y=Math.max(Y,D)}if(J){let X=9+$(Z).length;Y=Math.max(Y,X)}return Y}function b53(A,Q,B,$,J,Y,Z){let X;try{let E=T1.of(A),W=T0.of(A);X={foreground:E.colorScheme.foreground,background:E.colorScheme.background,border:W.app.keybind}}catch{X={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new y({color:X.foreground,bold:!0}),D=new y({color:X.foreground}),G=new y({color:X.foreground,dim:!0}),V=[],U=new y({color:X.foreground,underline:!0}),K=(E,W)=>new M(W,U,void 0,CI(E),()=>{lA(A,E)});if($.length<=1){if(V.push(new M(`${Q.label}: `,F)),Q.link)V.push(K(Q.link,Y(Q.value)));else V.push(new M(Y(Q.value),D));if(Q.meta)V.push(new M(` (${Q.meta})`,G))}else{let E=Z==="stacked-bar"||Z==="stacked-area";V.push(new M(`${Q.label}
7101
7101
  `,F));let W=0;for(let H=0;H<$.length;H++){let z=$[H],q=z.points[B];if(!q)continue;W+=q.value;let N=z.color??J[H%J.length]??X.foreground;if(V.push(new M("● ",new y({color:N}))),V.push(new M(`${z.name}: `,G)),q.link)V.push(K(q.link,Y(q.value)));else V.push(new M(Y(q.value),D));if(H<$.length-1||E)V.push(new M(`
7102
- `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new p0({decoration:{color:X.background,border:n1.all(new a1(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}l0();M3();E8();Q3();m7();y7();o9();C2();SB();yV();i4();Iv();aT();R1();l0();o9();class c21{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;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 A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778070211-gdd8fb4"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await w80(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Cw extends v0{props;constructor(A){super();this.props=A}createState(){return new j8A}}class j8A extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class R8A extends k0{controller=new L8;focusNode=new F6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=n1.all(new a1(B.foreground,1,"solid")),F=new eB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Q1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new y({color:B.foreground}))})}),new k1({child:F})]}),G=new p0({padding:z0.symmetric(1,0),child:new l({text:this.widget.props.title?new M(this.widget.props.title,new y({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new y({color:$.keybind}))),V.push(new M(" to submit, ",new y({color:B.foreground,dim:!0})));V.push(new M("Esc",new y({color:$.keybind}))),V.push(new M(" to cancel",new y({color:B.foreground,dim:!0})));let U=new p0({padding:z0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:z0.all(1),child:new f0({children:[G,new W0({height:1}),D,new Y5,U]})})}}class $e extends v0{props;constructor(A){super();this.props=A}createState(){return new R8A}}SB();class P8A extends k0{controller=new L8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new F6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=t9)return!1;let Q=await JF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,Y=e1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new $G({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:L4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new O1({maxHeight:Z}),padding:z0.symmetric(1,0),child:F}),G=new p0({padding:z0.symmetric(1,0),child:new l({text:new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=new p0({padding:z0.symmetric(1,0),child:new l({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new y({color:$.keybind})),new M(" again to clear input",new y({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new y({color:B.foreground,dim:!0})),new M("Enter",new y({color:$.keybind})),new M(" to submit, ",new y({color:B.foreground,dim:!0})),new M("Esc",new y({color:$.keybind})),new M(" to clear",new y({color:B.foreground,dim:!0}))])})}),U=[G,new W0({height:1}),new k1({child:D}),new W0({height:1}),V];return new p0({decoration:{border:n1.all(new a1(B.foreground,1,"solid")),color:B.background},padding:z0.all(1),child:new f0({children:U})})}}class l21 extends v0{props;constructor(A){super();this.props=A}createState(){return new P8A}}function _8A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class i21 extends w1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>_8A(J.pubDate).length));return new p6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=T0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new W0({width:H,child:Q1.end([new l({text:new M(W,new y({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:z0.symmetric(2,0),child:new Q1({children:[new k1({child:new l({text:new M(J.title,new y({color:U})),overflow:"ellipsis",maxLines:1})}),new W0({width:2}),E(_8A(J.pubDate),B)]})})}})}}class GB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GB._instance)GB._instance=new GB;return GB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}l0();class T8A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new p6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:z0.symmetric(2,0),child:new l({text:new M("",void 0,[new M("Create new label: ",new y({color:E})),new M(H,new y({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:z0.symmetric(2,0),child:new l({text:new M(D.name,new y({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class n21 extends v0{props;constructor(A){super();this.props=A}createState(){return new T8A}}class ZG extends v0{props;constructor(A){super();this.props=A}createState(){return new S8A}}class S8A extends k0{_spinner=new z6;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(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=n1.all(new a1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new M("",void 0,[new M(Y,new y({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new y({color:B.foreground}))])}),F=[new k1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new W0({height:2,child:new p0({padding:z0.symmetric(2,0),child:new l({text:new M("",new y({dim:!0}),[new M("Press ",new y({color:B.foreground})),new M("Esc",new y({color:B.info})),new M(" to cancel",new y({color:B.foreground}))])})})}));let D=new p0({decoration:new x4(B.background,J),child:new W0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class FK extends v0{props;constructor(A){super();this.props=A}createState(){return new k8A}}class k8A extends k0{scrollController=new rA;scrollAreaKey=new Y2("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(A){return A instanceof y2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=T0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=hG0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=n1.all(new a1(Q.colors.border,1,"solid")),Z=new p0({padding:z0.symmetric(1,0),child:new l({text:new M($.title,new y({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new y({color:Q.colors.foreground})),selectable:!0}),F=new k1({child:new J8({child:new p0({padding:z0.symmetric(1,0),child:new Q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new PA({controller:this.scrollController,autofocus:!0,child:X})}),new D2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:z0.symmetric(1,0),child:new l({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new y({color:Q.colors.foreground,dim:!0})),new M("R",new y({color:Q.app.keybind})),new M(" to retry, ",new y({color:Q.colors.foreground,dim:!0})),new M("Esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new y({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new y({color:Q.app.keybind}),U=new y({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new y({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new f1({onClick:()=>{},child:new W0}),new m4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 p0({decoration:{border:Y,color:Q.colors.background},padding:z0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new W0({height:1}),F,D]})})})]})})}}M3();class v8A extends v0{props;constructor(A){super();this.props=A}createState(){return new y8A}}class y8A extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=g8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new M("No plugins found.",new y({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${H4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${H4(Z,"command")}, ${X} ${H4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
7102
+ `))}if(E)V.push(new M(" ",G)),V.push(new M("Total: ",G)),V.push(new M(Y(W),D))}return new p0({decoration:{color:X.background,border:n1.all(new a1(X.border,1,"rounded"))},child:new l({text:new M(void 0,void 0,V)})})}l0();M3();E8();Q3();m7();y7();o9();C2();SB();yV();i4();Iv();aT();R1();l0();o9();class c21{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(A,Q){this.enabled=A;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 A=Array.from(this.commandCounts.entries()).map(([Q,B])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1778070540-gc7ef03"},parameters:{metadata:{count:B}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(A);await w80(Q,this.configService)}catch(Q){j.error("Failed to export command telemetry events",Q)}}async submit(A){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(A)||0;this.commandCounts.set(A,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class Cw extends v0{props;constructor(A){super();this.props=A}createState(){return new j8A}}class j8A extends k0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(A){let Q=(B)=>{this.setState(()=>{this._state=B(this._state)})};return this.widget.props.builder(A,Q,this._state)}}class R8A extends k0{controller=new L8;focusNode=new F6({debugLabel:"CommandArgumentPrompt",onKey:(A)=>{if(A.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(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=this.widget.props.isRequiredArg??!0,Y=this.controller.text.trim().length>0,Z=!J||Y,X=n1.all(new a1(B.foreground,1,"solid")),F=new eB({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(K)=>{let E=K.trim();if(J&&E.length===0)return;this.widget.props.onSubmit(E)},autofocus:!0,style:{textColor:B.foreground,border:null},maxLines:1}),D=new Q1({children:[new p0({decoration:{color:B.background},child:new l({text:new M(">",new y({color:B.foreground}))})}),new k1({child:F})]}),G=new p0({padding:z0.symmetric(1,0),child:new l({text:this.widget.props.title?new M(this.widget.props.title,new y({color:$.command,bold:!0})):new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=[];if(Z)V.push(new M("Enter",new y({color:$.keybind}))),V.push(new M(" to submit, ",new y({color:B.foreground,dim:!0})));V.push(new M("Esc",new y({color:$.keybind}))),V.push(new M(" to cancel",new y({color:B.foreground,dim:!0})));let U=new p0({padding:z0.symmetric(1,0),child:new l({text:new M("",void 0,V)})});return new p0({decoration:{border:X,color:B.background},padding:z0.all(1),child:new f0({children:[G,new W0({height:1}),D,new Y5,U]})})}}class $e extends v0{props;constructor(A){super();this.props=A}createState(){return new R8A}}SB();class P8A extends k0{controller=new L8;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new F6({debugLabel:"CommandMultilinePrompt",onKey:(A)=>{if(A.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(A)=>{if(this.imageAttachments.length>=t9)return!1;let Q=await JF(A);if(typeof Q==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Q],this.imagePaths=[...this.imagePaths,A]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(A){let Q=T0.of(A),{colors:B,app:$}=Q,Y=e1.of(A).size.height,Z=Math.max(Math.floor(Y*0.5),10),X=new $G({controller:this.controller,triggers:[new PJ],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(K)=>{this.widget.props.onSubmit(K.trim(),this.imageAttachments)},theme:B,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:L4.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new m4({debugLabel:"CommandMultilinePrompt",focusNode:this.focusNode,child:X}),D=new p0({constraints:new O1({maxHeight:Z}),padding:z0.symmetric(1,0),child:F}),G=new p0({padding:z0.symmetric(1,0),child:new l({text:new M("",void 0,[new M("Command: ",new y({color:B.foreground})),new M(this.widget.props.commandName,new y({color:$.command,bold:!0}))])})}),V=new p0({padding:z0.symmetric(1,0),child:new l({text:this.isConfirmingClearInput?new M("",void 0,[new M("Esc",new y({color:$.keybind})),new M(" again to clear input",new y({color:B.foreground,dim:!0}))]):new M("",void 0,[new M("Press ",new y({color:B.foreground,dim:!0})),new M("Enter",new y({color:$.keybind})),new M(" to submit, ",new y({color:B.foreground,dim:!0})),new M("Esc",new y({color:$.keybind})),new M(" to clear",new y({color:B.foreground,dim:!0}))])})}),U=[G,new W0({height:1}),new k1({child:D}),new W0({height:1}),V];return new p0({decoration:{border:n1.all(new a1(B.foreground,1,"solid")),color:B.background},padding:z0.all(1),child:new f0({children:U})})}}class l21 extends v0{props;constructor(A){super();this.props=A}createState(){return new P8A}}function _8A(A){let B=new Date().getTime()-A.getTime(),$=Math.floor(B/60000),J=Math.floor(B/3600000),Y=Math.floor(B/86400000);if($<1)return"just now";if($<60)return`${$}m ago`;if(J<24)return`${J}h ago`;if(Y<7)return`${Y}d ago`;return A.toLocaleDateString()}class i21 extends w1{props;debugLabel="NewsFeedPicker";constructor(A){super();this.props=A}build(A){let Q=[...this.props.entries].sort((J,Y)=>Y.pubDate.getTime()-J.pubDate.getTime()),B=Math.max(0,...Q.map((J)=>_8A(J.pubDate).length));return new p6({items:Q,getLabel:(J)=>J.title,onAccept:(J)=>this.props.onSelect?.(J),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(J,Y,Z,X)=>{let F=T0.of(X),{colors:D}=F,G=F.app,V=Y?G.selectionBackground:void 0,U=Y?G.selectionForeground:D.foreground,K=D.mutedForeground,E=(W,H)=>new W0({width:H,child:Q1.end([new l({text:new M(W,new y({color:K}))})])});return new p0({decoration:V?{color:V}:void 0,padding:z0.symmetric(2,0),child:new Q1({children:[new k1({child:new l({text:new M(J.title,new y({color:U})),overflow:"ellipsis",maxLines:1})}),new W0({width:2}),E(_8A(J.pubDate),B)]})})}})}}class GB{static _instance=null;_allExpanded=!1;_listeners=new Set;static get instance(){if(!GB._instance)GB._instance=new GB;return GB._instance}get allExpanded(){return this._allExpanded}setAllExpanded(A){if(this._allExpanded===A)return;this._allExpanded=A,this._notifyListeners()}toggleAll(){this.setAllExpanded(!this._allExpanded)}addListener(A){return this._listeners.add(A),()=>this.removeListener(A)}removeListener(A){this._listeners.delete(A)}_notifyListeners(){for(let A of this._listeners)A()}}l0();class T8A extends k0{labels=[];isLoading=!0;currentQuery="";initState(){this.loadLabels()}async loadLabels(){try{let A=await this.widget.props.internalAPIClient.getUserLabels({query:""},{config:this.widget.props.configService});if(!A.ok){j.error("Failed to load labels",A.error),this.isLoading=!1,this.labels=[],this.setState();return}this.labels=A.result,this.isLoading=!1,this.setState()}catch(A){j.error("Failed to load labels",A),this.isLoading=!1,this.labels=[],this.setState()}}getValidationError(A){let Q=A.trim().toLowerCase();if(Q.length===0)return null;if(Q.length>32)return"Label name cannot exceed 32 characters";if(!/^[a-z0-9][a-z0-9-]*$/.test(Q))return"Label must be alphanumeric with hyphens, starting with a letter or number";return null}isValidLabelName(A){return this.getValidationError(A)===null&&A.length>0}getAvailableLabels(){let A=this.widget.props.currentLabels||[];return this.labels.filter((Q)=>!A.includes(Q.name))}shouldShowCreateMarker(A){if(A.length===0||this.isLoading)return!1;let Q=A.trim().toLowerCase();if(!this.isValidLabelName(Q))return!1;let B=this.widget.props.currentLabels||[],$=this.labels.some((Y)=>Y.name===Q),J=B.includes(Q);return!$&&!J}build(A){let Q=T0.of(A),{app:B,colors:$}=Q,J=this.currentQuery.trim().toLowerCase(),Y=J.length>0?this.getValidationError(J):null,Z=this.getAvailableLabels(),F=[{id:"__create__",name:"__create_placeholder__",createdAt:"",__isCreateMarker:!0},...Z];return new p6({title:"Add Label",items:F,getLabel:(D)=>{if("__isCreateMarker"in D)return this.currentQuery.trim().toLowerCase();return D.name},onAccept:(D)=>{if("__isCreateMarker"in D)this.widget.props.onSelect(this.currentQuery.trim().toLowerCase());else this.widget.props.onSelect(D.name)},onDismiss:this.widget.props.onDismiss,isLoading:this.isLoading,loadingText:"Loading labels...",emptyStateText:Y||"Type to create a new label",renderItem:(D,G,V,U)=>{let K=G?B.selectionBackground:void 0,E=G?B.selectionForeground:$.foreground;if("__isCreateMarker"in D&&D.__isCreateMarker){let H=this.currentQuery.trim().toLowerCase();return new p0({decoration:K?{color:K}:void 0,padding:z0.symmetric(2,0),child:new l({text:new M("",void 0,[new M("Create new label: ",new y({color:E})),new M(H,new y({color:E,bold:!0}))])})})}return new p0({decoration:K?{color:K}:void 0,padding:z0.symmetric(2,0),child:new l({text:new M(D.name,new y({color:E}))})})},filterItem:(D,G)=>{if(this.currentQuery!==G)this.currentQuery=G,setTimeout(()=>this.setState(),0);if("__isCreateMarker"in D&&D.__isCreateMarker)return this.shouldShowCreateMarker(G);let U=G.trim().toLowerCase();return U.length===0||D.name.includes(U)},sortItems:(D,G,V)=>{let U="__isCreateMarker"in D.item&&D.item.__isCreateMarker,K="__isCreateMarker"in G.item&&G.item.__isCreateMarker;if(U&&!K)return-1;if(!U&&K)return 1;return G.score-D.score}})}}class n21 extends v0{props;constructor(A){super();this.props=A}createState(){return new T8A}}class ZG extends v0{props;constructor(A){super();this.props=A}createState(){return new S8A}}class S8A extends k0{_spinner=new z6;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(A){let Q=T0.of(A),{colors:B,app:$}=Q,J=n1.all(new a1(B.foreground,1,"solid")),Y=this._spinner.toBraille(),Z=new l({textAlign:"center",text:new M("",void 0,[new M(Y,new y({color:$.processing})),new M(" ",void 0),new M(this.widget.props.message,new y({color:B.foreground}))])}),F=[new k1({child:new f0({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[Z]})})];if(this.widget.props.onAbort)F.push(new W0({height:2,child:new p0({padding:z0.symmetric(2,0),child:new l({text:new M("",new y({dim:!0}),[new M("Press ",new y({color:B.foreground})),new M("Esc",new y({color:B.info})),new M(" to cancel",new y({color:B.foreground}))])})})}));let D=new p0({decoration:new x4(B.background,J),child:new W0({width:60,height:7,child:new f0({mainAxisAlignment:"start",children:F})})});if(this.widget.props.onAbort)return new c4({debugLabel:"LoadingDialog",child:new m4({debugLabel:"LoadingDialog",autofocus:!0,onKey:(G)=>{if(G.key==="Escape")return this.widget.props.onAbort?.(),"handled";return"ignored"},child:D})});return D}}class FK extends v0{props;constructor(A){super();this.props=A}createState(){return new k8A}}class k8A extends k0{scrollController=new rA;scrollAreaKey=new Y2("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(A){return A instanceof y2}resolveFooterStyle(A){if(this.isWidgetMessage(A))return A.footerStyle;return"default"}getViewportHeight(){let Q=this.scrollAreaKey.currentElement?.renderObject;if(Q&&"size"in Q){let B=Q.size;if(typeof B.height==="number"&&B.height>0)return this.viewportHeight=B.height,B.height}return this.viewportHeight}build(A){let Q=T0.of(A),B=this.widget.props.message,$=(()=>{if(this.isWidgetMessage(B))return{title:B.title,type:B.type};if(B instanceof Error&&B.name==="CommandCancelledError")return{title:"Cancelled",type:"info",description:B.message};if(B instanceof Error&&B.name==="CommandTimeoutError")return{title:"Timeout",type:"error",description:B.message};let G=hG0(B);return{title:G.title,type:G.type,description:G.description}})(),J=$.type==="error"?Q.app.toolError:Q.app.command,Y=n1.all(new a1(Q.colors.border,1,"solid")),Z=new p0({padding:z0.symmetric(1,0),child:new l({text:new M($.title,new y({color:J,bold:!0}))})}),X=this.isWidgetMessage(B)?B.widget:new l({text:new M($.description,new y({color:Q.colors.foreground})),selectable:!0}),F=new k1({child:new J8({child:new p0({padding:z0.symmetric(1,0),child:new Q1({key:this.scrollAreaKey,crossAxisAlignment:"stretch",children:[new k1({child:new PA({controller:this.scrollController,autofocus:!0,child:X})}),new D2({controller:this.scrollController,thumbColor:Q.app.scrollbarThumb,trackColor:Q.app.scrollbarTrack,getScrollInfo:()=>{let G=this.scrollController.maxScrollExtent,V=this.scrollController.offset,U=this.getViewportHeight(),K=G+U;return{totalContentHeight:Math.max(K,0),viewportHeight:Math.max(U,1),scrollOffset:Math.max(V,0)}}})]})})})}),D=new p0({padding:z0.symmetric(1,0),child:new l({text:(()=>{if(this.widget.props.onRetry)return new M("",void 0,[new M("Press ",new y({color:Q.colors.foreground,dim:!0})),new M("R",new y({color:Q.app.keybind})),new M(" to retry, ",new y({color:Q.colors.foreground,dim:!0})),new M("Esc",new y({color:Q.app.keybind})),new M(" to cancel",new y({color:Q.colors.foreground,dim:!0}))]);let G=this.resolveFooterStyle(this.widget.props.message);if(G==="none")return new M("",new y({color:Q.colors.foreground,dim:!0}));if(G==="help"){let V=new y({color:Q.app.keybind}),U=new y({color:Q.colors.foreground,dim:!0});return new M("",U,[new M("Press ",U),new M("Escape",V),new M(" to close • Use ",U),new M("↑↓",V),new M(" or ",U),new M("j/k",V),new M(" to scroll",U)])}return new M("Press any key to close",new y({color:Q.colors.foreground,dim:!0,italic:!0}))})()})});return new c4({debugLabel:"MessageDialog",child:new t4({fit:"expand",children:[new f1({onClick:()=>{},child:new W0}),new m4({onKey:(G)=>{if(this.widget.props.onRetry&&G.key==="r")return this.widget.props.onRetry(),"handled";if(G.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 p0({decoration:{border:Y,color:Q.colors.background},padding:z0.all(1),child:new f0({mainAxisAlignment:"center",children:[Z,new W0({height:1}),F,D]})})})]})})}}M3();class v8A extends v0{props;constructor(A){super();this.props=A}createState(){return new y8A}}class y8A extends k0{plugins=[];subscription=null;initState(){this.subscription=this.widget.props.pluginService.plugins.subscribe((A)=>{this.plugins=A,this.setState(()=>{})})}dispose(){this.subscription?.unsubscribe(),super.dispose()}getRelativePath(A){let Q=A.startsWith("file://")?A.slice(7):A,B=this.widget.props.cwd;if(Q.startsWith(B))return Q.slice(B.length+1);return Q}statusIcon(A){let Q=g8.default(),{colors:B,app:$}=Q;switch(A){case"loading":return{icon:"◌",color:B.warning};case"active":return{icon:"✓",color:$.toolSuccess};case"error":return{icon:"✗",color:$.toolError}}}build(A){let Q=T0.of(A),{app:B}=Q;if(this.plugins.length===0)return new l({text:new M("No plugins found.",new y({dim:!0}))});let $=[],J=this.plugins.length,Y=this.plugins.filter((F)=>F.status==="active").length,Z=this.plugins.reduce((F,D)=>F+D.registeredCommands.length,0),X=this.plugins.reduce((F,D)=>F+D.registeredTools.length,0);if($.push(new M(`${Y}/${J} ${H4(J,"plugin")} active`,new y({bold:!0}))),Z>0||X>0)$.push(new M(` (${Z} ${H4(Z,"command")}, ${X} ${H4(X,"tool")})`,new y({dim:!0})));$.push(new M(`
7103
7103
 
7104
7104
  `));for(let F of this.plugins){let{icon:D,color:G}=this.statusIcon(F.status),V=this.getRelativePath(F.uri.toString());if($.push(new M(`${D} `,new y({color:G}))),$.push(new M(V,new y({bold:!0}))),$.push(new M(` ${F.status}`,new y({dim:!0}))),$.push(new M(`
7105
7105
  `)),F.status==="active"&&F.registeredEvents.length>0)$.push(new M(" Events: ",new y({dim:!0}))),$.push(new M(F.registeredEvents.join(", "),new y({color:B.link}))),$.push(new M(`
@@ -7277,7 +7277,7 @@ ${s.content||""}`:s.content||"",x0=[],A1=s.baseDir.startsWith("file://")?UE0(s.b
7277
7277
  `)}function E7A(A,Q){A.command("usage").description("Show your current Amp usage and credit balance").action(async(B,$)=>{let J=$.optsWithGlobals(),Y=await Q(J),Z=await Y.settings.get("proxy"),X=u44({settings:{url:Y.ampURL,proxy:Z},secrets:{getToken:(D,G)=>Y.secrets.get(D,G)}}),F=await YA.userDisplayBalanceInfo({},{config:X});if(!F.ok){if(F.error.code==="auth-required")process.stderr.write(o0.red("Error: ")+"You must be logged in to view usage. Run `amp login` first.\n"),process.exit(1);process.stderr.write(o0.red("Error: ")+F.error.message+`
7278
7278
  `),process.exit(1)}process.stdout.write(await B93(F.result.displayText)+`
7279
7279
  `),process.exit(0)})}var L$3=me.join(lZ,"logs","headless.log"),rQ1=me.join(Kf,"device-id.json"),O$3=`cli-tui-${m$A(16).toString("hex")}`;async function j$3(){for(let A of AL)try{if((await A.listConfigs()).length>0)return A}catch(Q){j.debug("Failed to detect query-based IDE integration",{ideName:A.ideName,error:Q})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => I4(zu(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(A){fJ.write(`Failed to change directory to ${process.env.AMP_PWD}: ${A}
7280
- `)}function R$3(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function h2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",T$3(Q.model))}function x$A(A){let Q=A.indexOf(":");if(Q===-1)throw new X4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new X4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function P$3(A){if(A===void 0)return;let Q=A.trim();if(O44(Q))return Q;throw new X4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function _$3(A,Q){if(lF(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new X4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function T$3(A){if(!A.includes("="))return x$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new X4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new X4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new X4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);x$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new X4("No valid model overrides found in --model flag value.",1);return Q}function S$3(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function k$3(A){try{return await p$A(A,"utf-8")}catch{return A}}async function sQ1(A,Q,B){let $=S$3(A,Q);if(!$)return;let J=fA(B)?B.features:[],Y=fA(B)?B.user.email:void 0;if(!JW0(J,OB.HARNESS_SYSTEM_PROMPT)&&!(Y&&k7(Y)))throw new X4("You are not allowed to do this.",1);FY("systemPrompt",await k$3($))}function JW0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function v$3(A){return A!=="pending"}function VP(A){if(!fA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function y$3(A){let Q=VP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function x$3(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function f$3(A){let $=x$3(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new X4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function pe(A,Q){let B=Te0(Error(A.error.message));if(B.message===G7.networkOffline||B.message===G7.networkTimeout)return f$3(Q);if(B.message!==G7.internalBug)return new X4(B.message,1,B.suggestion);return new X4(A.error.message.replace(/^Error: /,""),1)}var f$A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??oX,description:`Custom settings file path (overrides the default location ${oX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Qr})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:X9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:tM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],b$A=(A)=>("deprecated"in A)&&A.deprecated===!0,b$3=(A)=>("hidden"in A)&&A.hidden===!0,u$3=(A)=>("default"in A),h$3=(A)=>("default"in A)?A.default:void 0;function QW0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=P$3(Q.effort);if(B!==void 0)_$3(Q.mode,B);return B}function g$3(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new X4(G7.unknownCommand(B),1,Z)}}async function YW0(A){return{...A,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>VD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new fL(A.fileSystem),generateThreadTitle:fD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>LQ(A.configService),pluginService:A.pluginService}}function d$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>VD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var BW0=t0.file(M$3.homedir()),tQ1=process.env.XDG_CONFIG_HOME?t0.file(process.env.XDG_CONFIG_HOME):K1.joinPath(BW0,".config");function m$3(A){return GT4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(ZD0())XD0();else eZ0(Q);let B=XR(),$=Ys();if((!B||$||zf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(iD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(iD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(XR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function d8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;H44("0.0.1778070211-gdd8fb4");let Y=R80({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(t0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:BW0,userConfigDir:tQ1});k6A(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let g=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(g),j.info("API key lookup before login",{found:Boolean(g),ampURL:A.ampURL,deferAuth:$}),!g)if($)j.info("No API key found, continuing startup with deferred auth");else{D5.write(`No API key found. Starting login flow...
7280
+ `)}function R$3(A){process.emitWarning=(Q,B,$,J)=>{let Y=typeof Q==="string"?Q:Q.message||String(Q),Z=B||"Warning",X=!1;A.warn(Y,{name:Z,code:$})}}function h2(A,Q){if(A.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")FY("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(A.getOptionValueSourceWithGlobals("mode")==="cli")FY("experimental.agentMode",Q.mode);if(A.getOptionValueSourceWithGlobals("model")==="cli"&&Q.model)FY("internal.model",T$3(Q.model))}function x$A(A){let Q=A.indexOf(":");if(Q===-1)throw new X4(`Invalid model format "${A}". Expected "provider:model" (e.g., "anthropic:claude-sonnet-4-20250514").`,1);let B=A.slice(0,Q).trim(),$=A.slice(Q+1).trim();if(!B||!$)throw new X4(`Invalid model format "${A}". Both provider and model must be non-empty (e.g., "anthropic:claude-sonnet-4-20250514").`,1)}function P$3(A){if(A===void 0)return;let Q=A.trim();if(O44(Q))return Q;throw new X4(`Invalid effort "${A}". Expected one of: none, minimal, low, medium, high, xhigh, max.`,1)}function _$3(A,Q){if(lF(A,Q))return;let B=d$(A)?.levels,$=B?` Allowed for ${A}: ${B.join(", ")}.`:"";throw new X4(`Reasoning effort "${Q}" is not available for ${A} mode.${$}`,1)}function T$3(A){if(!A.includes("="))return x$A(A),A;let Q={};for(let B of A.split(",")){let $=B.trim();if(!$)continue;let J=$.indexOf("=");if(J===-1)throw new X4(`Invalid mode-specific model entry "${$}". Expected "mode=provider:model" (e.g., "smart=anthropic:claude-sonnet-4-20250514").`,1);let Y=$.slice(0,J).trim(),Z=$.slice(J+1).trim();if(!Y)throw new X4(`Missing mode name in "${$}". Expected "mode=provider:model".`,1);if(!Z)throw new X4(`Missing model value for mode "${Y}". Expected "${Y}=provider:model".`,1);x$A(Z),Q[Y]=Z}if(Object.keys(Q).length===0)throw new X4("No valid model overrides found in --model flag value.",1);return Q}function S$3(A,Q){if(A.getOptionValueSourceWithGlobals("sp")==="cli"&&Q.sp)return Q.sp;if(A.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Q.systemPrompt)return Q.systemPrompt;return}async function k$3(A){try{return await p$A(A,"utf-8")}catch{return A}}async function sQ1(A,Q,B){let $=S$3(A,Q);if(!$)return;let J=fA(B)?B.features:[],Y=fA(B)?B.user.email:void 0;if(!JW0(J,OB.HARNESS_SYSTEM_PROMPT)&&!(Y&&k7(Y)))throw new X4("You are not allowed to do this.",1);FY("systemPrompt",await k$3($))}function JW0(A,Q){return A?.some((B)=>B.name===Q&&B.enabled)??!1}function v$3(A){return A!=="pending"}function VP(A){if(!fA(A))return null;return{...A.user,features:A.features??[],team:A.workspace??void 0}}function y$3(A){let Q=VP(A);if(Q)return Q.id;if(cF(A))throw Error(A.error.message);throw Error("unreachable")}function x$3(A){try{let Q=new URL(A);return Q.hostname==="localhost"||Q.hostname==="127.0.0.1"}catch{return A.includes("localhost")||A.includes("127.0.0.1")}}function f$3(A){let $=x$3(A)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new X4(`Couldn't connect to the Amp server at ${A}.`,1,$)}function pe(A,Q){let B=Te0(Error(A.error.message));if(B.message===G7.networkOffline||B.message===G7.networkTimeout)return f$3(Q);if(B.message!==G7.internalBug)return new X4(B.message,1,B.suggestion);return new X4(A.error.message.replace(/^Error: /,""),1)}var f$A=[{name:"notifications",long:"notifications",type:"flag",description:(A)=>`${A?"Enable":"Disable"} notification alerts (audio locally, terminal bell over SSH; enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(A)=>`${A?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??oX,description:`Custom settings file path (overrides the default location ${oX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(j).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Qr})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","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:X9(),description:(A)=>A?"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:(A)=>A?"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:(A)=>A?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:tM.SMART.key,description:`Set the agent mode (${m$({}).map((A)=>A.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:Array.from(new Set(m$().map((A)=>A.mode))),hiddenChoices:["frontier"]},{name:"effort",long:"effort",type:"option",description:"Set reasoning effort for the new thread, when supported by the selected mode",choices:["none","minimal","low","medium","high","xhigh","max"]},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable thread-actors mode and use the legacy worker runtime",hidden:!0},{name:"neoOrb",long:"neo-orb",type:"switch",description:"Use the experimental Neo splash orb",hidden:!0},{name:"showWelcome",long:"show-welcome",type:"switch",description:"Show the welcome experience on startup",hidden:!0},{name:"observe",long:"observe",type:"option",description:"Open the Neo TUI as an observer of an existing thread (thread ID or URL)",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless thread-actor executor (no TUI). Optionally provide a thread ID to connect to existing thread, otherwise create one.",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0},{name:"model",long:"model",type:"option",description:'Override the model. Use "provider:model" for all modes, or "mode=provider:model,mode=provider:model" for mode-specific overrides',hidden:!0}],b$A=(A)=>("deprecated"in A)&&A.deprecated===!0,b$3=(A)=>("hidden"in A)&&A.hidden===!0,u$3=(A)=>("default"in A),h$3=(A)=>("default"in A)?A.default:void 0;function QW0(A,Q){if(A.getOptionValueSourceWithGlobals("effort")!=="cli")return;let B=P$3(Q.effort);if(B!==void 0)_$3(Q.mode,B);return B}function g$3(A,Q){let B=Q.args[0],$=Q.commands.map((Y)=>Y.name());if(B&&!B.includes(" ")&&B.length<30&&!/[./\\]/.test(B)){let Y=$.filter((X)=>B.includes(X)||X.includes(B)),Z="Run amp --help for a list of available commands.";if(Y.length>0)Z=`Did you mean: ${Y.join(", ")}? Or run amp --help for all commands.`;throw new X4(G7.unknownCommand(B),1,Z)}}async function YW0(A){return{...A,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>VD({filesystem:A.fileSystem},Q,B),osFileSystem:A.fileSystem,skillService:A.skillService,fileChangeTrackerStorage:new fL(A.fileSystem),generateThreadTitle:fD4,deleteThread:(Q)=>A.threadService.delete(Q),getServerStatus:()=>LQ(A.configService),pluginService:A.pluginService}}function d$A(A){return{toolService:A.toolService,configService:A.configService,skillService:A.skillService,getThreadEnvironment:TW,getEnvironmentData:(Q,B)=>VD({filesystem:A.fileSystem},Q,B),filesystem:A.fileSystem,threadService:A.threadService}}var BW0=t0.file(M$3.homedir()),tQ1=process.env.XDG_CONFIG_HOME?t0.file(process.env.XDG_CONFIG_HOME):K1.joinPath(BW0,".config");function m$3(A){return GT4({playNotificationSound:async(Q)=>{if(A.useNotificationsForService){if(ZD0())XD0();else eZ0(Q);let B=XR(),$=Ys();if((!B||$||zf())&&A.config.settings["notifications.system.enabled"]!==!1){if(Q==="idle")process.stdout.write(iD("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Q==="requires-user-input")process.stdout.write(iD("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(XR()),threadService:A.threadService,configService:A.configService,threadViewStates$:A.threadViewStates$})}async function d8(A,Q,B){let $=B?.deferAuth??!1,J=B?.skipToolProviders??!1;H44("0.0.1778070540-gc7ef03");let Y=R80({storage:A.settings,secretStorage:A.secrets,workspaceRoot:m0.of(t0.file(process.cwd())),defaultAmpURL:A.ampURL,homeDir:BW0,userConfigDir:tQ1});k6A(Y);let Z=await Y.getLatest();j.debug("Global configuration initialized",{settingsKeys:Object.keys(Z.settings)});let X=!1;{let g=await A.secrets.get("apiKey",A.ampURL);if(X=Boolean(g),j.info("API key lookup before login",{found:Boolean(g),ampURL:A.ampURL,deferAuth:$}),!g)if($)j.info("No API key found, continuing startup with deferred auth");else{D5.write(`No API key found. Starting login flow...
7281
7281
  `);let n=await p$3(A),c=await A.secrets.get("apiKey",A.ampURL);if(j.info("Login flow completed",{success:n,storedKeyPresent:Boolean(c),ampURL:A.ampURL}),!n)await bW(),process.exit(1);X=!0}}{let g=await Y.getLatest(),n=g.settings.url,c=g.secrets.isSet?.[n];j.info("Config secrets state after login",{configURL:n,apiKeySet:c?.apiKey??!1})}let F=x1(LQ(Y).pipe(E5(v$3))),D=$?"pending":await F;if(!$)j.info("Server status resolved",{status:"ready",isAuthenticated:fA(D),isError:cF(D),errorMessage:cF(D)?D.error.message:void 0});let G=F.then((g)=>y$3(g));G.catch(()=>{return});let U=!Q.takeMeBack&&fA(D)&&JW0(D.features,OB.THREAD_ACTORS_TUI)?"all":process.env.PLUGINS??"permissions",{toolService:K,dispose:E}=YT4({configService:Y}),W=new Map,H=()=>W.clear(),z=new mb0(Y,A.settings.getWorkspaceRootPath()),q=UX4({configService:Y,filesystem:j3}),N=$$4({configService:Y,trustStore:z,skillMCPServers:q.skillMCPServers,createOAuthProvider:async(g,n,c)=>{let $0=`${g}:${n}`,E0=W.get($0);if(E0)return j.debug("Reusing existing OAuth provider for server",{serverName:g,serverUrl:n}),E0;j.debug("Creating OAuth provider for server",{serverName:g,serverUrl:n});let i=(async()=>{let J0=new ZL(A.secrets),Q0=await J0.getClientInfo(g,n),I0=c?.scopes??Q0?.scopes,A0=sp4();j.info("OAuth headless mode check",{useHeadless:A0,executeMode:A.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:D5.isTTY});let D0;if(A0)D0=A.executeMode?rp4():op4(g);let a=new tv0({storage:J0,serverName:g,serverUrl:n,clientId:c?.clientId??Q0?.clientId,clientSecret:c?.clientSecret??Q0?.clientSecret,authUrl:c?.authUrl??Q0?.authUrl,tokenUrl:c?.tokenUrl??Q0?.tokenUrl,scopes:I0,headlessAuthHandler:D0});return j.debug("OAuth provider created",{serverName:g,serverUrl:n,hasManualClientId:!!(c?.clientId??Q0?.clientId),willUseDCR:!(c?.clientId??Q0?.clientId),scopes:I0,headlessMode:A0,executeMode:A.executeMode}),a})();return W.set($0,i),i}}),I=ga0({configService:Y,filesystem:j3,spawn:NZ0}),w=Q.headless?E6A():void 0,C=w??new PU0({configService:Y}),O=C instanceof PU0?C:void 0;if(O)O.pluginExecutorKind="local";let _=Ju0({configService:Y,fileSystem:j3,platform:C,loadGlobalPlugins:x01(Y),pluginFilter:U}),T=QJ4(_),S=[N,I,T],b;if(J)b=new Map;else if(A.executeMode){let g=await xR4({toolService:K,providers:S,initialTimeout:15000});b=g.registrations;for(let[n,c]of g.initErrors)j.warn(`${n} provider initialization slow or failed:`,c)}else b=ma0({toolService:K,providers:S});if(Q.jetbrains)aM("JetBrains");else if(Q.ide&&xd4())aM("VS Code");else if(Q.ide&&fd4())aM("Neovim");else if(Q.ide){let g=await j$3();if(g){let n=b80(g.ideName);if(n)aM(n)}}if(A.executeMode)z44(!0);let h,x=u3.status.pipe(L1((g)=>Boolean(g.connected&&g.authenticated&&g.ideName&&EA4(g.ideName))),P4()).subscribe((g)=>{if(g){if(!h)h=K.registerTool(yR4)}else h?.dispose(),h=void 0}),v;if(!A.executeMode){let g=await A.settings.get("fuzzy.alwaysIncludePaths")??[];v=new $D0(process.cwd(),{alwaysIncludePaths:g},!0)}else v=new class extends $D0{async start(){}async query(){return[]}async queryCompletions(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let u=new $m0(Xi(Y,{usesThreadActors:!1}),{maxThreads:200});j.info("Starting Amp background services");let m=new c81,d={configService:Y,toolService:K,mcpService:N,skillService:q,toolboxService:I,trustStore:z,threadService:u,secretStorage:A.secrets,settingsStorage:A.settings,fuzzyServer:v,fileSystem:j3,terminal:m,pluginService:_,pluginPlatform:O,headlessPluginPlatform:w,serverStatus:D,serverStatusPromise:F,viewerUserIDPromise:G,hasAPIKeyAtStartup:X};return{...d,async asyncDispose(){if(d.mcpService.hasAuthenticatingClients())j.info("Waiting for OAuth authentication to complete before exit..."),await d.mcpService.waitForAuthentication();for(let g of b.values())g.dispose();await d.mcpService.dispose(),H(),await d.threadService.asyncDispose(),d.configService.unsubscribe(),E(),d.fuzzyServer.dispose(),d.settingsStorage[Symbol.dispose](),x.unsubscribe(),h?.dispose(),await d.pluginService.dispose()}}}async function p$3(A){if(!A.executeMode){if(!await nD0("Would you like to log in to Amp? [(y)es, (n)o]: "))return D5.write(`Login cancelled. Run the command again to retry.
7282
7282
  `),!1}return await c$A(A)}async function c$A(A){let Q=m$A(32).toString("hex"),B=await Of(A.ampURL,Q),$=new AbortController;try{await hF(B,$.signal)}catch(Y){j.error("Error opening browser",{error:Y})}let J=await Of(A.ampURL,Q,!1);D5.write(`If your browser does not open automatically, visit:
7283
7283
 
@@ -7285,7 +7285,7 @@ ${o0.blue.bold(J)}
7285
7285
 
7286
7286
  `);try{return await el4(A.ampURL,Q,A.secrets,$),D5.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(Y){return j.error("Login failed",{error:Y}),fJ.write(`
7287
7287
  Login failed: ${Y instanceof Error?Y.message:String(Y)}
7288
- `),!1}}async function d$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new X4("No Amp API key found. Run `amp login` first.",1);let J=I$3("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(X)=>Y(X??1))})}function c$3(A){let Q=new rN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)hj(),process.exit(0);let z=H.originalError??H;dh4(z)}),Zn4(Q,{version:"0.0.1778070211-gdd8fb4",buildTimestamp:"2026-05-06T12:27:20.020Z",buildType:"'release'"}),Q.addHelpText("after",kd4()),Q.configureHelp({formatHelp:vd4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let q=z.optsWithGlobals(),N=await l5(q);await e$3(N)}),Q.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 q=z.optsWithGlobals(),N=await l5(q);await t$3(N,await n01(q,N.settings))}),gh4(Q,l5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let z=H.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=H.filter((w)=>w!==z).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=z.optsWithGlobals(),I=await l5(N);await d$3(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,z,q)=>{let N=q.optsWithGlobals(),I=await l5(N);await mp4(H??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,z)=>{let q=z.optsWithGlobals(),N=await l5(q);await pp4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await tc4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7288
+ `),!1}}async function d$3(A,Q,B){let $=await Q.get("apiKey",A);if(!$)throw new X4("No Amp API key found. Run `amp login` first.",1);let J=I$3("curl",["-H",`Authorization: Bearer ${$}`,...B],{stdio:"inherit"});process.exitCode=await new Promise((Y,Z)=>{J.on("error",Z),J.on("close",(X)=>Y(X??1))})}function c$3(A){let Q=new rN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Q.exitOverride((H)=>{if(H.code==="commander.help"||H.code==="commander.version"||H.exitCode===0)hj(),process.exit(0);let z=H.originalError??H;dh4(z)}),Zn4(Q,{version:"0.0.1778070540-gc7ef03",buildTimestamp:"2026-05-06T12:32:43.933Z",buildType:"'release'"}),Q.addHelpText("after",kd4()),Q.configureHelp({formatHelp:vd4}),Q.command("logout").description("Log out by removing stored API key").action(async(H,z)=>{let q=z.optsWithGlobals(),N=await l5(q);await e$3(N)}),Q.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 q=z.optsWithGlobals(),N=await l5(q);await t$3(N,await n01(q,N.settings))}),gh4(Q,l5);let $=Q.command("internal",{hidden:!0}).description("Internal commands").command("curl [args...]").description("Internal: run curl with the current Amp API key as a bearer token").allowUnknownOption(!0).allowExcessArguments(!0).action(async(...H)=>{let z=H.find((w)=>typeof w==="object"&&w!==null&&typeof w.optsWithGlobals==="function")??$,q=H.filter((w)=>w!==z).flatMap((w)=>Array.isArray(w)?w:typeof w==="string"?[w]:[]),N=z.optsWithGlobals(),I=await l5(N);await d$3(I.ampURL,I.secrets,q),process.exit(process.exitCode??0)});Q.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(H,z,q)=>{let N=q.optsWithGlobals(),I=await l5(N);await mp4(H??"get",I.ampURL,I.secrets),process.exit(process.exitCode??0)}),Q.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(H,z)=>{let q=z.optsWithGlobals(),N=await l5(q);await pp4(N.ampURL,N.secrets),process.exit(process.exitCode??0)}),Q.command("keyboard-tester",{hidden:!0}).summary("Keyboard input tester").description("Internal: stream parsed terminal input events as JSONL.").option("--raw","Log raw incoming terminal bytes before parsing").action(async(H)=>{await tc4({raw:H.raw===!0}),process.exit(process.exitCode??0)}),Q.command("live-sync [threadIDOrURL]",{hidden:!0}).summary("Mirror live DTW thread changes into the current checkout").description("Experimental: watch a v2 thread URL or ID and mirror its live working-tree changes into your local checkout, or apply the current snapshot once and exit.").addHelpText("after",["","Examples:"," amp live-sync T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync --apply T-5928a90d-d53b-488f-a829-4e36442142ee"," amp live-sync https://ampcode.com/threads/T-5928a90d-d53b-488f-a829-4e36442142ee"].join(`
7289
7289
  `)).option("--apply <threadIDOrURL>","Apply the current DTW thread snapshot once and exit").option("--checkout","Automatically check out the thread commit when it differs").option("--skip-checkout","Skip the startup checkout prompt when commits differ").action(async(H,z,q)=>{if(H&&z.apply)throw new X4("Choose either a positional thread ID/URL or --apply <thread-id>, not both.",1);let N=z.apply??H;if(!N||N.trim().length===0)D5.write(`live-sync watches a v2 thread and mirrors its live changes locally. Use --apply <thread-id> to materialize the current snapshot once and exit.
7290
7290
 
7291
7291
  `),q.outputHelp(),process.exit(0);let I=w2(N)??qJ(N),w=q.optsWithGlobals(),C=await l5(w);h2(q,w);let O=await d8(C,w),_=!1;try{if(z.checkout&&z.skipCheckout)throw new X4("Choose either --checkout or --skip-checkout, not both.",1);if(cF(O.serverStatus))throw pe(O.serverStatus,C.ampURL);let T=fA(O.serverStatus)?O.serverStatus.features:void 0;if(!JW0(T,OB.V2))throw new X4("live-sync is not enabled for your user",1);await pl4({ampURL:C.ampURL,threadId:I,configService:O.configService,threadService:O.threadService,apiKey:process.env.AMP_API_KEY,applyOnce:typeof z.apply==="string",checkoutMode:z.checkout?"always":z.skipCheckout?"never":"prompt",promptForYesNo:nD0}),_=!0}finally{if(await O.asyncDispose(),_)process.exit(0)}});let J=async(H,z,q)=>{R80({storage:z.settings,secretStorage:z.secrets,workspaceRoot:m0.of(t0.file(process.cwd())),defaultAmpURL:z.ampURL,homeDir:BW0,userConfigDir:tQ1});let N={...z,executeMode:!1};await $W0(N,{...H,openThreadSwitcher:!0},q,A)},Y=Q.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").option("--include-archived","Include archived threads in the list").action(async(H,z)=>{let q=z.optsWithGlobals(),N=await l5(q);await g$A(q,N,z)});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 q=z.optsWithGlobals(),N=await l5(q);await GJ3(q,N,z)}),Y.command("continue [threadIDOrURL]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, interactive mode shows a picker. Use --last to continue the last thread for the current mode directly.").option("--last","Continue the last thread for the current mode directly").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(H,z,q)=>{let N=q.optsWithGlobals(),I=await l5(N);if(z.pick)fJ.write(`${o0.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
@@ -7318,8 +7318,8 @@ ${C}
7318
7318
  `))}),z.args.length>0)g$3(N,z);await $W0(N,q,z,A)}),Ec4(Q),Q}async function qu(A,Q){await CJ((B)=>tD0(B,A,Q))}async function u$A(A,Q,B){let $=Date.now(),[J,Y]=await Promise.all([YA.getThreadLinkInfo({thread:A},{config:Q}),B]);if(j.info(`[fetchAndStartThread] Ownership check in ${Date.now()-$}ms`),J.ok){let Z=J.result.creatorUserID;if(Z&&Z!==Y&&!process.env.AMP_RESUME_OTHER_USER_THREADS_INSECURE)throw new X4(`Cannot resume thread created by another user.
7319
7319
 
7320
7320
  This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function l$A(A){if(A.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof A.execute==="string"){let Q=(await TU0()).trimEnd();return{userInput:A.execute,stdinInput:Q||null}}return{userInput:(await TU0()).trimEnd(),stdinInput:null}}function i$A(A,Q,B){if(A.streamJson&&!Q)throw new X4("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(A.streamJsonInput&&!Q)throw new X4("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(A.streamJsonInput&&!A.streamJson)throw new X4("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(A.stats&&A.streamJson)throw new X4("The --stats and --stream-json flags are mutually exclusive output formats",1,'Use one or the other: amp --execute "your message" --stats OR amp --execute "your message" --stream-json');if(A.stats&&!Q)throw new X4("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(A.archive&&!Q)throw new X4("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(A.streamJsonInput&&typeof A.execute==="string"&&A.execute.trim()!=="")throw new X4("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Q&&B===""&&!A.streamJsonInput&&!A.headless)throw new X4("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"
7321
- Or pipe via stdin: echo "your message" | amp --execute`)}function l$3(A,Q){if(m54([h30.parse({tool:"*",action:"allow"})]),S54({bypass:!0}),H6A(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:h81})}async function $W0(A,Q,B,$){if(Q.headless)return i$3(A,Q,B);let J=await d8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=fA(Y)&&JW0(Y.features,OB.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new X4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return l$3(Z,J.pluginService),n$3(A,Q,B,J);else{if(Q.threadId&&wQ(Q.threadId)){let D=await YA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new X4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return a$3(A,Q,B,$,{dependencies:J})}}async function i$3(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=ps0();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};h2(B,Q);let J=process.hrtime.bigint(),Y=await d8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw pe(Z,A.ampURL);let X=fA(Z)?Z:null,F=X?.user.email;await sQ1(B,Q,Z);let D=VP(Z),G=Us(Q,D);if(G instanceof Error)u5(G.message);if(X&&!SS(Q.mode,F))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!k7(F)))throw new X4("Headless executor mode is only available for Amp employees",1);CF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new X4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!wQ(K))throw new X4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await FJ3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new X4("Failed to resolve headless thread ID",1);let H=await Qd4(W);if(H.status==="already-running")await Y.asyncDispose(),await bW(),process.exit(0);try{await ip4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await H.release(),await Y.asyncDispose()}await bW(),process.exit(0)}async function n$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await l$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;i$A({...Q,streamJson:Z},A.executeMode,J),h2(B,Q),kh4(),CF0();let X=Q.threadId&&wQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?w2(Q.observe)??qJ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw pe(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new X4("API key required. Please run `amp login` first.",1);let V=fA(D)&&k7(D.user.email);if(A.executeMode){o11($.mcpService,A.settings);try{let U=QW0(B,Q),K=await TI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await jf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=await Gp4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:W});if(await qu(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await bW(),process.exit(0)}else{let U=QW0(B,Q),K=Xi($.configService),E=new Je($.fuzzyServer),W=process.cwd();await X6A({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??dX(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:H})=>Bf({fileSystem:$.fileSystem,workspaceRoot:W},H),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(H)=>K.getThread(H),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function a$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(Q0,I0)=>{let A0=Number(process.hrtime.bigint()-I0)/1e6,D0=ps0();j.info("Startup phase",{phase:Q0,phaseMs:Math.round(A0),sinceMainMs:D0===null?void 0:Math.round(D0)})},{userInput:X,stdinInput:F}=await l$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;i$A({...Q,streamJson:D},A.executeMode,X),h2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await d8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&cF(E))throw pe(E,A.ampURL);let W=fA(E)?E:null,H=W?.user.email,z=!!(H&&k7(H));if(z)CF0();if(!K)await sQ1(B,Q,E);let q=VP(E),N=q?.features??[],I=q?.team??null,w=Us(Q,q);if(w instanceof Error)u5(w.message);if(W&&!SS(Q.mode,H))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&wQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await YW0(V);Z("runMainThread:createWorkerDeps",G);let _=A.executeMode?void 0:async(Q0)=>qu(Q0,"interactive"),T={threadService:V.threadService,workerDeps:O,createThread:async(Q0)=>{let I0=K?await V.serverStatusPromise:E,A0=await MF0(A.settings,process.cwd(),VP(I0),w);if(A0 instanceof Error)u5(A0.message);return M71(O,{threadMeta:A0?QZ(A0):void 0,agentMode:Q0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(Q0,I0)=>{if(I0?.nonBlockingOwnershipCheck){u$A(Q0,V.configService,V.viewerUserIDPromise).catch((A0)=>{if(A0 instanceof X4){if(I0.onOwnershipError){I0.onOwnershipError(A0,Q0);return}uW(A0,Q0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})});return}try{await u$A(Q0,V.configService,V.viewerUserIDPromise)}catch(A0){if(A0 instanceof X4)throw A0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:_,handleError:uW},S=async()=>{try{return G7A(T,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(Q0){if(Q0 instanceof X4)throw Q0;throw await uW(Q0,Q.threadId),Error("handleError should have called process.exit()")}},b=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let Q0=await V.configService.getLatest(),I0=qp(Q0),A0=await YA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(I0)});if(A0.ok)return j.info("User free tier status:",A0),A0.result;return}catch(Q0){j.error("Failed to fetch free tier status:",Q0);return}})(),x=!A.executeMode?new o81:null,v,u=null;if(x)v=x,u=(async()=>{let Q0=K?await V.serverStatusPromise:V.serverStatus;if(cF(Q0))throw pe(Q0,A.ampURL);await sQ1(B,Q,Q0);let I0=process.hrtime.bigint(),A0=await S();if(Z("runMainThread:createThreadPool",I0),x.attach(A0),X){let D0=await x1(A0.threadHandles$);if(!D0)throw new X4("No active thread is available yet.",1);await D0.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(Q0)=>{let I0=Q0 instanceof Error?Q0:Error(String(Q0));x.setInitError(I0),await uW(Q0,Q.threadId)});else G=process.hrtime.bigint(),v=await S(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let d=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),m$3({configService:V.configService,threadService:V.threadService,config:d,useNotificationsForService:m,threadViewStates$:()=>v.threadHandles$.pipe(u4((Q0)=>{if(!Q0)return m0.of({});return P6(Q0.thread$,Q0.threadViewState$).pipe(L1(([I0,A0])=>({[I0.id]:A0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){o11(V.mcpService,A.settings);let Q0=QW0(B,Q),I0=await TI(),A0=C?Q0:aD0({agentMode:Q.mode,explicitEffort:Q0,sessionState:I0}),D0={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:A0,labels:Q.label},a=await Gg4({threadPool:v,...D0});if(await qu(a,"execute"),Q.archive)await V.threadService.archive(a,!0);await V.asyncDispose(),process.exit(0)}let g=!1,n=!1;if(Q.jetbrains||Q.ide){await u80();let Q0=await nF({jetbrainsOnly:Q.jetbrains});if(Q0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(Q0.length===1){let I0=Q0[0];if(I0)u3.selectConfig(I0)}else n=!0}G=process.hrtime.bigint();let c=W11("0.0.1778070211-gdd8fb4",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let $0=new r11(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let Q0=await x1(v.threadHandles$);if(!Q0)throw new X4("No active thread is available yet.",1);await Q0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let E0=await TI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",E0);let i=QW0(B,Q),J0={...E0,launchCount:E0.launchCount+1,lastReasoningEffortByMode:i?{...E0.lastReasoningEffortByMode,[Q.mode]:i}:E0.lastReasoningEffortByMode};CJ((Q0)=>({...Q0,launchCount:Q0.launchCount+1}));try{if(G=process.hrtime.bigint(),await O5A({history:new Er,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:YA,threadPool:v,createSystemPromptDeps:async()=>d$A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:$0,updateService:c,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:g,showIdePickerHint:n,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:O$3,logFile:{path:$},sessionState:J0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-06T12:27:20.020Z"},(Q0)=>new Q21({...Q0,threadPool:Q0.threadPool},(I0)=>new w71({...I0,threadState:I0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await v.dispose().catch((Q0)=>{j.error("Failed to dispose thread pool during shutdown",Q0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function l5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7322
- `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await F$4({get:async(X)=>{if(X!==wc)return;try{let F=await p$A(rQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==wc)return;await w$3(me.dirname(rQ1),{recursive:!0}),await C$3(rQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:F70()});q44($);let J=await Ed4({...A,workspaceTrust:{current:!0,changes:oS0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await Di4(A.mcpConfig);J=Gi4(J,X)}let Y=me.dirname(J.getSettingsFilePath());DT4(Kf,Y),J=oe1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=v7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!dz(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:P6A(await n01(A,J))}}function o$3(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function r$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=me.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?L$3:Qr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function s$3(){Ix4();let A=o$3(process.argv),Q=r$3(process.argv,A),B=vh4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(R$3(j),j.info("Starting Amp CLI.",{version:"0.0.1778070211-gdd8fb4",buildTimestamp:"2026-05-06T12:27:20.020Z"}),process.platform==="win32"&&oj())Qc4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new X4(G7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await c$3(B).parseAsync(process.argv)}XT4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await s$3().catch(uW)});async function t$3(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7321
+ Or pipe via stdin: echo "your message" | amp --execute`)}function l$3(A,Q){if(m54([h30.parse({tool:"*",action:"allow"})]),S54({bypass:!0}),H6A(A.settings))j.debug("Enabling permissions plugin"),Q.registerInternalPlugin({name:"permissions",entryPoint:h81})}async function $W0(A,Q,B,$){if(Q.headless)return i$3(A,Q,B);let J=await d8(A,Q),Y=await J.serverStatusPromise,Z=await J.configService.getLatest(),X=fA(Y)&&JW0(Y.features,OB.THREAD_ACTORS_TUI),F=X&&!Q.takeMeBack;if(Q.showWelcome&&!X)throw await J.asyncDispose(),new X4("--show-welcome is only available with the new Amp CLI feature flag",1);if(F)return l$3(Z,J.pluginService),n$3(A,Q,B,J);else{if(Q.threadId&&wQ(Q.threadId)){let D=await YA.getThreadLinkInfo({thread:Q.threadId},{config:J.configService}).catch(()=>null);if(D?.ok&&D.result.usesThreadActors)throw await J.asyncDispose(),new X4(`Thread ${Q.threadId} was created with the Neo TUI and cannot be continued in the legacy CLI.`,1,"Re-run without --take-me-back to continue this thread.")}return a$3(A,Q,B,$,{dependencies:J})}}async function i$3(A,Q,B){let $=(z,q)=>{let N=Number(process.hrtime.bigint()-q)/1e6,I=ps0();j.info("Startup phase",{phase:z,phaseMs:Math.round(N),sinceMainMs:I===null?void 0:Math.round(I)})};h2(B,Q);let J=process.hrtime.bigint(),Y=await d8(A,Q);$("runMainThread:createThreadDependencies",J);let{serverStatus:Z}=Y;if(cF(Z))throw pe(Z,A.ampURL);let X=fA(Z)?Z:null,F=X?.user.email;await sQ1(B,Q,Z);let D=VP(Z),G=Us(Q,D);if(G instanceof Error)u5(G.message);if(X&&!SS(Q.mode,F))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);if(process.env.AMP_EXECUTOR!=="1"&&(!F||!k7(F)))throw new X4("Headless executor mode is only available for Amp employees",1);CF0();let U=await Y.secretStorage.get("apiKey",A.ampURL);if(!U)throw new X4("API key required for headless mode. Please run `amp login` first.",1);let K=typeof Q.headless==="string"&&Q.headless!=="true"?Q.headless:void 0;if(K&&!wQ(K))throw new X4(`Invalid thread ID: ${K}`,1);let E=K?void 0:await FJ3({dependencies:Y,apiKey:U,visibility:G??void 0}),W=K??E?.threadId;if(!W)throw new X4("Failed to resolve headless thread ID",1);let H=await Qd4(W);if(H.status==="already-running")await Y.asyncDispose(),await bW(),process.exit(0);try{await ip4({ampURL:A.ampURL,apiKey:U,workspaceRoot:process.cwd(),threadId:W,ownerUserId:E?.ownerUserId,threadVersion:E?.threadVersion,agentMode:E?.agentMode,initialToolDiscovery:Promise.all([Y.mcpService.initialized,Y.toolboxService.initialized,Y.pluginService.initialized]).then(()=>{return}),configService:Y.configService,mcpService:Y.mcpService,toolService:Y.toolService,skillService:Y.skillService,fileSystem:Y.fileSystem,pluginService:Y.pluginService,pluginPlatform:Y.headlessPluginPlatform})}finally{await H.release(),await Y.asyncDispose()}await bW(),process.exit(0)}async function n$3(A,Q,B,$){let{userInput:J,stdinInput:Y}=await l$A(Q),Z=!!Q.streamJson||!!Q.streamJsonThinking;i$A({...Q,streamJson:Z},A.executeMode,J),h2(B,Q),kh4(),CF0();let X=Q.threadId&&wQ(Q.threadId)?Q.threadId:void 0,F=Q.observe?w2(Q.observe)??qJ(Q.observe):void 0,D=await $.serverStatusPromise;if(cF(D))throw pe(D,A.ampURL);let G=await $.secretStorage.get("apiKey",A.ampURL);if(!G)throw new X4("API key required. Please run `amp login` first.",1);let V=fA(D)&&k7(D.user.email);if(A.executeMode){o11($.mcpService,A.settings);try{let U=QW0(B,Q),K=await TI(),E=X?U:aD0({agentMode:Q.mode,explicitEffort:U,sessionState:K}),W=X?void 0:oD0(await jf($.configService),{agentMode:Q.mode,explicitEffort:U,sessionState:K}),H=await Gp4({apiKey:G,ampURL:A.ampURL,workspaceRoot:process.cwd(),dependencies:$,userInput:J,stdinInput:Y,stats:!!Q.stats,streamJson:Z,streamJsonThinking:!!Q.streamJsonThinking,streamJsonInput:!!Q.streamJsonInput,stdin:process.stdin,agentMode:Q.mode,reasoningEffort:E,labels:Q.label,initialThreadID:X,initialSettings:W});if(await qu(H,"execute"),Q.archive)await $.threadService.archive(H,!0)}finally{await $.asyncDispose()}await bW(),process.exit(0)}else{let U=QW0(B,Q),K=Xi($.configService),E=new Je($.fuzzyServer),W=process.cwd();await X6A({ampURL:A.ampURL,apiKey:G,rivetEndpoint:process.env.RIVET_PUBLIC_ENDPOINT??dX(A.ampURL),configService:$.configService,toolService:$.toolService,pluginPlatform:$.pluginPlatform,pluginService:$.pluginService,skillService:$.skillService,mcpService:$.mcpService,readFileSystemDirectory:({uri:H})=>Bf({fileSystem:$.fileSystem,workspaceRoot:W},H),completionBuilder:E,workspaceRoot:W,listThreads:()=>K.listThreads(),getThreadFromServer:(H)=>K.getThread(H),toolboxes:$.toolboxService.toolboxes,isInternalUser:V,settingsFilePath:$.settingsStorage.getSettingsFilePath()},{initialThreadID:F??X,initialUserInput:J||void 0,openThreadPickerOnStart:Q.openThreadSwitcher,observerOnly:!!F,splashOrbVisualStyle:"neo",showNeoWelcome:Q.showWelcome,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,initialReasoningEffort:U}),process.exit(0)}}async function a$3(A,Q,B,$,J){let Y=process.hrtime.bigint(),Z=(Q0,I0)=>{let A0=Number(process.hrtime.bigint()-I0)/1e6,D0=ps0();j.info("Startup phase",{phase:Q0,phaseMs:Math.round(A0),sinceMainMs:D0===null?void 0:Math.round(D0)})},{userInput:X,stdinInput:F}=await l$A(Q),D=!!Q.streamJson||!!Q.streamJsonThinking;i$A({...Q,streamJson:D},A.executeMode,X),h2(B,Q);let G=process.hrtime.bigint(),V=J?.dependencies??await d8(A,Q),U=V.hasAPIKeyAtStartup,K=V.serverStatus==="pending";if(j.info("Interactive auth startup mode",{deferInteractiveAuth:K,hasAPIKeyAtStartup:U,executeMode:A.executeMode,headless:Boolean(Q.headless)}),!J)Z("runMainThread:createThreadDependencies",G);let{serverStatus:E}=V;if(!K&&cF(E))throw pe(E,A.ampURL);let W=fA(E)?E:null,H=W?.user.email,z=!!(H&&k7(H));if(z)CF0();if(!K)await sQ1(B,Q,E);let q=VP(E),N=q?.features??[],I=q?.team??null,w=Us(Q,q);if(w instanceof Error)u5(w.message);if(W&&!SS(Q.mode,H))throw new X4(`Agent mode '${Q.mode}' is only available for Amp employees`,1);let C=Q.threadId&&wQ(Q.threadId)?Q.threadId:void 0;G=process.hrtime.bigint();let O=await YW0(V);Z("runMainThread:createWorkerDeps",G);let _=A.executeMode?void 0:async(Q0)=>qu(Q0,"interactive"),T={threadService:V.threadService,workerDeps:O,createThread:async(Q0)=>{let I0=K?await V.serverStatusPromise:E,A0=await MF0(A.settings,process.cwd(),VP(I0),w);if(A0 instanceof Error)u5(A0.message);return M71(O,{threadMeta:A0?QZ(A0):void 0,agentMode:Q0??Q.mode,onFirstAssistantMessage:_})},validateThreadOwnership:async(Q0,I0)=>{if(I0?.nonBlockingOwnershipCheck){u$A(Q0,V.configService,V.viewerUserIDPromise).catch((A0)=>{if(A0 instanceof X4){if(I0.onOwnershipError){I0.onOwnershipError(A0,Q0);return}uW(A0,Q0);return}j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})});return}try{await u$A(Q0,V.configService,V.viewerUserIDPromise)}catch(A0){if(A0 instanceof X4)throw A0;j.warn("Failed to validate thread ownership in CLI, allowing to open",{error:A0})}},switchThreadVisibility:w,switchThreadAgentMode:Q.mode,onFirstAssistantMessage:_,handleError:uW},S=async()=>{try{return G7A(T,Q.threadId,{nonBlockingOwnershipCheck:Q.nonBlockingThreadOwnershipCheck})}catch(Q0){if(Q0 instanceof X4)throw Q0;throw await uW(Q0,Q.threadId),Error("handleError should have called process.exit()")}},b=(async()=>{if(K){j.info("Skipping initial free tier status fetch until auth is complete");return}try{let Q0=await V.configService.getLatest(),I0=qp(Q0),A0=await YA.getUserFreeTierStatus({},{config:V.configService,signal:AbortSignal.timeout(I0)});if(A0.ok)return j.info("User free tier status:",A0),A0.result;return}catch(Q0){j.error("Failed to fetch free tier status:",Q0);return}})(),x=!A.executeMode?new o81:null,v,u=null;if(x)v=x,u=(async()=>{let Q0=K?await V.serverStatusPromise:V.serverStatus;if(cF(Q0))throw pe(Q0,A.ampURL);await sQ1(B,Q,Q0);let I0=process.hrtime.bigint(),A0=await S();if(Z("runMainThread:createThreadPool",I0),x.attach(A0),X){let D0=await x1(A0.threadHandles$);if(!D0)throw new X4("No active thread is available yet.",1);await D0.sendMessage({content:[{type:"text",text:X}]})}})(),u.catch(async(Q0)=>{let I0=Q0 instanceof Error?Q0:Error(String(Q0));x.setInitError(I0),await uW(Q0,Q.threadId)});else G=process.hrtime.bigint(),v=await S(),Z("runMainThread:createThreadPool",G);let m=Q.notifications!==void 0?Q.notifications:!A.executeMode;G=process.hrtime.bigint();let d=await V.configService.getLatest();if(Z("runMainThread:configService.getLatest",G),G=process.hrtime.bigint(),m$3({configService:V.configService,threadService:V.threadService,config:d,useNotificationsForService:m,threadViewStates$:()=>v.threadHandles$.pipe(u4((Q0)=>{if(!Q0)return m0.of({});return P6(Q0.thread$,Q0.threadViewState$).pipe(L1(([I0,A0])=>({[I0.id]:A0})))}))}),Z("runMainThread:createCliNotificationService",G),A.executeMode){o11(V.mcpService,A.settings);let Q0=QW0(B,Q),I0=await TI(),A0=C?Q0:aD0({agentMode:Q.mode,explicitEffort:Q0,sessionState:I0}),D0={userInput:X,stdinInput:F,dependencies:V,streamJson:D,streamJsonInput:!!Q.streamJsonInput,streamJsonThinking:!!Q.streamJsonThinking,stats:!!Q.stats,ampURL:A.ampURL,isInternalUser:z,agentMode:Q.mode,reasoningEffort:A0,labels:Q.label},a=await Gg4({threadPool:v,...D0});if(await qu(a,"execute"),Q.archive)await V.threadService.archive(a,!0);await V.asyncDispose(),process.exit(0)}let g=!1,n=!1;if(Q.jetbrains||Q.ide){await u80();let Q0=await nF({jetbrainsOnly:Q.jetbrains});if(Q0.length===0){if(Q.jetbrains)g=!await V.configService.get("jetbrains.skipInstall")}else if(Q0.length===1){let I0=Q0[0];if(I0)u3.selectConfig(I0)}else n=!0}G=process.hrtime.bigint();let c=W11("0.0.1778070540-gc7ef03",V.settingsStorage,{startDelayMs:3000});Z("runMainThread:createUpdateService",G),G=process.hrtime.bigint();let $0=new r11(V.mcpService,A.settings.getWorkspaceRootPath());if(Z("runMainThread:createMcpTrustHandler",G),X&&A.executeMode){let Q0=await x1(v.threadHandles$);if(!Q0)throw new X4("No active thread is available yet.",1);await Q0.sendMessage({content:[{type:"text",text:X}]})}G=process.hrtime.bigint();let E0=await TI();Z("runMainThread:loadSessionState",G),j.info("Loaded session state:",E0);let i=QW0(B,Q),J0={...E0,launchCount:E0.launchCount+1,lastReasoningEffortByMode:i?{...E0.lastReasoningEffortByMode,[Q.mode]:i}:E0.lastReasoningEffortByMode};CJ((Q0)=>({...Q0,launchCount:Q0.launchCount+1}));try{if(G=process.hrtime.bigint(),await O5A({history:new Er,fuzzyServer:V.fuzzyServer,settingsStorage:V.settingsStorage,threadService:V.threadService,skillService:V.skillService,configService:V.configService,secretStorage:V.secretStorage,internalAPIClient:YA,threadPool:v,createSystemPromptDeps:async()=>d$A(V),ideClient:u3,mcpService:V.mcpService,toolboxService:V.toolboxService,mcpTrustHandler:$0,updateService:c,pluginPlatform:V.pluginPlatform,pluginService:V.pluginService},{initialServerStatus:V.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:V.hasAPIKeyAtStartup,ampURL:A.ampURL,startupThreadID:C,showJetBrainsInstaller:g,showIdePickerHint:n,openThreadSwitcher:Q.openThreadSwitcher,jetbrainsMode:Q.jetbrains,clientId:O$3,logFile:{path:$},sessionState:J0,freeTierStatusPromise:b,workspace:I??null,features:N,isInternalUser:z,initialAgentMode:B.getOptionValueSourceWithGlobals("mode")==="cli"?Q.mode:void 0,splashOrbVisualStyle:Q.neoOrb?"neo":"classic",buildTimestamp:"2026-05-06T12:32:43.933Z"},(Q0)=>new Q21({...Q0,threadPool:Q0.threadPool},(I0)=>new w71({...I0,threadState:I0.threadState}))),Z("runMainThread:mountApp-returned",G),u)await u}finally{await v.dispose().catch((Q0)=>{j.error("Failed to dispose thread pool during shutdown",Q0)})}await V.asyncDispose(),Z("runMainThread:dependencies.asyncDispose",Y),process.exit(0)}async function l5(A){if(j.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),A.interactive)fJ.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
7322
+ `);let Q=!!A.execute||!process.stdout.isTTY&&!A.streamJson,B=process.stdout.isTTY&&process.stderr.isTTY;j.info("Execution mode resolved",{executeMode:Q,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:A.streamJson,executeFlag:A.execute});let $=await F$4({get:async(X)=>{if(X!==wc)return;try{let F=await p$A(rQ1,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(X,F)=>{if(X!==wc)return;await w$3(me.dirname(rQ1),{recursive:!0}),await C$3(rQ1,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:F70()});q44($);let J=await Ed4({...A,workspaceTrust:{current:!0,changes:oS0},getHook:process.env.AMP_URL?(X,F)=>{if(X==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(A.mcpConfig){let X=await Di4(A.mcpConfig);J=Gi4(J,X)}let Y=me.dirname(J.getSettingsFilePath());DT4(Kf,Y),J=oe1(J);let Z=await J.get("url","admin")??await J.get("url","global");if(!Z)Z=v7;if(j.info("Resolved Amp URL",{ampURL:Z,settingsFile:J.getSettingsFilePath(),workspaceRoot:J.getWorkspaceRootPath()}),!dz(Z))j.info("Targeting custom Amp server",{ampURL:Z});return{executeMode:Q,isTTY:B,ampURL:Z,settings:J,secrets:P6A(await n01(A,J))}}function o$3(A){let Q={};for(let B=0;B<A.length;B++){let $=A[B];if($?.startsWith("--")){let Y=$.slice(2).replace(/-([a-z])/g,(X,F)=>F.toUpperCase()),Z=A[B+1];if(Z&&!Z.startsWith("--"))Q[Y]=Z,B++}}return Q}function r$3(A,Q){let B=A.includes("--headless")||A.some((J)=>J.startsWith("--headless=")),$=me.resolve(Q.logFile??process.env.AMP_LOG_FILE??(B?L$3:Qr));return{logLevel:Q.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:$}}async function s$3(){Ix4();let A=o$3(process.argv),Q=r$3(process.argv,A),B=vh4(Q),$=process.argv.includes("--no-color"),J=process.argv.includes("--color"),Y=process.stdout.isTTY&&process.stderr.isTTY;if($||!J&&!Y)o0.level=0;if(R$3(j),j.info("Starting Amp CLI.",{version:"0.0.1778070540-gc7ef03",buildTimestamp:"2026-05-06T12:32:43.933Z"}),process.platform==="win32"&&oj())Qc4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new X4(G7.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await c$3(B).parseAsync(process.argv)}XT4().startActiveSpan("main",async(A)=>{process.on("exit",()=>A.end()),await s$3().catch(uW)});async function t$3(A,Q){let B=A.ampURL.includes("localhost")||A.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!B)await A.settings.set("url",process.env.AMP_URL,"global"),D5.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
7323
7323
  `);else if(!dz(A.ampURL))D5.write(`Logging in to ${new URL(A.ampURL).hostname}
7324
7324
  `);let $=process.env.AMP_API_KEY;if($)D5.write(`API key found in environment variable, storing...
7325
7325
  `),await Q.set("apiKey",$,A.ampURL),D5.write(`API key successfully stored.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sourcegraph/amp",
3
- "version": "0.0.1778070211-gdd8fb4",
3
+ "version": "0.0.1778070540-gc7ef03",
4
4
  "description": "CLI for Amp, the frontier coding agent.",
5
5
  "homepage": "https://ampcode.com/",
6
6
  "author": {