@sourcegraph/amp 0.0.1761904583-g218c5a → 0.0.1761911084-ge88213
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +10 -10
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4739,8 +4739,8 @@ Try registering OAuth credentials manually:
|
|
|
4739
4739
|
Required: --server-url, --client-id
|
|
4740
4740
|
Optional: --auth-url, --token-url (auto-discovered if not provided), --client-secret, --scopes
|
|
4741
4741
|
|
|
4742
|
-
If manual registration doesn't work, this server likely doesn't support OAuth.`;return{type:"connection-failed",error:{message:R,stderr:w.stderr}}}return{type:"connected",capabilities:A.getServerCapabilities(),serverInfo:A.getServerVersion()}})),F=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(GU1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/tools/list_changed")}),S2(void 0),k0(()=>A))})),B=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(tz1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/resources/list_changed")}),S2(void 0),k0(()=>A))})),M=F.pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{return(await A.listTools({signal:w})).tools})})),N=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(YU1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/prompts/list_changed")}),S2(void 0),k0(()=>A))})).pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{if(!A.getServerCapabilities()?.prompts)return[];return(await A.listPrompts({signal:w})).prompts})})),L=B.pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{if(!A.getServerCapabilities()?.resources)return[];return(await A.listResources({signal:w})).resources})}));return{status:H,tools:M,resources:L,prompts:N,async callTool(A,w,R){let O=await zS(U);if(O===H7)throw Error("cannot call tools for disabled client");let $=G?A20.get(O):void 0;w90(O,w.thread,{configService:w.configService});let j=await O.callTool(A,void 0,{signal:R,timeout:999999000});if(!("content"in j))throw Error("unexpected response");if($)try{L3({feature:"mcp.tool_usage",action:"remote_tool_called",metadata:{url:$.url,transport:$.type,toolName:A.name,threadId:w.thread.id}})}catch(E){u.debug("Failed to record MCP tool usage telemetry",{error:E})}return ix6(j.content)},async listResources(A,w){let R=await zS(U);if(R===H7)throw Error("cannot list resources for disabled client");if(!R.getServerCapabilities()?.resources)return[];return(await R.listResources(A,{signal:w,timeout:999999000})).resources},async readResource(A,w){let R=await zS(U);if(R===H7)throw Error("cannot read resource for disabled client");return(await R.readResource(A,{signal:w,timeout:999999000})).contents},async getPrompt(A,w,R){let O=await zS(U);if(O===H7)return null;try{return await O.getPrompt({name:A,arguments:w},{signal:R,timeout:999999000})}catch($){return null}},async
|
|
4743
|
-
`);return F};if(U instanceof Error){if(U.message.includes("Connection closed"))throw W("MCP server connection was closed unexpectedly.");else if(U.message.includes("Invalid content type"))throw W('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in J&&U.message.includes("fetch failed"))throw W(`Could not connect to MCP server at ${J.url}. Check that the server is running and accessible.`);else if(z.length>0)throw W(U.message)}throw U}}function j_(){return new Promise((J,Q)=>{let Z=setTimeout(()=>{clearTimeout(Z),Q(Error("Connection timeout: MCP server did not respond within 60 seconds"))},60000)})}function O_(J,Q){return J.replace(/\$\{([^}]+)\}/g,(Z,X)=>{let Y=Q[X];if(Y===void 0)return Z;return Y})}function rx6(J){let{AMP_API_KEY:Q,...Z}=J;return Z}async function O20(J){let Q=sx6(J),Z=JSON.stringify(Q);if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle){let K=new TextEncoder().encode(Z),G=await globalThis.crypto.subtle.digest("SHA-256",K);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let{createHash:X}=await import("node:crypto");return X("sha256").update(Z).digest("hex")}function sx6(J){if("command"in J)return{type:"command",command:J.command,args:J.args||[],env:R20(J.env||{})};return{type:"url",url:J.url,headers:R20(J.headers||{}),transport:J.transport||"http"}}function R20(J){let Q={};for(let Z of Object.keys(J).sort())Q[Z]=J[Z];return Q}I0();class KB1{async isTrusted(J){return!0}async setTrust(J,Q){}isWorkspaceTrusted(){return r1.of(!0)}async allowWorkspace(J){}}function $20({configService:J,toolService:Q,externalMCPServers:Z=r1.of({}),createOAuthProvider:X,trustStore:Y=new KB1}){let K=new E20,G=new F8,q,z=j9(J.config,Z).pipe(k0(([{settings:{mcpServers:j,mcpPermissions:E,"terminal.commands.nodeSpawn.loadProfile":I,"security.audit.logMcpConnections":T}},S])=>({mcpServers:j,mcpPermissions:E,loadProfile:I,logMcpConnections:T,externalMCPServers:S})),G8()),U=J.workspaceRoots.pipe(k0((j)=>j?.at(0))),W=new Map,H,F=j9(z,U,G.pipe(S2(void 0))).pipe(XG(300),q8(([{mcpServers:j,mcpPermissions:E,loadProfile:I,logMcpConnections:T,externalMCPServers:S},x,h])=>c6(async(v)=>{let _=K.consume(),b={...j,...S},g=tx6(H,E);H=E;for(let[k,f]of Object.entries(b)){let y=W.get(k);if(!_&&y&&ox6(y.spec,f)&&g)continue;let a="url"in f&&(!!f.oauth||!f.headers&&f.transport!=="http")&&X?await X(k):void 0,p=f._target==="workspace",e=await O20(f),G1=!1,W1;if(p){let Z1={serverName:k,specHash:e};if(!await Y.isTrusted(Z1)){if(W1=Pn(f,{workingDirectory:x,loadProfile:I},!0,E,a,k,T),G1=!0,u.info(`MCP server ${k} requires approval before execution`,{specHash:e}),!await Y.hasEntry?.(Z1))q?.(k,f)}else W1=Pn(f,{workingDirectory:x,loadProfile:I},!1,E,a,k,T)}else W1=Pn(f,{workingDirectory:x,loadProfile:I},!1,E,a,k,T);if(W.set(k,{spec:f,client:W1,isExternal:Boolean(S[k]),requiresApproval:G1,specHash:e}),y)await y.client.dispose()}for(let[k,{client:f}]of W.entries())if(!b||!(k in b))await f.dispose(),W.delete(k);return Array.from(W.entries())})),M9({shouldCountRefs:!1})),B=F.subscribe({}),M=new Map,V=30000,N=(j)=>{if(j)M.delete(j);else M.clear()},L=F.pipe(q8((j)=>j.length===0?r1.of(!0):j9(...j.map(([E,{client:I}])=>I.tools.pipe(P7((T)=>T!==s5&&T!==H7),SN(1)))).pipe(k0(()=>!0))),SN(1)),A=j9(F.pipe(q8((j)=>j.length===0?r1.of([]):j9(...j.map(([E,{spec:I,client:T}])=>T.tools.pipe(k0((S)=>({name:E,spec:I,tools:S===s5||S instanceof Error||S===H7?[]:S,client:T}))))))),J.config.pipe(k0((j)=>j.settings.mcpPermissions),G8())).pipe(k0(([j,E])=>({mcpServers:j,mcpPermissions:E}))),w,R=A.subscribe(({mcpServers:j,mcpPermissions:E})=>{if(w)for(let T of w)T.dispose();w=[];let I=[];for(let{name:T,spec:S,tools:x,client:h}of j){if(!li(E,S)){if(x.length>0)u.error(`Ignoring ${x.length} tools from MCP server ${T} due to MCP permissions`);else u.debug(`Ignoring tools from MCP server ${T} due to MCP permissions`);continue}for(let v of x){u.debug("mcpService.toolRegisterer",{name:v.name});try{let _=j20(v,h,T);w.push(Q.registerTool(_)),I.push(_.spec.name)}catch(_){u.warn(`Failed to register MCP tool ${v.name} from ${T}:`,_)}}}if(I.length>0)G6(Q.tools.pipe(k0((T)=>I.every((S)=>T.some((x)=>x.spec.name===S))),P7(Boolean),SN(1)),AbortSignal.timeout(5000)).then(()=>{u.debug("mcpService.toolsRegistered",{registeredCount:I.length})}).catch((T)=>{u.warn("Failed to verify tool registration:",T)})},(j)=>{u.error("MCP toolRegisterer error",j)}),O=new Promise((j)=>{try{G6(L,AbortSignal.timeout(1e4)).then(()=>{u.info("mcpService.initialized",{value:Array.from(W.keys())}),j()}).catch((E)=>{u.warn("MCP service initialization failed, but service will continue:",E),j()})}catch(E){u.warn("MCP service initialization failed, but service will continue:",E),j()}}),$=j9(J.config,F).pipe(q8(([j,E])=>E.length===0?r1.of([]):j9(...E.map(([I,{spec:T,client:S,isExternal:x,requiresApproval:h,specHash:v}])=>j9(S.status,S.tools,S.prompts).pipe(k0(([_,b,g])=>({name:I,spec:T,isExternal:x,requiresApproval:h,specHash:v,status:_,tools:b instanceof Error?b:b===s5||b===H7?[]:b.map((k)=>({spec:{name:k.name,description:k.description,inputSchema:k.inputSchema,source:{mcp:I}},...fS({name:k.name,source:{mcp:I}},j)})),prompts:g instanceof Error?g:g===s5||g===H7?[]:g})))))),M9({shouldCountRefs:!1}));return{initialized:O,servers:$,restartServers(){K.replenish(),G.next()},async approveWorkspaceServer(j){let E=W.get(j);if(!E)throw Error(`MCP server not found: ${j}`);if(E.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await Y.setTrust({serverName:j,specHash:E.specHash},!0),this.restartServers()},async denyWorkspaceServer(j){let E=W.get(j);if(!E)throw Error(`MCP server not found: ${j}`);if(E.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await Y.setTrust({serverName:j,specHash:E.specHash},!1)},isWorkspaceTrusted(){return Y.isWorkspaceTrusted?.()??r1.of(!0)},getClient(j){return W.get(j)?.client},async searchResources(j){try{let E=await G6(F),I=Date.now(),T=[];for(let[S,{client:x}]of E){if((await G6(x.status)).type!=="connected")continue;try{let v,_=M.get(S);if(_&&I<_.expires)v=_.resources;else v=await x.listResources(),M.set(S,{resources:v,timestamp:I,expires:I+30000});for(let b of v){let g=b.title||b.name;if(!j||S.toLowerCase().includes(j.toLowerCase())||g.toLowerCase().includes(j.toLowerCase())||b.description?.toLowerCase().includes(j.toLowerCase())||b.uri.toLowerCase().includes(j.toLowerCase()))T.push({resource:b,serverName:S})}}catch(v){u.warn(`Failed to list resources from MCP server ${S}`,v),N(S)}}return T.slice(0,50)}catch(E){return u.warn("Failed to search MCP resources",E),[]}},async getPrompt(j,E,I,T){let S=W.get(E);if(S)try{return await S.client.getPrompt(j,I,T)}catch(x){return null}return null},async registerToolsWithService(j){return new Promise((E)=>{let I=[],T=!1,S=A.subscribe(({mcpServers:x})=>{if(u.debug("MCP tool registration triggered",{serverCount:x.length,toolCount:x.reduce((h,v)=>h+v.tools.length,0)}),I.length>0)u.debug("Disposing previous MCP tool registrations",{count:I.length});for(let h of I)h.dispose();I.length=0;for(let{name:h,tools:v,client:_}of x){u.debug("Registering MCP tools for server",{serverName:h,toolCount:v.length,toolNames:v.map((b)=>b.name)});for(let b of v)I.push(j.registerTool(j20(b,_,h)))}if(u.debug("MCP tool registration complete",{totalRegistered:I.length}),!T)T=!0,E({dispose:()=>{S.unsubscribe();for(let h of I)h.dispose();I.length=0}})},(x)=>{u.error("MCP external tool registration error",x)})})},async addServer(j,E){let I=(await J.getLatest()).settings.mcpServers;if(I&&j in I)throw Error(`MCP server already exists with name ${JSON.stringify(j)}`);if("command"in E&&typeof E.command!=="string")throw Error("Command must be a string");if("url"in E)try{new URL(E.url)}catch(T){throw Error(`Invalid URL: ${E.url}`)}await J.updateSettings("mcpServers",{...I,[j]:E},"global")},async removeServer(j){let E=(await J.getLatest()).settings.mcpServers;if(!E||!(j in E))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);let I={...E};delete I[j],await J.updateSettings("mcpServers",I,"global")},async updateServer(j,E){let I=(await J.getLatest()).settings.mcpServers;if(!I||!(j in I))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);await J.updateSettings("mcpServers",{...I,[j]:E},"global")},searchPrompts(j){return this.servers.pipe(k0((E)=>{let I=[];for(let T of E)if(T.status.type==="connected"&&Array.isArray(T.prompts)){let S=T.prompts.map((x)=>ex6(x,T.name)).filter((x)=>{if(!j)return!0;let h=j.toLowerCase();return x.label.toLowerCase().includes(h)||x.detail&&x.detail.toLowerCase().includes(h)});I.push(...S)}return I.sort((T,S)=>T.label.localeCompare(S.label)).slice(0,Math.min(10,tB))}))},async dispose(){R.unsubscribe(),B.unsubscribe();let j=Array.from(W.values()).map(async({client:E})=>{try{await E.dispose()}catch(I){u.error("Error disposing MCP client:",I)}});await Promise.all(j),W.clear()},get onUntrustedWorkspaceServer(){return q},set onUntrustedWorkspaceServer(j){q=j}}}function ox6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function tx6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function j20(J,Q,Z){let X=`mcp__${Z.replace(/\s+/g,"_")}__${J.name.replace(/\s+/g,"_")}`,Y=X.length>=64?J.name:X;return{spec:{name:Y,description:J.description??"",inputSchema:J.inputSchema,source:{mcp:Z}},fn:({args:K},G)=>c6((q)=>Q.callTool({name:J.name,arguments:K??void 0},G,q).then((z)=>{return u.debug("MCP tool call succeeded",{serverName:Z,toolName:J.name,longName:Y}),{status:"done",result:z.map((U)=>{if(U.type==="text"||U.type==="image")return U;throw Error(`unsupported content type: ${U.type}`)})}},(z)=>{throw u.error("MCP tool call failed",{serverName:Z,toolName:J.name,longName:Y,error:z instanceof Error?z.message:String(z),errorName:z instanceof Error?z.name:typeof z,stack:z instanceof Error?z.stack:void 0}),z}))}}class E20{forceRestart=!1;consume(){let J=this.forceRestart;return this.forceRestart=!1,J}replenish(){this.forceRestart=!0}}function ex6(J,Q){let Z=J.arguments?.map((Y)=>({name:Y.name,required:Y.required??!1}))||[],X={uri:$6(`mcp://${Q}/${J.name}`),label:`${Q}/${J.name}`,detail:J.description||`From ${Q}`,insertText:"",filterText:`${J.name} ${J.description||""}`.toLowerCase()};return{...X,kind:"prompt",promptData:{...X,arguments:Z}}}FG();qB1();b6();I0();G0();H3();var c20=C6(x20(),1);b6();I0();G0();FB1();jZ();Vj();import*as uX from"node:fs";import*as fn from"node:path";var $2={readFile:async(J,Q)=>{try{return await uX.promises.readFile(N8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await uX.promises.readFile(N8(J).fsPath,{signal:Q?.signal})}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await uX.promises.stat(N8(J).fsPath)).mtimeMs}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},stat:async(J,Q)=>{J=N8(J);try{let Z=await uX.promises.stat(J.fsPath);return{name:fn.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},realpath:async(J,Q)=>{return _b6(N8(J))},rename:async(J,Q)=>{try{await uX.promises.rename(N8(J).fsPath,N8(Q).fsPath)}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await uX.promises.writeFile(N8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=N8(J);try{if(Q?.recursive)await uX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await uX.promises.unlink(J.fsPath)}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},mkdirp:async(J)=>{await uX.promises.mkdir(N8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=N8(J);try{return(await uX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:A0.file(fn.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await yn(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>VG(X)?A0.file(X):y0.joinPath(J.base,X))}catch(Z){return u.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=N8(J);kb6(Z);try{await uX.promises.access(Z.fsPath)}catch(X){if(pW(X))throw new ZJ(Z);throw X}}};function kb6(J){if(!WB(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function pW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function _b6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return A0.file(await uX.promises.realpath(J.fsPath))}catch(Q){if(pW(Q))throw new ZJ(J);throw Q}}async function d20(J,Q){if(!J.startsWith(process.cwd()))return;if(await C7.isConnected())try{let Z=await C7.sendRequest("readFile",{path:J});if(Z?.content)return Q(Z.content);throw Error(`Failed to readFile via IDE ${J}: ${Z?.message??"unknown cause"}`)}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;u.debug("IDE readFile failed, falling back to Node.js filesystem",{path:J,error:Z});return}else return}async function xb6(J,Q){if(!J.startsWith(process.cwd()))return!1;if(await C7.isConnected())try{let Z=await C7.sendRequest("editFile",{path:J,fullContent:Q});if(!Z?.success)throw Error(`Failed to writeFile via IDE ${J}: ${Z?.message??"unknown cause"}`);return!0}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;return u.debug("IDE writeFile failed, falling back to Node.js filesystem",{path:J,error:Z}),!1}else return!1}var l20={readFile:async(J,Q)=>{let Z=N8(J).fsPath;return u.debug("ide-fs",{method:"readFile",path:Z}),await d20(Z,(X)=>X)??await $2.readFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readFile",uri:J})})},readBinaryFile:async(J,Q)=>{let Z=N8(J).fsPath;u.debug("ide-fs",{method:"readBinaryFile",path:Z});let X;if(!await c20.isBinaryFile(Z))X=await d20(Z,(Y)=>Buffer.from(Y,"utf8"));return X??await $2.readBinaryFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readBinaryFile",uri:J})})},getMtime:async(J,Q)=>{return $2.getMtime(J,Q)},stat:async(J,Q)=>{return $2.stat(J,Q)},realpath:async(J,Q)=>{return $2.realpath(J,Q)},rename:async(J,Q)=>{return $2.rename(J,Q)},writeFile:async(J,Q,Z)=>{let X=N8(J).fsPath;if(u.debug("ide-fs",{method:"writeFile",path:X}),await xb6(X,Q))return;return await $2.writeFile(J,Q,Z).finally(()=>{u.debug("ide-fs",{fallback:"writeFile",uri:J})})},delete:async(J,Q)=>{return $2.delete(J,Q)},mkdirp:async(J)=>{return $2.mkdirp(J)},readdir:async(J,Q)=>{return $2.readdir(J,Q)},findFiles:async(J,Q)=>{return $2.findFiles(J,Q)},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return $2.access(J,Q)}};jG();gY();AD();b6();import{homedir as mb6}from"node:os";import e20 from"node:path";var J$=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,s20=new Set,MB1=typeof process==="object"&&!!process?process:{},o20=(J,Q,Z,X)=>{typeof MB1.emitWarning==="function"?MB1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},gn=globalThis.AbortController,r20=globalThis.AbortSignal;if(typeof gn>"u"){r20=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},gn=class{constructor(){Q()}signal=new r20;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=MB1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,o20("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}var hb6=(J)=>!s20.has(J),F$9=Symbol("type"),jD=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),t20=(J)=>!jD(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?S_:null;class S_ extends Array{constructor(J){super(J);this.fill(0)}}class Q${heap;length;static#J=!1;static create(J){let Q=t20(J);if(!Q)return[];Q$.#J=!0;let Z=new Q$(J,Q);return Q$.#J=!1,Z}constructor(J,Q){if(!Q$.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}class mn{#J;#Q;#Y;#X;#q;#I;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#G;#Z;#B;#M;#F;#W;#A;#H;#w;#R;#V;#O;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#R,ttls:J.#V,sizes:J.#w,keyMap:J.#z,keyList:J.#G,valList:J.#Z,next:J.#B,prev:J.#M,get head(){return J.#F},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#j(Q),rindexes:(Q)=>J.#$(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Q}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#I}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#q}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:G,allowStale:q,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:H,noUpdateTTL:F,maxSize:B=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:O,ignoreFetchAbort:$}=J;if(Q!==0&&!jD(Q))throw TypeError("max option must be a nonnegative integer");let j=Q?t20(Q):Array;if(!j)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Q=B,this.maxEntrySize=M||this.#Q,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Q&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#I=N,this.#C=!!N,this.#z=new Map,this.#G=Array(Q).fill(void 0),this.#Z=Array(Q).fill(void 0),this.#B=new j(Q),this.#M=new j(Q),this.#F=0,this.#W=0,this.#A=Q$.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#q=W,this.#H=[];else this.#q=void 0,this.#H=void 0;if(this.#O=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#q,this.noDisposeOnSet=!!H,this.noUpdateTTL=!!F,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#Q!==0){if(!jD(this.#Q))throw TypeError("maxSize must be a positive integer if specified")}if(!jD(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!q,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!G,this.ttlResolution=jD(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!jD(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Q===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Q){if(hb6("LRU_CACHE_UNBOUNDED"))s20.add("LRU_CACHE_UNBOUNDED"),o20("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",mn)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new S_(this.#J),Q=new S_(this.#J);this.#V=J,this.#R=Q,this.#h=(Y,K,G=J$.now())=>{if(Q[Y]=K!==0?G:0,J[Y]=K,K!==0&&this.ttlAutopurge){let q=setTimeout(()=>{if(this.#N(Y))this.#E(this.#G[Y],"expire")},K+1);if(q.unref)q.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?J$.now():0},this.#P=(Y,K)=>{if(J[K]){let G=J[K],q=Q[K];if(!G||!q)return;Y.ttl=G,Y.start=q,Y.now=Z||X();let z=Y.now-q;Y.remainingTTL=G-z}};let Z=0,X=()=>{let Y=J$.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let G=J[K],q=Q[K];if(!G||!q)return 1/0;let z=(Z||X())-q;return G-z},this.#N=(Y)=>{let K=Q[Y],G=J[Y];return!!G&&!!K&&(Z||X())-K>G}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new S_(this.#J);this.#L=0,this.#w=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!jD(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!jD(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#x=(Q,Z,X)=>{if(J[Q]=Z,this.#Q){let Y=this.#Q-J[Q];while(this.#L>Y)this.#b(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#x=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#F)break;else Q=this.#M[Q]}}*#$({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#F;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#G[J])===J}*entries(){for(let J of this.#j())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*rentries(){for(let J of this.#$())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*keys(){for(let J of this.#j()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*rkeys(){for(let J of this.#$()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*values(){for(let J of this.#j())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}*rvalues(){for(let J of this.#$())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#G[Z],this))return this.get(this.#G[Z],Q)}}forEach(J,Q=this){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}rforEach(J,Q=this){for(let Z of this.#$()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#$({allowStale:!0}))if(this.#N(Q))this.#E(this.#G[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Z[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#R){let K=this.#V[Q],G=this.#R[Q];if(K&&G){let q=K-(J$.now()-G);Y.ttl=q,Y.start=Date.now()}}if(this.#w)Y.size=this.#w[Q];return Y}dump(){let J=[];for(let Q of this.#j({allowStale:!0})){let Z=this.#G[Q],X=this.#Z[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#R){K.ttl=this.#V[Q];let G=J$.now()-this.#R[Q];K.start=Math.floor(Date.now()-G)}if(this.#w)K.size=this.#w[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=J$.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:G=this.sizeCalculation,status:q}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,G);if(this.maxEntrySize&&U>this.maxEntrySize){if(q)q.set="miss",q.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#b(!1):this.#U,this.#G[W]=J,this.#Z[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#x(W,U,q),q)q.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let H=this.#Z[W];if(Q!==H){if(this.#C&&this.#K(H)){H.__abortController.abort(Error("replaced"));let{__staleWhileFetching:F}=H;if(F!==void 0&&!K){if(this.#O)this.#Y?.(F,J,"set");if(this.#D)this.#H?.push([F,J,"set"])}}else if(!K){if(this.#O)this.#Y?.(H,J,"set");if(this.#D)this.#H?.push([H,J,"set"])}if(this.#v(W),this.#x(W,U,q),this.#Z[W]=Q,q){q.set="replace";let F=H&&this.#K(H)?H.__staleWhileFetching:H;if(F!==void 0)q.oldValue=F}}else if(q)q.set="update";if(this.#_)this.onInsert?.(Q,J,Q===H?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(q)this.#P(q,W)}if(!K&&this.#D&&this.#H){let H=this.#H,F;while(F=H?.shift())this.#q?.(...F)}return this}pop(){try{while(this.#U){let J=this.#Z[this.#F];if(this.#b(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#H){let J=this.#H,Q;while(Q=J?.shift())this.#q?.(...Q)}}}#b(J){let Q=this.#F,Z=this.#G[Q],X=this.#Z[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(X,Z,"evict");if(this.#D)this.#H?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#G[Q]=void 0,this.#Z[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#F=this.#W=0,this.#A.length=0;else this.#F=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Z[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Z[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Z[Q];if(this.#K(Y))return Y;let K=new gn,{signal:G}=Z;G?.addEventListener("abort",()=>K.abort(G.reason),{signal:K.signal});let q={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=F;if(this.#Z[Q]===F)if(M===void 0)if(A.__staleWhileFetching)this.#Z[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,q.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,w=F;if(this.#Z[Q]===F){if(!A||w.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Z[Q]=w.__staleWhileFetching}if(L){if(Z.status&&w.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw M},H=(M,V)=>{let N=this.#I?.(J,Y,q);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let F=new Promise(H).then(z,U),B=Object.assign(F,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,B,{...q.options,status:void 0}),Q=this.#z.get(J);else this.#Z[Q]=B;return B}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof gn}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:G=this.noDisposeOnSet,size:q=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:H=this.allowStaleOnFetchRejection,ignoreFetchAbort:F=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:G,size:q,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:H,allowStaleOnFetchAbort:B,ignoreFetchAbort:F,status:N,signal:L},w=this.#z.get(J);if(w===void 0){if(N)N.fetch="miss";let R=this.#y(J,w,A,M);return R.__returned=R}else{let R=this.#Z[w];if(this.#K(R)){let I=Z&&R.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",I)N.returnedStale=!0}return I?R.__staleWhileFetching:R.__returned=R}let O=this.#N(w);if(!V&&!O){if(N)N.fetch="hit";if(this.#k(w),X)this.#S(w);if(N)this.#P(N,w);return R}let $=this.#y(J,w,A,M),E=$.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=O?"stale":"refresh",E&&O)N.returnedStale=!0}return E?$.__staleWhileFetching:$.__returned=$}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,G=this.get(J,K);if(!Y&&G!==void 0)return G;let q=Z(J,G,{options:K,context:X});return this.set(J,q,K),q}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,G=this.#z.get(J);if(G!==void 0){let q=this.#Z[G],z=this.#K(q);if(K)this.#P(K,G);if(this.#N(G)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?q:void 0}else{if(K&&Z&&q.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?q.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return q.__staleWhileFetching;if(this.#k(G),X)this.#S(G);return q}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#F)this.#F=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Z[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(Y,J,Q);if(this.#D)this.#H?.push([Y,J,Q])}if(this.#z.delete(J),this.#G[X]=void 0,this.#Z[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#F)this.#F=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let G=this.#B[X];this.#M[G]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#H?.length){let X=this.#H,Y;while(Y=X?.shift())this.#q?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#$({allowStale:!0})){let Z=this.#Z[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#G[Q];if(this.#O)this.#Y?.(Z,X,J);if(this.#D)this.#H?.push([Z,X,J])}}if(this.#z.clear(),this.#Z.fill(void 0),this.#G.fill(void 0),this.#V&&this.#R)this.#V.fill(0),this.#R.fill(0);if(this.#w)this.#w.fill(0);if(this.#F=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#H){let Q=this.#H,Z;while(Z=Q?.shift())this.#q?.(...Z)}}}b6();I0();G0();jZ();function un(J,Q,Z){let X=new F8,K=(()=>{let B=new Map;return(M,V)=>{let L=(B.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(B.get(M)===L)B.delete(M)});return B.set(M,L),L}})(),G=Z?y0.joinPath(Q,Z):Q;function q(B){return y0.joinPath(G,`${B.toString()}.json`)}async function z(B){let M=q(B);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);u.warn(`File too large to load safely: ${String(B)} (${L}MB)`,{key:String(B),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:w,contentPreview:R}=gb6(V);u.warn("Corrupted JSON detected.",{key:String(B),storageUri:G.toString(),error:A.message,contentLength:w,contentPreview:R});return}}catch(V){if(EQ(V))return;throw V}}async function U(B,M){let V=q(B),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(y0.joinPath(V,"..")),await K(B,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(B)}async function W(B){let M=q(B);await K(B,async()=>{await J.delete(M)}),X.next(B)}async function H(){let B;try{B=await J.readdir(G)}catch(M){if(EQ(M))return[];throw M}return B.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function F(B){return q(B).fsPath}return{get:z,set:U,delete:W,keys:H,path:F,changes:X}}function gb6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}async function J40(J){let Q=J.isDevelopment||!1,Z=ub6(),Y=un($2,Z,Q?"threads-development":"threads");return new Q40(Y)}class Q40{delegate;cache=new mn({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){this.cache.set(J,Q),await this.delegate.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function ub6(){let J=process.env.XDG_DATA_HOME||e20.join(mb6(),".local","share"),Q=e20.resolve(J,"amp");return A0.file(Q)}pn();Q2();b6();G0();Z$();k_();class NB1{storage;index=new Map;initialized=!1;initPromise=null;constructor(J){this.storage=J;this.ensureInitialized(),this.setupChangeListener()}async search(J,Q=20){if(!this.initialized)return[];if(this.index.size===0)return[];let Z=Array.from(this.index.entries()).map(([K,G])=>{return new IZ({id:K,kind:"file",path:G,uri:A0.parse(`thread://${K}`),metadata:{size:0,mtime:0,isSymlink:!1}})});return new dn(J,{maxResults:Q,minScore:J?400:0}).match(Z).map((K)=>({id:K.entry.id,title:K.entry.path,score:K.score}))}async ensureInitialized(){if(this.initialized)return;if(this.initPromise)return this.initPromise;return this.initPromise=this.loadIndex(),this.initPromise}async loadIndex(){try{let J=await this.storage.keys(),Q=50;for(let Z=0;Z<J.length;Z+=50){let X=J.slice(Z,Z+50),Y=await Promise.all(X.map(async(K)=>{return(await this.storage.get(K))?.title||null}));for(let K=0;K<X.length;K++){let G=X[K],q=Y[K];if(G&&q&&q.trim().length>0)this.index.set(G,q)}if(Z+50<J.length)await new Promise((K)=>setImmediate(K))}this.initialized=!0,u.debug("Thread fuzzy indexer initialized",{indexedCount:this.index.size})}catch(J){u.warn("Failed to load thread index",J),this.initialized=!0}}setupChangeListener(){this.storage.changes.subscribe(async(J)=>{if(!this.initialized)return;if(J===void 0){await this.loadIndex();return}try{let Q=await this.storage.get(J);if(Q?.title)this.index.set(J,Q.title);else this.index.delete(J)}catch(Q){u.warn("Failed to update thread index for change",{key:J,error:Q})}})}dispose(){this.index.clear(),this.initialized=!1,this.initPromise=null}}I0();I0();function Z40(J){let Q={},Z=!0;return J.changes.pipe(S2(void 0),GW(async(X,Y)=>{if(X===void 0||Z){let K=await J.keys();Y?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(K.map(async(G)=>[G,await J.get(G)]))),Y?.throwIfAborted(),Z=!1}else{let K=await J.get(X);if(Y?.throwIfAborted(),K===void 0)Q={...Q,[X]:void 0},delete Q[X];else Q={...Q,[X]:K}}return Q}))}Q2();class LB1{storage;constructor(J,Q={}){this.storage=J;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=Cc1(Z40(this.storage).pipe(k0((J)=>{let Q=Object.values(J).filter((X)=>X&&("messages"in X)).toSorted((X,Y)=>Y.created-X.created),Z=[];for(let X of Q)if(!(X.messages.length===0&&!X.draft))Z.push(X);return Z.map((X)=>({id:X.id,v:X.v,created:X.created,title:X.title??null,userLastInteractedAt:ln(X),env:X.env,originThreadID:X.originThreadID,mainThreadID:X.mainThreadID,summaryStats:{diffStats:Rc(X)}})).toSorted((X,Y)=>Y.userLastInteractedAt-X.userLastInteractedAt)}),M9()))}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable}observeThreadList(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable.pipe(G8((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Z,X)=>{let Y=Q[X];if(!Y)return!1;return Z.id===Y.id&&Z.title===Y.title&&Z.userLastInteractedAt===Y.userLastInteractedAt&&Z.mainThreadID===Y.mainThreadID&&JSON.stringify(Z.env?.initial?.trees?.map((K)=>K.displayName))===JSON.stringify(Y.env?.initial?.trees?.map((K)=>K.displayName))})}))}_observeHistory;dispose(){this._observeHistory?.subscription.unsubscribe()}}function ln(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}Q2();function Y$(J,Q){let Z=[];if(Z.push(cb6(J,Q)),J.title)Z.push(`# ${J.title}`);let X=DZ(J),Y=X?X.index:0;for(let K=Y;K<J.messages.length;K++){let G=J.messages[K];if(G)Z.push(lb6(G))}return Z.join(`
|
|
4742
|
+
If manual registration doesn't work, this server likely doesn't support OAuth.`;return{type:"connection-failed",error:{message:R,stderr:w.stderr}}}return{type:"connected",capabilities:A.getServerCapabilities(),serverInfo:A.getServerVersion()}})),F=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(GU1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/tools/list_changed")}),S2(void 0),k0(()=>A))})),B=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(tz1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/resources/list_changed")}),S2(void 0),k0(()=>A))})),M=F.pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{return(await A.listTools({signal:w})).tools})})),N=U.pipe(q8((A)=>{if(A===s5||A instanceof Error||A===H7)return r1.of(A);let w=new F8;return A.setNotificationHandler(YU1,()=>{w.next()}),w.pipe(qS({onUnsubscribe:()=>A.removeNotificationHandler("notifications/prompts/list_changed")}),S2(void 0),k0(()=>A))})).pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{if(!A.getServerCapabilities()?.prompts)return[];return(await A.listPrompts({signal:w})).prompts})})),L=B.pipe(kN((A)=>{if(A instanceof Error)return r1.of(A);if(A===H7)return r1.of(H7);return c6(async(w)=>{if(!A.getServerCapabilities()?.resources)return[];return(await A.listResources({signal:w})).resources})}));return{status:H,tools:M,resources:L,prompts:N,async callTool(A,w,R){let O=await zS(U);if(O===H7)throw Error("cannot call tools for disabled client");let $=G?A20.get(O):void 0;w90(O,w.thread,{configService:w.configService});let j=await O.callTool(A,void 0,{signal:R,timeout:999999000});if(!("content"in j))throw Error("unexpected response");if($)try{L3({feature:"mcp.tool_usage",action:"remote_tool_called",metadata:{url:$.url,transport:$.type,toolName:A.name,threadId:w.thread.id}})}catch(E){u.debug("Failed to record MCP tool usage telemetry",{error:E})}return ix6(j.content)},async listResources(A,w){let R=await zS(U);if(R===H7)throw Error("cannot list resources for disabled client");if(!R.getServerCapabilities()?.resources)return[];return(await R.listResources(A,{signal:w,timeout:999999000})).resources},async readResource(A,w){let R=await zS(U);if(R===H7)throw Error("cannot read resource for disabled client");return(await R.readResource(A,{signal:w,timeout:999999000})).contents},async getPrompt(A,w,R){let O=await zS(U);if(O===H7)return null;try{return await O.getPrompt({name:A,arguments:w},{signal:R,timeout:999999000})}catch($){return null}},async[Symbol.asyncDispose](){W.unsubscribe();try{await(z??q).close()}catch(A){u.error("Error closing MCP client:",A)}}}}function w20(J){let Q=new URL(J.toString());Q.username="",Q.password="",Q.hash="";let Z=["token","key","api_key","apikey","access_token","secret","password","auth","authorization","bearer","jwt","session","sessionid","sid"];for(let X of Array.from(Q.searchParams.keys())){let Y=X.toLowerCase();if(Z.some((K)=>Y.includes(K))){let K=Q.searchParams.getAll(X);Q.searchParams.delete(X);for(let G=0;G<K.length;G++)Q.searchParams.append(X,"[REDACTED]")}}return Q.toString()}async function ax6(J,Q,Z,X,Y,K){let G=Z?{headers:Z}:void 0,z=new av(Q,Y?{requestInit:G,authProvider:Y}:G?{requestInit:G}:void 0);try{await Promise.race([X.connect(z),j_()]),u.debug("Connected using StreamableHTTPClientTransport");let F=w20(Q);try{L3({feature:"mcp.connection",action:"remote_connected",metadata:{url:F,transport:"StreamableHTTPClientTransport"}})}catch(B){u.debug("Failed to record MCP connection telemetry",{error:B})}return{client:X,transportInfo:{type:"StreamableHTTPClientTransport",url:F}}}catch(F){if(sU1(F)&&Y){u.debug("OAuth authorization required, starting OAuth flow",{serverName:J,baseUrl:Q.toString()});try{return await oU1({transport:z,oauthProvider:Y,oldClient:X,baseUrl:Q,requestInit:G,connectionTimeout:j_,transportType:"HTTP",serverName:J})}catch(B){u.debug("HTTP OAuth flow failed, will try SSE fallback",{serverName:J,error:B.message})}}u.debug("StreamableHTTPClientTransport failed, falling back to SSE",{serverName:J,baseUrl:Q.toString(),error:F.message})}try{await X.close()}catch(F){u.debug("Failed to close previous client",{error:F})}let U=new Kj(In.clientInfo,{capabilities:In.capabilities}),H=new iv(Q,Y?{requestInit:G,authProvider:Y}:G?{requestInit:G}:void 0);try{let F=U.connect(H);F.catch(()=>{}),await Promise.race([F,j_()]),u.debug("Connected using SSEClientTransport");let B=w20(Q);try{L3({feature:"mcp.connection",action:"remote_connected",metadata:{url:B,transport:"SSEClientTransport"}})}catch(M){u.debug("Failed to record MCP connection telemetry",{error:M})}return{client:U,transportInfo:{type:"SSEClientTransport",url:B}}}catch(F){if(sU1(F)&&Y)return u.debug("SSE OAuth authorization required, completing flow",{serverName:J,baseUrl:Q.toString()}),await oU1({transport:H,oauthProvider:Y,oldClient:U,baseUrl:Q,requestInit:G,connectionTimeout:j_,transportType:"SSE",serverName:J});throw F}}async function nx6(J,Q,Z,X,Y,K,G){if(!li(X,J))throw Error("MCP server is not allowed by MCP permissions");let q;if("url"in J){let U=O_(J.url,process.env),W=J.headers?Object.entries(J.headers).reduce((F,[B,M])=>({...F,[B]:O_(M,process.env)}),{}):void 0,H=new URL(U);return await ax6(K,H,J.headers,Q,Y,G)}else{let{loadProfileEnvironmentVariables:U}=await Promise.resolve().then(() => (aF1(),O90)),W=Z.loadProfile==="never"||!Z.workingDirectory||!WB(Z.workingDirectory)?process.env:await G6(U(Z.workingDirectory.fsPath,Z.loadProfile)),H=J.env?Object.entries(J.env).reduce((V,[N,L])=>({...V,[N]:O_(L,W)}),{}):void 0,F=rx6({...W,...H}),B=O_(J.command,F),M=J.args?J.args.map((V)=>O_(V,F)):void 0;q=await Promise.resolve().then(() => (L20(),N20)).then(({StdioClientTransport:V})=>{return new V({command:B,args:M,stderr:"pipe",cwd:Z.workingDirectory&&WB(Z.workingDirectory)?Z.workingDirectory.fsPath:void 0,env:F})})}let z=[];if("stderr"in q&&q.stderr&&typeof q.stderr==="object"&&q.stderr!==null&&"on"in q.stderr&&typeof q.stderr.on==="function")q.stderr.on("data",(U)=>{let W=U.toString().trim();if(W){if(z.push(W),z.length>50)z=["[...]",...z.slice(-49)];u.info("mcp-server-stderr",{stderr:W,server:{type:"stdio"}})}});try{let U=Q.connect(q);return U.catch(()=>{}),await Promise.race([U,j_()]),{client:Q}}catch(U){let W=(H)=>{let F=Error(H);if(z.length>0)F.stderr=z.join(`
|
|
4743
|
+
`);return F};if(U instanceof Error){if(U.message.includes("Connection closed"))throw W("MCP server connection was closed unexpectedly.");else if(U.message.includes("Invalid content type"))throw W('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in J&&U.message.includes("fetch failed"))throw W(`Could not connect to MCP server at ${J.url}. Check that the server is running and accessible.`);else if(z.length>0)throw W(U.message)}throw U}}function j_(){return new Promise((J,Q)=>{let Z=setTimeout(()=>{clearTimeout(Z),Q(Error("Connection timeout: MCP server did not respond within 60 seconds"))},60000)})}function O_(J,Q){return J.replace(/\$\{([^}]+)\}/g,(Z,X)=>{let Y=Q[X];if(Y===void 0)return Z;return Y})}function rx6(J){let{AMP_API_KEY:Q,...Z}=J;return Z}async function O20(J){let Q=sx6(J),Z=JSON.stringify(Q);if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle){let K=new TextEncoder().encode(Z),G=await globalThis.crypto.subtle.digest("SHA-256",K);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let{createHash:X}=await import("node:crypto");return X("sha256").update(Z).digest("hex")}function sx6(J){if("command"in J)return{type:"command",command:J.command,args:J.args||[],env:R20(J.env||{})};return{type:"url",url:J.url,headers:R20(J.headers||{}),transport:J.transport||"http"}}function R20(J){let Q={};for(let Z of Object.keys(J).sort())Q[Z]=J[Z];return Q}I0();class KB1{async isTrusted(J){return!0}async setTrust(J,Q){}isWorkspaceTrusted(){return r1.of(!0)}async allowWorkspace(J){}}function $20({configService:J,toolService:Q,externalMCPServers:Z=r1.of({}),createOAuthProvider:X,trustStore:Y=new KB1}){let K=new E20,G=new F8,q,z=j9(J.config,Z).pipe(k0(([{settings:{mcpServers:j,mcpPermissions:E,"terminal.commands.nodeSpawn.loadProfile":I,"security.audit.logMcpConnections":T}},S])=>({mcpServers:j,mcpPermissions:E,loadProfile:I,logMcpConnections:T,externalMCPServers:S})),G8()),U=J.workspaceRoots.pipe(k0((j)=>j?.at(0))),W=new Map,H,F=j9(z,U,G.pipe(S2(void 0))).pipe(XG(300),q8(([{mcpServers:j,mcpPermissions:E,loadProfile:I,logMcpConnections:T,externalMCPServers:S},x,h])=>c6(async(v)=>{let _=K.consume(),b={...j,...S},g=tx6(H,E);H=E;for(let[k,f]of Object.entries(b)){let y=W.get(k);if(!_&&y&&ox6(y.spec,f)&&g)continue;let a="url"in f&&(!!f.oauth||!f.headers&&f.transport!=="http")&&X?await X(k):void 0,p=f._target==="workspace",e=await O20(f),G1=!1,W1;if(p){let Z1={serverName:k,specHash:e};if(!await Y.isTrusted(Z1)){if(W1=Pn(f,{workingDirectory:x,loadProfile:I},!0,E,a,k,T),G1=!0,u.info(`MCP server ${k} requires approval before execution`,{specHash:e}),!await Y.hasEntry?.(Z1))q?.(k,f)}else W1=Pn(f,{workingDirectory:x,loadProfile:I},!1,E,a,k,T)}else W1=Pn(f,{workingDirectory:x,loadProfile:I},!1,E,a,k,T);if(W.set(k,{spec:f,client:W1,isExternal:Boolean(S[k]),requiresApproval:G1,specHash:e}),y)await y.client[Symbol.asyncDispose]()}for(let[k,{client:f}]of W.entries())if(!b||!(k in b))await f[Symbol.asyncDispose](),W.delete(k);return Array.from(W.entries())})),M9({shouldCountRefs:!1})),B=F.subscribe({}),M=new Map,V=30000,N=(j)=>{if(j)M.delete(j);else M.clear()},L=F.pipe(q8((j)=>j.length===0?r1.of(!0):j9(...j.map(([E,{client:I}])=>I.tools.pipe(P7((T)=>T!==s5&&T!==H7),SN(1)))).pipe(k0(()=>!0))),SN(1)),A=j9(F.pipe(q8((j)=>j.length===0?r1.of([]):j9(...j.map(([E,{spec:I,client:T}])=>T.tools.pipe(k0((S)=>({name:E,spec:I,tools:S===s5||S instanceof Error||S===H7?[]:S,client:T}))))))),J.config.pipe(k0((j)=>j.settings.mcpPermissions),G8())).pipe(k0(([j,E])=>({mcpServers:j,mcpPermissions:E}))),w,R=A.subscribe(({mcpServers:j,mcpPermissions:E})=>{if(w)for(let T of w)T.dispose();w=[];let I=[];for(let{name:T,spec:S,tools:x,client:h}of j){if(!li(E,S)){if(x.length>0)u.error(`Ignoring ${x.length} tools from MCP server ${T} due to MCP permissions`);else u.debug(`Ignoring tools from MCP server ${T} due to MCP permissions`);continue}for(let v of x){u.debug("mcpService.toolRegisterer",{name:v.name});try{let _=j20(v,h,T);w.push(Q.registerTool(_)),I.push(_.spec.name)}catch(_){u.warn(`Failed to register MCP tool ${v.name} from ${T}:`,_)}}}if(I.length>0)G6(Q.tools.pipe(k0((T)=>I.every((S)=>T.some((x)=>x.spec.name===S))),P7(Boolean),SN(1)),AbortSignal.timeout(5000)).then(()=>{u.debug("mcpService.toolsRegistered",{registeredCount:I.length})}).catch((T)=>{u.warn("Failed to verify tool registration:",T)})},(j)=>{u.error("MCP toolRegisterer error",j)}),O=new Promise((j)=>{try{G6(L,AbortSignal.timeout(1e4)).then(()=>{u.info("mcpService.initialized",{value:Array.from(W.keys())}),j()}).catch((E)=>{u.warn("MCP service initialization failed, but service will continue:",E),j()})}catch(E){u.warn("MCP service initialization failed, but service will continue:",E),j()}}),$=j9(J.config,F).pipe(q8(([j,E])=>E.length===0?r1.of([]):j9(...E.map(([I,{spec:T,client:S,isExternal:x,requiresApproval:h,specHash:v}])=>j9(S.status,S.tools,S.prompts).pipe(k0(([_,b,g])=>({name:I,spec:T,isExternal:x,requiresApproval:h,specHash:v,status:_,tools:b instanceof Error?b:b===s5||b===H7?[]:b.map((k)=>({spec:{name:k.name,description:k.description,inputSchema:k.inputSchema,source:{mcp:I}},...fS({name:k.name,source:{mcp:I}},j)})),prompts:g instanceof Error?g:g===s5||g===H7?[]:g})))))),M9({shouldCountRefs:!1}));return{initialized:O,servers:$,restartServers(){K.replenish(),G.next()},async approveWorkspaceServer(j){let E=W.get(j);if(!E)throw Error(`MCP server not found: ${j}`);if(E.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await Y.setTrust({serverName:j,specHash:E.specHash},!0),this.restartServers()},async denyWorkspaceServer(j){let E=W.get(j);if(!E)throw Error(`MCP server not found: ${j}`);if(E.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await Y.setTrust({serverName:j,specHash:E.specHash},!1)},isWorkspaceTrusted(){return Y.isWorkspaceTrusted?.()??r1.of(!0)},getClient(j){return W.get(j)?.client},async searchResources(j){try{let E=await G6(F),I=Date.now(),T=[];for(let[S,{client:x}]of E){if((await G6(x.status)).type!=="connected")continue;try{let v,_=M.get(S);if(_&&I<_.expires)v=_.resources;else v=await x.listResources(),M.set(S,{resources:v,timestamp:I,expires:I+30000});for(let b of v){let g=b.title||b.name;if(!j||S.toLowerCase().includes(j.toLowerCase())||g.toLowerCase().includes(j.toLowerCase())||b.description?.toLowerCase().includes(j.toLowerCase())||b.uri.toLowerCase().includes(j.toLowerCase()))T.push({resource:b,serverName:S})}}catch(v){u.warn(`Failed to list resources from MCP server ${S}`,v),N(S)}}return T.slice(0,50)}catch(E){return u.warn("Failed to search MCP resources",E),[]}},async getPrompt(j,E,I,T){let S=W.get(E);if(S)try{return await S.client.getPrompt(j,I,T)}catch(x){return null}return null},async registerToolsWithService(j){return new Promise((E)=>{let I=[],T=!1,S=A.subscribe(({mcpServers:x})=>{if(u.debug("MCP tool registration triggered",{serverCount:x.length,toolCount:x.reduce((h,v)=>h+v.tools.length,0)}),I.length>0)u.debug("Disposing previous MCP tool registrations",{count:I.length});for(let h of I)h.dispose();I.length=0;for(let{name:h,tools:v,client:_}of x){u.debug("Registering MCP tools for server",{serverName:h,toolCount:v.length,toolNames:v.map((b)=>b.name)});for(let b of v)I.push(j.registerTool(j20(b,_,h)))}if(u.debug("MCP tool registration complete",{totalRegistered:I.length}),!T)T=!0,E({dispose:()=>{S.unsubscribe();for(let h of I)h.dispose();I.length=0}})},(x)=>{u.error("MCP external tool registration error",x)})})},async addServer(j,E){let I=(await J.getLatest()).settings.mcpServers;if(I&&j in I)throw Error(`MCP server already exists with name ${JSON.stringify(j)}`);if("command"in E&&typeof E.command!=="string")throw Error("Command must be a string");if("url"in E)try{new URL(E.url)}catch(T){throw Error(`Invalid URL: ${E.url}`)}await J.updateSettings("mcpServers",{...I,[j]:E},"global")},async removeServer(j){let E=(await J.getLatest()).settings.mcpServers;if(!E||!(j in E))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);let I={...E};delete I[j],await J.updateSettings("mcpServers",I,"global")},async updateServer(j,E){let I=(await J.getLatest()).settings.mcpServers;if(!I||!(j in I))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);await J.updateSettings("mcpServers",{...I,[j]:E},"global")},searchPrompts(j){return this.servers.pipe(k0((E)=>{let I=[];for(let T of E)if(T.status.type==="connected"&&Array.isArray(T.prompts)){let S=T.prompts.map((x)=>ex6(x,T.name)).filter((x)=>{if(!j)return!0;let h=j.toLowerCase();return x.label.toLowerCase().includes(h)||x.detail&&x.detail.toLowerCase().includes(h)});I.push(...S)}return I.sort((T,S)=>T.label.localeCompare(S.label)).slice(0,Math.min(10,tB))}))},async dispose(){R.unsubscribe(),B.unsubscribe();let j=Array.from(W.values()).map(async({client:E})=>{try{await E[Symbol.asyncDispose]()}catch(I){u.error("Error disposing MCP client:",I)}});await Promise.all(j),W.clear()},get onUntrustedWorkspaceServer(){return q},set onUntrustedWorkspaceServer(j){q=j}}}function ox6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function tx6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function j20(J,Q,Z){let X=`mcp__${Z.replace(/[\s-]+/g,"_")}__${J.name.replace(/\s+/g,"_")}`,Y=X.length>=64?J.name:X;return{spec:{name:Y,description:J.description??"",inputSchema:J.inputSchema,source:{mcp:Z}},fn:({args:K},G)=>c6((q)=>Q.callTool({name:J.name,arguments:K??void 0},G,q).then((z)=>{return u.debug("MCP tool call succeeded",{serverName:Z,toolName:J.name,longName:Y}),{status:"done",result:z.map((U)=>{if(U.type==="text"||U.type==="image")return U;throw Error(`unsupported content type: ${U.type}`)})}},(z)=>{throw u.error("MCP tool call failed",{serverName:Z,toolName:J.name,longName:Y,error:z instanceof Error?z.message:String(z),errorName:z instanceof Error?z.name:typeof z,stack:z instanceof Error?z.stack:void 0}),z}))}}class E20{forceRestart=!1;consume(){let J=this.forceRestart;return this.forceRestart=!1,J}replenish(){this.forceRestart=!0}}function ex6(J,Q){let Z=J.arguments?.map((Y)=>({name:Y.name,required:Y.required??!1}))||[],X={uri:$6(`mcp://${Q}/${J.name}`),label:`${Q}/${J.name}`,detail:J.description||`From ${Q}`,insertText:"",filterText:`${J.name} ${J.description||""}`.toLowerCase()};return{...X,kind:"prompt",promptData:{...X,arguments:Z}}}FG();qB1();b6();I0();G0();H3();var c20=C6(x20(),1);b6();I0();G0();FB1();jZ();Vj();import*as uX from"node:fs";import*as fn from"node:path";var $2={readFile:async(J,Q)=>{try{return await uX.promises.readFile(N8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await uX.promises.readFile(N8(J).fsPath,{signal:Q?.signal})}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await uX.promises.stat(N8(J).fsPath)).mtimeMs}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},stat:async(J,Q)=>{J=N8(J);try{let Z=await uX.promises.stat(J.fsPath);return{name:fn.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},realpath:async(J,Q)=>{return _b6(N8(J))},rename:async(J,Q)=>{try{await uX.promises.rename(N8(J).fsPath,N8(Q).fsPath)}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await uX.promises.writeFile(N8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=N8(J);try{if(Q?.recursive)await uX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await uX.promises.unlink(J.fsPath)}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},mkdirp:async(J)=>{await uX.promises.mkdir(N8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=N8(J);try{return(await uX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:A0.file(fn.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(pW(Z))throw new ZJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await yn(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>VG(X)?A0.file(X):y0.joinPath(J.base,X))}catch(Z){return u.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=N8(J);kb6(Z);try{await uX.promises.access(Z.fsPath)}catch(X){if(pW(X))throw new ZJ(Z);throw X}}};function kb6(J){if(!WB(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function pW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function _b6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return A0.file(await uX.promises.realpath(J.fsPath))}catch(Q){if(pW(Q))throw new ZJ(J);throw Q}}async function d20(J,Q){if(!J.startsWith(process.cwd()))return;if(await C7.isConnected())try{let Z=await C7.sendRequest("readFile",{path:J});if(Z?.content)return Q(Z.content);throw Error(`Failed to readFile via IDE ${J}: ${Z?.message??"unknown cause"}`)}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;u.debug("IDE readFile failed, falling back to Node.js filesystem",{path:J,error:Z});return}else return}async function xb6(J,Q){if(!J.startsWith(process.cwd()))return!1;if(await C7.isConnected())try{let Z=await C7.sendRequest("editFile",{path:J,fullContent:Q});if(!Z?.success)throw Error(`Failed to writeFile via IDE ${J}: ${Z?.message??"unknown cause"}`);return!0}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;return u.debug("IDE writeFile failed, falling back to Node.js filesystem",{path:J,error:Z}),!1}else return!1}var l20={readFile:async(J,Q)=>{let Z=N8(J).fsPath;return u.debug("ide-fs",{method:"readFile",path:Z}),await d20(Z,(X)=>X)??await $2.readFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readFile",uri:J})})},readBinaryFile:async(J,Q)=>{let Z=N8(J).fsPath;u.debug("ide-fs",{method:"readBinaryFile",path:Z});let X;if(!await c20.isBinaryFile(Z))X=await d20(Z,(Y)=>Buffer.from(Y,"utf8"));return X??await $2.readBinaryFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readBinaryFile",uri:J})})},getMtime:async(J,Q)=>{return $2.getMtime(J,Q)},stat:async(J,Q)=>{return $2.stat(J,Q)},realpath:async(J,Q)=>{return $2.realpath(J,Q)},rename:async(J,Q)=>{return $2.rename(J,Q)},writeFile:async(J,Q,Z)=>{let X=N8(J).fsPath;if(u.debug("ide-fs",{method:"writeFile",path:X}),await xb6(X,Q))return;return await $2.writeFile(J,Q,Z).finally(()=>{u.debug("ide-fs",{fallback:"writeFile",uri:J})})},delete:async(J,Q)=>{return $2.delete(J,Q)},mkdirp:async(J)=>{return $2.mkdirp(J)},readdir:async(J,Q)=>{return $2.readdir(J,Q)},findFiles:async(J,Q)=>{return $2.findFiles(J,Q)},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return $2.access(J,Q)}};jG();gY();AD();b6();import{homedir as mb6}from"node:os";import e20 from"node:path";var J$=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,s20=new Set,MB1=typeof process==="object"&&!!process?process:{},o20=(J,Q,Z,X)=>{typeof MB1.emitWarning==="function"?MB1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},gn=globalThis.AbortController,r20=globalThis.AbortSignal;if(typeof gn>"u"){r20=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},gn=class{constructor(){Q()}signal=new r20;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=MB1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,o20("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}var hb6=(J)=>!s20.has(J),F$9=Symbol("type"),jD=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),t20=(J)=>!jD(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?S_:null;class S_ extends Array{constructor(J){super(J);this.fill(0)}}class Q${heap;length;static#J=!1;static create(J){let Q=t20(J);if(!Q)return[];Q$.#J=!0;let Z=new Q$(J,Q);return Q$.#J=!1,Z}constructor(J,Q){if(!Q$.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}class mn{#J;#Q;#Y;#X;#q;#I;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#G;#Z;#B;#M;#F;#W;#A;#H;#w;#R;#V;#O;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#R,ttls:J.#V,sizes:J.#w,keyMap:J.#z,keyList:J.#G,valList:J.#Z,next:J.#B,prev:J.#M,get head(){return J.#F},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#j(Q),rindexes:(Q)=>J.#$(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Q}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#I}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#q}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:G,allowStale:q,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:H,noUpdateTTL:F,maxSize:B=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:O,ignoreFetchAbort:$}=J;if(Q!==0&&!jD(Q))throw TypeError("max option must be a nonnegative integer");let j=Q?t20(Q):Array;if(!j)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Q=B,this.maxEntrySize=M||this.#Q,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Q&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#I=N,this.#C=!!N,this.#z=new Map,this.#G=Array(Q).fill(void 0),this.#Z=Array(Q).fill(void 0),this.#B=new j(Q),this.#M=new j(Q),this.#F=0,this.#W=0,this.#A=Q$.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#q=W,this.#H=[];else this.#q=void 0,this.#H=void 0;if(this.#O=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#q,this.noDisposeOnSet=!!H,this.noUpdateTTL=!!F,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!$,this.maxEntrySize!==0){if(this.#Q!==0){if(!jD(this.#Q))throw TypeError("maxSize must be a positive integer if specified")}if(!jD(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!q,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!G,this.ttlResolution=jD(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!jD(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Q===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Q){if(hb6("LRU_CACHE_UNBOUNDED"))s20.add("LRU_CACHE_UNBOUNDED"),o20("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",mn)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new S_(this.#J),Q=new S_(this.#J);this.#V=J,this.#R=Q,this.#h=(Y,K,G=J$.now())=>{if(Q[Y]=K!==0?G:0,J[Y]=K,K!==0&&this.ttlAutopurge){let q=setTimeout(()=>{if(this.#N(Y))this.#E(this.#G[Y],"expire")},K+1);if(q.unref)q.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?J$.now():0},this.#P=(Y,K)=>{if(J[K]){let G=J[K],q=Q[K];if(!G||!q)return;Y.ttl=G,Y.start=q,Y.now=Z||X();let z=Y.now-q;Y.remainingTTL=G-z}};let Z=0,X=()=>{let Y=J$.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let G=J[K],q=Q[K];if(!G||!q)return 1/0;let z=(Z||X())-q;return G-z},this.#N=(Y)=>{let K=Q[Y],G=J[Y];return!!G&&!!K&&(Z||X())-K>G}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new S_(this.#J);this.#L=0,this.#w=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!jD(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!jD(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#x=(Q,Z,X)=>{if(J[Q]=Z,this.#Q){let Y=this.#Q-J[Q];while(this.#L>Y)this.#b(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#x=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#F)break;else Q=this.#M[Q]}}*#$({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#F;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#G[J])===J}*entries(){for(let J of this.#j())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*rentries(){for(let J of this.#$())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*keys(){for(let J of this.#j()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*rkeys(){for(let J of this.#$()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*values(){for(let J of this.#j())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}*rvalues(){for(let J of this.#$())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#G[Z],this))return this.get(this.#G[Z],Q)}}forEach(J,Q=this){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}rforEach(J,Q=this){for(let Z of this.#$()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#$({allowStale:!0}))if(this.#N(Q))this.#E(this.#G[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Z[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#R){let K=this.#V[Q],G=this.#R[Q];if(K&&G){let q=K-(J$.now()-G);Y.ttl=q,Y.start=Date.now()}}if(this.#w)Y.size=this.#w[Q];return Y}dump(){let J=[];for(let Q of this.#j({allowStale:!0})){let Z=this.#G[Q],X=this.#Z[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#R){K.ttl=this.#V[Q];let G=J$.now()-this.#R[Q];K.start=Math.floor(Date.now()-G)}if(this.#w)K.size=this.#w[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=J$.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:G=this.sizeCalculation,status:q}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,G);if(this.maxEntrySize&&U>this.maxEntrySize){if(q)q.set="miss",q.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#b(!1):this.#U,this.#G[W]=J,this.#Z[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#x(W,U,q),q)q.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let H=this.#Z[W];if(Q!==H){if(this.#C&&this.#K(H)){H.__abortController.abort(Error("replaced"));let{__staleWhileFetching:F}=H;if(F!==void 0&&!K){if(this.#O)this.#Y?.(F,J,"set");if(this.#D)this.#H?.push([F,J,"set"])}}else if(!K){if(this.#O)this.#Y?.(H,J,"set");if(this.#D)this.#H?.push([H,J,"set"])}if(this.#v(W),this.#x(W,U,q),this.#Z[W]=Q,q){q.set="replace";let F=H&&this.#K(H)?H.__staleWhileFetching:H;if(F!==void 0)q.oldValue=F}}else if(q)q.set="update";if(this.#_)this.onInsert?.(Q,J,Q===H?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(q)this.#P(q,W)}if(!K&&this.#D&&this.#H){let H=this.#H,F;while(F=H?.shift())this.#q?.(...F)}return this}pop(){try{while(this.#U){let J=this.#Z[this.#F];if(this.#b(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#H){let J=this.#H,Q;while(Q=J?.shift())this.#q?.(...Q)}}}#b(J){let Q=this.#F,Z=this.#G[Q],X=this.#Z[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(X,Z,"evict");if(this.#D)this.#H?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#G[Q]=void 0,this.#Z[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#F=this.#W=0,this.#A.length=0;else this.#F=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Z[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Z[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Z[Q];if(this.#K(Y))return Y;let K=new gn,{signal:G}=Z;G?.addEventListener("abort",()=>K.abort(G.reason),{signal:K.signal});let q={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=F;if(this.#Z[Q]===F)if(M===void 0)if(A.__staleWhileFetching)this.#Z[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,q.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,w=F;if(this.#Z[Q]===F){if(!A||w.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Z[Q]=w.__staleWhileFetching}if(L){if(Z.status&&w.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw M},H=(M,V)=>{let N=this.#I?.(J,Y,q);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let F=new Promise(H).then(z,U),B=Object.assign(F,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,B,{...q.options,status:void 0}),Q=this.#z.get(J);else this.#Z[Q]=B;return B}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof gn}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:G=this.noDisposeOnSet,size:q=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:H=this.allowStaleOnFetchRejection,ignoreFetchAbort:F=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:G,size:q,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:H,allowStaleOnFetchAbort:B,ignoreFetchAbort:F,status:N,signal:L},w=this.#z.get(J);if(w===void 0){if(N)N.fetch="miss";let R=this.#y(J,w,A,M);return R.__returned=R}else{let R=this.#Z[w];if(this.#K(R)){let I=Z&&R.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",I)N.returnedStale=!0}return I?R.__staleWhileFetching:R.__returned=R}let O=this.#N(w);if(!V&&!O){if(N)N.fetch="hit";if(this.#k(w),X)this.#S(w);if(N)this.#P(N,w);return R}let $=this.#y(J,w,A,M),E=$.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=O?"stale":"refresh",E&&O)N.returnedStale=!0}return E?$.__staleWhileFetching:$.__returned=$}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,G=this.get(J,K);if(!Y&&G!==void 0)return G;let q=Z(J,G,{options:K,context:X});return this.set(J,q,K),q}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,G=this.#z.get(J);if(G!==void 0){let q=this.#Z[G],z=this.#K(q);if(K)this.#P(K,G);if(this.#N(G)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?q:void 0}else{if(K&&Z&&q.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?q.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return q.__staleWhileFetching;if(this.#k(G),X)this.#S(G);return q}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#F)this.#F=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Z[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(Y,J,Q);if(this.#D)this.#H?.push([Y,J,Q])}if(this.#z.delete(J),this.#G[X]=void 0,this.#Z[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#F)this.#F=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let G=this.#B[X];this.#M[G]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#H?.length){let X=this.#H,Y;while(Y=X?.shift())this.#q?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#$({allowStale:!0})){let Z=this.#Z[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#G[Q];if(this.#O)this.#Y?.(Z,X,J);if(this.#D)this.#H?.push([Z,X,J])}}if(this.#z.clear(),this.#Z.fill(void 0),this.#G.fill(void 0),this.#V&&this.#R)this.#V.fill(0),this.#R.fill(0);if(this.#w)this.#w.fill(0);if(this.#F=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#H){let Q=this.#H,Z;while(Z=Q?.shift())this.#q?.(...Z)}}}b6();I0();G0();jZ();function un(J,Q,Z){let X=new F8,K=(()=>{let B=new Map;return(M,V)=>{let L=(B.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(B.get(M)===L)B.delete(M)});return B.set(M,L),L}})(),G=Z?y0.joinPath(Q,Z):Q;function q(B){return y0.joinPath(G,`${B.toString()}.json`)}async function z(B){let M=q(B);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);u.warn(`File too large to load safely: ${String(B)} (${L}MB)`,{key:String(B),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:w,contentPreview:R}=gb6(V);u.warn("Corrupted JSON detected.",{key:String(B),storageUri:G.toString(),error:A.message,contentLength:w,contentPreview:R});return}}catch(V){if(EQ(V))return;throw V}}async function U(B,M){let V=q(B),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(y0.joinPath(V,"..")),await K(B,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(B)}async function W(B){let M=q(B);await K(B,async()=>{await J.delete(M)}),X.next(B)}async function H(){let B;try{B=await J.readdir(G)}catch(M){if(EQ(M))return[];throw M}return B.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function F(B){return q(B).fsPath}return{get:z,set:U,delete:W,keys:H,path:F,changes:X}}function gb6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}async function J40(J){let Q=J.isDevelopment||!1,Z=ub6(),Y=un($2,Z,Q?"threads-development":"threads");return new Q40(Y)}class Q40{delegate;cache=new mn({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){this.cache.set(J,Q),await this.delegate.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function ub6(){let J=process.env.XDG_DATA_HOME||e20.join(mb6(),".local","share"),Q=e20.resolve(J,"amp");return A0.file(Q)}pn();Q2();b6();G0();Z$();k_();class NB1{storage;index=new Map;initialized=!1;initPromise=null;constructor(J){this.storage=J;this.ensureInitialized(),this.setupChangeListener()}async search(J,Q=20){if(!this.initialized)return[];if(this.index.size===0)return[];let Z=Array.from(this.index.entries()).map(([K,G])=>{return new IZ({id:K,kind:"file",path:G,uri:A0.parse(`thread://${K}`),metadata:{size:0,mtime:0,isSymlink:!1}})});return new dn(J,{maxResults:Q,minScore:J?400:0}).match(Z).map((K)=>({id:K.entry.id,title:K.entry.path,score:K.score}))}async ensureInitialized(){if(this.initialized)return;if(this.initPromise)return this.initPromise;return this.initPromise=this.loadIndex(),this.initPromise}async loadIndex(){try{let J=await this.storage.keys(),Q=50;for(let Z=0;Z<J.length;Z+=50){let X=J.slice(Z,Z+50),Y=await Promise.all(X.map(async(K)=>{return(await this.storage.get(K))?.title||null}));for(let K=0;K<X.length;K++){let G=X[K],q=Y[K];if(G&&q&&q.trim().length>0)this.index.set(G,q)}if(Z+50<J.length)await new Promise((K)=>setImmediate(K))}this.initialized=!0,u.debug("Thread fuzzy indexer initialized",{indexedCount:this.index.size})}catch(J){u.warn("Failed to load thread index",J),this.initialized=!0}}setupChangeListener(){this.storage.changes.subscribe(async(J)=>{if(!this.initialized)return;if(J===void 0){await this.loadIndex();return}try{let Q=await this.storage.get(J);if(Q?.title)this.index.set(J,Q.title);else this.index.delete(J)}catch(Q){u.warn("Failed to update thread index for change",{key:J,error:Q})}})}dispose(){this.index.clear(),this.initialized=!1,this.initPromise=null}}I0();I0();function Z40(J){let Q={},Z=!0;return J.changes.pipe(S2(void 0),GW(async(X,Y)=>{if(X===void 0||Z){let K=await J.keys();Y?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(K.map(async(G)=>[G,await J.get(G)]))),Y?.throwIfAborted(),Z=!1}else{let K=await J.get(X);if(Y?.throwIfAborted(),K===void 0)Q={...Q,[X]:void 0},delete Q[X];else Q={...Q,[X]:K}}return Q}))}Q2();class LB1{storage;constructor(J,Q={}){this.storage=J;if(!Q.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=Cc1(Z40(this.storage).pipe(k0((J)=>{let Q=Object.values(J).filter((X)=>X&&("messages"in X)).toSorted((X,Y)=>Y.created-X.created),Z=[];for(let X of Q)if(!(X.messages.length===0&&!X.draft))Z.push(X);return Z.map((X)=>({id:X.id,v:X.v,created:X.created,title:X.title??null,userLastInteractedAt:ln(X),env:X.env,originThreadID:X.originThreadID,mainThreadID:X.mainThreadID,summaryStats:{diffStats:Rc(X)}})).toSorted((X,Y)=>Y.userLastInteractedAt-X.userLastInteractedAt)}),M9()))}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable}observeThreadList(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable.pipe(G8((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Z,X)=>{let Y=Q[X];if(!Y)return!1;return Z.id===Y.id&&Z.title===Y.title&&Z.userLastInteractedAt===Y.userLastInteractedAt&&Z.mainThreadID===Y.mainThreadID&&JSON.stringify(Z.env?.initial?.trees?.map((K)=>K.displayName))===JSON.stringify(Y.env?.initial?.trees?.map((K)=>K.displayName))})}))}_observeHistory;dispose(){this._observeHistory?.subscription.unsubscribe()}}function ln(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}Q2();function Y$(J,Q){let Z=[];if(Z.push(cb6(J,Q)),J.title)Z.push(`# ${J.title}`);let X=DZ(J),Y=X?X.index:0;for(let K=Y;K<J.messages.length;K++){let G=J.messages[K];if(G)Z.push(lb6(G))}return Z.join(`
|
|
4744
4744
|
|
|
4745
4745
|
`)}function cb6(J,Q){let Z=["---"];if(J.title)Z.push(`title: ${J.title}`);if(Q)Z.push(`author: ${Q}`);if(Z.push(`threadId: ${J.id}`),Z.push(`created: ${new Date(J.created).toISOString()}`),J.agentMode)Z.push(`agentMode: ${J.agentMode}`);return Z.push("---"),Z.join(`
|
|
4746
4746
|
`)}function lb6(J){switch(J.role){case"user":return ib6(J);case"assistant":return ab6(J);case"info":return nb6(J)}}function ib6(J){let Q=["## User"];if(J.interrupted)Q.push("*(interrupted)*");for(let Z of J.content)switch(Z.type){case"text":Q.push(AB1(Z,!0));break;case"image":Q.push(rb6(Z));break;case"tool_result":Q.push(eb6(Z));break}return Q.join(`
|
|
@@ -6139,11 +6139,11 @@ Actual: ${Y}`)}async function W29(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
6139
6139
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
6140
6140
|
|
|
6141
6141
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
6142
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(F)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function E51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=M29(J,G),z=q<0,U,W;if(K.time){let H=K.time[J],F=K.time[G],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function M29(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}I0();function qf1(J,Q){let Z=new F8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new nq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await A_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await E51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await $51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Zp(z.latestVersion,U);let W=await XN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await A_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as oU}from"node:process";function HZ6(J){let Q=new QR().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await Yf1(X.force||!1,X.verbose||!1,"0.0.
|
|
6142
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(F)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${F.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function E51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=M29(J,G),z=q<0,U,W;if(K.time){let H=K.time[J],F=K.time[G],B=Date.now();if(H)U=Math.floor((B-new Date(H).getTime())/3600000);if(F)W=Math.floor((B-new Date(F).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function M29(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}I0();function qf1(J,Q){let Z=new F8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new nq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await A_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await E51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await $51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Zp(z.latestVersion,U);let W=await XN(z.latestVersion),H={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",H),Z.next("updated");else Y.warn("success with warning",H),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await A_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as oU}from"node:process";function HZ6(J){let Q=new QR().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await Yf1(X.force||!1,X.verbose||!1,"0.0.1761911084-ge88213"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new QR("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await V29(X.version)});J.addCommand(Z)}async function V29(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")oU.write(W8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
6143
6143
|
|
|
6144
6144
|
`));try{if(!J){oU.write(W8.blue(`Checking for updates...
|
|
6145
|
-
`));let{hasUpdate:Z,latestVersion:X}=await E51("0.0.
|
|
6146
|
-
`));let Y=await XN("0.0.
|
|
6145
|
+
`));let{hasUpdate:Z,latestVersion:X}=await E51("0.0.1761911084-ge88213");if(!Z){oU.write(W8.green(`✓ Amp CLI is already up to date.
|
|
6146
|
+
`));let Y=await XN("0.0.1761911084-ge88213");if(Y.warning)oU.write(`
|
|
6147
6147
|
`+W8.yellow(Y.warning)+`
|
|
6148
6148
|
`);process.exit(0)}if(!X)oU.write(W8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}oU.write(W8.blue(`Updating to version ${J}...
|
|
6149
6149
|
`)),await Zp(J,void 0,(Z)=>{oU.write(W8.dim(`Running: ${Z}
|
|
@@ -6704,7 +6704,7 @@ exit code: ${q}`,new j1({color:X.foreground,dim:!0,italic:!0})));if(z)U.push(new
|
|
|
6704
6704
|
`,B),...M],N=new l0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a1({text:new M1("",void 0,V)})]}),L="high";if(this.agentMode==="fast")L="fast";else if(this.agentMode==="free")L="free";return J2.child(new f0({constraints:new j6(40,120,0,1/0),child:new Q8({mainAxisAlignment:"center",crossAxisAlignment:"center",children:[new R8({flex:1,child:new Fh1({width:40,height:40,colorMode:L,fps:G==="fast"?60:G==="slow"?15:0,...G==="disabled"&&{seed:42,t:3}})}),new H0({width:1}),new R8({flex:2,child:N})]})}))}}i8();class Hm1 extends c0{props;constructor(J){super({key:J.key});this.props=J;this.props.enabled??=!0}createState(){return new sG6}}class sG6 extends d0{build(J){let Z=A6.of(J).colors,{todos:X,title:Y="TODOs",enabled:K=!0}=this.widget.props;if(!Array.isArray(X)||X.length===0)return new H0({width:0,height:0});let G=K?Z.foreground:Z.mutedForeground,q=X.map((z)=>this.buildTodoItem(z,Z,K));return new f0({child:new T6({padding:N0.symmetric(1,0),child:new l0({crossAxisAlignment:"stretch",mainAxisSize:"min",children:[new a1({text:new M1(Y,new j1({bold:!0,color:G}))}),...q]})})})}buildTodoItem(J,Q,Z){let X=this.getStatusIcon(J.status),Y=Z?Q.foreground:Q.mutedForeground,K=new j1({bold:J.status==="in-progress",color:Y}),G=new j1({bold:J.status==="in-progress",strikethrough:J.status==="completed",color:Y});return new Q8({crossAxisAlignment:"start",children:[new a1({text:new M1(X,K)}),new H0({width:1}),new R8({child:new a1({text:new M1(J.content,G)})})]})}getStatusIcon(J){return J==="completed"?"✓":"•"}}class Fm1 extends O6{ad;onDismiss;onButtonClick;constructor({key:J,ad:Q,onDismiss:Z,onButtonClick:X}){super({key:J});this.ad=Q,this.onDismiss=Z,this.onButtonClick=X}build(J){let Q=A6.of(J),Z=Q.colors.primary,X=Q.colors.foreground;return new f0({decoration:new G9(void 0,new m8(new _8(Z,1,"rounded"),new _8(Z,1,"rounded"),void 0,new _8(Z,1,"rounded"))),child:new T6({padding:N0.horizontal(1),child:new l0({children:[new Q8({crossAxisAlignment:"start",children:[new R8({child:new a1({text:new M1(this.ad.content,new j1({color:X}))})}),new H0({width:4}),new DQ({uri:"https://ampcode.com/free",text:"Ad",style:new j1({color:X,dim:!0}),onError:(Y)=>{}})]}),new Q8({crossAxisAlignment:"start",children:[new nf1({text:this.ad.buttonLabel,onPressed:()=>this.onButtonClick?.(),padding:N0.horizontal(1),color:Z,reverse:!0}),new H0({width:2}),new a1({text:new M1(this.ad.destinationUrlHostname,new j1({color:X,dim:!0}))})]})]})})})}}B9();i8();class Bm1 extends c0{props;constructor(J){super();this.props=J}createState(){return new oG6(this.props.autofocus??!0)}}class oG6 extends d0{autofocus;constructor(J){super();this.autofocus=J}build(J){let Q=(q)=>{if(q.key==="Enter"&&this.widget.props.showCopyOption)return this.widget.props.onSelect("copy"),"handled";if(q.ctrlKey&&q.key==="c"||q.key==="Escape")return this.widget.props.onSelect(null),"handled";return"ignored"},Z=f8.sizeOf(J),X=Math.min(60,Z.width-4),Y=Z.height-4,K=[];if(this.widget.props.title)K.push(new a1({text:new M1(this.widget.props.title,new j1({bold:!0,color:E1.blue}))}),new H0({height:1}));if(this.widget.props.message)K.push(new a1({text:new M1(this.widget.props.message,void 0,void 0,{uri:this.widget.props.message,id:"ad-link"})}));if(this.widget.props.message)K.push(new H0({height:1}));let G=[];if(this.widget.props.showCopyOption)G.push(new a1({text:new M1("Enter to copy",new j1({dim:!0}))}));return G.push(new a1({text:new M1("Escape to close",new j1({dim:!0}))})),K.push(new Q8({children:G.flatMap((q,z)=>z<G.length-1?[q,new H0({width:1}),new a1({text:new M1("•",new j1({dim:!0}))}),new H0({width:1})]:[q]),mainAxisSize:"min"})),new J2({child:new f0({constraints:new j6(X,X,0,Y),decoration:new G9(E1.default(),new m8(new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"),new _8(E1.blue,1,"rounded"))),padding:new N0(2,2,2,2),child:new t8({autofocus:this.autofocus,onKey:Q,child:new l0({children:K,mainAxisSize:"min"})})})})}}function Dm1(J){let Q=J.match(/"([^"]*)"|'([^']*)'|([^\s"']+)/g);if(!Q)return[];return Q.map((Z)=>{if(Z.startsWith('"')&&Z.endsWith('"')||Z.startsWith("'")&&Z.endsWith("'"))return Z.slice(1,-1);return Z})}Bj();G0();import{spawn as jX9}from"node:child_process";import{promises as $X9}from"node:fs";function tG6(J){return J.kind==="executable"}function eG6(J){return J.kind==="markdown"}var YB=50000,Jq6=300000;async function Mm1(J,Q,Z,X={}){let{timeoutMs:Y=Jq6,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(u.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),eG6(G))return await EX9(G,Q);else if(tG6(G))return await IX9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return u.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function EX9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await $X9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>YB?Z.slice(0,YB)+`
|
|
6705
6705
|
... (output truncated at ${YB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function IX9(J,Q,Z=Jq6,X){return new Promise((Y)=>{let[K,G]=PX9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=Pe1(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=jX9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),H=[],F=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=YB)H.push(V);else{let N=YB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=YB)F.push(V);else{let N=YB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:H.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(q.signal.aborted){Y({success:!1,output:H.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=H.join(""),L=F.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6706
6706
|
${L}`:L;if(B>YB)A+=`
|
|
6707
|
-
... (output truncated at ${YB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function PX9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return CX9(Z,X?[...X]:null,Y,Q);else return TX9(Z,X?[...X]:null,Y,Q)}function TX9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CX9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();H2();SB();gY();mW();tC();import{execSync as Qq6}from"child_process";import{writeFile as SX9}from"fs/promises";import vX9 from"path";G0();gY();class Vm1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.
|
|
6707
|
+
... (output truncated at ${YB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:H.join(""),error:V})})})}function PX9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return CX9(Z,X?[...X]:null,Y,Q);else return TX9(Z,X?[...X]:null,Y,Q)}function TX9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function CX9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();H2();SB();gY();mW();tC();import{execSync as Qq6}from"child_process";import{writeFile as SX9}from"fs/promises";import vX9 from"path";G0();gY();class Vm1{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761911084-ge88213"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await Nn(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}function kX9(J){return J.startsWith("custom-command-")}function Zq6(J){return J.startsWith("agent-mode-")}function _X9(J){return J.replace(/^custom-command-/,"")}class Nm1{configService;registry;onExecute;onExecutionComplete;commands=new Map;latestCustom=[];telemetrySubmitter;constructor(J,Q,Z,X){this.configService=J;this.registry=Q;this.onExecute=Z;this.onExecutionComplete=X;this.configService.config.subscribe((Y)=>{this.commands.clear(),this.registerCommands(Y)}),this.registry.commands.subscribe((Y)=>this.latestCustom=Y),this.telemetrySubmitter=new Vm1(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService)}async execute(J,Q,Z=[]){this.telemetrySubmitter.submit(J).catch((W)=>{u.debug("Failed to submit command telemetry",W)});let X=new AbortController,Y=Date.now(),K=`command-${Y}-${Math.random().toString(36).substring(7)}`,G=this.commands.get(J);if(G){this.onExecute({id:K,name:G.id,startTime:Y,abortController:X});let W=await G.execute(Q,Z);return this.onExecutionComplete(),W}let q=_X9(J),z=this.latestCustom.find((W)=>W.name===q);if(!z)return;this.onExecute({id:K,name:z.name,startTime:Y,abortController:X});let U=await Mm1(q,Z,this.registry,{signal:X.signal});if(this.onExecutionComplete(),U.success){let W=Q.editorState.text,F=W.trim()&&!W.endsWith(`
|
|
6708
6708
|
|
|
6709
6709
|
`)?`
|
|
6710
6710
|
${U.output}`:U.output;Q.editorDispatch({type:"insert-text",text:F});return}return Error(U.error??`Command '${J}' failed`)}getPriority(J,Q){if(kX9(J))return 4;if(Q.editorState.hasSelection)switch(J){case"copy-selection":return 60}if(this.isThreadEmpty(Q)){if(Zq6(J))return 59;switch(J){case"set-agent-mode":return 58;case"toggle-agent-mode":return 57}}if(this.hasPromptText(Q)&&Q.isProcessing)switch(J){case"queue":return 39;case"dequeue":return 37}if(Q.isProcessing)switch(J){case"queue":return 29;case"dequeue":return 27}if(this.hasPromptText(Q))switch(J){case"handoff":return 19;case"editor":return 18;case"clear":return 17}if(Zq6(J))return 0;switch(J){case"help":return 10;case"continue":return 9;case"new":return 8;case"handoff":return 7;case"editor":return 6;case"browser":case"url":case"visibility":case"toggle-thinking-blocks":case"queue":case"clear":case"copy-selection":case"dequeue":case"generate-agent-file":case"agent-files":case"connect":case"disconnect":case"settings":case"permissions":case"permissions-enable":case"permissions-disable":case"ide":case"toggle-agent-mode":case"set-agent-mode":case"show-costs":case"refresh":case"debug-thread-json":return 1;case"quit":return 0}}getCommandFollows(J){switch(J){case"handoff":return["new"];case"quit":return["queue","dequeue"];case"set-agent-mode":case"toggle-agent-mode":return zW().map(({mode:Q})=>`agent-mode-${Q}`);default:return[]}}registerCommands(J){this.register({id:"new",noun:"thread",verb:"new",description:"Start new thread",aliases:["start"],execute:async(X)=>{await X.startNewThread()},isEnabled:(X)=>!this.isThreadEmpty(X)}),this.register({id:"continue",noun:"thread",verb:"switch",description:"Switch to existing thread",aliases:["continue"],gatherArguments:async(X,Y)=>{return await Y.launchThreadPicker()},execute:async(X,Y)=>{await X.switchToThread(Y)},isEnabled:()=>!0}),this.register({id:"handoff",noun:"thread",verb:"handoff",description:"Draft a new thread based on current thread",gatherArguments:async(X,Y)=>{if(this.hasPromptText(X))return{text:X.editorState.text,images:[]};return await Y.launchMultilinePrompt("handoff","Describe a prompt to hand off...")},execute:async(X,Y)=>{if(typeof Y==="string")return X.handleHandoff(Y,[]);return X.handleHandoff(Y.text,Y.images)},isEnabled:(X)=>!this.isThreadEmpty(X),getPromptText:(X)=>{if(this.hasPromptText(X))return this.truncatedPromptText(X)},nonBlocking:!0}),this.register({id:"browser",noun:"thread",verb:"open in browser",description:"Open thread in browser",execute:async({thread:X,ampURL:Y})=>{let K=N_(new URL(Y),X.id).toString();try{await $X(K)}catch(G){u.error("Failed to open browser",{error:G})}},isEnabled:(X)=>!this.isThreadEmpty(X)}),this.register({id:"url",noun:"thread",verb:"copy URL",description:"Copy thread URL",execute:async(X)=>{let Y=N_(new URL(X.ampURL),X.thread.id).toString();try{return await y9.instance.tuiInstance.clipboard.writeText(Y),new tK(`Thread URL: ${Y}
|
|
@@ -6760,7 +6760,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6760
6760
|
`),J.stdout.write(`Thread: ${F}
|
|
6761
6761
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6762
6762
|
`)}}function Xu1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):oY9(J)}function oY9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return E1.index(Z[X])}bf1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){JG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6763
|
-
`)}var Ku1=Yu1.join(kc1||Yu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function ZK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function dq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")KG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new _9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")KG("experimental.agentMode",Q.agentMode)}async function qu1(J){try{await eY9(Yu1.dirname(Ku1),{recursive:!0}),await JK9(Ku1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function XK9(){try{return(await Az6(Ku1,"utf-8")).trim()}catch(J){return null}}function YK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return od("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var Vz6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??$J,description:`Custom settings file path (overrides the default location ${$J})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cy1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:FQ(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:xl1}],Nz6=(J)=>("deprecated"in J)&&J.deprecated===!0,KK9=(J)=>("hidden"in J)&&J.hidden===!0,GK9=(J)=>("default"in J),qK9=(J)=>("default"in J)?J.default:void 0;function zK9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new _9(lK.unknownCommand(Z),1,G)}}var wz6=null;function ir2(){return wz6}function AQ1(J){return{...J,getThreadEnvironment:e71,vfs:n20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new v_(J.fileSystem),generateThreadTitle:qq0,deleteThread:(Q)=>J.threadService.delete(Q)}}var zu1=A0.file(QK9.homedir()),Rz6=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(zu1,".config");async function cq(J,Q){ii1("0.0.
|
|
6763
|
+
`)}var Ku1=Yu1.join(kc1||Yu1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function ZK9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function dq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")KG("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new _9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${W8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")KG("experimental.agentMode",Q.agentMode)}async function qu1(J){try{await eY9(Yu1.dirname(Ku1),{recursive:!0}),await JK9(Ku1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function XK9(){try{return(await Az6(Ku1,"utf-8")).trim()}catch(J){return null}}function YK9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return od("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var Vz6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??$J,description:`Custom settings file path (overrides the default location ${$J})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Cy1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:FQ(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:xl1}],Nz6=(J)=>("deprecated"in J)&&J.deprecated===!0,KK9=(J)=>("hidden"in J)&&J.hidden===!0,GK9=(J)=>("default"in J),qK9=(J)=>("default"in J)?J.default:void 0;function zK9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new _9(lK.unknownCommand(Z),1,G)}}var wz6=null;function ir2(){return wz6}function AQ1(J){return{...J,getThreadEnvironment:e71,vfs:n20({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new v_(J.fileSystem),generateThreadTitle:qq0,deleteThread:(Q)=>J.threadService.delete(Q)}}var zu1=A0.file(QK9.homedir()),Rz6=process.env.XDG_CONFIG_HOME?A0.file(process.env.XDG_CONFIG_HOME):y0.joinPath(zu1,".config");async function cq(J,Q){ii1("0.0.1761911084-ge88213");let Z=CX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:r1.of([A0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:zu1,userConfigDir:Rz6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (NQ1(),VQ1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=_n(xB({configService:Z})),G=new Map,q=()=>G.clear(),z=$20({configService:Z,toolService:K,createOAuthProvider:async(E)=>{let I=G.get(E);if(I)return u.debug("Reusing existing OAuth provider for server",{serverName:E}),I;u.debug("Creating OAuth provider for server",{serverName:E});let T=(async()=>{let S=new V3(J.secrets),x=await S.getClientInfo(E),h=new tU1({storage:S,serverName:E,clientId:x?.clientId,clientSecret:x?.clientSecret,scopes:x?.scopes});return u.debug("OAuth provider created",{serverName:E,hasManualClientId:!!x?.clientId,willUseDCR:!x?.clientId}),h})();return G.set(E,T),T}}),U=hR0(K,$2,z11).catch((E)=>{u.warn("Toolbox registration failed, continuing anyway:",E)}),W=z.initialized.catch((E)=>{u.warn("MCP service initialization failed, continuing anyway:",E)}),H=Promise.all([W,U]).then(()=>{});if(Q.jetbrains)CO("JetBrains");else if(Q.ide&&rQ6())CO("VS Code");else if(Q.ide&&sQ6())CO("Neovim");if(J.executeMode)ai1(!0);i96(K,{configService:Z});let F,B=C7.status.pipe(k0((E)=>Boolean(E.connected&&E.authenticated)),G8()).subscribe((E)=>{if(E){if(!F)F=K.registerTool(JE)}else F?.dispose(),F=void 0}),M;if(!J.executeMode)M=new D51(process.cwd(),{},!0);else M=new class extends D51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(t2.write(`No API key found. Starting login flow...
|
|
6764
6764
|
`),!await UK9(J))await FR(),process.exit(1)}let V=await J40({isDevelopment:!1}),N=new _V1(V,Z),L=new LB1(V,{lazy:!0}),A=Q.notifications!==void 0?Q.notifications:!J.executeMode,w=n96({playNotificationSound:async(E)=>{if(A){a96(E);let I=_f1(),T=xf1();if((!I||T)&&Y.settings["notifications.system.enabled"]!==!1){if(E==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(E==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:N,configService:Z});u.info("Starting Amp background services");let R=Gq0({threadService:N,threadHistoryService:L,configService:Z,isExtensionDevelopment:!1}),O;C7.status.subscribe((E)=>{O=E});let j={codebaseContextService:new RZ1({workspaceRoots:[A0.file(process.cwd())],getCurrentFile:()=>{if(!O?.openFile)return;try{return A0.parse(O.openFile)}catch(E){u.warn("Failed to parse current file URI",{uri:O.openFile,error:E});return}},getOpenFiles:()=>{if(!O?.visibleFiles?.length)return[];let E=O.openFile;return O.visibleFiles.filter((I)=>I!==E).map((I)=>{try{return A0.parse(I)}catch(T){return u.warn("Failed to parse visible file URI",{uri:I,error:T}),null}}).filter((I)=>I!==null)}}),configService:Z,toolService:K,mcpService:z,threadService:N,threadHistoryService:L,threadSyncService:R,threadStorage:V,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,notificationService:w,backgroundInit:H,fileSystem:Q.jetbrains||Q.ide?l20:$2};return{...j,async asyncDispose(){await j.mcpService.dispose(),q(),await j.threadService.asyncDispose(),j.configService.unsubscribe(),j.toolService.dispose(),j.fuzzyServer.dispose(),j.threadSyncService.dispose(),j.settingsStorage[Symbol.dispose](),B.unsubscribe(),F?.dispose()}}}async function UK9(J){if(!J.executeMode){if(!await Uf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return t2.write(`Login cancelled. Run the command again to retry.
|
|
6765
6765
|
`),!1}return await Oz6(J)}async function Oz6(J){let Q=tY9(32).toString("hex"),Z=await zf1(J.ampURL,Q),X=new AbortController;try{await $X(Z,X.signal)}catch(K){u.error("Error opening browser",{error:K})}let Y=await zf1(J.ampURL,Q,!1);t2.write(`If your browser does not open automatically, visit:
|
|
6766
6766
|
|
|
@@ -6770,13 +6770,13 @@ ${W8.blue.bold(Y)}
|
|
|
6770
6770
|
Login successful! You can now use the Amp CLI.
|
|
6771
6771
|
`),!0}catch(K){return u.error("Login failed",{error:K}),JG.write(`
|
|
6772
6772
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6773
|
-
`),!1}}function WK9(){let J=new QR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)MR(),process.exit(0);let H=W.originalError??W;rJ6(H)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.
|
|
6773
|
+
`),!1}}function WK9(){let J=new QR().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)MR(),process.exit(0);let H=W.originalError??W;rJ6(H)}),J.option("-V, --version","output the version number",()=>{t2.write(`0.0.1761911084-ge88213 (released 2025-10-31T11:49:44.330Z)
|
|
6774
6774
|
`),process.exit(0)}),J.addHelpText("after",iQ6()),J.configureHelp({formatHelp:aQ6}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);await DK9(B)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);await BK9(B,await oy1(F,B.settings))});let Q=async(W,H,F)=>{CX1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:r1.of([A0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:zu1,userConfigDir:Rz6});let B={...H,executeMode:!1};await Gu1(B,{...W,startWithPicker:!0},F)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);await Lz6(F,B,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);await wK9(F,B,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await NX(B);if(H.pick)JG.write(`${W8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6775
6775
|
`);if(H.last||W||M.executeMode)await AK9(B,M,W,F);else await Q(B,M,F)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await NX(B);await LK9(B,M,W,F)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);await Lz6(F,B,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await NX(B);await NK9(B,M,W,F,H.support)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(W,H,F,B)=>{let M=B.optsWithGlobals(),V=await NX(M);await MK9(M,V,W,H,B)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(W,H,F)=>{let B=F.optsWithGlobals(),M=await NX(B);await VK9(B,M,W,F)}),tZ6(J,async(W,H)=>{let F=await NX(H);dq(W,H);let B=await cq(F,H);return{context:F,mcpService:B.mcpService,toolService:B.toolService,configService:B.configService,cleanupTerminal:MR,asyncDispose:B.asyncDispose.bind(B)}}),IZ6(J),LZ6(J,async(W)=>{let H=await NX(W);return{settings:H.settings,secretStorage:H.secrets,getThreadDeps:async(F)=>{dq(F,W);let B=await cq(H,W);return{mcpService:B.mcpService,asyncDispose:B.asyncDispose.bind(B)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(W,H)=>{let F=H.optsWithGlobals(),B=await NX(F);dq(H,F);let M=await cq(B,F);try{await hy1(M,M.configService,{})}finally{await M.asyncDispose(),await MR()}});function Y(W,H,F){let M=typeof W.description==="string"?W.description:F===void 0?W.description(!0):W.description(F),V=new aV(H,M),N=qK9(W);if(N)V.default(N);if(V.hidden=KK9(W)||Nz6(W),"choices"in W)V.choices([...W.choices]);return V}for(let W of Vz6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new aV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(K);let G=new aV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(G);let q=new aV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(q);let z=new aV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(z);let U=new aV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(U),process.env.AMP_CONNECT==="1"){let W=new aV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(W)}return J.action(async(W,H)=>{let F=W,B=await NX(F);if(Object.keys(F).forEach((M)=>{let V=Vz6.find((N)=>N.name===M);if(V&&Nz6(V)&&!GK9(V))JG.write(W8.yellow(`Warning: '--${M}' flag is deprecated
|
|
6776
6776
|
`))}),H.args.length>0)zK9(B,H);await Gu1(B,F,H)}),HZ6(J),J}async function LQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Yz(),K=AQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await zJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,P51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(t7(z,"assistant"))await qu1(Y),q.unsubscribe()});return await G.resume(),G}async function Gu1(J,Q,Z){let X=I51(Q);if(X instanceof Error)eK(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let O=(await Hf1()).trimEnd();if(O)K=O}else Y=(await Hf1()).trimEnd();if(Q.remote&&!J.executeMode)throw new _9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new _9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new _9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new _9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new _9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new _9("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new _9("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new _9("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
6777
6777
|
Or pipe via stdin: echo "your message" | amp --execute`);dq(Z,Q);let G=await cq(J,Q);if(J.executeMode||Q.threadId)await G.backgroundInit;wz6=G;let q=AQ1(G),z=async(O)=>{let $=await Az6(O,"utf-8"),j=JSON.parse($);if(!HG(j.id))throw new _9(lK.invalidThreadId);return LQ1(G,{visibility:X,thread:j})},U=async(O)=>{if(!HG(O))throw new _9(lK.invalidThreadId);let $=await G.threadService.get(O)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${O}, agentMode: ${$?.agentMode??"undefined"}`),$?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${$.agentMode}`),KG("experimental.agentMode",$.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return LQ1(G,{visibility:X,thread:$})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return LQ1(G,{visibility:X})}catch(O){if(O instanceof _9)throw O;throw await K51(O,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return LQ1(G,{visibility:X})};if(Q.format==="jsonl")JG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6778
|
-
`),await FR(),process.exit(1);if(J.executeMode&&Q.remote)await PZ6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)await zQ6(F,F.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Gr1();let O=await iO({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)C7.selectConfig($)}else B=!0}let V=qf1("0.0.
|
|
6779
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await SQ6({...J,workspaceTrust:{current:!0,changes:GS},getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await AZ6(J.mcpConfig);X=YK9(X,G)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!OB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=Yl1(X),await X.get("debug.httpLogging"))rc1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:TZ6(await oy1(J,X))}}function HK9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function FK9(){let J=HK9(process.argv);if(kJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),ZK9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6778
|
+
`),await FR(),process.exit(1);if(J.executeMode&&Q.remote)await PZ6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let F=await W();if(J.executeMode)await zQ6(F,F.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await Gr1();let O=await iO({jetbrainsOnly:Q.jetbrains});if(O.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(O.length===1){let $=O[0];if($)C7.selectConfig($)}else B=!0}let V=qf1("0.0.1761911084-ge88213",G.settingsStorage),N=new NB1(G.threadStorage),L=r1.of([A0.file(process.cwd())]),A=cc1(void 0,L);if(Y)F.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let w;try{w=await XJ.getUserFreeTierStatus({},{config:G.configService,signal:AbortSignal.timeout(5000)})}catch(O){w={ok:!1,error:O}}u.info("User free tier status:",w);let R=await vZ6();u.info("Loaded session state:",R),await Mz6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new dy1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:F.threadID,threadFuzzyIndexer:N,worker:F,workerDeps:q,configService:G.configService,internalAPIClient:XJ,ampURL:J.ampURL,startNewThread:H,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:C7,connectedClientsService:new kX1,commandRegistry:A,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:R,freeTierStatus:w.ok?w.result:void 0,threadDependencies:G}),await G.asyncDispose(),process.exit(0)}async function NX(J){if(J.interactive)JG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6779
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await SQ6({...J,workspaceTrust:{current:!0,changes:GS},getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await AZ6(J.mcpConfig);X=YK9(X,G)}let Y=await X.get("url","global");if(!Y)Y=FZ;if(!OB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=Yl1(X),await X.get("debug.httpLogging"))rc1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:TZ6(await oy1(J,X))}}function HK9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function FK9(){let J=HK9(process.argv);if(kJ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),ZK9(u),u.info("Starting Amp CLI.",{version:"0.0.1761911084-ge88213",buildTimestamp:"2025-10-31T11:49:44.330Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _9(lK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await WK9().parseAsync(process.argv)}FK9().catch(K51);async function BK9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),t2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6780
6780
|
`);else if(!OB(J.ampURL))t2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6781
6781
|
`);let Z=process.env.AMP_API_KEY;if(Z)t2.write(`API key found in environment variable, storing...
|
|
6782
6782
|
`),await Q.set("apiKey",Z,J.ampURL),t2.write(`API key successfully stored.
|