@augmentcode/onison 1.2.0-prerelease.202608191009 → 1.2.0-prerelease.202608191212
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/auggie-v2.mjs +669 -669
- package/auggie-v2.mjs.d/extensions/mcp/index.js +1 -1
- package/package.json +1 -1
|
@@ -98,7 +98,7 @@ ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.t
|
|
|
98
98
|
`}var LF=rh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Oc(){let t={};for(let e of LF){let r=rh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ic=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Mc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new DF)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,$C.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Oc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:rh.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=AC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var NC=ki(zC(),1);function DC(t){if(t)try{return NC.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var zc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Cc({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var VF={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},It=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Nc=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Tc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??VF}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=bo(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new It(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new zc({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await d.read();if(h)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let m=xr.parse(JSON.parse(f.data));en(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await dr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ms(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=Ro(a);if(this._resourceMetadataUrl=h,this._scope=m,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=Ro(a);if(y==="insufficient_scope"){let S=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new It(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=S??void 0,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qe;return this.send(e)}}throw new It(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),vw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,l=a.headers.get("content-type"),p=DC(l);if(d)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(m=>xr.parse(m)):[xr.parse(f)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new It(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new It(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};function LC(t){return t.useShellInterpolation?process.platform==="win32"?{command:"cmd.exe",args:["/c",t.command]}:{command:"/bin/sh",args:["-c",t.command]}:{command:t.command,args:t.args}}var KF={NO_UPDATE_NOTIFIER:"1",npm_config_update_notifier:"false",npm_config_loglevel:"silent",npm_config_fund:"false",npm_config_audit:"false",npm_config_yes:"true",CI:"1"};function jC(t){return{...Oc(),...KF,...t??{}}}function FC(){return Oc()}var oh=class t extends Ic{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
|
|
99
99
|
`);this._lineBuffer=r.at(-1)??"",this._lineBuffer.length>t.MAX_LINE_BUFFER_CHARS&&(this._lineBuffer=this._lineBuffer.slice(-t.MAX_LINE_BUFFER_CHARS));for(let n of r.slice(0,-1))this.pushCapturedLine(`${n}
|
|
100
100
|
`)}pushCapturedLine(e){this._captured.push(e),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(e),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let e=this._captured.join("");return this._captured=[],e}getLogHistory(){return[...this._logHistory]}};function UC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new oh(e)}var Rn=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},sh=new WF;function ih(t,e){return sh.run(t,e)}function JF(t){sh.getStore()?.onFailure?.(t)}function qC({getHeaders:t,transport:e}){if(t)return async(r,n)=>{let o=r instanceof Request?r.headers:void 0,s=new Headers(o);for(let[u,d]of new Headers(n?.headers).entries())s.set(u,d);for(let[u,d]of Object.entries(t()))s.set(u,d);let i=await fetch(r,{...n,headers:s});if(i.ok||n?.method?.toUpperCase()!=="POST")return i;await i.body?.cancel().catch(()=>{});let a=sh.getStore(),c=new Rn({status:i.status,transport:e,operation:a?.operation??"transport"});throw JF(c),c}}function HC(t,e){let r=qC({getHeaders:e.getHeaders,transport:"http"});return new Nc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function GC(t,e){let r=qC({getHeaders:e.getHeaders,transport:"sse"});return new Ac(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function ZC(){return new Pc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var BC=bs,VC=xe;function St(t){return t instanceof Rn&&t.status===401||(t instanceof It||t instanceof gi)&&t.code===401}function WC(t){return t instanceof $&&t.code===M.MethodNotFound}function ah(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var YF=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function KC(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return YF.some(r=>e.includes(r))}function JC(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function ch(t){return t instanceof Rn&&t.transport==="http"&&t.status===404||t instanceof It&&t.code===404}var X=XF.child({prefix:"pi-mcp"});function QF(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function eU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&QF(r,o)})}var tU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),rU=/^Node\.js v\d/,nU=/^[\w$.]*error[\w$]*:/i,YC=400,oU=63e3,XC=3,sU=/[\\/]lib[\\/]cli\.js/,iU="npx/npm launcher is broken in this environment (Cannot find module .../lib/cli.js). This usually means npm/npx/corepack are file copies instead of symlinks in the base image; every npx-launched stdio MCP server will fail until the launcher symlinks are restored.",ox=Symbol("mcpReinitReported");function aU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,ox,{value:!0,enumerable:!1,configurable:!0})}function cU(t){return typeof t=="object"&&t!==null&&t[ox]===!0}function uU(t){let e=t.filter(a=>!rU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>sU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return iU;let o=r.findIndex(a=>nU.test(a)),i=(o===-1?r.slice(-XC):r.slice(o,o+XC)).join(" / ");return i.length>YC?`${i.slice(0,YC)}\u2026`:i}function dU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(tU,"").split(`
|
|
101
|
-
`).map(s=>s.trim()).filter(s=>s.length>0),o=uU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var lU=6e5,pU=18e5,QC=2147483647,fU=3e4,ex=1e4,sx=[250,1e3,2e3],Pn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},yi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},hU=250,tx=3,mU=[200,500];function gU(t){for(let e of Object.values(t))if(na(e))return!0;return!1}function ix(t){let e=new Set;for(let r of t.matchAll(Qo))e.add(oa(r[0]));return[...e].sort()}function lh(t){return[...new Set(t)].sort()}function rx(t,e){return Gg(e.map(r=>t?.[r]??"missing"))}function yU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return lh([...e&&t?dd(t):[],...n&&r?ix(r):[]])}var Dc="${augmentToken}";function vU(t){try{let e=new URL(t);if(e.protocol!=="https:")return!1;let{hostname:r}=e;return r==="augmentcode.com"||r.endsWith(".augmentcode.com")}catch{return!1}}function _U(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var ax="(unknown uri)",ph="unknown",nx=/=+$/,SU=/\s+/g,wU=/[-_]/g,bU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Cn(t,e){return typeof t=="string"?t:e}function cx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function RU(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function PU(t){let e=t.replace(SU,"").replace(wU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(nx,"");if(r.toString("base64").replace(nx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function ux(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function CU(t){let e=ux(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Cn(e.uri,ax),n=Cn(e.mimeType,ph);if(typeof e.blob=="string"&&RU(n)){let s=PU(e.blob);if(s!==void 0)return s}let o=cx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function xU(t){let e=Cn(t.type,"unknown");if(e==="resource")return CU(t);if(e==="audio"){let r=Cn(t.mimeType,ph),n=cx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Cn(t.uri,ax),n=Cn(t.name,""),o=Cn(t.mimeType,ph);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function kU(t){if(t.type!=="resource")return;let e=ux(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&bU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function EU(t){if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text};if(t.type==="image"&&typeof t.data=="string"&&typeof t.mimeType=="string")return{type:"image",mimeType:t.mimeType,data:t.data};let e=kU(t);return e||{type:"text",text:xU(t)}}function TU(t){let e=[];if(!Array.isArray(t))return e;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;typeof n.type=="string"&&e.push(EU(n))}return e}function AU(t){return zg(t,oU)}function $U(t,e){let r=TU(t);if(r.length===0){let o=AU(e);o!==void 0&&r.push({type:"text",text:o})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}var dx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),MU=new Set([502,503,504]),vi=sx.length+1,IU=2;function OU(t){let r=t?.cause?.code;if(typeof r=="string")return r;let n=t?.status;if(typeof n=="number")return String(n);let o=t?.code;return typeof o=="number"?String(o):void 0}function zU(t){if(St(t)||ch(t)||t instanceof lt)return;let e=t?.cause?.code;if(typeof e=="string")return dx.has(e)?{totalAttempts:vi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:IU}:MU.has(r)?{totalAttempts:vi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:vi}:void 0}var NU=80,DU=10,LU=/[^a-zA-Z0-9_.()-]/g,jU=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Lc(t){return t.replace(LU,"_").slice(0,NU)||"unknown"}function FU(t){let e=OU(t);if(e!==void 0&&(/^\d{3}$/.test(e)||dx.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=jU.has(e)?e:"Error",n=FU(t);return n===void 0?r:`${r}(${n})`}function uh(t,e,r){return t instanceof lt?new lt(Lc(t.serverName),t.missingKeys.slice(0,DU).map(Lc),void 0,t.reason).message:t instanceof Rn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function dh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Lc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var jc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Fc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>ad(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=uh(r,"connect",this._config.type),o=this._config.type==="stdio"&&!St(r)?ad(dU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=vi,r={available:!0};for(let n=1;n<=vi;n++)try{let o=await this._attemptConnect(r);return n>1&&X.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let s=zU(o);if(s===void 0||this._disposed||(e=Math.min(e,s.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let s=(sx[r-1]??0)+Math.floor(Math.random()*(hU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Vr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return St(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!re().tokens.get(this.name)?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new Pn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=ZC();this._client=s;let i;try{if(await ih({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(BC,()=>{X.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let a=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=a.tools??[],this._status="success",this._lastError=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=re();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&st(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=uh(e,r,this._config.type)){if(e instanceof lt){this._status="failed";let o=re();$o(o,this.name,e.reason,Jt(o,this.name,this._config.id))}else if(e instanceof yi||e instanceof Pn)this._status="failed";else if(St(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(St(e)){this._status="auth_required";let o=re(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=uh(e,r,this._config.type);cd(dh(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=LC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=jC(this._resolvedEnv??e.env);return UC({command:r.command,args:r.args,env:n,cwd:e.cwd})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return GC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=HC(e,{headers:r,getHeaders:()=>this._buildAuthHeaders()});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?gU(r):!1,o=e.type==="stdio"&&na(e.command);if(!(n||o))return;let s=re();if(!Hg(s)){let a=yU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new lt(this.name,a)}let i=Ug(s);n&&r&&await this._resolveMapSecretRefs(r,i,e.type==="stdio"),o&&e.type==="stdio"&&await this._resolveCommandSecretRefs(e.command,i)}async _resolveMapSecretRefs(e,r,n){let o;try{o=await Bg({configEnv:e,localEnv:n?FC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new lt(this.name,dd(e),i,"transient")}let s=lh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new lt(this.name,s,void 0,rx(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Vg(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new lt(this.name,ix(e),s,"transient")}let o=lh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new lt(this.name,o,void 0,rx(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Dc)))return;let o;if(vU(e.url)){let i=re().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Dc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Dc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${_U(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Dc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=re();if(n.diagnostics.some(i=>i.server===this.name&&i.message===e))return;n.diagnostics.push({server:this.name,message:e});let s=`MCP server "${this.name}": ${e}`;r==="error"?X.error(s):X.warn(s)}_usableToken(){let e=re(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Be(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=re().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&Mu(o)&&re().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Zo(o)&&re().tokens.markAuthRequired(this.name))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=re(),r=e.refreshes.get(this.name);if(r)return r.then(a=>a??{kind:"refreshed"});let n={state:e,tokenStore:e.tokens,serverGeneration:e.serverGenerations.get(this.name)??0,configRevision:e.configRevisions.get(this.name)??0,credential:e.credentialRevisions.get(this.name),localRefreshEnabled:e.shouldProactivelyRefreshTokens,failureScope:Jt(e,this.name,this._config.id),token:this._usableToken(),hostWasUntracked:e.servers.get(this.name)===void 0},o=JSON.stringify([this.name,n.serverGeneration,n.configRevision,n.credential?.domain??null,n.credential?.revision??null]),s=e.refreshes.get(o);if(s)return s.then(a=>a??{kind:"refreshed"});let i=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===i&&e.refreshes.delete(o),this._refreshPromise===i&&(this._refreshPromise=void 0)});return this._refreshPromise=i,e.refreshes.set(o,i),i}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=Z(r,this.name)?.retirement?.incumbent.host,s=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&s&&(r.serverGenerations.get(this.name)??0)===e.serverGeneration&&(r.configRevisions.get(this.name)??0)===e.configRevision&&this._ownsRefreshCredential(e,n)&&(e.localRefreshEnabled===r.shouldProactivelyRefreshTokens||this._refreshPersisting)}_ownsRefreshCredential(e,r){return e.state.tokens===e.tokenStore&&e.tokenStore.get(this.name)===e.token&&r?.domain===e.credential?.domain&&r?.revision===e.credential?.revision}async _restoreAfterSupersededRefresh(e,r,n,o){let s=e.state.servers.get(this.name),i=e.state.tokens,a=i.get(this.name),c=e.state.credentialRevisions.get(this.name);if(!(i!==e.tokenStore||!s||!a||!Be(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),Fr({state:e.state,name:this.name,revision:o});return}let u=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o);if(!u||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain)return;Fr({state:e.state,name:this.name,revision:u});let d=e.state.currentLoad?.latestPi;d&&J(d,e.state)}catch{X.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof B?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof B)&&Ou(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&$o(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),$o(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await zu(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let s=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,s),{kind:"transient_failure"};e.tokenStore.commit(this.name,o),Fr({state:e.state,name:this.name,revision:s}),st(e.state,this.name);let i=e.state.currentLoad?.latestPi;return i&&J(i,e.state),X.debug(`MCP server "${this.name}" token refreshed`),{kind:"refreshed"}}catch(r){return this._handleRefreshFailure(r,e)}}_isSessionExpiredError(e){return this._config.type!=="http"||this._activeTransport?.sessionId===void 0?!1:ch(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),aU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Pn}async _withAuthRetry(e,r,n){let o=this._config,s=re(),i=Jt(s,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),ih({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!St(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new yi;if(this._hostedCredentialProvenance!==void 0)throw new Pn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw St(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=re();$o(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new jc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new jc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},fU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=re(),r=Jt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=tx&&n.outcome==="transient";i++)await Vr(mU[i-2]??0),n=await this._runProbe();let o=Jt(e,this.name,this._config.id),s=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return s&&n.outcome==="alive"&&st(e,this.name,r),s&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?X.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&X.debug(`MCP server "${this.name}" startup verification ping remained transient after ${tx} attempts; not caching as failed: ${n.error}`),n}getLastProbeResult(){return this._lastProbeResult}async _runProbe(){let e=!this._client||this._disposed;if(e)return{ok:!1,outcome:"transient",error:"MCP client is not available",isAuthError:!1};try{return await this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.ping({timeout:ex})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":WC(e)||ah(e)?"alive":St(e)?"authFailure":KC(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!(!e||this._disposed))try{await e.ping({timeout:ex})}catch(r){if(this._reinitializingPromise||this._disposed||ah(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return St(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!St(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!eU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>QC)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${QC}.`);let s={timeout:this._config.timeoutMs??lU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??pU,onprogress:d=>{X.debug(`MCP server "${this.name}" tool "${e}" progress: ${d.progress}${d.total===void 0?"":`/${d.total}`}${d.message?` - ${d.message}`:""}`)}},i,a=new Promise((d,l)=>{i={reject:l,livenessRejected:!1,sessionRecoveryOwned:!1}});a.catch(()=>{}),i&&this._inFlightCalls.add(i);let u=this._withSessionRetry(()=>this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.callTool({name:e,arguments:r??{}},VC,s)},"tool_call",{call:i})).then(d=>(i&&this._settleInFlightCall(i,!0,void 0),d),d=>{throw i&&this._settleInFlightCall(i,!1,d),d});try{let d=await Promise.race([u,a]),l=$U(d.content,d.structuredContent);return{isError:d.isError===!0,content:l.content,rawItemCount:l.rawItemCount}}catch(d){if(n?.aborted||d instanceof Error&&d.name==="AbortError")throw d;return this._reportAndThrowToolError(d,e)}finally{i&&!this._wedgeRecoveryOwners.has(i)&&(i.failure=void 0,this._inFlightCalls.delete(i))}}_reportAndThrowToolError(e,r){if(e instanceof Pn||e instanceof yi)throw e;if(St(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Lc(r),s=He(e),i=JC(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw cU(e)||cd(dh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),dh(a,s)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._stopHeartbeat(),this._failInFlightCalls(new Error(`MCP server "${this.name}" is being disposed`),!1),this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1}async dispose(e){this.beginDisposal(),await this._refreshPromise,this._stopHeartbeat();let r=this._client;if(this._client=void 0,this._activeTransport=void 0,this._reinitializingPromise=void 0,this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1,this._stdioTransport=void 0,!!r)try{await r.close()}catch(n){if(X.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var lx=qU.child({prefix:"pi-mcp"}),HU=3,GU=6e4;function ZU(t,e){let r=Date.now(),n=r-GU,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=HU?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function px(t){Br(t),Fi(t)}async function BU(t,e,r){if(!ZU(e,t)){lx.warn(`MCP server "${t}" automatic restart rate-limited`);return}lx.warn(`MCP server "${t}" wedged; recycling transport`),await Dr(t,e,r)}function Uc(t,e,r){if(VU(e)){px(t);return}bu(t,r),In(e)&&px(t)}function VU(t){return Lo()||t.toolSearchLatched}function Vt(t,e,r){return Vh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function fh(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,st(t,e),t.authRefreshNeededReportKeys.delete(e),r}function WU(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name);return o!==void 0&&s!==void 0&&i!==void 0&&i.revision===o.revision&&i.domain===o.domain&&e.oauthCredentialDomains.get(r.name)===o.domain&&ut(o.domain)===We(r.id)?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function hh(t){let{state:e,config:r,generation:n}=t;return new Fc(r,WU({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function mh(t,e){if(e.id&&e.registrySource!==void 0){let r={...e};t.registryConfigNamesById.set(e.id,e.name),t.registryCredentialConfigs.set(e.name,r),t.registryCredentialConfigsById.set(e.id,r)}}function gh(t,e,r){return t.configDesiredRevisions.get(e)===r}function fx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function yh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Vt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(UU,c)},t.onWedged=()=>{if(!Vt(t,e,r))return;let i=r.currentLoad?.latestPi??n;BU(t.name,r,i)};let o=t.hostedCredentialProvenance,s=o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0?{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}:void 0;t.onAuthRefreshNeeded=()=>{if(!Vt(t,e,r)||!s)return;let i=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==i&&(r.authRefreshNeededReportKeys.set(t.name,i),J(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!Vt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&st(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Vt(t,e,r)&&t.status==="success"&&Uc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Ru(i,t,e),i!==n&&Ru(n,t,e)}}async function hx(t,e,r,n){let o=setTimeout(()=>{Vt(t,e,r)&&J(n(),r)},Ei);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Vt(t,e,r)&&J(n(),r)}}async function mx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function qc(t,e){if(e.status!=="installed")return!1;let r=Z(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function KU(t){let{state:e,config:r,displaced:n,retirement:o}=t;mh(e,n.config),zo(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():ct(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function JU(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=bt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function YU(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Vt(r,o,e)?a?.(n)===!1?(await JU({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Uc(c(),e,r),J(c(),e),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:i}):{status:"superseded",config:n}}function XU(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=Z(e,r.name);if(!gh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=fh(e,r.name),l=hh({state:e,config:r,generation:d});return yh(l,d,e,o),$i({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:YU({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function QU(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!gh(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):Z(r,a.name),l=En(a,s),p=Oo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>XU({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await KU({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await uu(p.retirement),h());return p.retirement?m():h()}async function wt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await QU({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Ei);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function eq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!fx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);mh(e,s),zo(e,t);let a=bt({state:e,name:t,owner:i.owner,revision:i.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),we({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw we({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(Z(e,t)?.revision!==i.revision||!fx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=fh(e,t),u=hh({state:e,config:s,generation:c});if(yh(u,c,e,r),!$i({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await hx(u,c,e,d),Vt(u,c,e)&&u.status==="success"&&Uc(d(),e,u),!0}function Dr(t,e,r){e.reconnects??=new Map,e.configRevisions??=new Map,e.reconnectDesiredGenerations??=new Map,e.statusFailureCategories??=new Map;let n=(e.reconnectDesiredGenerations.get(t)??0)+1;e.reconnectDesiredGenerations.set(t,n);let o=e.reconnects.get(t);if(o)return o;let s=(async()=>{let i=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await eq({name:t,state:e,pi:r,configRevision:a}))return;i=c}while(i<(e.reconnectDesiredGenerations.get(t)??i))})().finally(()=>{e.reconnects.get(t)===s&&e.reconnects.delete(t)});return e.reconnects.set(t,s),s}async function tq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;mh(e,n.config),zo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():ct(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function gx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=$n(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=Oo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await tq({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await uu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!gh(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=fh(e,t),h=hh({state:e,config:a,generation:f});yh(h,f,e,r),$i({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await hx(h,f,e,s),Vt(h,f,e)&&h.status==="success"&&Uc(s(),e,h))}async function _i(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Dr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as rq}from"@hermes/logger";var vh=rq.child({prefix:"pi-mcp"}),nq=1e6,oq=1e3,sq=/^\d+$/;function yx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function xn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(!(typeof e!="string"||!sq.test(e)||typeof r!="string"||r.length===0))return{revision:e.replace(/^0+(?=\d)/,""),domain:yx(r)}}function iq(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function aq(t,e,r,n){let o=e.credential_revision??e.credentialRevision,s=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||s!==void 0)&&r===void 0)return vh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";if(i?.kind==="blocked"||i?.kind==="domain"&&ut(r.domain)!==i.domain)return"reject";let a=n?.acceptedDomains?.get(t);if(a!==void 0&&yx(a)!==r.domain)return"reject";let c=iq(n?.acceptedRevisions,r.domain,s);if(c===void 0)return"apply";let u=mr(r.revision,c);return u>0||u===0&&a===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":u===0?"equal":"reject"}function cq(t,e,r,n){if(n!==void 0)return!1;let o=t.get(e);return o===void 0?!1:r.expiresAt===void 0||o.expiresAt===void 0||r.expiresAt<=o.expiresAt}function uq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function dq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*oq+Math.floor(t.access_token_expires_at.nanos/nq):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret}}}function Hc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!uq(s)){vh.warn(`Skipping MCP OAuth credentials for "${o}": entry is not an object with a non-empty access_token`),n.rejected.push(o);continue}let i=xn(s),a=aq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=dq(s);if(cq(t,o,c,i)){vh.warn(`Skipping MCP OAuth credentials for "${o}": legacy payload cannot prove freshness`),n.rejected.push(o);continue}t.set(o,c),r?.equalRevisionRebindDomains?.delete(o),i!==void 0&&(r?.acceptedRevisions?.set(i.domain,i.revision),r?.acceptedDomains?.set(o,i.domain)),n.applied.push(o)}return n}var pq=lq.child({prefix:"pi-mcp"});function fq(t,e){let r;for(let[n,o]of t.servers){if(o.config.id!==e)continue;let s=Q(t,n,o);if(!(s.host!==o||s.owner.kind!=="registry"||s.owner.identity!==`user:${e}`)){if(r)return;r={name:n,server:o}}}return r}function hq(t,e){let r=Object.values(t).filter(n=>{let o=xn(n);return o!==void 0&&ut(o.domain)===`user:${e}`});return r.length===1?r[0]:void 0}async function vx(t){let{pi:e,state:r,update:n}=t,o=fq(r,n.configId),s=hq(n.credentials,n.configId);if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=Hc(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let p=xn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Dr,l=t.report??J;await d(o.name,r,u).catch(p=>{pq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),ze(r)}import{logger as Pq}from"@hermes/logger";import{execFile as mq}from"node:child_process";import{logger as gq}from"@hermes/logger";var yq=5e3;function vq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function _x(t,e=yq){let r=gq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=vq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=mq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as _q}from"node:http";function Gc(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Sx(t){let e=Gc(t.title),r=Gc(t.heading),n=Gc(t.message),o=t.details?Gc(t.details):void 0,s=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
|
|
101
|
+
`).map(s=>s.trim()).filter(s=>s.length>0),o=uU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var lU=6e5,pU=18e5,QC=2147483647,fU=3e4,ex=1e4,sx=[250,1e3,2e3],Pn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},yi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},hU=250,tx=3,mU=[200,500];function gU(t){for(let e of Object.values(t))if(na(e))return!0;return!1}function ix(t){let e=new Set;for(let r of t.matchAll(Qo))e.add(oa(r[0]));return[...e].sort()}function lh(t){return[...new Set(t)].sort()}function rx(t,e){return Gg(e.map(r=>t?.[r]??"missing"))}function yU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return lh([...e&&t?dd(t):[],...n&&r?ix(r):[]])}var Dc="${augmentToken}";function vU(t){try{let e=new URL(t);if(e.protocol!=="https:")return!1;let{hostname:r}=e;return r==="augmentcode.com"||r.endsWith(".augmentcode.com")}catch{return!1}}function _U(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var ax="(unknown uri)",ph="unknown",nx=/=+$/,SU=/\s+/g,wU=/[-_]/g,bU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Cn(t,e){return typeof t=="string"?t:e}function cx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function RU(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function PU(t){let e=t.replace(SU,"").replace(wU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(nx,"");if(r.toString("base64").replace(nx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function ux(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function CU(t){let e=ux(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Cn(e.uri,ax),n=Cn(e.mimeType,ph);if(typeof e.blob=="string"&&RU(n)){let s=PU(e.blob);if(s!==void 0)return s}let o=cx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function xU(t){let e=Cn(t.type,"unknown");if(e==="resource")return CU(t);if(e==="audio"){let r=Cn(t.mimeType,ph),n=cx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Cn(t.uri,ax),n=Cn(t.name,""),o=Cn(t.mimeType,ph);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function kU(t){if(t.type!=="resource")return;let e=ux(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&bU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function EU(t){if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text};if(t.type==="image"&&typeof t.data=="string"&&typeof t.mimeType=="string")return{type:"image",mimeType:t.mimeType,data:t.data};let e=kU(t);return e||{type:"text",text:xU(t)}}function TU(t){let e=[];if(!Array.isArray(t))return e;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;typeof n.type=="string"&&e.push(EU(n))}return e}function AU(t){return zg(t,oU)}function $U(t,e){let r=TU(t);if(r.length===0){let o=AU(e);o!==void 0&&r.push({type:"text",text:o})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}var dx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),MU=new Set([502,503,504]),vi=sx.length+1,IU=2;function OU(t){let r=t?.cause?.code;if(typeof r=="string")return r;let n=t?.status;if(typeof n=="number")return String(n);let o=t?.code;return typeof o=="number"?String(o):void 0}function zU(t){if(St(t)||ch(t)||t instanceof lt)return;let e=t?.cause?.code;if(typeof e=="string")return dx.has(e)?{totalAttempts:vi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:IU}:MU.has(r)?{totalAttempts:vi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:vi}:void 0}var NU=80,DU=10,LU=/[^a-zA-Z0-9_.()-]/g,jU=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Lc(t){return t.replace(LU,"_").slice(0,NU)||"unknown"}function FU(t){let e=OU(t);if(e!==void 0&&(/^\d{3}$/.test(e)||dx.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=jU.has(e)?e:"Error",n=FU(t);return n===void 0?r:`${r}(${n})`}function uh(t,e,r){return t instanceof lt?new lt(Lc(t.serverName),t.missingKeys.slice(0,DU).map(Lc),void 0,t.reason).message:t instanceof Rn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function dh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Lc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var jc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Fc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>ad(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=uh(r,"connect",this._config.type),o=this._config.type==="stdio"&&!St(r)?ad(dU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=vi,r={available:!0};for(let n=1;n<=vi;n++)try{let o=await this._attemptConnect(r);return n>1&&X.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let s=zU(o);if(s===void 0||this._disposed||(e=Math.min(e,s.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let s=(sx[r-1]??0)+Math.floor(Math.random()*(hU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Vr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return St(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!re().tokens.get(this.name)?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new Pn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=ZC();this._client=s;let i;try{if(await ih({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(BC,()=>{X.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let a=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=a.tools??[],this._status="success",this._lastError=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=re();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&st(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=uh(e,r,this._config.type)){if(e instanceof lt){this._status="failed";let o=re();$o(o,this.name,e.reason,Jt(o,this.name,this._config.id))}else if(e instanceof yi||e instanceof Pn)this._status="failed";else if(St(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(St(e)){this._status="auth_required";let o=re(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=uh(e,r,this._config.type);cd(dh(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=LC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=jC(this._resolvedEnv??e.env);return UC({command:r.command,args:r.args,env:n,cwd:e.cwd})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return GC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=HC(e,{headers:r,getHeaders:()=>this._buildAuthHeaders()});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?gU(r):!1,o=e.type==="stdio"&&na(e.command);if(!(n||o))return;let s=re();if(!Hg(s)){let a=yU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new lt(this.name,a)}let i=Ug(s);n&&r&&await this._resolveMapSecretRefs(r,i,e.type==="stdio"),o&&e.type==="stdio"&&await this._resolveCommandSecretRefs(e.command,i)}async _resolveMapSecretRefs(e,r,n){let o;try{o=await Bg({configEnv:e,localEnv:n?FC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new lt(this.name,dd(e),i,"transient")}let s=lh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new lt(this.name,s,void 0,rx(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Vg(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new lt(this.name,ix(e),s,"transient")}let o=lh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new lt(this.name,o,void 0,rx(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Dc)))return;let o;if(vU(e.url)){let i=re().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Dc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Dc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${_U(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Dc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=re();if(n.diagnostics.some(i=>i.server===this.name&&i.message===e))return;n.diagnostics.push({server:this.name,message:e});let s=`MCP server "${this.name}": ${e}`;r==="error"?X.error(s):X.warn(s)}_usableToken(){let e=re(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Be(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=re().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&Mu(o)&&re().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Zo(o)&&re().tokens.markAuthRequired(this.name))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=re(),r=e.refreshes.get(this.name);if(r)return r.then(a=>a??{kind:"refreshed"});let n={state:e,tokenStore:e.tokens,serverGeneration:e.serverGenerations.get(this.name)??0,configRevision:e.configRevisions.get(this.name)??0,credential:e.credentialRevisions.get(this.name),localRefreshEnabled:e.shouldProactivelyRefreshTokens,failureScope:Jt(e,this.name,this._config.id),token:this._usableToken(),hostWasUntracked:e.servers.get(this.name)===void 0},o=JSON.stringify([this.name,n.serverGeneration,n.configRevision,n.credential?.domain??null,n.credential?.revision??null]),s=e.refreshes.get(o);if(s)return s.then(a=>a??{kind:"refreshed"});let i=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===i&&e.refreshes.delete(o),this._refreshPromise===i&&(this._refreshPromise=void 0)});return this._refreshPromise=i,e.refreshes.set(o,i),i}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=Z(r,this.name)?.retirement?.incumbent.host,s=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&s&&(r.serverGenerations.get(this.name)??0)===e.serverGeneration&&(r.configRevisions.get(this.name)??0)===e.configRevision&&this._ownsRefreshCredential(e,n)&&(e.localRefreshEnabled===r.shouldProactivelyRefreshTokens||this._refreshPersisting)}_ownsRefreshCredential(e,r){return e.state.tokens===e.tokenStore&&e.tokenStore.get(this.name)===e.token&&r?.domain===e.credential?.domain&&r?.revision===e.credential?.revision}async _restoreAfterSupersededRefresh(e,r,n,o){let s=e.state.servers.get(this.name),i=e.state.tokens,a=i.get(this.name),c=e.state.credentialRevisions.get(this.name);if(!(i!==e.tokenStore||!s||!a||!Be(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),Fr({state:e.state,name:this.name,revision:o});return}let u=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o);if(!u||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain)return;Fr({state:e.state,name:this.name,revision:u});let d=e.state.currentLoad?.latestPi;d&&J(d,e.state)}catch{X.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof B?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof B)&&Ou(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&$o(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),$o(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await zu(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let s=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,s),{kind:"transient_failure"};e.tokenStore.commit(this.name,o),Fr({state:e.state,name:this.name,revision:s}),st(e.state,this.name);let i=e.state.currentLoad?.latestPi;return i&&J(i,e.state),X.debug(`MCP server "${this.name}" token refreshed`),{kind:"refreshed"}}catch(r){return this._handleRefreshFailure(r,e)}}_isSessionExpiredError(e){return this._config.type!=="http"||this._activeTransport?.sessionId===void 0?!1:ch(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),aU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Pn}async _withAuthRetry(e,r,n){let o=this._config,s=re(),i=Jt(s,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),ih({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!St(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new yi;if(this._hostedCredentialProvenance!==void 0)throw new Pn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw St(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=re();$o(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new jc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new jc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},fU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=re(),r=Jt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=tx&&n.outcome==="transient";i++)await Vr(mU[i-2]??0),n=await this._runProbe();let o=Jt(e,this.name,this._config.id),s=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return s&&n.outcome==="alive"&&st(e,this.name,r),s&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?X.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&X.debug(`MCP server "${this.name}" startup verification ping remained transient after ${tx} attempts; not caching as failed: ${n.error}`),n}getLastProbeResult(){return this._lastProbeResult}async _runProbe(){let e=!this._client||this._disposed;if(e)return{ok:!1,outcome:"transient",error:"MCP client is not available",isAuthError:!1};try{return await this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.ping({timeout:ex})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":WC(e)||ah(e)?"alive":St(e)?"authFailure":KC(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!(!e||this._disposed))try{await e.ping({timeout:ex})}catch(r){if(this._reinitializingPromise||this._disposed||ah(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return St(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!St(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!eU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>QC)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${QC}.`);let s={timeout:this._config.timeoutMs??lU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??pU,onprogress:d=>{X.debug(`MCP server "${this.name}" tool "${e}" progress: ${d.progress}${d.total===void 0?"":`/${d.total}`}${d.message?` - ${d.message}`:""}`)}},i,a=new Promise((d,l)=>{i={reject:l,livenessRejected:!1,sessionRecoveryOwned:!1}});a.catch(()=>{}),i&&this._inFlightCalls.add(i);let u=this._withSessionRetry(()=>this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.callTool({name:e,arguments:r??{}},VC,s)},"tool_call",{call:i})).then(d=>(i&&this._settleInFlightCall(i,!0,void 0),d),d=>{throw i&&this._settleInFlightCall(i,!1,d),d});try{let d=await Promise.race([u,a]),l=$U(d.content,d.structuredContent);return{isError:d.isError===!0,content:l.content,rawItemCount:l.rawItemCount}}catch(d){if(n?.aborted||d instanceof Error&&d.name==="AbortError")throw d;return this._reportAndThrowToolError(d,e)}finally{i&&!this._wedgeRecoveryOwners.has(i)&&(i.failure=void 0,this._inFlightCalls.delete(i))}}_reportAndThrowToolError(e,r){if(e instanceof Pn||e instanceof yi)throw e;if(St(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Lc(r),s=He(e),i=JC(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw cU(e)||cd(dh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),dh(a,s)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._stopHeartbeat(),this._failInFlightCalls(new Error(`MCP server "${this.name}" is being disposed`),!1),this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1}async dispose(e){this.beginDisposal(),await this._refreshPromise,this._stopHeartbeat();let r=this._client;if(this._client=void 0,this._activeTransport=void 0,this._reinitializingPromise=void 0,this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1,this._stdioTransport=void 0,!!r)try{await r.close()}catch(n){if(X.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var lx=qU.child({prefix:"pi-mcp"}),HU=3,GU=6e4;function ZU(t,e){let r=Date.now(),n=r-GU,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=HU?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function px(t){Br(t),Fi(t)}async function BU(t,e,r){if(!ZU(e,t)){lx.warn(`MCP server "${t}" automatic restart rate-limited`);return}lx.warn(`MCP server "${t}" wedged; recycling transport`),await Dr(t,e,r)}function Uc(t,e,r){if(VU(e)){px(t);return}bu(t,r),In(e)&&px(t)}function VU(t){return Lo()||t.toolSearchLatched}function Vt(t,e,r){return Vh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function fh(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,st(t,e),t.authRefreshNeededReportKeys.delete(e),r}function WU(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name);return o!==void 0&&s!==void 0&&i!==void 0&&i.revision===o.revision&&i.domain===o.domain&&e.oauthCredentialDomains.get(r.name)===o.domain&&ut(o.domain)===We(r.id)?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function hh(t){let{state:e,config:r,generation:n}=t;return new Fc(r,WU({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function mh(t,e){if(e.id&&e.registrySource!==void 0){let r={...e};t.registryConfigNamesById.set(e.id,e.name),t.registryCredentialConfigs.set(e.name,r),t.registryCredentialConfigsById.set(e.id,r)}}function gh(t,e,r){return t.configDesiredRevisions.get(e)===r}function fx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function yh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Vt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(UU,c)},t.onWedged=()=>{if(!Vt(t,e,r))return;let i=r.currentLoad?.latestPi??n;BU(t.name,r,i)};let o=t.hostedCredentialProvenance,s=o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0?{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}:void 0;t.onAuthRefreshNeeded=()=>{if(!Vt(t,e,r)||!s)return;let i=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==i&&(r.authRefreshNeededReportKeys.set(t.name,i),J(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!Vt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&st(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Vt(t,e,r)&&t.status==="success"&&Uc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Ru(i,t,e),i!==n&&Ru(n,t,e)}}async function hx(t,e,r,n){let o=setTimeout(()=>{Vt(t,e,r)&&J(n(),r)},Ei);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Vt(t,e,r)&&J(n(),r)}}async function mx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function qc(t,e){if(e.status!=="installed")return!1;let r=Z(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function KU(t){let{state:e,config:r,displaced:n,retirement:o}=t;mh(e,n.config),zo(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():ct(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function JU(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=bt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function YU(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Vt(r,o,e)?a?.(n)===!1?(await JU({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Uc(c(),e,r),J(c(),e),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:i}):{status:"superseded",config:n}}function XU(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=Z(e,r.name);if(!gh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=fh(e,r.name),l=hh({state:e,config:r,generation:d});return yh(l,d,e,o),$i({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:YU({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function QU(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!gh(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):Z(r,a.name),l=En(a,s),p=Oo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>XU({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await KU({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await uu(p.retirement),h());return p.retirement?m():h()}async function wt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await QU({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Ei);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function eq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!fx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);mh(e,s),zo(e,t);let a=bt({state:e,name:t,owner:i.owner,revision:i.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),we({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw we({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(Z(e,t)?.revision!==i.revision||!fx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=fh(e,t),u=hh({state:e,config:s,generation:c});if(yh(u,c,e,r),!$i({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await hx(u,c,e,d),Vt(u,c,e)&&u.status==="success"&&Uc(d(),e,u),!0}function Dr(t,e,r){e.reconnects??=new Map,e.configRevisions??=new Map,e.reconnectDesiredGenerations??=new Map,e.statusFailureCategories??=new Map;let n=(e.reconnectDesiredGenerations.get(t)??0)+1;e.reconnectDesiredGenerations.set(t,n);let o=e.reconnects.get(t);if(o)return o;let s=(async()=>{let i=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await eq({name:t,state:e,pi:r,configRevision:a}))return;i=c}while(i<(e.reconnectDesiredGenerations.get(t)??i))})().finally(()=>{e.reconnects.get(t)===s&&e.reconnects.delete(t)});return e.reconnects.set(t,s),s}async function tq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;mh(e,n.config),zo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():ct(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function gx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=$n(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=Oo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await tq({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await uu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!gh(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=fh(e,t),h=hh({state:e,config:a,generation:f});yh(h,f,e,r),$i({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await hx(h,f,e,s),Vt(h,f,e)&&h.status==="success"&&Uc(s(),e,h))}async function _i(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Dr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as rq}from"@hermes/logger";var vh=rq.child({prefix:"pi-mcp"}),nq=1e6,oq=1e3,sq=/^\d+$/;function yx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function xn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(!(typeof e!="string"||!sq.test(e)||typeof r!="string"||r.length===0))return{revision:e.replace(/^0+(?=\d)/,""),domain:yx(r)}}function iq(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function aq(t,e,r,n){let o=e.credential_revision??e.credentialRevision,s=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||s!==void 0)&&r===void 0)return vh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";if(i?.kind==="blocked"||i?.kind==="domain"&&ut(r.domain)!==i.domain)return"reject";let a=n?.acceptedDomains?.get(t);if(a!==void 0&&yx(a)!==r.domain)return"reject";let c=iq(n?.acceptedRevisions,r.domain,s);if(c===void 0)return"apply";let u=mr(r.revision,c);return u>0||u===0&&a===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":u===0?"equal":"reject"}function cq(t,e,r,n){if(n!==void 0)return!1;let o=t.get(e);return o===void 0?!1:r.expiresAt===void 0||o.expiresAt===void 0||r.expiresAt<=o.expiresAt}function uq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function dq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*oq+Math.floor(t.access_token_expires_at.nanos/nq):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret,...t.token_endpoint_auth_method===void 0?{}:{token_endpoint_auth_method:t.token_endpoint_auth_method}}}}function Hc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!uq(s)){vh.warn(`Skipping MCP OAuth credentials for "${o}": entry is not an object with a non-empty access_token`),n.rejected.push(o);continue}let i=xn(s),a=aq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=dq(s);if(cq(t,o,c,i)){vh.warn(`Skipping MCP OAuth credentials for "${o}": legacy payload cannot prove freshness`),n.rejected.push(o);continue}t.set(o,c),r?.equalRevisionRebindDomains?.delete(o),i!==void 0&&(r?.acceptedRevisions?.set(i.domain,i.revision),r?.acceptedDomains?.set(o,i.domain)),n.applied.push(o)}return n}var pq=lq.child({prefix:"pi-mcp"});function fq(t,e){let r;for(let[n,o]of t.servers){if(o.config.id!==e)continue;let s=Q(t,n,o);if(!(s.host!==o||s.owner.kind!=="registry"||s.owner.identity!==`user:${e}`)){if(r)return;r={name:n,server:o}}}return r}function hq(t,e){let r=Object.values(t).filter(n=>{let o=xn(n);return o!==void 0&&ut(o.domain)===`user:${e}`});return r.length===1?r[0]:void 0}async function vx(t){let{pi:e,state:r,update:n}=t,o=fq(r,n.configId),s=hq(n.credentials,n.configId);if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=Hc(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let p=xn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Dr,l=t.report??J;await d(o.name,r,u).catch(p=>{pq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),ze(r)}import{logger as Pq}from"@hermes/logger";import{execFile as mq}from"node:child_process";import{logger as gq}from"@hermes/logger";var yq=5e3;function vq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function _x(t,e=yq){let r=gq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=vq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=mq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as _q}from"node:http";function Gc(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Sx(t){let e=Gc(t.title),r=Gc(t.heading),n=Gc(t.message),o=t.details?Gc(t.details):void 0,s=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
|
|
102
102
|
<html lang="en">
|
|
103
103
|
<head>
|
|
104
104
|
<meta charset="utf-8" />
|
package/package.json
CHANGED