@augmentcode/onison 1.2.0-prerelease.202611061212 → 1.2.0-prerelease.202611090911
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 +1444 -1448
- package/auggie-v2.mjs.d/extensions/mcp/index.js +26 -26
- package/indexing-worker.mjs +91 -91
- package/package.json +1 -1
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
var UT=Object.create;var Yu=Object.defineProperty;var qT=Object.getOwnPropertyDescriptor;var HT=Object.getOwnPropertyNames;var GT=Object.getPrototypeOf,ZT=Object.prototype.hasOwnProperty;var Pr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Xu=(t,e)=>{for(var r in e)Yu(t,r,{get:e[r],enumerable:!0})},BT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of HT(e))!ZT.call(t,o)&&o!==r&&Yu(t,o,{get:()=>e[o],enumerable:!(n=qT(e,o))||n.enumerable});return t};var ca=(t,e,r)=>(r=t!=null?UT(GT(t)):{},BT(e||!t||!t.__esModule?Yu(r,"default",{value:t,enumerable:!0}):r,t));var cs=P(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var ss=class{};J._CodeOrName=ss;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var xn=class extends ss{constructor(e){if(super(),!J.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};J.Name=xn;var bt=class extends ss{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof xn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};J._Code=bt;J.nil=new bt("");function Jb(t,...e){let r=[t[0]],n=0;for(;n<e.length;)zf(r,e[n]),r.push(t[++n]);return new bt(r)}J._=Jb;var Of=new bt("+");function Yb(t,...e){let r=[as(t[0])],n=0;for(;n<e.length;)r.push(Of),zf(r,e[n]),r.push(Of,as(t[++n]));return ON(r),new bt(r)}J.str=Yb;function zf(t,e){e instanceof bt?t.push(...e._items):e instanceof xn?t.push(e):t.push(DN(e))}J.addCodeArg=zf;function ON(t){let e=1;for(;e<t.length-1;){if(t[e]===Of){let r=zN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function zN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof xn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof xn))return`"${t}${e.slice(1)}`}function NN(t,e){return e.emptyStr()?t:t.emptyStr()?e:Yb`${t}${e}`}J.strConcat=NN;function DN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:as(Array.isArray(t)?t.join(","):t)}function LN(t){return new bt(as(t))}J.stringify=LN;function as(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=as;function jN(t){return typeof t=="string"&&J.IDENTIFIER.test(t)?new bt(`.${t}`):Jb`[${t}]`}J.getProperty=jN;function FN(t){if(typeof t=="string"&&J.IDENTIFIER.test(t))return new bt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}J.getEsmExportName=FN;function UN(t){return new bt(t.toString())}J.regexpCode=UN});var Lf=P(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.ValueScope=rt.ValueScopeName=rt.Scope=rt.varKinds=rt.UsedValueState=void 0;var tt=cs(),Nf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Pc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Pc||(rt.UsedValueState=Pc={}));rt.varKinds={const:new tt.Name("const"),let:new tt.Name("let"),var:new tt.Name("var")};var xc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof tt.Name?e:this.name(e)}name(e){return new tt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};rt.Scope=xc;var Ec=class extends tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,tt._)`.${new tt.Name(r)}[${n}]`}};rt.ValueScopeName=Ec;var qN=(0,tt._)`\n`,Df=class extends xc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qN:tt.nil}}get(){return this._scope}name(e){return new Ec(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let d=a.get(s);if(d)return d}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:i,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,tt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let i=tt.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Pc.Started);let d=r(u);if(d){let l=this.opts.es5?rt.varKinds.var:rt.varKinds.const;i=(0,tt._)`${i}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))i=(0,tt._)`${i}${d}${this.opts._n}`;else throw new Nf(u);c.set(u,Pc.Completed)})}return i}};rt.ValueScope=Df});var j=P(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var G=cs(),Ot=Lf(),Vr=cs();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return Vr._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return Vr.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return Vr.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return Vr.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return Vr.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return Vr.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return Vr.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return Vr.Name}});var Mc=Lf();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return Mc.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return Mc.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return Mc.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return Mc.varKinds}});F.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var hr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},jf=class extends hr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ot.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Eo(this.rhs,e,r)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},kc=class extends hr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof G.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Eo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof G.Name?{}:{...this.lhs.names};return Ac(e,this.rhs)}},Ff=class extends kc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Uf=class extends hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},qf=class extends hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Hf=class extends hr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Gf=class extends hr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Eo(this.code,e,r),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},us=class extends hr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(e,r)||(HN(e,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Tn(e,r.names),{})}},mr=class extends us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Zf=class extends us{},xo=class extends mr{};xo.kind="else";var En=class t extends mr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new xo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Xb(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Eo(this.condition,e,r),this}get names(){let e=super.names;return Ac(e,this.condition),this.else&&Tn(e,this.else.names),e}};En.kind="if";var kn=class extends mr{};kn.kind="for";var Bf=class extends kn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Eo(this.iteration,e,r),this}get names(){return Tn(super.names,this.iteration.names)}},Wf=class extends kn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ot.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=Ac(super.names,this.from);return Ac(e,this.to)}},Tc=class extends kn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Eo(this.iterable,e,r),this}get names(){return Tn(super.names,this.iterable.names)}},ds=class extends mr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ds.kind="func";var ls=class extends us{render(e){return"return "+super.render(e)}};ls.kind="return";var Vf=class extends mr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Tn(e,this.catch.names),this.finally&&Tn(e,this.finally.names),e}},fs=class extends mr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fs.kind="catch";var ps=class extends mr{render(e){return"finally"+super.render(e)}};ps.kind="finally";var Kf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2
|
-
`:""},this._extScope=e,this._scope=new Ot.Scope({parent:e}),this._nodes=[new Zf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new jf(e,i,n)),i}const(e,r,n){return this._def(Ot.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ot.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ot.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new kc(e,r,n))}add(e,r){return this._leafNode(new Ff(e,F.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==G.nil&&this._leafNode(new Gf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,G.addCodeArg)(r,o));return r.push("}"),new G._Code(r)}if(e,r,n){if(this._blockNode(new En(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new En(e))}else(){return this._elseNode(new xo)}endIf(){return this._endBlockNode(En,xo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Bf(e),r)}forRange(e,r,n,o,i=this.opts.es5?Ot.varKinds.var:Ot.varKinds.let){let s=this._scope.toName(e);return this._for(new Wf(i,s,r,n),()=>o(s))}forOf(e,r,n,o=Ot.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=r instanceof G.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,G._)`${s}.length`,a=>{this.var(i,(0,G._)`${s}[${a}]`),n(i)})}return this._for(new Tc("of",o,i,r),()=>n(i))}forIn(e,r,n,o=this.opts.es5?Ot.varKinds.var:Ot.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,G._)`Object.keys(${r})`,n);let i=this._scope.toName(e);return this._for(new Tc("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(kn)}label(e){return this._leafNode(new Uf(e))}break(e){return this._leafNode(new qf(e))}return(e){let r=new ls;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ls)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Vf;if(this._blockNode(o),this.code(e),r){let i=this.name("e");this._currNode=o.catch=new fs(i),r(i)}return n&&(this._currNode=o.finally=new ps,this.code(n)),this._endBlockNode(fs,ps)}throw(e){return this._leafNode(new Hf(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=G.nil,n,o){return this._blockNode(new ds(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ds)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof En))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};F.CodeGen=Kf;function Tn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ac(t,e){return e instanceof G._CodeOrName?Tn(t,e.names):t}function Eo(t,e,r){if(t instanceof G.Name)return n(t);if(!o(t))return t;return new G._Code(t._items.reduce((i,s)=>(s instanceof G.Name&&(s=n(s)),s instanceof G._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof G._Code&&i._items.some(s=>s instanceof G.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function HN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Xb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,G._)`!${Jf(t)}`}F.not=Xb;var GN=Qb(F.operators.AND);function ZN(...t){return t.reduce(GN)}F.and=ZN;var BN=Qb(F.operators.OR);function WN(...t){return t.reduce(BN)}F.or=WN;function Qb(t){return(e,r)=>e===G.nil?r:r===G.nil?e:(0,G._)`${Jf(e)} ${t} ${Jf(r)}`}function Jf(t){return t instanceof G.Name?t:(0,G._)`(${t})`}});var B=P(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.checkStrictMode=U.getErrorPath=U.Type=U.useFunc=U.setEvaluated=U.evaluatedPropsToName=U.mergeEvaluated=U.eachItem=U.unescapeJsonPointer=U.escapeJsonPointer=U.escapeFragment=U.unescapeFragment=U.schemaRefOrVal=U.schemaHasRulesButRef=U.schemaHasRules=U.checkUnknownRules=U.alwaysValidSchema=U.toHash=void 0;var se=j(),VN=cs();function KN(t){let e={};for(let r of t)e[r]=!0;return e}U.toHash=KN;function JN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(rR(t,e),!nR(e,t.self.RULES.all))}U.alwaysValidSchema=JN;function rR(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let i in e)o[i]||sR(t,`unknown keyword: "${i}"`)}U.checkUnknownRules=rR;function nR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}U.schemaHasRules=nR;function YN(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}U.schemaHasRulesButRef=YN;function XN({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${t}${e}${(0,se.getProperty)(n)}`}U.schemaRefOrVal=XN;function QN(t){return oR(decodeURIComponent(t))}U.unescapeFragment=QN;function eD(t){return encodeURIComponent(Xf(t))}U.escapeFragment=eD;function Xf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}U.escapeJsonPointer=Xf;function oR(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}U.unescapeJsonPointer=oR;function tD(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}U.eachItem=tD;function eR({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof se.Name?(i instanceof se.Name?t(o,i,s):e(o,i,s),s):i instanceof se.Name?(e(o,s,i),i):r(i,s);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}U.mergeEvaluated={props:eR({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,se._)`${r} || {}`),Qf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:iR}),items:eR({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function iR(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&Qf(t,r,e),r}U.evaluatedPropsToName=iR;function Qf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}U.setEvaluated=Qf;var tR={};function rD(t,e){return t.scopeValue("func",{ref:e,code:tR[e.code]||(tR[e.code]=new VN._Code(e.code))})}U.useFunc=rD;var Yf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Yf||(U.Type=Yf={}));function nD(t,e,r){if(t instanceof se.Name){let n=e===Yf.Num;return r?n?(0,se._)`"[" + ${t} + "]"`:(0,se._)`"['" + ${t} + "']"`:n?(0,se._)`"/" + ${t}`:(0,se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(t).toString():"/"+Xf(t)}U.getErrorPath=nD;function sR(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}U.checkStrictMode=sR});var gr=P(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Fe=j(),oD={data:new Fe.Name("data"),valCxt:new Fe.Name("valCxt"),instancePath:new Fe.Name("instancePath"),parentData:new Fe.Name("parentData"),parentDataProperty:new Fe.Name("parentDataProperty"),rootData:new Fe.Name("rootData"),dynamicAnchors:new Fe.Name("dynamicAnchors"),vErrors:new Fe.Name("vErrors"),errors:new Fe.Name("errors"),this:new Fe.Name("this"),self:new Fe.Name("self"),scope:new Fe.Name("scope"),json:new Fe.Name("json"),jsonPos:new Fe.Name("jsonPos"),jsonLen:new Fe.Name("jsonLen"),jsonPart:new Fe.Name("jsonPart")};ep.default=oD});var hs=P(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.extendErrors=Ue.resetErrorsCount=Ue.reportExtraError=Ue.reportError=Ue.keyword$DataError=Ue.keywordError=void 0;var W=j(),$c=B(),Ze=gr();Ue.keywordError={message:({keyword:t})=>(0,W.str)`must pass "${t}" keyword validation`};Ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,W.str)`"${t}" keyword must be ${e} ($data)`:(0,W.str)`"${t}" keyword is invalid ($data)`};function iD(t,e=Ue.keywordError,r,n){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=uR(t,e,r);n??(s||a)?aR(i,c):cR(o,(0,W._)`[${c}]`)}Ue.reportError=iD;function sD(t,e=Ue.keywordError,r){let{it:n}=t,{gen:o,compositeRule:i,allErrors:s}=n,a=uR(t,e,r);aR(o,a),i||s||cR(n,Ze.default.vErrors)}Ue.reportExtraError=sD;function aD(t,e){t.assign(Ze.default.errors,e),t.if((0,W._)`${Ze.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,W._)`${Ze.default.vErrors}.length`,e),()=>t.assign(Ze.default.vErrors,null)))}Ue.resetErrorsCount=aD;function cD({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,Ze.default.errors,a=>{t.const(s,(0,W._)`${Ze.default.vErrors}[${a}]`),t.if((0,W._)`${s}.instancePath === undefined`,()=>t.assign((0,W._)`${s}.instancePath`,(0,W.strConcat)(Ze.default.instancePath,i.errorPath))),t.assign((0,W._)`${s}.schemaPath`,(0,W.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,W._)`${s}.schema`,r),t.assign((0,W._)`${s}.data`,n))})}Ue.extendErrors=cD;function aR(t,e){let r=t.const("err",e);t.if((0,W._)`${Ze.default.vErrors} === null`,()=>t.assign(Ze.default.vErrors,(0,W._)`[${r}]`),(0,W._)`${Ze.default.vErrors}.push(${r})`),t.code((0,W._)`${Ze.default.errors}++`)}function cR(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,W._)`new ${t.ValidationError}(${e})`):(r.assign((0,W._)`${n}.errors`,e),r.return(!1))}var An={keyword:new W.Name("keyword"),schemaPath:new W.Name("schemaPath"),params:new W.Name("params"),propertyName:new W.Name("propertyName"),message:new W.Name("message"),schema:new W.Name("schema"),parentSchema:new W.Name("parentSchema")};function uR(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,W._)`{}`:uD(t,e,r)}function uD(t,e,r={}){let{gen:n,it:o}=t,i=[dD(o,r),lD(t,r)];return fD(t,e,i),n.object(...i)}function dD({errorPath:t},{instancePath:e}){let r=e?(0,W.str)`${t}${(0,$c.getErrorPath)(e,$c.Type.Str)}`:t;return[Ze.default.instancePath,(0,W.strConcat)(Ze.default.instancePath,r)]}function lD({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,W.str)`${e}/${t}`;return r&&(o=(0,W.str)`${o}${(0,$c.getErrorPath)(r,$c.Type.Str)}`),[An.schemaPath,o]}function fD(t,{params:e,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([An.keyword,o],[An.params,typeof e=="function"?e(t):e||(0,W._)`{}`]),c.messages&&n.push([An.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([An.schema,s],[An.parentSchema,(0,W._)`${d}${l}`],[Ze.default.data,i]),u&&n.push([An.propertyName,u])}});var lR=P(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.boolOrEmptySchema=ko.topBoolOrEmptySchema=void 0;var pD=hs(),hD=j(),mD=gr(),gD={message:"boolean schema is false"};function yD(t){let{gen:e,schema:r,validateName:n}=t;r===!1?dR(t,!1):typeof r=="object"&&r.$async===!0?e.return(mD.default.data):(e.assign((0,hD._)`${n}.errors`,null),e.return(!0))}ko.topBoolOrEmptySchema=yD;function vD(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),dR(t)):r.var(e,!0)}ko.boolOrEmptySchema=vD;function dR(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,pD.reportError)(o,gD,void 0,e)}});var tp=P(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.getRules=To.isJSONType=void 0;var _D=["string","number","integer","boolean","null","object","array"],SD=new Set(_D);function wD(t){return typeof t=="string"&&SD.has(t)}To.isJSONType=wD;function bD(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}To.getRules=bD});var rp=P(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.shouldUseRule=Kr.shouldUseGroup=Kr.schemaHasRulesForType=void 0;function RD({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&fR(t,n)}Kr.schemaHasRulesForType=RD;function fR(t,e){return e.rules.some(r=>pR(t,r))}Kr.shouldUseGroup=fR;function pR(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Kr.shouldUseRule=pR});var ms=P(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.reportTypeError=qe.checkDataTypes=qe.checkDataType=qe.coerceAndCheckDataType=qe.getJSONTypes=qe.getSchemaTypes=qe.DataType=void 0;var CD=tp(),PD=rp(),xD=hs(),L=j(),hR=B(),Ao;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ao||(qe.DataType=Ao={}));function ED(t){let e=mR(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}qe.getSchemaTypes=ED;function mR(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(CD.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}qe.getJSONTypes=mR;function kD(t,e){let{gen:r,data:n,opts:o}=t,i=TD(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,PD.schemaHasRulesForType)(t,e[0]));if(s){let a=op(e,n,o.strictNumbers,Ao.Wrong);r.if(a,()=>{i.length?AD(t,e,i):ip(t)})}return s}qe.coerceAndCheckDataType=kD;var gR=new Set(["string","number","integer","boolean","null"]);function TD(t,e){return e?t.filter(r=>gR.has(r)||e==="array"&&r==="array"):[]}function AD(t,e,r){let{gen:n,data:o,opts:i}=t,s=n.let("dataType",(0,L._)`typeof ${o}`),a=n.let("coerced",(0,L._)`undefined`);i.coerceTypes==="array"&&n.if((0,L._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,L._)`${o}[0]`).assign(s,(0,L._)`typeof ${o}`).if(op(e,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,L._)`${a} !== undefined`);for(let u of r)(gR.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);n.else(),ip(t),n.endIf(),n.if((0,L._)`${a} !== undefined`,()=>{n.assign(o,a),MD(t,a)});function c(u){switch(u){case"string":n.elseIf((0,L._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,L._)`"" + ${o}`).elseIf((0,L._)`${o} === null`).assign(a,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${s} == "boolean" || ${o} === null
|
|
1
|
+
var KT=Object.create;var Qu=Object.defineProperty;var JT=Object.getOwnPropertyDescriptor;var YT=Object.getOwnPropertyNames;var XT=Object.getPrototypeOf,QT=Object.prototype.hasOwnProperty;var Er=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},ed=(t,e)=>{for(var r in e)Qu(t,r,{get:e[r],enumerable:!0})},eA=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of YT(e))!QT.call(t,o)&&o!==r&&Qu(t,o,{get:()=>e[o],enumerable:!(n=JT(e,o))||n.enumerable});return t};var ca=(t,e,r)=>(r=t!=null?KT(XT(t)):{},eA(e||!t||!t.__esModule?Qu(r,"default",{value:t,enumerable:!0}):r,t));var wR=P(Xf=>{"use strict";var vR=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,pD=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,_R=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,hD=/\\([\u000b\u0020-\u00ff])/g,mD=/([\\"])/g,SR=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Xf.format=gD;Xf.parse=yD;function gD(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!SR.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,i=Object.keys(e).sort(),s=0;s<i.length;s++){if(o=i[s],!_R.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+_D(e[o])}return n}function yD(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?vD(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!SR.test(n))throw new TypeError("invalid media type");var o=new SD(n.toLowerCase());if(r!==-1){var i,s,a;for(vR.lastIndex=r;s=vR.exec(e);){if(s.index!==r)throw new TypeError("invalid parameter format");r+=s[0].length,i=s[1].toLowerCase(),a=s[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(hD,"$1"))),o.parameters[i]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function vD(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function _D(t){var e=String(t);if(_R.test(e))return e;if(e.length>0&&!pD.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(mD,"\\$1")+'"'}function SD(t){this.parameters=Object.create(null),this.type=t}});var Es=P(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.regexpCode=J.getEsmExportName=J.getProperty=J.safeStringify=J.stringify=J.strConcat=J.addCodeArg=J.str=J._=J.nil=J._Code=J.Name=J.IDENTIFIER=J._CodeOrName=void 0;var Cs=class{};J._CodeOrName=Cs;J.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Nn=class extends Cs{constructor(e){if(super(),!J.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};J.Name=Nn;var Rt=class extends Cs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Nn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};J._Code=Rt;J.nil=new Rt("");function ER(t,...e){let r=[t[0]],n=0;for(;n<e.length;)np(r,e[n]),r.push(t[++n]);return new Rt(r)}J._=ER;var rp=new Rt("+");function xR(t,...e){let r=[Ps(t[0])],n=0;for(;n<e.length;)r.push(rp),np(r,e[n]),r.push(rp,Ps(t[++n]));return xD(r),new Rt(r)}J.str=xR;function np(t,e){e instanceof Rt?t.push(...e._items):e instanceof Nn?t.push(e):t.push(AD(e))}J.addCodeArg=np;function xD(t){let e=1;for(;e<t.length-1;){if(t[e]===rp){let r=kD(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function kD(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Nn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Nn))return`"${t}${e.slice(1)}`}function TD(t,e){return e.emptyStr()?t:t.emptyStr()?e:xR`${t}${e}`}J.strConcat=TD;function AD(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ps(Array.isArray(t)?t.join(","):t)}function MD(t){return new Rt(Ps(t))}J.stringify=MD;function Ps(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}J.safeStringify=Ps;function $D(t){return typeof t=="string"&&J.IDENTIFIER.test(t)?new Rt(`.${t}`):ER`[${t}]`}J.getProperty=$D;function ID(t){if(typeof t=="string"&&J.IDENTIFIER.test(t))return new Rt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}J.getEsmExportName=ID;function OD(t){return new Rt(t.toString())}J.regexpCode=OD});var sp=P(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ValueScope=ot.ValueScopeName=ot.Scope=ot.varKinds=ot.UsedValueState=void 0;var nt=Es(),op=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Oc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Oc||(ot.UsedValueState=Oc={}));ot.varKinds={const:new nt.Name("const"),let:new nt.Name("let"),var:new nt.Name("var")};var zc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof nt.Name?e:this.name(e)}name(e){return new nt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ot.Scope=zc;var Nc=class extends nt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,nt._)`.${new nt.Name(r)}[${n}]`}};ot.ValueScopeName=Nc;var zD=(0,nt._)`\n`,ip=class extends zc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?zD:nt.nil}}get(){return this._scope}name(e){return new Nc(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let d=a.get(s);if(d)return d}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:i,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,nt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let i=nt.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Oc.Started);let d=r(u);if(d){let l=this.opts.es5?ot.varKinds.var:ot.varKinds.const;i=(0,nt._)`${i}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))i=(0,nt._)`${i}${d}${this.opts._n}`;else throw new op(u);c.set(u,Oc.Completed)})}return i}};ot.ValueScope=ip});var j=P(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.or=F.and=F.not=F.CodeGen=F.operators=F.varKinds=F.ValueScopeName=F.ValueScope=F.Scope=F.Name=F.regexpCode=F.stringify=F.getProperty=F.nil=F.strConcat=F.str=F._=void 0;var G=Es(),Nt=sp(),Yr=Es();Object.defineProperty(F,"_",{enumerable:!0,get:function(){return Yr._}});Object.defineProperty(F,"str",{enumerable:!0,get:function(){return Yr.str}});Object.defineProperty(F,"strConcat",{enumerable:!0,get:function(){return Yr.strConcat}});Object.defineProperty(F,"nil",{enumerable:!0,get:function(){return Yr.nil}});Object.defineProperty(F,"getProperty",{enumerable:!0,get:function(){return Yr.getProperty}});Object.defineProperty(F,"stringify",{enumerable:!0,get:function(){return Yr.stringify}});Object.defineProperty(F,"regexpCode",{enumerable:!0,get:function(){return Yr.regexpCode}});Object.defineProperty(F,"Name",{enumerable:!0,get:function(){return Yr.Name}});var Fc=sp();Object.defineProperty(F,"Scope",{enumerable:!0,get:function(){return Fc.Scope}});Object.defineProperty(F,"ValueScope",{enumerable:!0,get:function(){return Fc.ValueScope}});Object.defineProperty(F,"ValueScopeName",{enumerable:!0,get:function(){return Fc.ValueScopeName}});Object.defineProperty(F,"varKinds",{enumerable:!0,get:function(){return Fc.varKinds}});F.operators={GT:new G._Code(">"),GTE:new G._Code(">="),LT:new G._Code("<"),LTE:new G._Code("<="),EQ:new G._Code("==="),NEQ:new G._Code("!=="),NOT:new G._Code("!"),OR:new G._Code("||"),AND:new G._Code("&&"),ADD:new G._Code("+")};var vr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ap=class extends vr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Nt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=zo(this.rhs,e,r)),this}get names(){return this.rhs instanceof G._CodeOrName?this.rhs.names:{}}},Dc=class extends vr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof G.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=zo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof G.Name?{}:{...this.lhs.names};return jc(e,this.rhs)}},cp=class extends Dc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},up=class extends vr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},dp=class extends vr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},lp=class extends vr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},fp=class extends vr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=zo(this.code,e,r),this}get names(){return this.code instanceof G._CodeOrName?this.code.names:{}}},xs=class extends vr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(e,r)||(ND(e,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>jn(e,r.names),{})}},_r=class extends xs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},pp=class extends xs{},Oo=class extends _r{};Oo.kind="else";var Dn=class t extends _r{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Oo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(kR(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=zo(this.condition,e,r),this}get names(){let e=super.names;return jc(e,this.condition),this.else&&jn(e,this.else.names),e}};Dn.kind="if";var Ln=class extends _r{};Ln.kind="for";var hp=class extends Ln{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=zo(this.iteration,e,r),this}get names(){return jn(super.names,this.iteration.names)}},mp=class extends Ln{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Nt.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=jc(super.names,this.from);return jc(e,this.to)}},Lc=class extends Ln{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=zo(this.iterable,e,r),this}get names(){return jn(super.names,this.iterable.names)}},ks=class extends _r{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ks.kind="func";var Ts=class extends xs{render(e){return"return "+super.render(e)}};Ts.kind="return";var gp=class extends _r{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&jn(e,this.catch.names),this.finally&&jn(e,this.finally.names),e}},As=class extends _r{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};As.kind="catch";var Ms=class extends _r{render(e){return"finally"+super.render(e)}};Ms.kind="finally";var yp=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2
|
+
`:""},this._extScope=e,this._scope=new Nt.Scope({parent:e}),this._nodes=[new pp]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new ap(e,i,n)),i}const(e,r,n){return this._def(Nt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Nt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Nt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Dc(e,r,n))}add(e,r){return this._leafNode(new cp(e,F.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==G.nil&&this._leafNode(new fp(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,G.addCodeArg)(r,o));return r.push("}"),new G._Code(r)}if(e,r,n){if(this._blockNode(new Dn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Dn(e))}else(){return this._elseNode(new Oo)}endIf(){return this._endBlockNode(Dn,Oo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new hp(e),r)}forRange(e,r,n,o,i=this.opts.es5?Nt.varKinds.var:Nt.varKinds.let){let s=this._scope.toName(e);return this._for(new mp(i,s,r,n),()=>o(s))}forOf(e,r,n,o=Nt.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let s=r instanceof G.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,G._)`${s}.length`,a=>{this.var(i,(0,G._)`${s}[${a}]`),n(i)})}return this._for(new Lc("of",o,i,r),()=>n(i))}forIn(e,r,n,o=this.opts.es5?Nt.varKinds.var:Nt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,G._)`Object.keys(${r})`,n);let i=this._scope.toName(e);return this._for(new Lc("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(Ln)}label(e){return this._leafNode(new up(e))}break(e){return this._leafNode(new dp(e))}return(e){let r=new Ts;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ts)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new gp;if(this._blockNode(o),this.code(e),r){let i=this.name("e");this._currNode=o.catch=new As(i),r(i)}return n&&(this._currNode=o.finally=new Ms,this.code(n)),this._endBlockNode(As,Ms)}throw(e){return this._leafNode(new lp(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=G.nil,n,o){return this._blockNode(new ks(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ks)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Dn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};F.CodeGen=yp;function jn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function jc(t,e){return e instanceof G._CodeOrName?jn(t,e.names):t}function zo(t,e,r){if(t instanceof G.Name)return n(t);if(!o(t))return t;return new G._Code(t._items.reduce((i,s)=>(s instanceof G.Name&&(s=n(s)),s instanceof G._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||e[i.str]!==1?i:(delete e[i.str],s)}function o(i){return i instanceof G._Code&&i._items.some(s=>s instanceof G.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function ND(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function kR(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,G._)`!${vp(t)}`}F.not=kR;var DD=TR(F.operators.AND);function LD(...t){return t.reduce(DD)}F.and=LD;var jD=TR(F.operators.OR);function FD(...t){return t.reduce(jD)}F.or=FD;function TR(t){return(e,r)=>e===G.nil?r:r===G.nil?e:(0,G._)`${vp(e)} ${t} ${vp(r)}`}function vp(t){return t instanceof G.Name?t:(0,G._)`(${t})`}});var B=P(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.checkStrictMode=U.getErrorPath=U.Type=U.useFunc=U.setEvaluated=U.evaluatedPropsToName=U.mergeEvaluated=U.eachItem=U.unescapeJsonPointer=U.escapeJsonPointer=U.escapeFragment=U.unescapeFragment=U.schemaRefOrVal=U.schemaHasRulesButRef=U.schemaHasRules=U.checkUnknownRules=U.alwaysValidSchema=U.toHash=void 0;var se=j(),UD=Es();function qD(t){let e={};for(let r of t)e[r]=!0;return e}U.toHash=qD;function HD(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:($R(t,e),!IR(e,t.self.RULES.all))}U.alwaysValidSchema=HD;function $R(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let i in e)o[i]||NR(t,`unknown keyword: "${i}"`)}U.checkUnknownRules=$R;function IR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}U.schemaHasRules=IR;function GD(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}U.schemaHasRulesButRef=GD;function ZD({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${t}${e}${(0,se.getProperty)(n)}`}U.schemaRefOrVal=ZD;function BD(t){return OR(decodeURIComponent(t))}U.unescapeFragment=BD;function WD(t){return encodeURIComponent(Sp(t))}U.escapeFragment=WD;function Sp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}U.escapeJsonPointer=Sp;function OR(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}U.unescapeJsonPointer=OR;function VD(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}U.eachItem=VD;function AR({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof se.Name?(i instanceof se.Name?t(o,i,s):e(o,i,s),s):i instanceof se.Name?(e(o,s,i),i):r(i,s);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}U.mergeEvaluated={props:AR({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,se._)`${r} || {}`),wp(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:zR}),items:AR({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function zR(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&wp(t,r,e),r}U.evaluatedPropsToName=zR;function wp(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}U.setEvaluated=wp;var MR={};function KD(t,e){return t.scopeValue("func",{ref:e,code:MR[e.code]||(MR[e.code]=new UD._Code(e.code))})}U.useFunc=KD;var _p;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_p||(U.Type=_p={}));function JD(t,e,r){if(t instanceof se.Name){let n=e===_p.Num;return r?n?(0,se._)`"[" + ${t} + "]"`:(0,se._)`"['" + ${t} + "']"`:n?(0,se._)`"/" + ${t}`:(0,se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(t).toString():"/"+Sp(t)}U.getErrorPath=JD;function NR(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}U.checkStrictMode=NR});var Sr=P(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var Ue=j(),YD={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};bp.default=YD});var $s=P(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.extendErrors=qe.resetErrorsCount=qe.reportExtraError=qe.reportError=qe.keyword$DataError=qe.keywordError=void 0;var W=j(),Uc=B(),Be=Sr();qe.keywordError={message:({keyword:t})=>(0,W.str)`must pass "${t}" keyword validation`};qe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,W.str)`"${t}" keyword must be ${e} ($data)`:(0,W.str)`"${t}" keyword is invalid ($data)`};function XD(t,e=qe.keywordError,r,n){let{it:o}=t,{gen:i,compositeRule:s,allErrors:a}=o,c=jR(t,e,r);n??(s||a)?DR(i,c):LR(o,(0,W._)`[${c}]`)}qe.reportError=XD;function QD(t,e=qe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:i,allErrors:s}=n,a=jR(t,e,r);DR(o,a),i||s||LR(n,Be.default.vErrors)}qe.reportExtraError=QD;function eL(t,e){t.assign(Be.default.errors,e),t.if((0,W._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,W._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}qe.resetErrorsCount=eL;function tL({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(s,(0,W._)`${Be.default.vErrors}[${a}]`),t.if((0,W._)`${s}.instancePath === undefined`,()=>t.assign((0,W._)`${s}.instancePath`,(0,W.strConcat)(Be.default.instancePath,i.errorPath))),t.assign((0,W._)`${s}.schemaPath`,(0,W.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(t.assign((0,W._)`${s}.schema`,r),t.assign((0,W._)`${s}.data`,n))})}qe.extendErrors=tL;function DR(t,e){let r=t.const("err",e);t.if((0,W._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,W._)`[${r}]`),(0,W._)`${Be.default.vErrors}.push(${r})`),t.code((0,W._)`${Be.default.errors}++`)}function LR(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,W._)`new ${t.ValidationError}(${e})`):(r.assign((0,W._)`${n}.errors`,e),r.return(!1))}var Fn={keyword:new W.Name("keyword"),schemaPath:new W.Name("schemaPath"),params:new W.Name("params"),propertyName:new W.Name("propertyName"),message:new W.Name("message"),schema:new W.Name("schema"),parentSchema:new W.Name("parentSchema")};function jR(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,W._)`{}`:rL(t,e,r)}function rL(t,e,r={}){let{gen:n,it:o}=t,i=[nL(o,r),oL(t,r)];return iL(t,e,i),n.object(...i)}function nL({errorPath:t},{instancePath:e}){let r=e?(0,W.str)`${t}${(0,Uc.getErrorPath)(e,Uc.Type.Str)}`:t;return[Be.default.instancePath,(0,W.strConcat)(Be.default.instancePath,r)]}function oL({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,W.str)`${e}/${t}`;return r&&(o=(0,W.str)`${o}${(0,Uc.getErrorPath)(r,Uc.Type.Str)}`),[Fn.schemaPath,o]}function iL(t,{params:e,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([Fn.keyword,o],[Fn.params,typeof e=="function"?e(t):e||(0,W._)`{}`]),c.messages&&n.push([Fn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Fn.schema,s],[Fn.parentSchema,(0,W._)`${d}${l}`],[Be.default.data,i]),u&&n.push([Fn.propertyName,u])}});var UR=P(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.boolOrEmptySchema=No.topBoolOrEmptySchema=void 0;var sL=$s(),aL=j(),cL=Sr(),uL={message:"boolean schema is false"};function dL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?FR(t,!1):typeof r=="object"&&r.$async===!0?e.return(cL.default.data):(e.assign((0,aL._)`${n}.errors`,null),e.return(!0))}No.topBoolOrEmptySchema=dL;function lL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),FR(t)):r.var(e,!0)}No.boolOrEmptySchema=lL;function FR(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,sL.reportError)(o,uL,void 0,e)}});var Rp=P(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.getRules=Do.isJSONType=void 0;var fL=["string","number","integer","boolean","null","object","array"],pL=new Set(fL);function hL(t){return typeof t=="string"&&pL.has(t)}Do.isJSONType=hL;function mL(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Do.getRules=mL});var Cp=P(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.shouldUseRule=Xr.shouldUseGroup=Xr.schemaHasRulesForType=void 0;function gL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&qR(t,n)}Xr.schemaHasRulesForType=gL;function qR(t,e){return e.rules.some(r=>HR(t,r))}Xr.shouldUseGroup=qR;function HR(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Xr.shouldUseRule=HR});var Is=P(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.reportTypeError=He.checkDataTypes=He.checkDataType=He.coerceAndCheckDataType=He.getJSONTypes=He.getSchemaTypes=He.DataType=void 0;var yL=Rp(),vL=Cp(),_L=$s(),L=j(),GR=B(),Lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lo||(He.DataType=Lo={}));function SL(t){let e=ZR(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}He.getSchemaTypes=SL;function ZR(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(yL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}He.getJSONTypes=ZR;function wL(t,e){let{gen:r,data:n,opts:o}=t,i=bL(e,o.coerceTypes),s=e.length>0&&!(i.length===0&&e.length===1&&(0,vL.schemaHasRulesForType)(t,e[0]));if(s){let a=Ep(e,n,o.strictNumbers,Lo.Wrong);r.if(a,()=>{i.length?RL(t,e,i):xp(t)})}return s}He.coerceAndCheckDataType=wL;var BR=new Set(["string","number","integer","boolean","null"]);function bL(t,e){return e?t.filter(r=>BR.has(r)||e==="array"&&r==="array"):[]}function RL(t,e,r){let{gen:n,data:o,opts:i}=t,s=n.let("dataType",(0,L._)`typeof ${o}`),a=n.let("coerced",(0,L._)`undefined`);i.coerceTypes==="array"&&n.if((0,L._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,L._)`${o}[0]`).assign(s,(0,L._)`typeof ${o}`).if(Ep(e,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,L._)`${a} !== undefined`);for(let u of r)(BR.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);n.else(),xp(t),n.endIf(),n.if((0,L._)`${a} !== undefined`,()=>{n.assign(o,a),CL(t,a)});function c(u){switch(u){case"string":n.elseIf((0,L._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,L._)`"" + ${o}`).elseIf((0,L._)`${o} === null`).assign(a,(0,L._)`""`);return;case"number":n.elseIf((0,L._)`${s} == "boolean" || ${o} === null
|
|
3
3
|
|| (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,L._)`+${o}`);return;case"integer":n.elseIf((0,L._)`${s} === "boolean" || ${o} === null
|
|
4
4
|
|| (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,L._)`+${o}`);return;case"boolean":n.elseIf((0,L._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,L._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,L._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,L._)`${s} === "string" || ${s} === "number"
|
|
5
|
-
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,L._)`[${o}]`)}}}function MD({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,L._)`${e} !== undefined`,()=>t.assign((0,L._)`${e}[${r}]`,n))}function np(t,e,r,n=Ao.Correct){let o=n===Ao.Correct?L.operators.EQ:L.operators.NEQ,i;switch(t){case"null":return(0,L._)`${e} ${o} null`;case"array":i=(0,L._)`Array.isArray(${e})`;break;case"object":i=(0,L._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,L._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,L._)`typeof ${e} ${o} ${t}`}return n===Ao.Correct?i:(0,L.not)(i);function s(a=L.nil){return(0,L.and)((0,L._)`typeof ${e} == "number"`,a,r?(0,L._)`isFinite(${e})`:L.nil)}}qe.checkDataType=np;function op(t,e,r,n){if(t.length===1)return np(t[0],e,r,n);let o,i=(0,hR.toHash)(t);if(i.array&&i.object){let s=(0,L._)`typeof ${e} != "object"`;o=i.null?s:(0,L._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=L.nil;i.number&&delete i.integer;for(let s in i)o=(0,L.and)(o,np(s,e,r,n));return o}qe.checkDataTypes=op;var $D={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,L._)`{type: ${t}}`:(0,L._)`{type: ${e}}`};function ip(t){let e=ID(t);(0,xD.reportError)(e,$D)}qe.reportTypeError=ip;function ID(t){let{gen:e,data:r,schema:n}=t,o=(0,hR.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var vR=P(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.assignDefaults=void 0;var Mo=j(),OD=B();function zD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)yR(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>yR(t,i,o.default))}Ic.assignDefaults=zD;function yR(t,e,r){let{gen:n,compositeRule:o,data:i,opts:s}=t;if(r===void 0)return;let a=(0,Mo._)`${i}${(0,Mo.getProperty)(e)}`;if(o){(0,OD.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Mo._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,Mo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Mo._)`${a} = ${(0,Mo.stringify)(r)}`)}});var Rt=P(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var de=j(),sp=B(),Jr=gr(),ND=B();function DD(t,e){let{gen:r,data:n,it:o}=t;r.if(cp(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}ne.checkReportMissingProp=DD;function LD({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(i=>(0,de.and)(cp(t,e,i,r.ownProperties),(0,de._)`${o} = ${i}`)))}ne.checkMissingProp=LD;function jD(t,e){t.setParams({missingProperty:e},!0),t.error()}ne.reportMissingProp=jD;function _R(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}ne.hasPropFunc=_R;function ap(t,e,r){return(0,de._)`${_R(t)}.call(${e}, ${r})`}ne.isOwnProperty=ap;function FD(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${ap(t,e,r)}`:o}ne.propertyInData=FD;function cp(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(ap(t,e,r))):o}ne.noPropertyInData=cp;function SR(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ne.allSchemaProperties=SR;function UD(t,e){return SR(e).filter(r=>!(0,sp.alwaysValidSchema)(t,e[r]))}ne.schemaProperties=UD;function qD({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[Jr.default.instancePath,(0,de.strConcat)(Jr.default.instancePath,i)],[Jr.default.parentData,s.parentData],[Jr.default.parentDataProperty,s.parentDataProperty],[Jr.default.rootData,Jr.default.rootData]];s.opts.dynamicRef&&l.push([Jr.default.dynamicAnchors,Jr.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}ne.callValidateCode=qD;var HD=(0,de._)`new RegExp`;function GD({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,de._)`${o.code==="new RegExp"?HD:(0,ND.useFunc)(t,o)}(${r}, ${n})`})}ne.usePattern=GD;function ZD(t){let{gen:e,data:r,keyword:n,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:sp.Type.Num},i),e.if((0,de.not)(i),a)})}}ne.validateArray=ZD;function BD(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,sp.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(s,(0,de._)`${s} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ne.validateUnion=BD});var RR=P(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.validateKeywordUsage=Xt.validSchemaType=Xt.funcKeywordCode=Xt.macroKeywordCode=void 0;var Be=j(),Mn=gr(),WD=Rt(),VD=hs();function KD(t,e){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=bR(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Be.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Xt.macroKeywordCode=KD;function JD(t,e){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;XD(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,d=bR(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&wR(t),g(()=>t.error());else{let v=e.async?p():h();e.modifying&&wR(t),g(()=>YD(t,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,Be._)`await `),w=>n.assign(l,!1).if((0,Be._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Be._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,Be._)`${d}.errors`;return n.assign(v,null),m(Be.nil),v}function m(v=e.async?(0,Be._)`await `:Be.nil){let w=c.opts.passContext?Mn.default.this:Mn.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Be._)`${v}${(0,WD.callValidateCode)(t,d,w,b)}`,e.modifying)}function g(v){var w;n.if((0,Be.not)((w=e.valid)!==null&&w!==void 0?w:l),v)}}Xt.funcKeywordCode=JD;function wR(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Be._)`${n.parentData}[${n.parentDataProperty}]`))}function YD(t,e){let{gen:r}=t;r.if((0,Be._)`Array.isArray(${e})`,()=>{r.assign(Mn.default.vErrors,(0,Be._)`${Mn.default.vErrors} === null ? ${e} : ${Mn.default.vErrors}.concat(${e})`).assign(Mn.default.errors,(0,Be._)`${Mn.default.vErrors}.length`),(0,VD.extendErrors)(t)},()=>t.error())}function XD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function bR(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Be.stringify)(r)})}function QD(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Xt.validSchemaType=QD;function eL({schema:t,opts:e,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Xt.validateKeywordUsage=eL});var PR=P(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.extendSubschemaMode=Yr.extendSubschemaData=Yr.getSubschema=void 0;var Qt=j(),CR=B();function tL(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}${(0,Qt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,CR.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Yr.getSubschema=tL;function rL(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=a.let("data",(0,Qt._)`${e.data}${(0,Qt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Qt.str)`${u}${(0,CR.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Qt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Qt.Name?o:a.let("data",o,!0);c(u),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Yr.extendSubschemaData=rL;function nL(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}Yr.extendSubschemaMode=nL});var up=P((j3,xR)=>{"use strict";xR.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var kR=P((F3,ER)=>{"use strict";var Xr=ER.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Oc(e,n,o,t,"",t)};Xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Xr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Oc(t,e,r,n,o,i,s,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,s,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Xr.arrayKeywords)for(var f=0;f<l.length;f++)Oc(t,e,r,l[f],o+"/"+d+"/"+f,i,o,d,n,f)}else if(d in Xr.propsKeywords){if(l&&typeof l=="object")for(var p in l)Oc(t,e,r,l[p],o+"/"+d+"/"+oL(p),i,o,d,n,p)}else(d in Xr.keywords||t.allKeys&&!(d in Xr.skipKeywords))&&Oc(t,e,r,l,o+"/"+d,i,o,d,n)}r(n,o,i,s,a,c,u)}}function oL(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gs=P(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.getSchemaRefs=nt.resolveUrl=nt.normalizeId=nt._getFullPath=nt.getFullPath=nt.inlineRef=void 0;var iL=B(),sL=up(),aL=kR(),cL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function uL(t,e=!0){return typeof t=="boolean"?!0:e===!0?!dp(t):e?TR(t)<=e:!1}nt.inlineRef=uL;var dL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dp(t){for(let e in t){if(dL.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(dp)||typeof r=="object"&&dp(r))return!0}return!1}function TR(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!cL.has(r)&&(typeof t[r]=="object"&&(0,iL.eachItem)(t[r],n=>e+=TR(n)),e===1/0))return 1/0}return e}function AR(t,e="",r){r!==!1&&(e=$o(e));let n=t.parse(e);return MR(t,n)}nt.getFullPath=AR;function MR(t,e){return t.serialize(e).split("#")[0]+"#"}nt._getFullPath=MR;var lL=/#\/?$/;function $o(t){return t?t.replace(lL,""):""}nt.normalizeId=$o;function fL(t,e,r){return r=$o(r),t.resolve(e,r)}nt.resolveUrl=fL;var pL=/^[a-z_][-a-z0-9._]*$/i;function hL(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=$o(t[r]||e),i={"":o},s=AR(n,o,!1),a={},c=new Set;return aL(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let m=s+f,g=i[h];typeof l[r]=="string"&&(g=v.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),i[f]=g;function v(b){let R=this.opts.uriResolver.resolve;if(b=$o(g?R(g,b):b),c.has(b))throw d(b);c.add(b);let _=this.refs[b];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?u(l,_.schema,b):b!==$o(m)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!pL.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(l,f,p){if(f!==void 0&&!sL(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}nt.getSchemaRefs=hL});var _s=P(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getData=Qr.KeywordCxt=Qr.validateFunctionCode=void 0;var NR=lR(),$R=ms(),fp=rp(),zc=ms(),mL=vR(),vs=RR(),lp=PR(),A=j(),z=gr(),gL=gs(),yr=B(),ys=hs();function yL(t){if(jR(t)&&(FR(t),LR(t))){SL(t);return}DR(t,()=>(0,NR.topBoolOrEmptySchema)(t))}Qr.validateFunctionCode=yL;function DR({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},i){o.code.es5?t.func(e,(0,A._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,A._)`"use strict"; ${IR(r,o)}`),_L(t,o),t.code(i)}):t.func(e,(0,A._)`${z.default.data}, ${vL(o)}`,n.$async,()=>t.code(IR(r,o)).code(i))}function vL(t){return(0,A._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,A._)`, ${z.default.dynamicAnchors}={}`:A.nil}}={}`}function _L(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,A._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,A._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,A._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,A._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,A._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,A._)`""`),t.var(z.default.parentData,(0,A._)`undefined`),t.var(z.default.parentDataProperty,(0,A._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,A._)`{}`)})}function SL(t){let{schema:e,opts:r,gen:n}=t;DR(t,()=>{r.$comment&&e.$comment&&qR(t),PL(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&wL(t),UR(t),kL(t)})}function wL(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,A._)`${r}.evaluated`),e.if((0,A._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,A._)`${t.evaluated}.props`,(0,A._)`undefined`)),e.if((0,A._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,A._)`${t.evaluated}.items`,(0,A._)`undefined`))}function IR(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,A._)`/*# sourceURL=${r} */`:A.nil}function bL(t,e){if(jR(t)&&(FR(t),LR(t))){RL(t,e);return}(0,NR.boolOrEmptySchema)(t,e)}function LR({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function jR(t){return typeof t.schema!="boolean"}function RL(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&qR(t),xL(t),EL(t);let i=n.const("_errs",z.default.errors);UR(t,i),n.var(e,(0,A._)`${i} === ${z.default.errors}`)}function FR(t){(0,yr.checkUnknownRules)(t),CL(t)}function UR(t,e){if(t.opts.jtd)return OR(t,[],!1,e);let r=(0,$R.getSchemaTypes)(t.schema),n=(0,$R.coerceAndCheckDataType)(t,r);OR(t,r,!n,e)}function CL(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,yr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function PL(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,yr.checkStrictMode)(t,"default is ignored in the schema root")}function xL(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,gL.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function EL(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qR({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)t.code((0,A._)`${z.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,A.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,A._)`${z.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function kL(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=t;r.$async?e.if((0,A._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,A._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,A._)`${n}.errors`,z.default.vErrors),i.unevaluated&&TL(t),e.return((0,A._)`${z.default.errors} === 0`))}function TL({gen:t,evaluated:e,props:r,items:n}){r instanceof A.Name&&t.assign((0,A._)`${e}.props`,r),n instanceof A.Name&&t.assign((0,A._)`${e}.items`,n)}function OR(t,e,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,yr.schemaHasRulesButRef)(i,d))){o.block(()=>GR(t,"$ref",d.all.$ref.definition));return}c.jtd||AL(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,fp.shouldUseGroup)(i,f)&&(f.type?(o.if((0,zc.checkDataType)(f.type,s,c.strictNumbers)),zR(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,zc.reportTypeError)(t)),o.endIf()):zR(t,f),a||o.if((0,A._)`${z.default.errors} === ${n||0}`))}}function zR(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,mL.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,fp.shouldUseRule)(n,i)&&GR(t,i.keyword,i.definition,e.type)})}function AL(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(ML(t,e),t.opts.allowUnionTypes||$L(t,e),IL(t,t.dataTypes))}function ML(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{HR(t.dataTypes,r)||pp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),zL(t,e)}}function $L(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&pp(t,"use allowUnionTypes to allow union type keyword")}function IL(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,fp.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>OL(e,s))&&pp(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function OL(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function HR(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function zL(t,e){let r=[];for(let n of t.dataTypes)HR(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function pp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,yr.checkStrictMode)(t,e,t.opts.strictTypes)}var Nc=class{constructor(e,r,n){if((0,vs.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,yr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",ZR(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,vs.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",z.default.errors))}result(e,r,n){this.failResult((0,A.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,A.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,A._)`${r} !== undefined && (${(0,A.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ys.reportExtraError:ys.reportError)(this,this.def.error,r)}$dataError(){(0,ys.reportError)(this,this.def.$dataError||ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ys.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=A.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=A.nil,r=A.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,A.or)((0,A._)`${o} === undefined`,r)),e!==A.nil&&n.assign(e,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==A.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,A.or)(s(),a());function s(){if(n.length){if(!(r instanceof A.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,A._)`${(0,zc.checkDataTypes)(c,r,i.opts.strictNumbers,zc.DataType.Wrong)}`}return A.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,A._)`!${c}(${r})`}return A.nil}}subschema(e,r){let n=(0,lp.getSubschema)(this.it,e);(0,lp.extendSubschemaData)(n,this.it,e),(0,lp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return bL(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=yr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=yr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,A.Name)),!0}};Qr.KeywordCxt=Nc;function GR(t,e,r,n){let o=new Nc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,vs.funcKeywordCode)(o,r):"macro"in r?(0,vs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,vs.funcKeywordCode)(o,r)}var NL=/^\/(?:[^~]|~0|~1)*$/,DL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ZR(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,i;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!NL.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=z.default.rootData}else{let u=DL.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(i=r[e-d],!o)return i}let s=i,a=o.split("/");for(let u of a)u&&(i=(0,A._)`${i}${(0,A.getProperty)((0,yr.unescapeJsonPointer)(u))}`,s=(0,A._)`${s} && ${i}`);return s;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Qr.getData=ZR});var Dc=P(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var hp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};mp.default=hp});var Ss=P(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var gp=gs(),yp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,gp.resolveUrl)(e,r,n),this.missingSchema=(0,gp.normalizeId)((0,gp.getFullPath)(e,this.missingRef))}};vp.default=yp});var jc=P(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.resolveSchema=Ct.getCompilingSchema=Ct.resolveRef=Ct.compileSchema=Ct.SchemaEnv=void 0;var zt=j(),LL=Dc(),$n=gr(),Nt=gs(),BR=B(),jL=_s(),Io=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Nt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ct.SchemaEnv=Io;function Sp(t){let e=WR.call(this,t);if(e)return e;let r=(0,Nt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new zt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:LL.default,code:(0,zt._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:$n.default.data,parentData:$n.default.parentData,parentDataProperty:$n.default.parentDataProperty,dataNames:[$n.default.data],dataPathArr:[zt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,zt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:zt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,zt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,jL.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let l=s.toString();d=`${s.scopeRefs($n.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${$n.default.self}`,`${$n.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:m}=u;p.evaluated={props:h instanceof zt.Name?void 0:h,items:m instanceof zt.Name?void 0:m,dynamicProps:h instanceof zt.Name,dynamicItems:m instanceof zt.Name},p.source&&(p.source.evaluated=(0,zt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Ct.compileSchema=Sp;function FL(t,e,r){var n;r=(0,Nt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let i=HL.call(this,t,r);if(i===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new Io({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=UL.call(this,i)}Ct.resolveRef=FL;function UL(t){return(0,Nt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sp.call(this,t)}function WR(t){for(let e of this._compilations)if(qL(e,t))return e}Ct.getCompilingSchema=WR;function qL(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function HL(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Lc.call(this,t,e)}function Lc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Nt._getFullPath)(this.opts.uriResolver,r),o=(0,Nt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return _p.call(this,r,t);let i=(0,Nt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Lc.call(this,t,s);return typeof a?.schema!="object"?void 0:_p.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Sp.call(this,s),i===(0,Nt.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Nt.resolveUrl)(this.opts.uriResolver,o,u)),new Io({schema:a,schemaId:c,root:t,baseId:o})}return _p.call(this,r,s)}}Ct.resolveSchema=Lc;var GL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _p(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,BR.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!GL.has(a)&&u&&(e=(0,Nt.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,BR.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Nt.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=Lc.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new Io({schema:r,schemaId:s,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var VR=P((B3,ZL)=>{ZL.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Rp=P((W3,eC)=>{"use strict";var BL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),JR=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),wp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),YR=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),WL=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function bp(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var VL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function KR(t){return t.length=0,!0}function KL(t,e,r){if(t.length){let n=bp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function JL(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=KL;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=KR}else{o.push(u);continue}}return o.length&&(a===KR?r.zone=o.join(""):s?n.push(o.join("")):n.push(bp(o))),r.address=n.join(""),r}function XR(t){if(YL(t,":")<2)return{host:t,isIPV6:!1};let e=JL(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function YL(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function XL(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var QL={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ej=/[@/?#:]/g,tj=/[@/?#]/g;function QR(t,e){let r=e?tj:ej;return r.lastIndex=0,t.replace(r,n=>QL[n])}function rj(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(wp(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));e&&YR(s)?r+=s:r+="%"+i,n+=2;continue}}r+=t[n]}return r}function nj(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(wp(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&YR(i)?e+=i:e+="%"+o,r+=2;continue}}WL(t[r])?e+=t[r]:e+=escape(t[r])}return e}function oj(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(wp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function ij(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!JR(r)){let n=XR(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=QR(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}eC.exports={nonSimpleDomain:VL,recomposeAuthority:ij,reescapeHostDelimiters:QR,normalizePercentEncoding:rj,normalizePathEncoding:nj,escapePreservingEscapes:oj,removeDotSegments:XL,isIPv4:JR,isUUID:BL,normalizeIPv6:XR,stringArrayToHexStripped:bp}});var iC=P((V3,oC)=>{"use strict";var{isUUID:sj}=Rp(),aj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,cj=["http","https","ws","wss","urn","urn:uuid"];function uj(t){return cj.indexOf(t)!==-1}function Cp(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function tC(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function rC(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function dj(t){return t.secure=Cp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function lj(t){if((t.port===(Cp(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function fj(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(aj);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,i=Pp(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function pj(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,i=Pp(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function hj(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!sj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function mj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var nC={scheme:"http",domainHost:!0,parse:tC,serialize:rC},gj={scheme:"https",domainHost:nC.domainHost,parse:tC,serialize:rC},Fc={scheme:"ws",domainHost:!0,parse:dj,serialize:lj},yj={scheme:"wss",domainHost:Fc.domainHost,parse:Fc.parse,serialize:Fc.serialize},vj={scheme:"urn",parse:fj,serialize:pj,skipNormalize:!0},_j={scheme:"urn:uuid",parse:hj,serialize:mj,skipNormalize:!0},Uc={http:nC,https:gj,ws:Fc,wss:yj,urn:vj,"urn:uuid":_j};Object.setPrototypeOf(Uc,null);function Pp(t){return t&&(Uc[t]||Uc[t.toLowerCase()])||void 0}oC.exports={wsIsSecure:Cp,SCHEMES:Uc,isValidSchemeName:uj,getSchemeHandler:Pp}});var dC=P((K3,Gc)=>{"use strict";var{normalizeIPv6:Sj,removeDotSegments:ws,recomposeAuthority:wj,normalizePercentEncoding:bj,normalizePathEncoding:Rj,escapePreservingEscapes:Cj,reescapeHostDelimiters:Pj,isIPv4:xj,nonSimpleDomain:Ej}=Rp(),{SCHEMES:kj,getSchemeHandler:aC}=iC();function Tj(t,e){return typeof t=="string"?t=Nj(t,e):typeof t=="object"&&(t=Hc(In(t,e),e)),t}function Aj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:i}=qc(t,n),{parsed:s,malformedAuthorityOrPort:a}=qc(e,n);if(i||a)throw new Error(o.error||s.error||"URI is malformed.");let c=cC(o,s,n,!0);return n.skipEscape=!0,In(c,n)}function cC(t,e,r,n){let o={};return n||(t=Hc(In(t,r),r),e=Hc(In(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ws(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ws(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ws(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ws(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function Mj(t,e,r){let n=sC(t,r),o=sC(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function In(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],i=aC(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=bj(r.path):(r.path=Cj(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=wj(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=ws(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var $j=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Ij=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Oj=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function zj(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function qc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(Ij);s!==null&&s[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(Oj);if(a!==null){let u=a[1],d=u.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match($j);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let u=zj(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(xj(n.host)===!1){let f=Sj(n.host);n.host=f.host.toLowerCase(),i=f.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=aC(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&i===!1&&Ej(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!d||d&&!d.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Pj(unescape(n.host),i))),n.path&&(n.path=Rj(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Hc(t,e){return qc(t,e).parsed}function Nj(t,e){return uC(t,e).normalized}function uC(t,e){let{parsed:r,malformedAuthorityOrPort:n}=qc(t,e);return{normalized:n?t:In(r,e),malformedAuthorityOrPort:n}}function sC(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=uC(t,e);return n?void 0:r}if(typeof t=="object")return In(t,e)}var xp={SCHEMES:kj,normalize:Tj,resolve:Aj,resolveComponent:cC,equal:Mj,serialize:In,parse:Hc};Gc.exports=xp;Gc.exports.default=xp;Gc.exports.fastUri=xp});var fC=P(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var lC=dC();lC.code='require("ajv/dist/runtime/uri").default';Ep.default=lC});var SC=P(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=void 0;var Dj=_s();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return Dj.KeywordCxt}});var Oo=j();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Oo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Oo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Oo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Oo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Oo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Oo.CodeGen}});var Lj=Dc(),yC=Ss(),jj=tp(),bs=jc(),Fj=j(),Rs=gs(),Zc=ms(),Tp=B(),pC=VR(),Uj=fC(),vC=(t,e)=>new RegExp(t,e);vC.code="new RegExp";var qj=["removeAdditional","useDefaults","coerceTypes"],Hj=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Gj={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Zj={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},hC=200;function Bj(t){var e,r,n,o,i,s,a,c,u,d,l,f,p,h,m,g,v,w,b,R,_,C,I,ee,pe;let be=t.strict,qt=(e=t.code)===null||e===void 0?void 0:e.optimize,un=qt===!0||qt===void 0?1:qt||0,pt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:vC,Cr=(o=t.uriResolver)!==null&&o!==void 0?o:Uj.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:be)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:be)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:be)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:be)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:be)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:un,regExp:pt}:{optimize:un,regExp:pt},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:hC,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:hC,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(pe=t.int32range)!==null&&pe!==void 0?pe:!0,uriResolver:Cr}}var Cs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...Bj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Fj.ValueScope({scope:{},prefixes:Hj,es5:r,lines:n}),this.logger=Xj(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jj.getRules)(),mC.call(this,Gj,e,"NOT SUPPORTED"),mC.call(this,Zj,e,"DEPRECATED","warn"),this._metaOpts=Jj.call(this),e.formats&&Vj.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Kj.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Wj.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=pC;n==="id"&&(o={...pC},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await i.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||s.call(this,f)}async function i(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function s(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof yC.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),s.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await i.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Rs.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let r;for(;typeof(r=gC.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new bs.SchemaEnv({schema:{},schemaId:n});if(r=bs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=gC.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Rs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(e1.call(this,n,r),!r)return(0,Tp.eachItem)(n,i=>kp.call(this,i)),this;r1.call(this,r);let o={...r,type:(0,Zc.getJSONTypes)(r.type),schemaType:(0,Zc.getJSONTypes)(r.schemaType)};return(0,Tp.eachItem)(n,o.type.length===0?i=>kp.call(this,i,o):i=>o.type.forEach(s=>kp.call(this,i,o,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=s[a];u&&d&&(s[a]=_C(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Rs.normalizeId)(s||n);let u=Rs.getSchemaRefs.call(this,e,n);return c=new bs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):bs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{bs.compileSchema.call(this,e)}finally{this.opts=r}}};Cs.ValidationError=Lj.default;Cs.MissingRefError=yC.default;De.default=Cs;function mC(t,e,r,n="error"){for(let o in t){let i=o;i in e&&this.logger[n](`${r}: option ${o}. ${t[i]}`)}}function gC(t){return t=(0,Rs.normalizeId)(t),this.schemas[t]||this.refs[t]}function Wj(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function Vj(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Kj(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function Jj(){let t={...this.opts};for(let e of qj)delete t[e];return t}var Yj={log(){},warn(){},error(){}};function Xj(t){if(t===!1)return Yj;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var Qj=/^[a-z_$][a-z0-9_$:-]*$/i;function e1(t,e){let{RULES:r}=this;if((0,Tp.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Qj.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function kp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Zc.getJSONTypes)(e.type),schemaType:(0,Zc.getJSONTypes)(e.schemaType)}};e.before?t1.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function t1(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function r1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=_C(e)),t.validateSchema=this.compile(e,!0))}var n1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _C(t){return{anyOf:[t,n1]}}});var wC=P(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var o1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ap.default=o1});var PC=P(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.callRef=On.getValidate=void 0;var i1=Ss(),bC=Rt(),ot=j(),zo=gr(),RC=jc(),Bc=B(),s1={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:u}=i;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=RC.resolveRef.call(c,u,o,r);if(d===void 0)throw new i1.default(n.opts.uriResolver,o,r);if(d instanceof RC.SchemaEnv)return f(d);return p(d);function l(){if(i===u)return Wc(t,s,i,i.$async);let h=e.scopeValue("root",{ref:u});return Wc(t,(0,ot._)`${h}.validate`,u,u.$async)}function f(h){let m=CC(t,h);Wc(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,ot.stringify)(h)}:{ref:h}),g=e.name("valid"),v=t.subschema({schema:h,dataTypes:[],schemaPath:ot.nil,topSchemaRef:m,errSchemaPath:r},g);t.mergeEvaluated(v),t.ok(g)}}};function CC(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,ot._)`${r.scopeValue("wrapper",{ref:e})}.validate`}On.getValidate=CC;function Wc(t,e,r,n){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?zo.default.this:ot.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,ot._)`await ${(0,bC.callValidateCode)(t,e,u)}`),p(e),s||o.assign(h,!0)},m=>{o.if((0,ot._)`!(${m} instanceof ${i.ValidationError})`,()=>o.throw(m)),f(m),s||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,bC.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let m=(0,ot._)`${h}.errors`;o.assign(zo.default.vErrors,(0,ot._)`${zo.default.vErrors} === null ? ${m} : ${zo.default.vErrors}.concat(${m})`),o.assign(zo.default.errors,(0,ot._)`${zo.default.vErrors}.length`)}function p(h){var m;if(!i.opts.unevaluated)return;let g=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=Bc.mergeEvaluated.props(o,g.props,i.props));else{let v=o.var("props",(0,ot._)`${h}.evaluated.props`);i.props=Bc.mergeEvaluated.props(o,v,i.props,ot.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Bc.mergeEvaluated.items(o,g.items,i.items));else{let v=o.var("items",(0,ot._)`${h}.evaluated.items`);i.items=Bc.mergeEvaluated.items(o,v,i.items,ot.Name)}}}On.callRef=Wc;On.default=s1});var xC=P(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var a1=wC(),c1=PC(),u1=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",a1.default,c1.default];Mp.default=u1});var EC=P($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var Vc=j(),en=Vc.operators,Kc={maximum:{okStr:"<=",ok:en.LTE,fail:en.GT},minimum:{okStr:">=",ok:en.GTE,fail:en.LT},exclusiveMaximum:{okStr:"<",ok:en.LT,fail:en.GTE},exclusiveMinimum:{okStr:">",ok:en.GT,fail:en.LTE}},d1={message:({keyword:t,schemaCode:e})=>(0,Vc.str)`must be ${Kc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Vc._)`{comparison: ${Kc[t].okStr}, limit: ${e}}`},l1={keyword:Object.keys(Kc),type:"number",schemaType:"number",$data:!0,error:d1,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Vc._)`${r} ${Kc[e].fail} ${n} || isNaN(${r})`)}};$p.default=l1});var kC=P(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var Ps=j(),f1={message:({schemaCode:t})=>(0,Ps.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ps._)`{multipleOf: ${t}}`},p1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:f1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Ps._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Ps._)`${s} !== parseInt(${s})`;t.fail$data((0,Ps._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};Ip.default=p1});var AC=P(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});function TC(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Op.default=TC;TC.code='require("ajv/dist/runtime/ucs2length").default'});var MC=P(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var zn=j(),h1=B(),m1=AC(),g1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,zn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,zn._)`{limit: ${t}}`},y1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:g1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,i=e==="maxLength"?zn.operators.GT:zn.operators.LT,s=o.opts.unicode===!1?(0,zn._)`${r}.length`:(0,zn._)`${(0,h1.useFunc)(t.gen,m1.default)}(${r})`;t.fail$data((0,zn._)`${s} ${i} ${n}`)}};zp.default=y1});var $C=P(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var v1=Rt(),_1=B(),No=j(),S1={message:({schemaCode:t})=>(0,No.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,No._)`{pattern: ${t}}`},w1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:S1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,u=c.code==="new RegExp"?(0,No._)`new RegExp`:(0,_1.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,No._)`${u}(${i}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,No._)`!${d}`)}else{let c=(0,v1.usePattern)(t,o);t.fail$data((0,No._)`!${c}.test(${r})`)}}};Np.default=w1});var IC=P(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var xs=j(),b1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,xs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,xs._)`{limit: ${t}}`},R1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:b1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?xs.operators.GT:xs.operators.LT;t.fail$data((0,xs._)`Object.keys(${r}).length ${o} ${n}`)}};Dp.default=R1});var OC=P(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var Es=Rt(),ks=j(),C1=B(),P1={message:({params:{missingProperty:t}})=>(0,ks.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ks._)`{missingProperty: ${t}}`},x1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:P1,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?u():d(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let g=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${m}" is not defined at "${g}" (strictRequired)`;(0,C1.checkStrictMode)(s,v,s.opts.strictRequired)}}function u(){if(c||i)t.block$data(ks.nil,l);else for(let p of r)(0,Es.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||i){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,Es.checkMissingProp)(t,r,p)),(0,Es.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,Es.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,Es.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ks.not)(h),()=>{t.error(),e.break()})},ks.nil)}}};Lp.default=x1});var zC=P(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Ts=j(),E1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ts.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ts._)`{limit: ${t}}`},k1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:E1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ts.operators.GT:Ts.operators.LT;t.fail$data((0,Ts._)`${r}.length ${o} ${n}`)}};jp.default=k1});var Jc=P(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var NC=up();NC.code='require("ajv/dist/runtime/equal").default';Fp.default=NC});var DC=P(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Up=ms(),Le=j(),T1=B(),A1=Jc(),M1={message:({params:{i:t,j:e}})=>(0,Le.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Le._)`{i: ${t}, j: ${e}}`},$1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:M1,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=i.items?(0,Up.getSchemaTypes)(i.items):[];t.block$data(c,d,(0,Le._)`${s} === false`),t.ok(c);function d(){let h=e.let("i",(0,Le._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Le._)`${h} > 1`,()=>(l()?f:p)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,m){let g=e.name("item"),v=(0,Up.checkDataTypes)(u,g,a.opts.strictNumbers,Up.DataType.Wrong),w=e.const("indices",(0,Le._)`{}`);e.for((0,Le._)`;${h}--;`,()=>{e.let(g,(0,Le._)`${r}[${h}]`),e.if(v,(0,Le._)`continue`),u.length>1&&e.if((0,Le._)`typeof ${g} == "string"`,(0,Le._)`${g} += "_"`),e.if((0,Le._)`typeof ${w}[${g}] == "number"`,()=>{e.assign(m,(0,Le._)`${w}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Le._)`${w}[${g}] = ${h}`)})}function p(h,m){let g=(0,T1.useFunc)(e,A1.default),v=e.name("outer");e.label(v).for((0,Le._)`;${h}--;`,()=>e.for((0,Le._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Le._)`${g}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};qp.default=$1});var LC=P(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var Hp=j(),I1=B(),O1=Jc(),z1={message:"must be equal to constant",params:({schemaCode:t})=>(0,Hp._)`{allowedValue: ${t}}`},N1={keyword:"const",$data:!0,error:z1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,Hp._)`!${(0,I1.useFunc)(e,O1.default)}(${r}, ${o})`):t.fail((0,Hp._)`${i} !== ${r}`)}};Gp.default=N1});var jC=P(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});var As=j(),D1=B(),L1=Jc(),j1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,As._)`{allowedValues: ${t}}`},F1={keyword:"enum",schemaType:"array",$data:!0,error:j1,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:s}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,u=()=>c??(c=(0,D1.useFunc)(e,L1.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);d=(0,As.or)(...o.map((h,m)=>f(p,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",i,p=>e.if((0,As._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=o[h];return typeof m=="object"&&m!==null?(0,As._)`${u()}(${r}, ${p}[${h}])`:(0,As._)`${r} === ${m}`}}};Zp.default=F1});var FC=P(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var U1=EC(),q1=kC(),H1=MC(),G1=$C(),Z1=IC(),B1=OC(),W1=zC(),V1=DC(),K1=LC(),J1=jC(),Y1=[U1.default,q1.default,H1.default,G1.default,Z1.default,B1.default,W1.default,V1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},K1.default,J1.default];Bp.default=Y1});var Vp=P(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.validateAdditionalItems=void 0;var Nn=j(),Wp=B(),X1={message:({params:{len:t}})=>(0,Nn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Nn._)`{limit: ${t}}`},Q1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:X1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Wp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}UC(t,n)}};function UC(t,e){let{gen:r,schema:n,data:o,keyword:i,it:s}=t;s.items=!0;let a=r.const("len",(0,Nn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Nn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Wp.alwaysValidSchema)(s,n)){let u=r.var("valid",(0,Nn._)`${a} <= ${e.length}`);r.if((0,Nn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:i,dataProp:d,dataPropType:Wp.Type.Num},u),s.allErrors||r.if((0,Nn.not)(u),()=>r.break())})}}Ms.validateAdditionalItems=UC;Ms.default=Q1});var Kp=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.validateTuple=void 0;var qC=j(),Yc=B(),eF=Rt(),tF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return HC(t,"additionalItems",e);r.items=!0,!(0,Yc.alwaysValidSchema)(r,e)&&t.ok((0,eF.validateArray)(t))}};function HC(t,e,r=t.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Yc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,qC._)`${i}.length`);r.forEach((l,f)=>{(0,Yc.alwaysValidSchema)(a,l)||(n.if((0,qC._)`${u} > ${f}`,()=>t.subschema({keyword:s,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let g=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Yc.checkStrictMode)(a,g,f.strictTuples)}}}$s.validateTuple=HC;$s.default=tF});var GC=P(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var rF=Kp(),nF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,rF.validateTuple)(t,"items")};Jp.default=nF});var BC=P(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var ZC=j(),oF=B(),iF=Rt(),sF=Vp(),aF={message:({params:{len:t}})=>(0,ZC.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ZC._)`{limit: ${t}}`},cF={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:aF,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,oF.alwaysValidSchema)(n,e)&&(o?(0,sF.validateAdditionalItems)(t,o):t.ok((0,iF.validateArray)(t)))}};Yp.default=cF});var WC=P(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var Pt=j(),Xc=B(),uF={message:({params:{min:t,max:e}})=>e===void 0?(0,Pt.str)`must contain at least ${t} valid item(s)`:(0,Pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Pt._)`{minContains: ${t}}`:(0,Pt._)`{minContains: ${t}, maxContains: ${e}}`},dF={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:uF,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t,s,a,{minContains:c,maxContains:u}=n;i.opts.next?(s=c===void 0?1:c,a=u):s=1;let d=e.const("len",(0,Pt._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,Xc.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Xc.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Xc.alwaysValidSchema)(i,r)){let m=(0,Pt._)`${d} >= ${s}`;a!==void 0&&(m=(0,Pt._)`${m} && ${d} <= ${a}`),t.pass(m);return}i.items=!0;let l=e.name("valid");a===void 0&&s===1?p(l,()=>e.if(l,()=>e.break())):s===0?(e.let(l,!0),a!==void 0&&e.if((0,Pt._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),g=e.let("count",0);p(m,()=>e.if(m,()=>h(g)))}function p(m,g){e.forRange("i",0,d,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Xc.Type.Num,compositeRule:!0},m),g()})}function h(m){e.code((0,Pt._)`${m}++`),a===void 0?e.if((0,Pt._)`${m} >= ${s}`,()=>e.assign(l,!0).break()):(e.if((0,Pt._)`${m} > ${a}`,()=>e.assign(l,!1).break()),s===1?e.assign(l,!0):e.if((0,Pt._)`${m} >= ${s}`,()=>e.assign(l,!0)))}}};Xp.default=dF});var JC=P(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var Qp=j(),lF=B(),Is=Rt();er.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Qp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Qp._)`{property: ${t},
|
|
5
|
+
|| ${s} === "boolean" || ${o} === null`).assign(a,(0,L._)`[${o}]`)}}}function CL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,L._)`${e} !== undefined`,()=>t.assign((0,L._)`${e}[${r}]`,n))}function Pp(t,e,r,n=Lo.Correct){let o=n===Lo.Correct?L.operators.EQ:L.operators.NEQ,i;switch(t){case"null":return(0,L._)`${e} ${o} null`;case"array":i=(0,L._)`Array.isArray(${e})`;break;case"object":i=(0,L._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=s((0,L._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=s();break;default:return(0,L._)`typeof ${e} ${o} ${t}`}return n===Lo.Correct?i:(0,L.not)(i);function s(a=L.nil){return(0,L.and)((0,L._)`typeof ${e} == "number"`,a,r?(0,L._)`isFinite(${e})`:L.nil)}}He.checkDataType=Pp;function Ep(t,e,r,n){if(t.length===1)return Pp(t[0],e,r,n);let o,i=(0,GR.toHash)(t);if(i.array&&i.object){let s=(0,L._)`typeof ${e} != "object"`;o=i.null?s:(0,L._)`!${e} || ${s}`,delete i.null,delete i.array,delete i.object}else o=L.nil;i.number&&delete i.integer;for(let s in i)o=(0,L.and)(o,Pp(s,e,r,n));return o}He.checkDataTypes=Ep;var PL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,L._)`{type: ${t}}`:(0,L._)`{type: ${e}}`};function xp(t){let e=EL(t);(0,_L.reportError)(e,PL)}He.reportTypeError=xp;function EL(t){let{gen:e,data:r,schema:n}=t,o=(0,GR.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var VR=P(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.assignDefaults=void 0;var jo=j(),xL=B();function kL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)WR(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,i)=>WR(t,i,o.default))}qc.assignDefaults=kL;function WR(t,e,r){let{gen:n,compositeRule:o,data:i,opts:s}=t;if(r===void 0)return;let a=(0,jo._)`${i}${(0,jo.getProperty)(e)}`;if(o){(0,xL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,jo._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,jo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,jo._)`${a} = ${(0,jo.stringify)(r)}`)}});var Ct=P(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var de=j(),kp=B(),Qr=Sr(),TL=B();function AL(t,e){let{gen:r,data:n,it:o}=t;r.if(Ap(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}ne.checkReportMissingProp=AL;function ML({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(i=>(0,de.and)(Ap(t,e,i,r.ownProperties),(0,de._)`${o} = ${i}`)))}ne.checkMissingProp=ML;function $L(t,e){t.setParams({missingProperty:e},!0),t.error()}ne.reportMissingProp=$L;function KR(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}ne.hasPropFunc=KR;function Tp(t,e,r){return(0,de._)`${KR(t)}.call(${e}, ${r})`}ne.isOwnProperty=Tp;function IL(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Tp(t,e,r)}`:o}ne.propertyInData=IL;function Ap(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Tp(t,e,r))):o}ne.noPropertyInData=Ap;function JR(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ne.allSchemaProperties=JR;function OL(t,e){return JR(e).filter(r=>!(0,kp.alwaysValidSchema)(t,e[r]))}ne.schemaProperties=OL;function zL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[Qr.default.instancePath,(0,de.strConcat)(Qr.default.instancePath,i)],[Qr.default.parentData,s.parentData],[Qr.default.parentDataProperty,s.parentDataProperty],[Qr.default.rootData,Qr.default.rootData]];s.opts.dynamicRef&&l.push([Qr.default.dynamicAnchors,Qr.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}ne.callValidateCode=zL;var NL=(0,de._)`new RegExp`;function DL({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,i=o(r,n);return t.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,de._)`${o.code==="new RegExp"?NL:(0,TL.useFunc)(t,o)}(${r}, ${n})`})}ne.usePattern=DL;function LL(t){let{gen:e,data:r,keyword:n,it:o}=t,i=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return s(()=>e.assign(a,!1)),a}return e.var(i,!0),s(()=>e.break()),i;function s(a){let c=e.const("len",(0,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:kp.Type.Num},i),e.if((0,de.not)(i),a)})}}ne.validateArray=LL;function jL(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,kp.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(s,(0,de._)`${s} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ne.validateUnion=jL});var QR=P(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.validateKeywordUsage=Xt.validSchemaType=Xt.funcKeywordCode=Xt.macroKeywordCode=void 0;var We=j(),Un=Sr(),FL=Ct(),UL=$s();function qL(t,e){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=t,a=e.macro.call(s.self,o,i,s),c=XR(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Xt.macroKeywordCode=qL;function HL(t,e){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=t;ZL(c,e);let u=!a&&e.compile?e.compile.call(c.self,i,s,c):e.validate,d=XR(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)g(),e.modifying&&YR(t),m(()=>t.error());else{let v=e.async?p():h();e.modifying&&YR(t),m(()=>GL(t,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),w=>n.assign(l,!1).if((0,We._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,We._)`${w}.errors`),()=>n.throw(w))),v}function h(){let v=(0,We._)`${d}.errors`;return n.assign(v,null),g(We.nil),v}function g(v=e.async?(0,We._)`await `:We.nil){let w=c.opts.passContext?Un.default.this:Un.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,We._)`${v}${(0,FL.callValidateCode)(t,d,w,b)}`,e.modifying)}function m(v){var w;n.if((0,We.not)((w=e.valid)!==null&&w!==void 0?w:l),v)}}Xt.funcKeywordCode=HL;function YR(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function GL(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(Un.default.vErrors,(0,We._)`${Un.default.vErrors} === null ? ${e} : ${Un.default.vErrors}.concat(${e})`).assign(Un.default.errors,(0,We._)`${Un.default.vErrors}.length`),(0,UL.extendErrors)(t)},()=>t.error())}function ZL({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function XR(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}function BL(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Xt.validSchemaType=BL;function WL({schema:t,opts:e,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Xt.validateKeywordUsage=WL});var tC=P(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.extendSubschemaMode=en.extendSubschemaData=en.getSubschema=void 0;var Qt=j(),eC=B();function VL(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Qt._)`${t.schemaPath}${(0,Qt.getProperty)(e)}${(0,Qt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,eC.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}en.getSubschema=VL;function KL(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=a.let("data",(0,Qt._)`${e.data}${(0,Qt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Qt.str)`${u}${(0,eC.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Qt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Qt.Name?o:a.let("data",o,!0);c(u),s!==void 0&&(t.propertyName=s)}i&&(t.dataTypes=i);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}en.extendSubschemaData=KL;function JL(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),i!==void 0&&(t.allErrors=i),t.jtdDiscriminator=e,t.jtdMetadata=r}en.extendSubschemaMode=JL});var Mp=P((H8,rC)=>{"use strict";rC.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!t(e[s],r[s]))return!1}return!0}return e!==e&&r!==r}});var oC=P((G8,nC)=>{"use strict";var tn=nC.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Hc(e,n,o,t,"",t)};tn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};tn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};tn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};tn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Hc(t,e,r,n,o,i,s,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,i,s,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in tn.arrayKeywords)for(var f=0;f<l.length;f++)Hc(t,e,r,l[f],o+"/"+d+"/"+f,i,o,d,n,f)}else if(d in tn.propsKeywords){if(l&&typeof l=="object")for(var p in l)Hc(t,e,r,l[p],o+"/"+d+"/"+YL(p),i,o,d,n,p)}else(d in tn.keywords||t.allKeys&&!(d in tn.skipKeywords))&&Hc(t,e,r,l,o+"/"+d,i,o,d,n)}r(n,o,i,s,a,c,u)}}function YL(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Os=P(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.getSchemaRefs=it.resolveUrl=it.normalizeId=it._getFullPath=it.getFullPath=it.inlineRef=void 0;var XL=B(),QL=Mp(),ej=oC(),tj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function rj(t,e=!0){return typeof t=="boolean"?!0:e===!0?!$p(t):e?iC(t)<=e:!1}it.inlineRef=rj;var nj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function $p(t){for(let e in t){if(nj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some($p)||typeof r=="object"&&$p(r))return!0}return!1}function iC(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!tj.has(r)&&(typeof t[r]=="object"&&(0,XL.eachItem)(t[r],n=>e+=iC(n)),e===1/0))return 1/0}return e}function sC(t,e="",r){r!==!1&&(e=Fo(e));let n=t.parse(e);return aC(t,n)}it.getFullPath=sC;function aC(t,e){return t.serialize(e).split("#")[0]+"#"}it._getFullPath=aC;var oj=/#\/?$/;function Fo(t){return t?t.replace(oj,""):""}it.normalizeId=Fo;function ij(t,e,r){return r=Fo(r),t.resolve(e,r)}it.resolveUrl=ij;var sj=/^[a-z_][-a-z0-9._]*$/i;function aj(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Fo(t[r]||e),i={"":o},s=sC(n,o,!1),a={},c=new Set;return ej(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let g=s+f,m=i[h];typeof l[r]=="string"&&(m=v.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),i[f]=m;function v(b){let R=this.opts.uriResolver.resolve;if(b=Fo(m?R(m,b):b),c.has(b))throw d(b);c.add(b);let _=this.refs[b];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?u(l,_.schema,b):b!==Fo(g)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=g),b}function w(b){if(typeof b=="string"){if(!sj.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(l,f,p){if(f!==void 0&&!QL(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}it.getSchemaRefs=aj});var Ds=P(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.getData=rn.KeywordCxt=rn.validateFunctionCode=void 0;var fC=UR(),cC=Is(),Op=Cp(),Gc=Is(),cj=VR(),Ns=QR(),Ip=tC(),M=j(),z=Sr(),uj=Os(),wr=B(),zs=$s();function dj(t){if(mC(t)&&(gC(t),hC(t))){pj(t);return}pC(t,()=>(0,fC.topBoolOrEmptySchema)(t))}rn.validateFunctionCode=dj;function pC({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},i){o.code.es5?t.func(e,(0,M._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,M._)`"use strict"; ${uC(r,o)}`),fj(t,o),t.code(i)}):t.func(e,(0,M._)`${z.default.data}, ${lj(o)}`,n.$async,()=>t.code(uC(r,o)).code(i))}function lj(t){return(0,M._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,M._)`, ${z.default.dynamicAnchors}={}`:M.nil}}={}`}function fj(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,M._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,M._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,M._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,M._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,M._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,M._)`""`),t.var(z.default.parentData,(0,M._)`undefined`),t.var(z.default.parentDataProperty,(0,M._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,M._)`{}`)})}function pj(t){let{schema:e,opts:r,gen:n}=t;pC(t,()=>{r.$comment&&e.$comment&&vC(t),vj(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&hj(t),yC(t),wj(t)})}function hj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,M._)`${r}.evaluated`),e.if((0,M._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,M._)`${t.evaluated}.props`,(0,M._)`undefined`)),e.if((0,M._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,M._)`${t.evaluated}.items`,(0,M._)`undefined`))}function uC(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}function mj(t,e){if(mC(t)&&(gC(t),hC(t))){gj(t,e);return}(0,fC.boolOrEmptySchema)(t,e)}function hC({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function mC(t){return typeof t.schema!="boolean"}function gj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&vC(t),_j(t),Sj(t);let i=n.const("_errs",z.default.errors);yC(t,i),n.var(e,(0,M._)`${i} === ${z.default.errors}`)}function gC(t){(0,wr.checkUnknownRules)(t),yj(t)}function yC(t,e){if(t.opts.jtd)return dC(t,[],!1,e);let r=(0,cC.getSchemaTypes)(t.schema),n=(0,cC.coerceAndCheckDataType)(t,r);dC(t,r,!n,e)}function yj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,wr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function vj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,wr.checkStrictMode)(t,"default is ignored in the schema root")}function _j(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,uj.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function Sj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function vC({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)t.code((0,M._)`${z.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,M.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,M._)`${z.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function wj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=t;r.$async?e.if((0,M._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,M._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,M._)`${n}.errors`,z.default.vErrors),i.unevaluated&&bj(t),e.return((0,M._)`${z.default.errors} === 0`))}function bj({gen:t,evaluated:e,props:r,items:n}){r instanceof M.Name&&t.assign((0,M._)`${e}.props`,r),n instanceof M.Name&&t.assign((0,M._)`${e}.items`,n)}function dC(t,e,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,wr.schemaHasRulesButRef)(i,d))){o.block(()=>SC(t,"$ref",d.all.$ref.definition));return}c.jtd||Rj(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Op.shouldUseGroup)(i,f)&&(f.type?(o.if((0,Gc.checkDataType)(f.type,s,c.strictNumbers)),lC(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,Gc.reportTypeError)(t)),o.endIf()):lC(t,f),a||o.if((0,M._)`${z.default.errors} === ${n||0}`))}}function lC(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,cj.assignDefaults)(t,e.type),r.block(()=>{for(let i of e.rules)(0,Op.shouldUseRule)(n,i)&&SC(t,i.keyword,i.definition,e.type)})}function Rj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Cj(t,e),t.opts.allowUnionTypes||Pj(t,e),Ej(t,t.dataTypes))}function Cj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{_C(t.dataTypes,r)||zp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),kj(t,e)}}function Pj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zp(t,"use allowUnionTypes to allow union type keyword")}function Ej(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Op.shouldUseRule)(t.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>xj(e,s))&&zp(t,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function xj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function _C(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function kj(t,e){let r=[];for(let n of t.dataTypes)_C(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,wr.checkStrictMode)(t,e,t.opts.strictTypes)}var Zc=class{constructor(e,r,n){if((0,Ns.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,wr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",wC(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ns.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",z.default.errors))}result(e,r,n){this.failResult((0,M.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,M.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,M._)`${r} !== undefined && (${(0,M.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?zs.reportExtraError:zs.reportError)(this,this.def.error,r)}$dataError(){(0,zs.reportError)(this,this.def.$dataError||zs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=M.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,M.or)((0,M._)`${o} === undefined`,r)),e!==M.nil&&n.assign(e,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==M.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,M.or)(s(),a());function s(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,M._)`${(0,Gc.checkDataTypes)(c,r,i.opts.strictNumbers,Gc.DataType.Wrong)}`}return M.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,M._)`!${c}(${r})`}return M.nil}}subschema(e,r){let n=(0,Ip.getSubschema)(this.it,e);(0,Ip.extendSubschemaData)(n,this.it,e),(0,Ip.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return mj(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=wr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=wr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,M.Name)),!0}};rn.KeywordCxt=Zc;function SC(t,e,r,n){let o=new Zc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ns.funcKeywordCode)(o,r):"macro"in r?(0,Ns.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ns.funcKeywordCode)(o,r)}var Tj=/^\/(?:[^~]|~0|~1)*$/,Aj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wC(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,i;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!Tj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,i=z.default.rootData}else{let u=Aj.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let d=+u[1];if(o=u[2],o==="#"){if(d>=e)throw new Error(c("property/index",d));return n[e-d]}if(d>e)throw new Error(c("data",d));if(i=r[e-d],!o)return i}let s=i,a=o.split("/");for(let u of a)u&&(i=(0,M._)`${i}${(0,M.getProperty)((0,wr.unescapeJsonPointer)(u))}`,s=(0,M._)`${s} && ${i}`);return s;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}rn.getData=wC});var Bc=P(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var Np=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Dp.default=Np});var Ls=P(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var Lp=Os(),jp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lp.resolveUrl)(e,r,n),this.missingSchema=(0,Lp.normalizeId)((0,Lp.getFullPath)(e,this.missingRef))}};Fp.default=jp});var Vc=P(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.resolveSchema=Pt.getCompilingSchema=Pt.resolveRef=Pt.compileSchema=Pt.SchemaEnv=void 0;var Dt=j(),Mj=Bc(),qn=Sr(),Lt=Os(),bC=B(),$j=Ds(),Uo=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Lt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Pt.SchemaEnv=Uo;function qp(t){let e=RC.call(this,t);if(e)return e;let r=(0,Lt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new Dt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;t.$async&&(a=s.scopeValue("Error",{ref:Mj.default,code:(0,Dt._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");t.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:qn.default.data,parentData:qn.default.parentData,parentDataProperty:qn.default.parentDataProperty,dataNames:[qn.default.data],dataPathArr:[Dt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Dt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Dt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Dt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,$j.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let l=s.toString();d=`${s.scopeRefs(qn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${qn.default.self}`,`${qn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:s._values}),this.opts.unevaluated){let{props:h,items:g}=u;p.evaluated={props:h instanceof Dt.Name?void 0:h,items:g instanceof Dt.Name?void 0:g,dynamicProps:h instanceof Dt.Name,dynamicItems:g instanceof Dt.Name},p.source&&(p.source.evaluated=(0,Dt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Pt.compileSchema=qp;function Ij(t,e,r){var n;r=(0,Lt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let i=Nj.call(this,t,r);if(i===void 0){let s=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new Uo({schema:s,schemaId:a,root:t,baseId:e}))}if(i!==void 0)return t.refs[r]=Oj.call(this,i)}Pt.resolveRef=Ij;function Oj(t){return(0,Lt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qp.call(this,t)}function RC(t){for(let e of this._compilations)if(zj(e,t))return e}Pt.getCompilingSchema=RC;function zj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Nj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Wc.call(this,t,e)}function Wc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Lt._getFullPath)(this.opts.uriResolver,r),o=(0,Lt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Up.call(this,r,t);let i=(0,Lt.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Wc.call(this,t,s);return typeof a?.schema!="object"?void 0:Up.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||qp.call(this,s),i===(0,Lt.normalizeId)(e)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Lt.resolveUrl)(this.opts.uriResolver,o,u)),new Uo({schema:a,schemaId:c,root:t,baseId:o})}return Up.call(this,r,s)}}Pt.resolveSchema=Wc;var Dj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Up(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,bC.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!Dj.has(a)&&u&&(e=(0,Lt.resolveUrl)(this.opts.uriResolver,e,u))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,bC.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Lt.resolveUrl)(this.opts.uriResolver,e,r.$ref);i=Wc.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new Uo({schema:r,schemaId:s,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var CC=P((J8,Lj)=>{Lj.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Zp=P((Y8,AC)=>{"use strict";var jj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),EC=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Hp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),xC=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Fj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Gp(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var Uj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function PC(t){return t.length=0,!0}function qj(t,e,r){if(t.length){let n=Gp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Hj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],i=!1,s=!1,a=qj;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(i===!0&&(s=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(i=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=PC}else{o.push(u);continue}}return o.length&&(a===PC?r.zone=o.join(""):s?n.push(o.join("")):n.push(Gp(o))),r.address=n.join(""),r}function kC(t){if(Gj(t,":")<2)return{host:t,isIPV6:!1};let e=Hj(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Gj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Zj(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var Bj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Wj=/[@/?#:]/g,Vj=/[@/?#]/g;function TC(t,e){let r=e?Vj:Wj;return r.lastIndex=0,t.replace(r,n=>Bj[n])}function Kj(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Hp(o)){let i=o.toUpperCase(),s=String.fromCharCode(parseInt(i,16));e&&xC(s)?r+=s:r+="%"+i,n+=2;continue}}r+=t[n]}return r}function Jj(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Hp(n)){let o=n.toUpperCase(),i=String.fromCharCode(parseInt(o,16));i!=="."&&xC(i)?e+=i:e+="%"+o,r+=2;continue}}Fj(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Yj(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Hp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Xj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!EC(r)){let n=kC(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=TC(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}AC.exports={nonSimpleDomain:Uj,recomposeAuthority:Xj,reescapeHostDelimiters:TC,normalizePercentEncoding:Kj,normalizePathEncoding:Jj,escapePreservingEscapes:Yj,removeDotSegments:Zj,isIPv4:EC,isUUID:jj,normalizeIPv6:kC,stringArrayToHexStripped:Gp}});var zC=P((X8,OC)=>{"use strict";var{isUUID:Qj}=Zp(),e1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,t1=["http","https","ws","wss","urn","urn:uuid"];function r1(t){return t1.indexOf(t)!==-1}function Bp(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function MC(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function $C(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function n1(t){return t.secure=Bp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function o1(t){if((t.port===(Bp(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function i1(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(e1);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,i=Wp(o);t.path=void 0,i&&(t=i.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function s1(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,i=Wp(o);i&&(t=i.serialize(t,e));let s=t,a=t.nss;return s.path=`${n||e.nid}:${a}`,e.skipEscape=!0,s}function a1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Qj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function c1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var IC={scheme:"http",domainHost:!0,parse:MC,serialize:$C},u1={scheme:"https",domainHost:IC.domainHost,parse:MC,serialize:$C},Kc={scheme:"ws",domainHost:!0,parse:n1,serialize:o1},d1={scheme:"wss",domainHost:Kc.domainHost,parse:Kc.parse,serialize:Kc.serialize},l1={scheme:"urn",parse:i1,serialize:s1,skipNormalize:!0},f1={scheme:"urn:uuid",parse:a1,serialize:c1,skipNormalize:!0},Jc={http:IC,https:u1,ws:Kc,wss:d1,urn:l1,"urn:uuid":f1};Object.setPrototypeOf(Jc,null);function Wp(t){return t&&(Jc[t]||Jc[t.toLowerCase()])||void 0}OC.exports={wsIsSecure:Bp,SCHEMES:Jc,isValidSchemeName:r1,getSchemeHandler:Wp}});var FC=P((Q8,Qc)=>{"use strict";var{normalizeIPv6:p1,removeDotSegments:js,recomposeAuthority:h1,normalizePercentEncoding:m1,normalizePathEncoding:g1,escapePreservingEscapes:y1,reescapeHostDelimiters:v1,isIPv4:_1,nonSimpleDomain:S1}=Zp(),{SCHEMES:w1,getSchemeHandler:DC}=zC();function b1(t,e){return typeof t=="string"?t=T1(t,e):typeof t=="object"&&(t=Xc(Hn(t,e),e)),t}function R1(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:i}=Yc(t,n),{parsed:s,malformedAuthorityOrPort:a}=Yc(e,n);if(i||a)throw new Error(o.error||s.error||"URI is malformed.");let c=LC(o,s,n,!0);return n.skipEscape=!0,Hn(c,n)}function LC(t,e,r,n){let o={};return n||(t=Xc(Hn(t,r),r),e=Xc(Hn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=js(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=js(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=js(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=js(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function C1(t,e,r){let n=NC(t,r),o=NC(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Hn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],i=DC(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=m1(r.path):(r.path=y1(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let s=h1(r);if(s!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(s),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=js(a)),s===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var P1=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,E1=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,x1=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function k1(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function Yc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(E1);s!==null&&s[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(x1);if(a!==null){let u=a[1],d=u.replace(/[\t\n\r]/g,"");d.length>=2&&(d.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==d.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(P1);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let u=k1(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(_1(n.host)===!1){let f=p1(n.host);n.host=f.host.toLowerCase(),i=f.isIPV6}else i=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=DC(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&i===!1&&S1(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l}if((!d||d&&!d.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=v1(unescape(n.host),i))),n.path&&(n.path=g1(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}d&&d.parse&&d.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Xc(t,e){return Yc(t,e).parsed}function T1(t,e){return jC(t,e).normalized}function jC(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Yc(t,e);return{normalized:n?t:Hn(r,e),malformedAuthorityOrPort:n}}function NC(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=jC(t,e);return n?void 0:r}if(typeof t=="object")return Hn(t,e)}var Vp={SCHEMES:w1,normalize:b1,resolve:R1,resolveComponent:LC,equal:C1,serialize:Hn,parse:Xc};Qc.exports=Vp;Qc.exports.default=Vp;Qc.exports.fastUri=Vp});var qC=P(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var UC=FC();UC.code='require("ajv/dist/runtime/uri").default';Kp.default=UC});var JC=P(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.CodeGen=je.Name=je.nil=je.stringify=je.str=je._=je.KeywordCxt=void 0;var A1=Ds();Object.defineProperty(je,"KeywordCxt",{enumerable:!0,get:function(){return A1.KeywordCxt}});var qo=j();Object.defineProperty(je,"_",{enumerable:!0,get:function(){return qo._}});Object.defineProperty(je,"str",{enumerable:!0,get:function(){return qo.str}});Object.defineProperty(je,"stringify",{enumerable:!0,get:function(){return qo.stringify}});Object.defineProperty(je,"nil",{enumerable:!0,get:function(){return qo.nil}});Object.defineProperty(je,"Name",{enumerable:!0,get:function(){return qo.Name}});Object.defineProperty(je,"CodeGen",{enumerable:!0,get:function(){return qo.CodeGen}});var M1=Bc(),WC=Ls(),$1=Rp(),Fs=Vc(),I1=j(),Us=Os(),eu=Is(),Yp=B(),HC=CC(),O1=qC(),VC=(t,e)=>new RegExp(t,e);VC.code="new RegExp";var z1=["removeAdditional","useDefaults","coerceTypes"],N1=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),D1={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},L1={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},GC=200;function j1(t){var e,r,n,o,i,s,a,c,u,d,l,f,p,h,g,m,v,w,b,R,_,C,I,ee,pe;let be=t.strict,qt=(e=t.code)===null||e===void 0?void 0:e.optimize,fn=qt===!0||qt===void 0?1:qt||0,ht=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:VC,Pr=(o=t.uriResolver)!==null&&o!==void 0?o:O1.default;return{strictSchema:(s=(i=t.strictSchema)!==null&&i!==void 0?i:be)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:be)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:be)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:be)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:be)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:fn,regExp:ht}:{optimize:fn,regExp:ht},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:GC,loopEnum:(m=t.loopEnum)!==null&&m!==void 0?m:GC,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(R=t.schemaId)!==null&&R!==void 0?R:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(C=t.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(pe=t.int32range)!==null&&pe!==void 0?pe:!0,uriResolver:Pr}}var qs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...j1(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new I1.ValueScope({scope:{},prefixes:N1,es5:r,lines:n}),this.logger=Z1(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,$1.getRules)(),ZC.call(this,D1,e,"NOT SUPPORTED"),ZC.call(this,L1,e,"DEPRECATED","warn"),this._metaOpts=H1.call(this),e.formats&&U1.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&q1.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),F1.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=HC;n==="id"&&(o={...HC},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await i.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||s.call(this,f)}async function i(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function s(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof WC.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),s.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await i.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,n,o);return this}let i;if(typeof e=="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Us.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(e){let r;for(;typeof(r=BC.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Fs.SchemaEnv({schema:{},schemaId:n});if(r=Fs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=BC.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Us.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(W1.call(this,n,r),!r)return(0,Yp.eachItem)(n,i=>Jp.call(this,i)),this;K1.call(this,r);let o={...r,type:(0,eu.getJSONTypes)(r.type),schemaType:(0,eu.getJSONTypes)(r.schemaType)};return(0,Yp.eachItem)(n,o.type.length===0?i=>Jp.call(this,i,o):i=>o.type.forEach(s=>Jp.call(this,i,o,s))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let i=o.split("/").slice(1),s=e;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=s[a];u&&d&&(s[a]=KC(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof e=="object")s=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Us.normalizeId)(s||n);let u=Us.getSchemaRefs.call(this,e,n);return c=new Fs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Fs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Fs.compileSchema.call(this,e)}finally{this.opts=r}}};qs.ValidationError=M1.default;qs.MissingRefError=WC.default;je.default=qs;function ZC(t,e,r,n="error"){for(let o in t){let i=o;i in e&&this.logger[n](`${r}: option ${o}. ${t[i]}`)}}function BC(t){return t=(0,Us.normalizeId)(t),this.schemas[t]||this.refs[t]}function F1(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function U1(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function q1(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function H1(){let t={...this.opts};for(let e of z1)delete t[e];return t}var G1={log(){},warn(){},error(){}};function Z1(t){if(t===!1)return G1;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var B1=/^[a-z_$][a-z0-9_$:-]*$/i;function W1(t,e){let{RULES:r}=this;if((0,Yp.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!B1.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Jp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,eu.getJSONTypes)(e.type),schemaType:(0,eu.getJSONTypes)(e.schemaType)}};e.before?V1.call(this,s,a,e.before):s.rules.push(a),i.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function V1(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function K1(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=KC(e)),t.validateSchema=this.compile(e,!0))}var J1={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function KC(t){return{anyOf:[t,J1]}}});var YC=P(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var Y1={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xp.default=Y1});var tP=P(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.callRef=Gn.getValidate=void 0;var X1=Ls(),XC=Ct(),st=j(),Ho=Sr(),QC=Vc(),tu=B(),Q1={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:u}=i;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=QC.resolveRef.call(c,u,o,r);if(d===void 0)throw new X1.default(n.opts.uriResolver,o,r);if(d instanceof QC.SchemaEnv)return f(d);return p(d);function l(){if(i===u)return ru(t,s,i,i.$async);let h=e.scopeValue("root",{ref:u});return ru(t,(0,st._)`${h}.validate`,u,u.$async)}function f(h){let g=eP(t,h);ru(t,g,h,h.$async)}function p(h){let g=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,st.stringify)(h)}:{ref:h}),m=e.name("valid"),v=t.subschema({schema:h,dataTypes:[],schemaPath:st.nil,topSchemaRef:g,errSchemaPath:r},m);t.mergeEvaluated(v),t.ok(m)}}};function eP(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,st._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Gn.getValidate=eP;function ru(t,e,r,n){let{gen:o,it:i}=t,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?Ho.default.this:st.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,st._)`await ${(0,XC.callValidateCode)(t,e,u)}`),p(e),s||o.assign(h,!0)},g=>{o.if((0,st._)`!(${g} instanceof ${i.ValidationError})`,()=>o.throw(g)),f(g),s||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,XC.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let g=(0,st._)`${h}.errors`;o.assign(Ho.default.vErrors,(0,st._)`${Ho.default.vErrors} === null ? ${g} : ${Ho.default.vErrors}.concat(${g})`),o.assign(Ho.default.errors,(0,st._)`${Ho.default.vErrors}.length`)}function p(h){var g;if(!i.opts.unevaluated)return;let m=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(i.props!==!0)if(m&&!m.dynamicProps)m.props!==void 0&&(i.props=tu.mergeEvaluated.props(o,m.props,i.props));else{let v=o.var("props",(0,st._)`${h}.evaluated.props`);i.props=tu.mergeEvaluated.props(o,v,i.props,st.Name)}if(i.items!==!0)if(m&&!m.dynamicItems)m.items!==void 0&&(i.items=tu.mergeEvaluated.items(o,m.items,i.items));else{let v=o.var("items",(0,st._)`${h}.evaluated.items`);i.items=tu.mergeEvaluated.items(o,v,i.items,st.Name)}}}Gn.callRef=ru;Gn.default=Q1});var rP=P(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var eF=YC(),tF=tP(),rF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",eF.default,tF.default];Qp.default=rF});var nP=P(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var nu=j(),nn=nu.operators,ou={maximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},minimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},exclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},exclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},nF={message:({keyword:t,schemaCode:e})=>(0,nu.str)`must be ${ou[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,nu._)`{comparison: ${ou[t].okStr}, limit: ${e}}`},oF={keyword:Object.keys(ou),type:"number",schemaType:"number",$data:!0,error:nF,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,nu._)`${r} ${ou[e].fail} ${n} || isNaN(${r})`)}};eh.default=oF});var oP=P(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Hs=j(),iF={message:({schemaCode:t})=>(0,Hs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Hs._)`{multipleOf: ${t}}`},sF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:iF,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,i=o.opts.multipleOfPrecision,s=e.let("res"),a=i?(0,Hs._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Hs._)`${s} !== parseInt(${s})`;t.fail$data((0,Hs._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};th.default=sF});var sP=P(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});function iP(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}rh.default=iP;iP.code='require("ajv/dist/runtime/ucs2length").default'});var aP=P(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var Zn=j(),aF=B(),cF=sP(),uF={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Zn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Zn._)`{limit: ${t}}`},dF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:uF,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,i=e==="maxLength"?Zn.operators.GT:Zn.operators.LT,s=o.opts.unicode===!1?(0,Zn._)`${r}.length`:(0,Zn._)`${(0,aF.useFunc)(t.gen,cF.default)}(${r})`;t.fail$data((0,Zn._)`${s} ${i} ${n}`)}};nh.default=dF});var cP=P(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var lF=Ct(),fF=B(),Go=j(),pF={message:({schemaCode:t})=>(0,Go.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Go._)`{pattern: ${t}}`},hF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:pF,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:s}=t,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,u=c.code==="new RegExp"?(0,Go._)`new RegExp`:(0,fF.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Go._)`${u}(${i}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Go._)`!${d}`)}else{let c=(0,lF.usePattern)(t,o);t.fail$data((0,Go._)`!${c}.test(${r})`)}}};oh.default=hF});var uP=P(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var Gs=j(),mF={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Gs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Gs._)`{limit: ${t}}`},gF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:mF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Gs.operators.GT:Gs.operators.LT;t.fail$data((0,Gs._)`Object.keys(${r}).length ${o} ${n}`)}};ih.default=gF});var dP=P(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Zs=Ct(),Bs=j(),yF=B(),vF={message:({params:{missingProperty:t}})=>(0,Bs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Bs._)`{missingProperty: ${t}}`},_F={keyword:"required",type:"object",schemaType:"array",$data:!0,error:vF,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:i,it:s}=t,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?u():d(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let g of r)if(p?.[g]===void 0&&!h.has(g)){let m=s.schemaEnv.baseId+s.errSchemaPath,v=`required property "${g}" is not defined at "${m}" (strictRequired)`;(0,yF.checkStrictMode)(s,v,s.opts.strictRequired)}}function u(){if(c||i)t.block$data(Bs.nil,l);else for(let p of r)(0,Zs.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||i){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,Zs.checkMissingProp)(t,r,p)),(0,Zs.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,Zs.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,Zs.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Bs.not)(h),()=>{t.error(),e.break()})},Bs.nil)}}};sh.default=_F});var lP=P(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var Ws=j(),SF={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ws.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ws._)`{limit: ${t}}`},wF={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:SF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ws.operators.GT:Ws.operators.LT;t.fail$data((0,Ws._)`${r}.length ${o} ${n}`)}};ah.default=wF});var iu=P(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var fP=Mp();fP.code='require("ajv/dist/runtime/equal").default';ch.default=fP});var pP=P(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var uh=Is(),Fe=j(),bF=B(),RF=iu(),CF={message:({params:{i:t,j:e}})=>(0,Fe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Fe._)`{i: ${t}, j: ${e}}`},PF={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:CF,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=i.items?(0,uh.getSchemaTypes)(i.items):[];t.block$data(c,d,(0,Fe._)`${s} === false`),t.ok(c);function d(){let h=e.let("i",(0,Fe._)`${r}.length`),g=e.let("j");t.setParams({i:h,j:g}),e.assign(c,!0),e.if((0,Fe._)`${h} > 1`,()=>(l()?f:p)(h,g))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,g){let m=e.name("item"),v=(0,uh.checkDataTypes)(u,m,a.opts.strictNumbers,uh.DataType.Wrong),w=e.const("indices",(0,Fe._)`{}`);e.for((0,Fe._)`;${h}--;`,()=>{e.let(m,(0,Fe._)`${r}[${h}]`),e.if(v,(0,Fe._)`continue`),u.length>1&&e.if((0,Fe._)`typeof ${m} == "string"`,(0,Fe._)`${m} += "_"`),e.if((0,Fe._)`typeof ${w}[${m}] == "number"`,()=>{e.assign(g,(0,Fe._)`${w}[${m}]`),t.error(),e.assign(c,!1).break()}).code((0,Fe._)`${w}[${m}] = ${h}`)})}function p(h,g){let m=(0,bF.useFunc)(e,RF.default),v=e.name("outer");e.label(v).for((0,Fe._)`;${h}--;`,()=>e.for((0,Fe._)`${g} = ${h}; ${g}--;`,()=>e.if((0,Fe._)`${m}(${r}[${h}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};dh.default=PF});var hP=P(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var lh=j(),EF=B(),xF=iu(),kF={message:"must be equal to constant",params:({schemaCode:t})=>(0,lh._)`{allowedValue: ${t}}`},TF={keyword:"const",$data:!0,error:kF,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:i}=t;n||i&&typeof i=="object"?t.fail$data((0,lh._)`!${(0,EF.useFunc)(e,xF.default)}(${r}, ${o})`):t.fail((0,lh._)`${i} !== ${r}`)}};fh.default=TF});var mP=P(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var Vs=j(),AF=B(),MF=iu(),$F={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vs._)`{allowedValues: ${t}}`},IF={keyword:"enum",schemaType:"array",$data:!0,error:$F,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:i,it:s}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,u=()=>c??(c=(0,AF.useFunc)(e,MF.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",i);d=(0,Vs.or)(...o.map((h,g)=>f(p,g)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",i,p=>e.if((0,Vs._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let g=o[h];return typeof g=="object"&&g!==null?(0,Vs._)`${u()}(${r}, ${p}[${h}])`:(0,Vs._)`${r} === ${g}`}}};ph.default=IF});var gP=P(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var OF=nP(),zF=oP(),NF=aP(),DF=cP(),LF=uP(),jF=dP(),FF=lP(),UF=pP(),qF=hP(),HF=mP(),GF=[OF.default,zF.default,NF.default,DF.default,LF.default,jF.default,FF.default,UF.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},qF.default,HF.default];hh.default=GF});var gh=P(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.validateAdditionalItems=void 0;var Bn=j(),mh=B(),ZF={message:({params:{len:t}})=>(0,Bn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Bn._)`{limit: ${t}}`},BF={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ZF,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}yP(t,n)}};function yP(t,e){let{gen:r,schema:n,data:o,keyword:i,it:s}=t;s.items=!0;let a=r.const("len",(0,Bn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Bn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mh.alwaysValidSchema)(s,n)){let u=r.var("valid",(0,Bn._)`${a} <= ${e.length}`);r.if((0,Bn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:i,dataProp:d,dataPropType:mh.Type.Num},u),s.allErrors||r.if((0,Bn.not)(u),()=>r.break())})}}Ks.validateAdditionalItems=yP;Ks.default=BF});var yh=P(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.validateTuple=void 0;var vP=j(),su=B(),WF=Ct(),VF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return _P(t,"additionalItems",e);r.items=!0,!(0,su.alwaysValidSchema)(r,e)&&t.ok((0,WF.validateArray)(t))}};function _P(t,e,r=t.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=su.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,vP._)`${i}.length`);r.forEach((l,f)=>{(0,su.alwaysValidSchema)(a,l)||(n.if((0,vP._)`${u} > ${f}`,()=>t.subschema({keyword:s,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,g=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!g){let m=`"${s}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,su.checkStrictMode)(a,m,f.strictTuples)}}}Js.validateTuple=_P;Js.default=VF});var SP=P(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var KF=yh(),JF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,KF.validateTuple)(t,"items")};vh.default=JF});var bP=P(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var wP=j(),YF=B(),XF=Ct(),QF=gh(),eU={message:({params:{len:t}})=>(0,wP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,wP._)`{limit: ${t}}`},tU={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:eU,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,YF.alwaysValidSchema)(n,e)&&(o?(0,QF.validateAdditionalItems)(t,o):t.ok((0,XF.validateArray)(t)))}};_h.default=tU});var RP=P(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var Et=j(),au=B(),rU={message:({params:{min:t,max:e}})=>e===void 0?(0,Et.str)`must contain at least ${t} valid item(s)`:(0,Et.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Et._)`{minContains: ${t}}`:(0,Et._)`{minContains: ${t}, maxContains: ${e}}`},nU={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:rU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t,s,a,{minContains:c,maxContains:u}=n;i.opts.next?(s=c===void 0?1:c,a=u):s=1;let d=e.const("len",(0,Et._)`${o}.length`);if(t.setParams({min:s,max:a}),a===void 0&&s===0){(0,au.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,au.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,au.alwaysValidSchema)(i,r)){let g=(0,Et._)`${d} >= ${s}`;a!==void 0&&(g=(0,Et._)`${g} && ${d} <= ${a}`),t.pass(g);return}i.items=!0;let l=e.name("valid");a===void 0&&s===1?p(l,()=>e.if(l,()=>e.break())):s===0?(e.let(l,!0),a!==void 0&&e.if((0,Et._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let g=e.name("_valid"),m=e.let("count",0);p(g,()=>e.if(g,()=>h(m)))}function p(g,m){e.forRange("i",0,d,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:au.Type.Num,compositeRule:!0},g),m()})}function h(g){e.code((0,Et._)`${g}++`),a===void 0?e.if((0,Et._)`${g} >= ${s}`,()=>e.assign(l,!0).break()):(e.if((0,Et._)`${g} > ${a}`,()=>e.assign(l,!1).break()),s===1?e.assign(l,!0):e.if((0,Et._)`${g} >= ${s}`,()=>e.assign(l,!0)))}}};Sh.default=nU});var EP=P(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.validateSchemaDeps=er.validatePropertyDeps=er.error=void 0;var wh=j(),oU=B(),Ys=Ct();er.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,wh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,wh._)`{property: ${t},
|
|
6
6
|
missingProperty: ${n},
|
|
7
7
|
depsCount: ${e},
|
|
8
|
-
deps: ${r}}`};var fF={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(t){let[e,r]=pF(t);VC(t,e),KC(t,r)}};function pF({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function VC(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Is.propertyInData)(r,n,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Is.checkReportMissingProp)(t,u)}):(r.if((0,Qp._)`${c} && (${(0,Is.checkMissingProp)(t,a,i)})`),(0,Is.reportMissingProp)(t,i),r.else())}}er.validatePropertyDeps=VC;function KC(t,e=t.schema){let{gen:r,data:n,keyword:o,it:i}=t,s=r.name("valid");for(let a in e)(0,lF.alwaysValidSchema)(i,e[a])||(r.if((0,Is.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}er.validateSchemaDeps=KC;er.default=fF});var XC=P(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var YC=j(),hF=B(),mF={message:"property name must be valid",params:({params:t})=>(0,YC._)`{propertyName: ${t.propertyName}}`},gF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:mF,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,hF.alwaysValidSchema)(o,r))return;let i=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,YC.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};eh.default=gF});var rh=P(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Qc=Rt(),Dt=j(),yF=gr(),eu=B(),vF={message:"must NOT have additional properties",params:({params:t})=>(0,Dt._)`{additionalProperty: ${t.additionalProperty}}`},_F={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vF,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,eu.alwaysValidSchema)(s,r))return;let u=(0,Qc.allSchemaProperties)(n.properties),d=(0,Qc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Dt._)`${i} === ${yF.default.errors}`);function l(){e.forIn("key",o,g=>{!u.length&&!d.length?h(g):e.if(f(g),()=>h(g))})}function f(g){let v;if(u.length>8){let w=(0,eu.schemaRefOrVal)(s,n.properties,"properties");v=(0,Qc.isOwnProperty)(e,w,g)}else u.length?v=(0,Dt.or)(...u.map(w=>(0,Dt._)`${g} === ${w}`)):v=Dt.nil;return d.length&&(v=(0,Dt.or)(v,...d.map(w=>(0,Dt._)`${(0,Qc.usePattern)(t,w)}.test(${g})`))),(0,Dt.not)(v)}function p(g){e.code((0,Dt._)`delete ${o}[${g}]`)}function h(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,eu.alwaysValidSchema)(s,r)){let v=e.name("valid");c.removeAdditional==="failing"?(m(g,v,!1),e.if((0,Dt.not)(v),()=>{t.reset(),p(g)})):(m(g,v),a||e.if((0,Dt.not)(v),()=>e.break()))}}function m(g,v,w){let b={keyword:"additionalProperties",dataProp:g,dataPropType:eu.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};th.default=_F});var tP=P(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var SF=_s(),QC=Rt(),nh=B(),eP=rh(),wF={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&eP.default.code(new SF.KeywordCxt(i,eP.default,"additionalProperties"));let s=(0,QC.allSchemaProperties)(r);for(let l of s)i.definedProperties.add(l);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=nh.mergeEvaluated.props(e,(0,nh.toHash)(s),i.props));let a=s.filter(l=>!(0,nh.alwaysValidSchema)(i,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,QC.propertyInData)(e,o,l,i.opts.ownProperties)),d(l),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return i.opts.useDefaults&&!i.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};oh.default=wF});var iP=P(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var rP=Rt(),tu=j(),nP=B(),oP=B(),bF={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,rP.allSchemaProperties)(r),c=a.filter(m=>(0,nP.alwaysValidSchema)(i,r[m]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&o.properties,d=e.name("valid");i.props!==!0&&!(i.props instanceof tu.Name)&&(i.props=(0,oP.evaluatedPropsToName)(e,i.props));let{props:l}=i;f();function f(){for(let m of a)u&&p(m),i.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let g in u)new RegExp(m).test(g)&&(0,nP.checkStrictMode)(i,`property ${g} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,g=>{e.if((0,tu._)`${(0,rP.usePattern)(t,m)}.test(${g})`,()=>{let v=c.includes(m);v||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:g,dataPropType:oP.Type.Str},d),i.opts.unevaluated&&l!==!0?e.assign((0,tu._)`${l}[${g}]`,!0):!v&&!i.allErrors&&e.if((0,tu.not)(d),()=>e.break())})})}}};ih.default=bF});var sP=P(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var RF=B(),CF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,RF.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};sh.default=CF});var aP=P(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var PF=Rt(),xF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:PF.validateUnion,error:{message:"must match a schema in anyOf"}};ah.default=xF});var cP=P(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var ru=j(),EF=B(),kF={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ru._)`{passingSchemas: ${t.passing}}`},TF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kF,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(s,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((d,l)=>{let f;(0,EF.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,ru._)`${c} && ${s}`).assign(s,!1).assign(a,(0,ru._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,l),f&&t.mergeEvaluated(f,ru.Name)})})}}};ch.default=TF});var uP=P(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var AF=B(),MF={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((i,s)=>{if((0,AF.alwaysValidSchema)(n,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};uh.default=MF});var fP=P(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var nu=j(),lP=B(),$F={message:({params:t})=>(0,nu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,nu._)`{failingKeyword: ${t.ifClause}}`},IF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$F,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,lP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=dP(n,"then"),i=dP(n,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,nu.not)(a),u("else"));t.pass(s,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},a);e.assign(s,a),t.mergeValidEvaluated(f,s),l?e.assign(l,(0,nu._)`${d}`):t.setParams({ifClause:d})}}}};function dP(t,e){let r=t.schema[e];return r!==void 0&&!(0,lP.alwaysValidSchema)(t,r)}dh.default=IF});var pP=P(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var OF=B(),zF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,OF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};lh.default=zF});var hP=P(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var NF=Vp(),DF=GC(),LF=Kp(),jF=BC(),FF=WC(),UF=JC(),qF=XC(),HF=rh(),GF=tP(),ZF=iP(),BF=sP(),WF=aP(),VF=cP(),KF=uP(),JF=fP(),YF=pP();function XF(t=!1){let e=[BF.default,WF.default,VF.default,KF.default,JF.default,YF.default,qF.default,HF.default,UF.default,GF.default,ZF.default];return t?e.push(DF.default,jF.default):e.push(NF.default,LF.default),e.push(FF.default),e}fh.default=XF});var mP=P(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var Ce=j(),QF={message:({schemaCode:t})=>(0,Ce.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ce._)`{format: ${t}}`},eU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:QF,code(t,e){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,Ce._)`${h}[${s}]`),g=r.let("fType"),v=r.let("format");r.if((0,Ce._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(g,(0,Ce._)`${m}.type || "string"`).assign(v,(0,Ce._)`${m}.validate`),()=>r.assign(g,(0,Ce._)`"string"`).assign(v,m)),t.fail$data((0,Ce.or)(w(),b()));function w(){return c.strictSchema===!1?Ce.nil:(0,Ce._)`${s} && !${v}`}function b(){let R=d.$async?(0,Ce._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ce._)`${v}(${n})`,_=(0,Ce._)`(typeof ${v} == "function" ? ${R} : ${v}.test(${n}))`;return(0,Ce._)`${v} && ${v} !== true && ${g} === ${e} && !${_}`}}function p(){let h=l.formats[i];if(!h){w();return}if(h===!0)return;let[m,g,v]=b(h);m===e&&t.pass(R());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function b(_){let C=_ instanceof RegExp?(0,Ce.regexpCode)(_):c.code.formats?(0,Ce._)`${c.code.formats}${(0,Ce.getProperty)(i)}`:void 0,I=r.scopeValue("formats",{key:i,ref:_,code:C});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,Ce._)`${I}.validate`]:["string",_,I]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ce._)`await ${v}(${n})`}return typeof g=="function"?(0,Ce._)`${v}(${n})`:(0,Ce._)`${v}.test(${n})`}}}};ph.default=eU});var gP=P(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var tU=mP(),rU=[tU.default];hh.default=rU});var yP=P(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.contentVocabulary=Do.metadataVocabulary=void 0;Do.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Do.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var _P=P(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var nU=xC(),oU=FC(),iU=hP(),sU=gP(),vP=yP(),aU=[nU.default,oU.default,(0,iU.default)(),sU.default,vP.metadataVocabulary,vP.contentVocabulary];mh.default=aU});var wP=P(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});ou.DiscrError=void 0;var SP;(function(t){t.Tag="tag",t.Mapping="mapping"})(SP||(ou.DiscrError=SP={}))});var RP=P(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var Lo=j(),gh=wP(),bP=jc(),cU=Ss(),uU=B(),dU={message:({params:{discrError:t,tagName:e}})=>t===gh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},lU={keyword:"discriminator",type:"object",schemaType:"object",error:dU,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Lo._)`${r}${(0,Lo.getProperty)(a)}`);e.if((0,Lo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:gh.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Lo._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:gh.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,Lo.Name),h}function f(){var p;let h={},m=v(o),g=!0;for(let R=0;R<s.length;R++){let _=s[R];if(_?.$ref&&!(0,uU.schemaHasRulesButRef)(_,i.self.RULES)){let I=_.$ref;if(_=bP.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,I),_ instanceof bP.SchemaEnv&&(_=_.schema),_===void 0)throw new cU.default(i.opts.uriResolver,i.baseId,I)}let C=(p=_?.properties)===null||p===void 0?void 0:p[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(m||v(_)),w(C,R)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:R}){return Array.isArray(R)&&R.includes(a)}function w(R,_){if(R.const)b(R.const,_);else if(R.enum)for(let C of R.enum)b(C,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(R,_){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=_}}}};yh.default=lU});var CP=P((D8,fU)=>{fU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var _h=P((le,vh)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var pU=SC(),hU=_P(),mU=RP(),PP=CP(),gU=["/properties"],iu="http://json-schema.org/draft-07/schema",jo=class extends pU.default{_addVocabularies(){super._addVocabularies(),hU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(mU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(PP,gU):PP;this.addMetaSchema(e,iu,!1),this.refs["http://json-schema.org/schema"]=iu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(iu)?iu:void 0)}};le.Ajv=jo;vh.exports=le=jo;vh.exports.Ajv=jo;Object.defineProperty(le,"__esModule",{value:!0});le.default=jo;var yU=_s();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return yU.KeywordCxt}});var Fo=j();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Fo._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Fo.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Fo.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Fo.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Fo.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Fo.CodeGen}});var vU=Dc();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return vU.default}});var _U=Ss();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return _U.default}})});var IP=P(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(t,e){return{validate:t,compare:e}}rr.fullFormats={date:tr(TP,Rh),time:tr(wh(!0),Ch),"date-time":tr(xP(!0),MP),"iso-time":tr(wh(),AP),"iso-date-time":tr(xP(),$P),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:PU,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:$U,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:xU,int32:{type:"number",validate:TU},int64:{type:"number",validate:AU},float:{type:"number",validate:kP},double:{type:"number",validate:kP},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Rh),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ch),"date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,MP),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,AP),"iso-date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,$P),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rr.formatNames=Object.keys(rr.fullFormats);function SU(t){return t%4===0&&(t%100!==0||t%400===0)}var wU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function TP(t){let e=wU.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&SU(r)?29:bU[n])}function Rh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wh(t){return function(r){let n=Sh.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let l=i-d*c,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&s<61}}function Ch(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function AP(t,e){if(!(t&&e))return;let r=Sh.exec(t),n=Sh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var bh=/t|\s/i;function xP(t){let e=wh(t);return function(n){let o=n.split(bh);return o.length===2&&TP(o[0])&&e(o[1])}}function MP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function $P(t,e){if(!(t&&e))return;let[r,n]=t.split(bh),[o,i]=e.split(bh),s=Rh(r,o);if(s!==void 0)return s||Ch(n,i)}var RU=/\/|:/,CU=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function PU(t){return RU.test(t)&&CU.test(t)}var EP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function xU(t){return EP.lastIndex=0,EP.test(t)}var EU=-(2**31),kU=2**31-1;function TU(t){return Number.isInteger(t)&&t<=kU&&t>=EU}function AU(t){return Number.isInteger(t)}function kP(){return!0}var MU=/[^\\]\\Z/;function $U(t){if(MU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var OP=P(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.formatLimitDefinition=void 0;var IU=_h(),Lt=j(),tn=Lt.operators,su={formatMaximum:{okStr:"<=",ok:tn.LTE,fail:tn.GT},formatMinimum:{okStr:">=",ok:tn.GTE,fail:tn.LT},formatExclusiveMaximum:{okStr:"<",ok:tn.LT,fail:tn.GTE},formatExclusiveMinimum:{okStr:">",ok:tn.GT,fail:tn.LTE}},OU={message:({keyword:t,schemaCode:e})=>(0,Lt.str)`should be ${su[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Lt._)`{comparison: ${su[t].okStr}, limit: ${e}}`};Uo.formatLimitDefinition={keyword:Object.keys(su),type:"string",schemaType:"string",$data:!0,error:OU,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new IU.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,Lt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Lt.or)((0,Lt._)`typeof ${p} != "object"`,(0,Lt._)`${p} instanceof RegExp`,(0,Lt._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Lt._)`${s.code.formats}${(0,Lt.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,Lt._)`${f}.compare(${r}, ${n}) ${su[o].fail} 0`}},dependencies:["format"]};var zU=t=>(t.addKeyword(Uo.formatLimitDefinition),t);Uo.default=zU});var LP=P((Os,DP)=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});var qo=IP(),NU=OP(),Ph=j(),zP=new Ph.Name("fullFormats"),DU=new Ph.Name("fastFormats"),xh=(t,e={keywords:!0})=>{if(Array.isArray(e))return NP(t,e,qo.fullFormats,zP),t;let[r,n]=e.mode==="fast"?[qo.fastFormats,DU]:[qo.fullFormats,zP],o=e.formats||qo.formatNames;return NP(t,o,r,n),e.keywords&&(0,NU.default)(t),t};xh.get=(t,e="full")=>{let n=(e==="fast"?qo.fastFormats:qo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function NP(t,e,r,n){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Ph._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)t.addFormat(s,r[s])}DP.exports=Os=xh;Object.defineProperty(Os,"__esModule",{value:!0});Os.default=xh});var px=P((_Y,fx)=>{fx.exports=lx;lx.sync=mq;var ux=Pr("fs");function hq(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&t.substr(-o.length).toLowerCase()===o)return!0}return!1}function dx(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:hq(e,r)}function lx(t,e,r){ux.stat(t,function(n,o){r(n,n?!1:dx(o,t,e))})}function mq(t,e){return dx(ux.statSync(t),t,e)}});var vx=P((SY,yx)=>{yx.exports=mx;mx.sync=gq;var hx=Pr("fs");function mx(t,e,r){hx.stat(t,function(n,o){r(n,n?!1:gx(o,e))})}function gq(t,e){return gx(hx.statSync(t),e)}function gx(t,e){return t.isFile()&&yq(t,e)}function yq(t,e){var r=t.mode,n=t.uid,o=t.gid,i=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),d=a|c,l=r&u||r&c&&o===s||r&a&&n===i||r&d&&i===0;return l}});var Sx=P((bY,_x)=>{var wY=Pr("fs"),yu;process.platform==="win32"||global.TESTING_WINDOWS?yu=px():yu=vx();_x.exports=Zh;Zh.sync=vq;function Zh(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Zh(t,e||{},function(i,s){i?o(i):n(s)})})}yu(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function vq(t,e){try{return yu.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var Ex=P((RY,xx)=>{var Jo=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",wx=Pr("path"),_q=Jo?";":":",bx=Sx(),Rx=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),Cx=(t,e)=>{let r=e.colon||_q,n=t.match(/\//)||Jo&&t.match(/\\/)?[""]:[...Jo?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Jo?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Jo?o.split(r):[""];return Jo&&t.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},Px=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:i}=Cx(t,e),s=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&s.length?d(s):l(Rx(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=wx.join(p,t),m=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];bx(u+h,{pathExt:i},(m,g)=>{if(!m&&g)if(e.all)s.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},Sq=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=Cx(t,e),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=wx.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if(bx.sync(f,{pathExt:o}))if(e.all)i.push(f);else return f}catch{}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw Rx(t)};xx.exports=Px;Px.sync=Sq});var Tx=P((CY,Bh)=>{"use strict";var kx=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Bh.exports=kx;Bh.exports.default=kx});var Ix=P((PY,$x)=>{"use strict";var Ax=Pr("path"),wq=Ex(),bq=Tx();function Mx(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(t.options.cwd)}catch{}let s;try{s=wq.sync(t.command,{path:r[bq({env:r})],pathExt:e?Ax.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=Ax.resolve(o?t.options.cwd:"",s)),s}function Rq(t){return Mx(t)||Mx(t,!0)}$x.exports=Rq});var Ox=P((xY,Vh)=>{"use strict";var Wh=/([()\][%!^"`<>&|;, *?])/g;function Cq(t){return t=t.replace(Wh,"^$1"),t}function Pq(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Wh,"^$1"),e&&(t=t.replace(Wh,"^$1")),t}Vh.exports.command=Cq;Vh.exports.argument=Pq});var Nx=P((EY,zx)=>{"use strict";zx.exports=/^#!(.*)/});var Lx=P((kY,Dx)=>{"use strict";var xq=Nx();Dx.exports=(t="")=>{let e=t.match(xq);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Fx=P((TY,jx)=>{"use strict";var Kh=Pr("fs"),Eq=Lx();function kq(t){let r=Buffer.alloc(150),n;try{n=Kh.openSync(t,"r"),Kh.readSync(n,r,0,150,0),Kh.closeSync(n)}catch{}return Eq(r.toString())}jx.exports=kq});var Gx=P((AY,Hx)=>{"use strict";var Tq=Pr("path"),Ux=Ix(),qx=Ox(),Aq=Fx(),Mq=process.platform==="win32",$q=/\.(?:com|exe)$/i,Iq=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Oq(t){t.file=Ux(t);let e=t.file&&Aq(t.file);return e?(t.args.unshift(t.file),t.command=e,Ux(t)):t.file}function zq(t){if(!Mq)return t;let e=Oq(t),r=!$q.test(e);if(t.options.forceShell||r){let n=Iq.test(e);t.command=Tq.normalize(t.command),t.command=qx.command(t.command),t.args=t.args.map(i=>qx.argument(i,n));let o=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${o}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function Nq(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:zq(n)}Hx.exports=Nq});var Wx=P((MY,Bx)=>{"use strict";var Jh=process.platform==="win32";function Yh(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function Dq(t,e){if(!Jh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let i=Zx(o,e);if(i)return r.call(t,"error",i)}return r.apply(t,arguments)}}function Zx(t,e){return Jh&&t===1&&!e.file?Yh(e.original,"spawn"):null}function Lq(t,e){return Jh&&t===1&&!e.file?Yh(e.original,"spawnSync"):null}Bx.exports={hookChildProcess:Dq,verifyENOENT:Zx,verifyENOENTSync:Lq,notFoundError:Yh}});var Jx=P(($Y,Yo)=>{"use strict";var Vx=Pr("child_process"),Xh=Gx(),Qh=Wx();function Kx(t,e,r){let n=Xh(t,e,r),o=Vx.spawn(n.command,n.args,n.options);return Qh.hookChildProcess(o,n),o}function jq(t,e,r){let n=Xh(t,e,r),o=Vx.spawnSync(n.command,n.args,n.options);return o.error=o.error||Qh.verifyENOENTSync(o.status,n),o}Yo.exports=Kx;Yo.exports.spawn=Kx;Yo.exports.sync=jq;Yo.exports._parse=Xh;Yo.exports._enoent=Qh});var rE=P(tm=>{"use strict";var Qx=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,Gq=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,eE=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,Zq=/\\([\u000b\u0020-\u00ff])/g,Bq=/([\\"])/g,tE=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;tm.format=Wq;tm.parse=Vq;function Wq(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!tE.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,i=Object.keys(e).sort(),s=0;s<i.length;s++){if(o=i[s],!eE.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+Jq(e[o])}return n}function Vq(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?Kq(t):t;if(typeof e!="string")throw new TypeError("argument string is required to be a string");var r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if(!tE.test(n))throw new TypeError("invalid media type");var o=new Yq(n.toLowerCase());if(r!==-1){var i,s,a;for(Qx.lastIndex=r;s=Qx.exec(e);){if(s.index!==r)throw new TypeError("invalid parameter format");r+=s[0].length,i=s[1].toLowerCase(),a=s[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(Zq,"$1"))),o.parameters[i]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function Kq(t){var e;if(typeof t.getHeader=="function"?e=t.getHeader("content-type"):typeof t.headers=="object"&&(e=t.headers&&t.headers["content-type"]),typeof e!="string")throw new TypeError("content-type header is missing from object");return e}function Jq(t){var e=String(t);if(eE.test(e))return e;if(e.length>0&&!Gq.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(Bq,"\\$1")+'"'}function Yq(t){this.parameters=Object.create(null),this.type=t}});import{logger as K4}from"@hermes/logger";import{logger as kG,logPublic as KE}from"@hermes/logger";var WT="mcp-auth";function Se(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(WT,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as XH}from"@augmentcode/auggie-v2";import{logger as QH}from"@hermes/logger";import{logger as EA}from"@hermes/logger";import{logger as KT}from"@hermes/logger";function VT(t,e,r){let n=r?.get(t.name);return n!==void 0?n.host===t&&n.owner.kind==="plugin":e?.get(t.name)===t}function xr(t,e,r){let n=r?.get(t.name);if(n?.host===t)return n.owner.kind;let o=t.config;return o?.vfsSource!==void 0?"vfs":o?.registrySource!==void 0?"registry":VT(t,e,r)?"plugin":"local"}function JT(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var Qm=KT.child({prefix:"pi-mcp"}),YT="augment:mcp-status-report";function at(t,e,r){let n=t.servers.get(e),o=n?.hostedCredentialProvenance;if(o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0)return{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain};let i=n?.targetCredentialProvenance?n.targetCredentialProvenance.credential:t.credentialRevisions?.get(e);return{serverGeneration:t.serverGenerations?.get(e)??0,mcpConfigId:r??n?.config.id,credentialRevision:i?.revision,credentialRevisionDomain:i?.domain}}function ai(t,e,r,n){let o=at(t,e);return o.serverGeneration!==n.serverGeneration||o.mcpConfigId!==n.mcpConfigId||o.credentialRevision!==n.credentialRevision||o.credentialRevisionDomain!==n.credentialRevisionDomain?!1:(t.statusFailureCategories??=new Map,t.statusFailureCategories.set(e,{category:r,...n}),!0)}function ct(t,e,r){if(r){let o=at(t,e);if(o.serverGeneration!==r.serverGeneration||o.mcpConfigId!==r.mcpConfigId||o.credentialRevision!==r.credentialRevision||o.credentialRevisionDomain!==r.credentialRevisionDomain)return!1}let n=t.statusFailureCategories?.get(e);return t.statusFailureCategories?.delete(e),typeof n=="object"&&n.category==="auth_refresh_needed"&&t.authRefreshNeededReportKeys?.delete(e),!0}function XT(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=at(t,e);if(r?.serverGeneration===n.serverGeneration&&r.mcpConfigId===n.mcpConfigId&&r.credentialRevision===n.credentialRevision&&r.credentialRevisionDomain===n.credentialRevisionDomain)return r.category;t.statusFailureCategories.delete(e),t.authRefreshNeededReportKeys?.delete(e)}var ua=3e4;function QT(t){switch(t.status){case"success":return"connected";case"failed":case"auth_required":return"failed";case"initializing":{let e=t.connectStartedAt;return e!==void 0&&Date.now()-e>=ua?"failed":void 0}default:return}}var eg="authentication required",eA="Authentication refresh is pending in the backend; retry shortly.",tA="timed out connecting after 30s",rA="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",nA="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",oA="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",iA="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",sA="Server requires re-authentication \u2014 its saved credential is no longer valid. Reconnect it from the session MCP panel.",aA="Server was not started: its credential is temporarily unavailable. Re-initialize it in a moment.",cA=new Map([["manager_unavailable","retry"],["managed_provider_unavailable","retry"],["refresh_retryable","retry"],["reauth_required","reconnect"],["auth_terminal","reconnect"],["policy_excluded","blocked"],["share_identity_excluded","blocked"]]),uA="Server was not started: this session is not allowed to use it.",dA="Server was not started: this session's Space policy does not allow it.",lA="Server was not started: its shared credential is not available to this session's identity.",fA="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function pA(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),i=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),s=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=s(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?nA:rA,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=s(a);i.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...gA({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}hA({state:t,servers:e,liveConfigIds:r,reportedConfigIds:n,reportedNames:o,idlessReportedNames:i})}function hA(t){let{state:e,servers:r,liveConfigIds:n,reportedConfigIds:o,reportedNames:i,idlessReportedNames:s}=t;for(let[a,c]of e.oauthFailureCategoriesByConfigId??[]){if(n.has(a)||o.has(a)||e.sessionRemovedConfigIds.has(a))continue;let u=ng(e,a)??mA(e,c);if(u===void 0)continue;let d=e.registryConfigNamesById.get(a)??c.serverName;s.has(d)||(o.add(a),r.push({name:d,source:"registry",status:"failed",...u,mcpConfigId:a}),i.add(d))}}function tg(t){switch(t.disposition){case"retry":case"reconnect":case"blocked":return t.disposition;case void 0:return cA.get(t.category);default:return}}function mA(t,e){if(!(t.selectedRegistryConfigIds===void 0||tg(e)!=="retry"))return{errorMessage:aA,failureCategory:"transient"}}function rg(t,e){let r=new Map;for(let[n,o]of Object.entries(e)){if(!o||typeof o!="object")continue;let i=o;typeof i.category=="string"&&typeof i.config_id=="string"&&i.config_id!==""&&r.set(i.config_id,{category:i.category,serverName:n,...typeof i.disposition=="string"?{disposition:i.disposition}:{}})}t.oauthFailureCategoriesByConfigId=r}function ng(t,e){let r=t.oauthFailureCategoriesByConfigId?.get(e);if(r!==void 0)switch(tg(r)){case"reconnect":return{errorMessage:sA,failureCategory:"auth_terminal"};case"blocked":return r.category==="share_identity_excluded"?{errorMessage:lA,failureCategory:"share_identity_excluded"}:{errorMessage:r.category==="policy_excluded"?dA:uA,failureCategory:"policy_excluded"};default:return}}function gA(t){let{state:e,id:r,name:n,reportedNames:o}=t;if(e.authFallbackDisplacedConfigIds.has(r))return{errorMessage:fA,failureCategory:"auth_terminal"};let i=ng(e,r);return i!==void 0?i:{errorMessage:o.has(n)?iA:oA,failureCategory:"configuration"}}function yA(t,e){return e!==void 0?e.isAuthError?eg:e.error:t.status==="initializing"?tA:t.lastError??(t.status==="auth_required"?eg:void 0)}function og(t,e){if(t.targetCredentialProvenance)return t.targetCredentialProvenance.credential;let r=e.statusFailureCategories?.get(t.name);return typeof r=="object"?{revision:r.credentialRevision,domain:r.credentialRevisionDomain}:e.credentialRevisions?.get(t.name)}function vA(t,e,r){if(og(t,e)?.domain?.startsWith("recipient:"))return at(e,t.name).serverGeneration;let n=e.statusFailureCategories?.get(t.name);if(r&&typeof n=="object")return n.serverGeneration;let o=at(e,t.name).serverGeneration;return o>0?o:void 0}function _A(t,e){let r=QT(t);if(r===void 0)return;let n=XT(e,t.name),o=r==="connected"?JT(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let i={name:t.name,source:xr(t,e.pluginServerHosts,e.hostLeases),status:r,transport:t.config.type,tools:t.suppressesProviderDiagnostics?[]:t.tools.map(u=>u.name)},s=t.config.id;s!==void 0&&(i.mcpConfigId=s,e.dynamicallyAddedConfigIds.has(s)&&(i.dynamicallyAdded=!0));let a=og(t,e);a?.revision!==void 0&&a.domain!==void 0&&(i.credentialRevision=a.revision,i.credentialRevisionDomain=a.domain);let c=vA(t,e,r==="failed");return c!==void 0&&(i.serverGeneration=c),r==="failed"&&(i.errorMessage=n==="auth_refresh_needed"?eA:yA(t,o),i.failureCategory=n??(t.status==="auth_required"||o?.isAuthError===!0?"auth_terminal":"transport_transient")),i}function SA(t){let e=[];for(let r of t.servers.values()){let n=_A(r,t);n!==void 0&&e.push(n)}return pA(t,e),e}function N(t,e){try{let r=SA(e),n=JSON.stringify(r);if(n===e.lastStatusReport)return;e.lastStatusReport=n,e.statusHostGeneration??=1,e.statusReportSequence=(e.statusReportSequence??0)+1;let o={servers:r,observedAtMs:Date.now(),hostGeneration:e.statusHostGeneration,reportSequence:e.statusReportSequence};t.events.emit(YT,o),Qm.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){Qm.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var da={local:4,registry:3,plugin:2,vfs:1};function Ht(t){return t.hostLeases??=new Map,t.hostLeases}function wA(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function ci(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function ui(t,e){return t.kind===e.kind&&t.identity===e.identity}function ig(t){if(!t.host)return t.retirement;let e=()=>{},r=new Promise(n=>{e=n});return{incumbent:{owner:t.owner,revision:t.revision,host:t.host},teardown:r,settled:!1,resolve:e}}function Qu(t,e){let r=wA(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function la(t,e,r){if(r.kind==="registry"){ci(t).set(e,{kind:"domain",domain:r.identity});return}ci(t).set(e,{kind:"blocked"})}function ed(t,e,r){r&&t.servers.get(e)===r&&t.servers.delete(e),r&&t.pluginServerHosts.get(e)===r&&(t.pluginServerHosts.delete(e),t.pluginServerNames.delete(e))}function Er(t,e){return t.registrySource!==void 0?{kind:"registry",identity:`user:${t.id??t.name}`}:t.vfsSource!==void 0?{kind:"vfs",identity:t.id??t.name}:{kind:e??"local",identity:t.id??t.name}}function te(t,e,r){let n=Ht(t),o=n.get(e);if(o)return o;let i=t.pluginServerHosts.get(e)===r?"plugin":void 0,s=r.config,a=s?Er(s,i):{kind:i??"local",identity:e},c={owner:a,revision:Qu(t,e),host:r,connectionEpoch:t.mcpConnectionEpoch};return n.set(e,c),la(t,e,a),c}function sg(t){let{state:e,name:r,host:n}=t,o=Ht(e),i=o.get(r);if(!i||i.host!==n||i.owner.kind!=="local"||e.servers.get(r)!==n)return;let s={owner:{kind:"plugin",identity:n.config.id??r},revision:Qu(e,r),host:n};return o.set(r,s),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),la(e,r,s.owner),s}function di(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:i}=t,s=Ht(e),a=s.get(r);if(a){if(a.retirement?.settled)return;let l=da[n.kind]>da[a.owner.kind],f=da[n.kind]===da[a.owner.kind],p=o===a.revision&&(i===void 0||i===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?ig(a):void 0;ed(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,connectionEpoch:e.mcpConnectionEpoch,revision:Qu(e,r),host:void 0,...u?{retirement:u}:{}};return s.set(r,d),la(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function td(t){if(!t)return;let e=await t.teardown;if(e.status==="failed")throw e.error instanceof Error?e.error:new Error(String(e.error))}function _e(t){let{state:e,name:r,retirement:n,result:o}=t;if(n.settled)return!1;n.settled=!0,n.result=o;let s=Ht(e).get(r);return s?.retirement===n&&(o.status==="failed"?(s.host=void 0,ci(e).set(r,{kind:"blocked"})):s.retirement=void 0),n.resolve(o),!0}function fa(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e).get(r);return!s||s.revision!==o||!ui(s.owner,n)||s.host!==void 0||s.retirement!==void 0?!1:(s.host=i,e.servers.set(r,i),n.kind==="plugin"?(e.pluginServerNames.add(r),e.pluginServerHosts.set(r,i)):(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),!0)}function ut(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e).get(r);if(!s||s.revision!==o||!ui(s.owner,n)||s.host!==i||s.retirement!==void 0)return;let a=ig(s);if(a)return ed(e,r,i),s.host=void 0,s.retirement=a,a}function ag(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,i=Ht(e),s=i.get(r),a=o.result;return!s||s.retirement!==o||s.host!==void 0||!o.settled||!ui(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(s.retirement=void 0,!ui(s.owner,n)||s.revision!==o.incumbent.revision?(la(e,r,s.owner),!0):(i.delete(r),ci(e).set(r,{kind:"blocked"}),!0))}function Ee(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e),a=s.get(r);return!a||a.revision!==o||!ui(a.owner,n)||a.host!==i||a.retirement!==void 0?!1:(ed(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),s.delete(r),ci(e).set(r,{kind:"blocked"}),!0)}function D(t,e){return Ht(t).get(e)}function rd(t,e,r){let n=Ht(t).get(e);return n?.host===r&&(n.owner.kind!=="registry"||n.connectionEpoch===t.mcpConnectionEpoch)}function cg(t){if(t!==void 0)try{return new URL(t).toString()}catch{return t}}function kr(t,e){return!t||!e?!1:t.id===e.id&&t.name===e.name&&t.type===e.type&&cg(t.url)===cg(e.url)&&t.registrySource===e.registrySource&&t.vfsSource===e.vfsSource}var Xn=class{constructor(){this._tokens=new Map;this._authRequired=new Set;this._retiredCredentials=new Set;this._credentialRetirementGenerations=new Map;this._credentialIdentities=new Map}get(e){return this._tokens.get(e)}commit(e,r,n){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e),n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e)}hasCredentialIdentity(e,r){return kr(this._credentialIdentities.get(e),r)}reconcileCredentialIdentity(e,r,n){return this._tokens.get(e)!==r||this._retiredCredentials.has(e)?!1:(n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e),!0)}set(e,r,n){this.commit(e,r,n)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,i,s){return this.persist(e,n,s)}restoreAfterSupersededRefresh(e,r,n,o,i,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,i,s)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations),credentialIdentities:new Map([...this._credentialIdentities].map(([e,r])=>[e,{...r}]))}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n);for(let[r,n]of e.credentialIdentities??[])this._credentialIdentities.set(r,{...n})}delete(e,r){this._tokens.delete(e),this._credentialIdentities.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._credentialIdentities.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};function fi(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function nd(t){try{return new URL(t).toString()}catch{return t}}function li(t){if(!(t.type!=="http"&&t.type!=="sse"))return{id:t.id,name:t.name,type:t.type,url:nd(t.url),auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Gt(t,e){return li(e.config)}function ht(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:nd(t.url)===nd(e.url)}function od(t,e){let r=li(t),n=li(e);return!r||!n?ht(t,e):kr(r,n)}function Ie(t){return/^secret:(private|shared):.+/.test(t)}function id(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function pa(t,e,r){if(r===void 0||!Ie(r))return r;let n=t.credentialRevisions?.get(e);return n?.domain===r?n.ownerDomain:void 0}function bA(t){let{state:e,name:r,expectedRegistryConfigId:n,expectedConfig:o,currentConfig:i}=t;if(o)return o;let s=n?e.registryCredentialConfigsById?.get(n):void 0;if(s?.name===r)return s;let a=e.registryCredentialConfigs?.get(r);if(a?.id===n)return a;if(i?.id===n)return i}function RA(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!ht(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function ug(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!id(e,r):n!==void 0&&e!==n}function dg(t,e,r){return r&&e!==void 0&&t!==void 0&&id(t,e)}function CA(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(i=>i!==void 0&&!id(i,n))}function lg(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:i,expectedFence:s,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(RA({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&i!==void 0&&(i.owner.kind!=="registry"||ug({identity:i.owner.identity,...l}))||o&&s?.kind==="domain"&&ug({identity:s.domain,...l})?!0:CA({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function PA(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return li(r);if(n!==void 0)return{id:n,name:e}}function xA(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:i}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!i||!li(i)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...i}))}async function fg(t,e,r,n,o){let i=t.oauthCredentialDomains?.get(e),s=t.credentialRevisions?.get(e)?.domain,a=pa(t,e,i),c=pa(t,e,s),u=t.servers?.get(e)?.config,d=bA({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:u}),l=d?.id??r,f=d?.registrySource!==void 0||d===void 0&&r!==void 0,p=d?.registrySource===void 0?void 0:`user:${d.id??d.name}`,h=lg({currentConfig:u,retiredConfig:d,expectedRegistryConfigId:r,retiresRegistryIdentity:f,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:l,retiredOwnerIdentity:p,acceptedDomain:a,currentDomain:c}),m=dg(a,l,f),g=dg(c,l,f),v=!h,w=t.tokens?.get(e)!==void 0&&i===void 0&&s===void 0,R=h&&!(v||m||g||w);if(o==="durable"){let ee=PA({name:e,retiredConfig:d,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,ee,{preserveNameState:R})}let _=lg({currentConfig:t.servers?.get(e)?.config,retiredConfig:d,expectedRegistryConfigId:r,retiresRegistryIdentity:f,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:l,retiredOwnerIdentity:p,acceptedDomain:pa(t,e,t.oauthCredentialDomains?.get(e)),currentDomain:pa(t,e,t.credentialRevisions?.get(e)?.domain)}),C=v&&!_,I=!1;return t.equalRevisionRebindDomains?.delete(e),(C||m)&&t.oauthCredentialDomains?.get(e)===i&&(t.oauthCredentialDomains.delete(e),I=!0),(C||g)&&t.credentialRevisions?.get(e)?.domain===s&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),I=!0),C&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),xA({state:t,name:e,mode:o,stillOwnsNameScopedRevision:C,retiredConfig:d}),I&&(fi(t,e),ct(t,e),t.authRefreshNeededReportKeys?.delete(e)),C}function mt(t,e,r,n){return fg(t,e,r,n,"durable")}function pi(t,e,r,n){return fg(t,e,r,n,"session")}function ha(t){let e=[];if(Object.hasOwn(t,"credential_owner_domain")&&e.push(t.credential_owner_domain),Object.hasOwn(t,"credentialOwnerDomain")&&e.push(t.credentialOwnerDomain),e.length===0)return{kind:"absent"};if(e.some(n=>typeof n!="string"||!/^user:.+/.test(n)))return{kind:"invalid"};let r=e[0];return e.every(n=>n===r)?{kind:"valid",ownerDomain:r}:{kind:"invalid"}}function Tr(t,e){let r=t.replace(/^0+(?=\d)/,""),n=e.replace(/^0+(?=\d)/,"");return r.length!==n.length?r.length<n.length?-1:1:r===n?0:r<n?-1:1}var pg="augment:mcp-oauth-credentials",hg=300*1e3,kA=256,sd=EA.child({prefix:"pi-mcp"}),kt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function He(t){return`user:${t}`}function dn(t){let{state:e,name:r,revision:n}=t;if(e.credentialRevisions??=new Map,e.oauthCredentialRevisions??=new Map,e.oauthCredentialDomains??=new Map,e.hostedCredentialOwnership?.delete(r),n===void 0){e.credentialRevisions.delete(r),e.oauthCredentialDomains.delete(r),e.authRefreshNeededReportKeys?.delete(r);return}let o={...n,revision:n.revision.replace(/^0+(?=\d)/,"")},i=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(i?.revision!==o.revision||i?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let s=e.oauthCredentialRevisions.get(o.domain);(s===void 0||Tr(o.revision,s)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function Ar(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="recipient"&&r!=="user"&&r!=="tenant"?t:He(t.slice(e+1))}function ln(t){return t.ownerDomain??Ar(t.domain)}function mg(t,e,r){let n=He(e);return r!==void 0?r===n:Ie(t)||Ar(t)===n}function TA(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function AA(t,e,r){return{acceptedDomain:t.oauthCredentialDomains.get(e),credentialRevision:t.credentialRevisions.get(e),expectedDomain:t.expectedCredentialDomains.get(e),failure:t.statusFailureCategories.get(e),restoreFailure:r}}function MA(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function $A(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&TA(t.credentialRevisions.get(e),r.credentialRevision)&&MA(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function IA(t){return JSON.stringify({id:t.id,name:t.name,type:t.type,url:t.type==="stdio"?void 0:t.url,auth:t.type==="stdio"?void 0:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource})}function OA(t){let{state:e,config:r,domain:n}=t,o=r.id===void 0?void 0:e.registryCredentialConfigsById.get(r.id);return!o||e.sessionRemovedConfigIds.has(r.id??"")||!ht(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Mr(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function ar(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function gg(t){Mr(t);let e=new Set([...t.registryCredentialConfigs.keys(),...t.registryConfigNamesById.values(),...t.oauthCredentialDomains.keys(),...t.credentialRevisions.keys(),...t.preservedCredentialIdentities?.keys()??[],...[...t.bootOAuthCredentialBuffer?.values()??[]].map(n=>n.serverName),...[...t.registryCredentialIntents.values()].flatMap(n=>n.configName?[n.configName]:[])]);for(let[n,o]of t.hostLeases)o.owner.kind==="registry"&&e.add(n);for(let n of e){let o=t.hostLeases.get(n);if(o&&o.owner.kind!=="registry")continue;t.tokens.clearLocalCredential(n);let i=t.oauthCredentialDomains.get(n);i&&t.oauthCredentialRevisions.delete(i),t.oauthCredentialDomains.delete(n),t.credentialRevisions.delete(n),t.hostedCredentialOwnership?.delete(n),t.preservedCredentialIdentities?.delete(n),t.expectedCredentialDomains.set(n,{kind:"blocked"}),t.authRefreshNeededReportKeys?.delete(n)}let r=new Set(t.oauthCredentialDomains.values());for(let n of t.oauthCredentialRevisions.keys())r.has(n)||t.oauthCredentialRevisions.delete(n);for(let n of t.bootOAuthCredentialBuffer?.keys()??[])ar(t,n);t.registryCredentialIntents.clear(),t.pendingRegistryCredentialDomains.clear(),t.stagedOAuthCredentials.clear(),t.equalRevisionRebindDomains.clear(),t.registryCredentialConfigs.clear(),t.registryCredentialConfigsById.clear(),t.registryConfigNamesById.clear(),t.mcpRestartState.clear()}function yg(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)(o.connectionEpoch!==t.mcpConnectionEpoch||e-o.insertedAtMs>=hg)&&ar(t,n)}function zA(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&ar(t,e)}function vg(t,e){let r=t?.credential_revision_domain??t?.credentialRevisionDomain;if(!(r!==e&&(Ie(e)||typeof r=="string"&&Ie(r))))return t?.credential_revision??t?.credentialRevision}function _g(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:i}=t;Mr(e),e.bootOAuthCredentialBuffer??=new Map;let s=e.bootOAuthCredentialBuffer,a=Date.now();yg(e,a);let c=ln(n),u=Ie(c)?`${c}\0${r}`:c,d=s.get(u),l=vg(d?.credential,n.domain);if(typeof l=="string"&&Tr(n.revision,l)<=0)return;!d&&s.size>=kA&&zA(e),ar(e,u);let f={serverName:r,credential:o,suppressReconnect:i,insertedAtMs:a,connectionEpoch:e.mcpConnectionEpoch,expiryTimer:void 0};s.set(u,f),f.expiryTimer=setTimeout(()=>{s.get(u)===f&&ar(e,u)},hg),f.expiryTimer.unref?.(),sd.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function NA(t,e){Mr(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function Ye(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:i=!1}=t;Mr(e);let s=e.registryCredentialIntents.get(r);if(!(n!==void 0&&s?.epoch!==n)){if(!o&&s?.configName){let a=e.expectedCredentialDomains.get(s.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(s.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),i||ar(e,r)}}function ma(t){let{state:e,domain:r,forceNew:n=!1}=t;Mr(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let i=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Ye({state:e,domain:r,epoch:o.epoch});let s={epoch:NA(e,r),configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0};return e.registryCredentialIntents.set(r,s),i!==void 0&&i.configFingerprint===void 0&&e.stagedOAuthCredentials.set(r,{...i,intentEpoch:s.epoch}),e.pendingRegistryCredentialDomains.add(r),{domain:r,...s}}function Sg(t,e){Mr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Ye({state:t,domain:r,epoch:n.epoch});for(let r of t.pendingRegistryCredentialDomains)e.has(r)||(t.pendingRegistryCredentialDomains.delete(r),t.stagedOAuthCredentials.delete(r));for(let r of t.stagedOAuthCredentials.keys())e.has(r)||t.stagedOAuthCredentials.delete(r);for(let r of t.bootOAuthCredentialBuffer?.keys()??[]){let n=r.split("\0",1)[0];!e.has(r)&&!Ie(n)&&ar(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);ma({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function DA(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||D(e,r.name)?.owner.kind==="local")return;Mr(e);let n=He(r.id),o=IA(r),i=OA({state:e,config:r,domain:n});i||e.equalRevisionRebindDomains.delete(r.name);let s=e.registryCredentialIntents.get(n);if(s&&s.configFingerprint===void 0){s.configFingerprint=o,s.configName=r.name,s.allowEqualRevisionRebind=i;let a=e.stagedOAuthCredentials.get(n);a?.intentEpoch===s.epoch&&(a.configFingerprint=o)}else s&&s.configFingerprint!==o?(Ye({state:e,domain:n,epoch:s.epoch}),s=void 0):s&&(s.allowEqualRevisionRebind=i);if(!s){let a=ma({state:e,domain:n});if(s=e.registryCredentialIntents.get(n),!s||s.epoch!==a.epoch)return;s.configFingerprint=o,s.configName=r.name,s.allowEqualRevisionRebind=i}return e.pendingRegistryCredentialDomains.add(n),LA({state:e,config:r,domain:n}),{domain:n,...s}}function wg(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Mr(e);let i=ln(r),s=e.registryCredentialIntents.get(i);if(!s||!e.pendingRegistryCredentialDomains.has(i))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(i),d=c?.intentEpoch===s.epoch&&c.configFingerprint===s.configFingerprint?vg(c.credential,r.domain):void 0,l=a===void 0?void 0:Tr(r.revision,a),f=l===0;l!==void 0&&l<0||f&&s.configFingerprint!==void 0&&!s.allowEqualRevisionRebind||typeof d=="string"&&Tr(r.revision,d)<=0||e.stagedOAuthCredentials.set(i,{credential:n,suppressReconnect:o,intentEpoch:s.epoch,configFingerprint:s.configFingerprint,requiresEqualRevisionRebind:f})}function LA(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n});let i=e.credentialRevisions.get(r.name);(o===void 0||i?.ownerDomain!==void 0&&i.ownerDomain!==n||i?.ownerDomain===void 0&&!Ie(o)&&Ar(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),ct(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function jA(t){let{state:e,config:r,pi:n,intent:o}=t,i=e.stagedOAuthCredentials.get(o.domain);if(!i||i.intentEpoch!==o.epoch||i.configFingerprint!==o.configFingerprint||i.requiresEqualRevisionRebind&&!o.allowEqualRevisionRebind)return;e.stagedOAuthCredentials.delete(o.domain),i.requiresEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),Ye({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let s={[r.name]:i.credential};n.events.emit(pg,i.suppressReconnect?{credentials:s,suppressReconnect:!0}:s)}function FA(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();yg(e,o);let i=e.bootOAuthCredentialBuffer?.get(r);if(i)return ar(e,r),i;for(let[s,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&Ie(s.split("\0",1)[0]))return ar(e,s),a}function UA(t){let{config:e,pi:r,buffered:n}=t;sd.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),sd.info("MCP OAuth boot credential replayed",{hasRegistryConfigId:e.id!==void 0,registryOwned:e.registrySource!==void 0,visibility:"public"});let o={[e.name]:n.credential};r.events.emit(pg,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function qA(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(ht(n,r)){if(n.name===r.name)return;await pi(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await mt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function HA(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:i}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=$A(e,r.name,o);Ye({state:e,domain:n.domain,epoch:n.epoch,preserveFence:!c}),c&&(e.expectedCredentialDomains.set(r.name,{kind:"blocked"}),o.restoreFailure!==void 0&&e.statusFailureCategories.set(r.name,o.restoreFailure))}let a=`Registry credential replacement failed for ${r.name}: ${i instanceof Error?i.message:String(i)}`;return e.diagnostics.push({server:r.name,message:a,origin:"registry"}),new kt(a)}async function GA(t){let{state:e,config:r,pi:n,intent:o,previousConfig:i,rollbackSnapshot:s}=t,a=e.registryCredentialIntents.get(o.domain);if(a?.epoch!==o.epoch||a.configFingerprint!==o.configFingerprint)return!1;e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let c;try{c=await qA({state:e,config:r,previousConfig:i})}catch(h){throw HA({state:e,config:r,intent:o,rollbackSnapshot:s,cause:h})}let u=e.registryCredentialIntents.get(o.domain);c&&u?.epoch===o.epoch&&e.expectedCredentialDomains.get(r.name)===c&&e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let d=e.expectedCredentialDomains.get(r.name);if(u?.epoch!==o.epoch||u.configFingerprint!==o.configFingerprint||d?.kind!=="domain"||d.domain!==o.domain)return Ye({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),jA({state:e,config:r,pi:n,intent:o});let p=FA({state:e,domain:o.domain,serverName:r.name});return Ye({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&UA({config:r,pi:n,buffered:p}),!0}function $r(t){let{state:e,config:r,pi:n}=t;if(r.id===void 0||r.registrySource===void 0)return Promise.resolve(!0);let o=e.statusFailureCategories.get(r.name),i=DA({state:e,config:r});if(!i)return Promise.resolve(!1);let s=e.registryCredentialIntents.get(i.domain);if(!s||s.epoch!==i.epoch)return Promise.resolve(!1);if(s.finalization)return s.finalization;let a=AA(e,r.name,o),u=(e.registryCredentialFinalizationsByName.get(r.name)??Promise.resolve(!0)).catch(()=>!1).then(()=>{let d=e.registryCredentialConfigs.get(r.name)??(r.id===void 0?void 0:e.registryCredentialConfigsById.get(r.id))??e.servers.get(r.name)?.config;return GA({state:e,config:r,pi:n,intent:i,previousConfig:d,rollbackSnapshot:a})});return e.registryCredentialFinalizationsByName.set(r.name,u),s.finalization=u,u.then(()=>{e.registryCredentialFinalizationsByName.get(r.name)===u&&e.registryCredentialFinalizationsByName.delete(r.name)},()=>{e.registryCredentialFinalizationsByName.get(r.name)===u&&e.registryCredentialFinalizationsByName.delete(r.name)}),u}import{SettingsManager as nM}from"@augmentcode/auggie-v2";import{homedir as bg}from"node:os";import{sep as ZA}from"node:path";var ad=class extends Error{constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},BA=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,WA=/\\\$\{/g,VA=new Set(["workspaceFolder","augmentToken"]),Rg="${workspaceFolder}";function Cg(t,e){return t.includes(Rg)?t.split(Rg).join(e):t}function Pg(t,e){return t.includes("${")?t.replace(BA,(n,o,i)=>{if(VA.has(o))return n;let s=e[o];if(s!==void 0)return s;if(i!==void 0)return i;throw new ad(o)}).replace(WA,"${"):t}function KA(t){return t.startsWith("~")?t==="~"?bg():t.startsWith("~/")||t.startsWith(`~${ZA}`)?bg()+t.slice(1):t:t}function cd(t,e,r){return KA(Pg(Cg(t,e),r))}function Qn(t,e,r){return Pg(Cg(t,e),r)}function xg(t,e,r){let n={};for(let[o,i]of Object.entries(t))n[o]=Qn(i,e,r);return n}var JA="$augment-";function YA(t,e,r){if(!t)return;let n={};for(let[o,i]of Object.entries(t))n[o]=i.startsWith(JA)?i:Qn(i,e,r);return n}function Zt(t,e){let r=process.env;return{...t,url:Qn(t.url,e,r),headers:YA(t.headers,e,r)}}function Bt(t,e){let r=process.env;return{...t,command:cd(t.command,e,r),args:t.args.map(n=>Qn(n,e,r)),env:t.env?xg(t.env,e,r):void 0,cwd:t.cwd?cd(t.cwd,e,r):e}}import{readFileSync as QA}from"node:fs";var Tt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function eo(t){if(t.type==="stdio"||t.type==="http"||t.type==="sse")return t.type;if(t.url)return"http";if(t.command)return"stdio"}function XA(t){if(!t)return;let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=String(n));return Object.keys(e).length>0?e:void 0}function to(t,e){let r=eo(e);if(!r)throw new Tt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Tt(`MCP server "${t}" has type "${r}" but no 'url' property`);let a=typeof e.clientId=="string"?e.clientId.trim():void 0;return{type:r,name:e.name??t,disabled:e.disabled,url:e.url,headers:e.headers,auth:e.auth==="oauth"?"oauth":void 0,...a?{clientId:a}:{},timeoutMs:e.timeoutMs}}let n=e.command;if(!n)throw new Tt(`MCP server "${t}" has type "stdio" but no 'command' property`);let o=(e.args??[]).map(a=>String(a)),i=e.useShellInterpolation??!0,s=i&&o.length>0?`${n} ${o.join(" ")}`:n;return{type:"stdio",name:e.name??t,disabled:e.disabled,command:s,args:i?[]:o,env:XA(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:i}}var Tg=t=>QA(t,"utf8");function ga(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Eg(t){return ga(t)&&("command"in t||"url"in t)}function dd(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function kg(t,e){return dd(t.name)??e}function ud(t,e){let r=eo(t);if(r==="http"||r==="sse")return dd(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return dd(t.name,t.title,n)??e}function eM(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[ud(n,String(r)),n]});if(ga(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,i)=>{let s=o;return[ud(s,String(i)),s]})}for(let r of["servers","mcpServers"]){let n=t[r];if(ga(n))return Object.entries(n).map(([o,i])=>{let s=i;return[kg(s,o),s]})}if(Eg(t)){let r=t;return[[ud(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(Eg))return Object.entries(t).map(([r,n])=>{if(!ga(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[kg(o,r),o]})}throw new Error("unrecognized MCP config JSON shape (expected an array of servers, a { servers|mcpServers } array/record, a single server object, or a Claude-Desktop-style record)")}function ld(t){return t instanceof Error?t.message:String(t)}function tM(t,e,r,n,o){if(r)return e;try{return n(t)}catch(i){o.push({message:`Failed to read --mcp-config file "${t}": ${ld(i)}`});return}}function rM(t,e,r){let n=t.trim();if(n.length===0)return[];let o=n.startsWith("[")||n.startsWith("{"),i=o?"inline JSON":`file "${t}"`,s=tM(t,n,o,e,r);if(s===void 0)return[];let a;try{a=JSON.parse(s)}catch(c){return r.push({message:`Failed to parse --mcp-config ${i}: ${ld(c)}`}),[]}try{return eM(a)}catch(c){return r.push({message:`Invalid --mcp-config ${i}: ${ld(c)}`}),[]}}function fd(t,e=Tg){let r={},n=[];for(let o of t)for(let[i,s]of rM(o,e,n))r[i]=s;return{servers:r,diagnostics:n}}function pd(t,e=Tg){return!t||t.length===0?new Set:new Set(Object.keys(fd(t,e).servers))}var oM=["global","project","local","managed"];function iM(t,e){switch(e){case"global":return t.getGlobalSettings().mcpServers;case"project":return t.getProjectSettings().mcpServers;case"local":return t.getLocalSettings().mcpServers;case"managed":return t.getManagedSettings().mcpServers}}function sM(t){let e={};for(let r of t)if(r)for(let[n,o]of Object.entries(r)){if(o===null){delete e[n];continue}o&&(e[n]=structuredClone(o))}return e}function aM(t,e,r){let n=fd(t);r.push(...n.diagnostics);let o=n.servers;if(!e||e.size===0)return o;for(let[i,s]of Object.entries(o)){let a=e.get(i);a!==void 0&&(o[i]={...s,disabled:a})}return o}function cM(t,e,r){let n=nM.create(t,e);for(let{scope:o,error:i}of n.drainErrors()){let s=i.message.includes("parse settings JSON")?"parse":"read";r.push({message:`Failed to ${s} ${o} settings.json: ${i.message}`})}return sM(oM.map(o=>iM(n,o)))}function ro(t,e,r,n){let o=[],i=r!==void 0&&r.length>0,s=i?aM(r,n,o):cM(t,e,o),a=[];for(let[c,u]of Object.entries(s))try{let d=to(c,i?u:{...u,name:c});a.push(d.type==="stdio"?Bt(d,t):Zt(d,t))}catch(d){let l=d instanceof Tt?d.message:`Failed to normalize MCP server "${c}": ${d instanceof Error?d.message:String(d)}`;o.push({server:c,message:l})}return{servers:a,diagnostics:o}}import{recordToolCallMcpServer as SM,setToolSource as Ng}from"@augmentcode/auggie-v2";import{logger as wM}from"@hermes/logger";import{Type as bM}from"@sinclair/typebox";var ya=Symbol.for("__pi_mcp_state__");function uM(t,e){return t.id!==e.id||t.type!==e.type||t.type==="stdio"||e.type==="stdio"||t.auth!=="oauth"||e.auth!=="oauth"?!1:t.url===e.url&&t.auth===e.auth}function dM(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function lM(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([s,a])=>s!==r.name&&a.id===e&&uM(a,r)).map(([s])=>s),o=n.some(s=>{let a=t.oauthCredentialDomains.get(s);return a!==void 0&&dM(a,e)}),i=t.expectedCredentialDomains.get(r.name);if(!(!o||t.sessionRemovedConfigIds.has(e)||t.oauthCredentialDomains.has(r.name)||i?.kind!=="domain"||i.domain!==`user:${e}`)){t.equalRevisionRebindDomains.set(r.name,i.domain);for(let s of n)t.tokens.clearLocalCredential(s),t.oauthCredentialDomains.delete(s),t.credentialRevisions.delete(s),t.hostedCredentialOwnership?.delete(s),t.preservedCredentialIdentities?.delete(s),t.statusFailureCategories?.delete(s),t.authRefreshNeededReportKeys?.delete(s),t.expectedCredentialDomains.set(s,{kind:"blocked"})}}}function fM(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.initialConnectPromise??=null,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.transientReconnects??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let i=n;i.intentEpoch??=o.epoch,i.configFingerprint??=o.configFingerprint,i.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&lM(t),t.authenticationGeneration??=0,t.authenticatingServerName??=void 0,t.liveEditGenerations??=new Map,t.blockedVfsMcpNames??=new Set,t.pluginServerHosts||(t.pluginServerHosts=new Map),t.toolRegistrationsByPi??=new WeakMap,t.hostLeases??=new Map,t.hostLeaseRevisions??=new Map,t.expectedCredentialDomains??=new Map;for(let[r,n]of t.servers)n.config!==void 0&&te(t,r,n);t.pluginReconcileQueue??=Promise.resolve(),t.mcpAttachDisabled??=!1,t.mcpAttachCloudSignaled??=!1,t.attachResolvers??=new Map,t.attachResultListenerBound??=!1,t.cloudModeListenerBound??=!1,t.attachmentCommandGenerations??=new Map,t.attachmentCommandInFlightGenerations??=new Map,t.attachmentCommandAppliedGenerations??=new Map}async function hi(t,e){for(;;){let r=t.missingHostRemovals.get(e);if(!r)return;try{await r.promise}catch{}if(t.missingHostRemovals.get(e)===r)return}}function no(t){let{state:e,configId:r,generation:n}=t;e.attachmentCommandGenerations??=new Map,e.attachmentCommandInFlightGenerations??=new Map,e.attachmentCommandAppliedGenerations??=new Map;let o=e.attachmentCommandGenerations.get(r)??0;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o===0:n<o||n===e.attachmentCommandInFlightGenerations.get(r)||n===e.attachmentCommandAppliedGenerations.get(r)?!1:(e.attachmentCommandGenerations.set(r,n),e.attachmentCommandInFlightGenerations.set(r,n),!0)}function hd(t){let{state:e,configId:r,generation:n}=t;typeof n!="number"||n<=0||(e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r),e.attachmentCommandGenerations?.get(r)===n&&(e.attachmentCommandAppliedGenerations??=new Map,e.attachmentCommandAppliedGenerations.set(r,n)))}function va(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function _a(t){let{state:e,configId:r,generation:n,operation:o,wasApplied:i}=t;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o:o.then(s=>(i()?hd({state:e,configId:r,generation:n}):va({state:e,configId:r,generation:n}),s),s=>{throw va({state:e,configId:r,generation:n}),s})}function Y(){let t=globalThis;if(t[ya])return fM(t[ya]),t[ya];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Xn,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations:new Map,transientReconnects:new Map,serverGenerations:new Map,configRevisions:new Map,configDesiredRevisions:new Map,configDesiredSources:new Map,credentialRevisions:new Map,oauthCredentialRevisions:new Map,oauthCredentialDomains:new Map,equalRevisionRebindDomains:new Map,preservedCredentialIdentities:new Map,stagedOAuthCredentials:new Map,bootOAuthCredentialBuffer:new Map,pendingRegistryCredentialDomains:new Set,registryCredentialIntents:new Map,registryCredentialIntentEpochs:new Map,registryCredentialFinalizationsByName:new Map,statusHostGeneration:1,statusReportSequence:0,statusFailureCategories:new Map,authRefreshNeededReportKeys:new Map,hostedCredentialOwnership:new Map,shouldProactivelyRefreshTokens:!0,backgroundRefreshIntervalId:void 0,credsListenerBound:!1,configIdsListenerBound:!1,registryGeneration:0,liveEditGenerations:new Map,attachmentCommandGenerations:new Map,attachmentCommandInFlightGenerations:new Map,attachmentCommandAppliedGenerations:new Map,mcpConfigsListenerBound:!1,embeddedRegistryConfigs:void 0,vfsListenerBound:!1,addServerListenerBound:!1,restartServerListenerBound:!1,removeServerListenerBound:!1,mcpRestartState:new Map,vfsGeneration:0,lastSuccessfulVfsMcpSignature:void 0,blockedVfsMcpNames:new Set,credentials:void 0,secretsClient:void 0,headerSecrets:{},headerSecretFailures:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,initialConnectPromise:null,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,authFallbackDisplacedConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,oauthFailureCategoriesByConfigId:void 0,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1,isCloudMode:void 0,cloudModeListenerBound:!1};return t[ya]=e,e}var Ag=Symbol.for("__hermes_mcp_tool_registry__"),Mg=Symbol.for("__hermes_mcp_tool_server_registry__"),pM=Symbol.for("__hermes_mcp_extension_factory__");function gd(){let t=globalThis;return t[Ag]??=new Map,t[Ag]}function md(){let t=globalThis;return t[Mg]??=new Map,t[Mg]}function $g(t){return gd().get(t)}function Ir(t,e){gd().set(t.name,t),e===void 0?md().delete(t.name):md().set(t.name,e)}function oo(t,e){let r=gd();(e===void 0||r.get(t)===e)&&(r.delete(t),md().delete(t))}function Ig(t){Reflect.set(t,pM,!0)}function Sa(t,e,r,n){return r.includes(t)?n.includes(t)?`"${t}" is a built-in tool, not an MCP server. Call it directly.`:`Built-in tool "${t}" is not available (disabled).`:`MCP server "${t}" is not available (status: ${e??"unknown"}).`}function hM(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function mM(t){let e=[];for(let r of t)r.type==="text"?e.push({type:"text",text:r.text}):e.push({type:"image",mimeType:r.mimeType,data:r.data});return e}function gM(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
|
|
9
|
-
`).trim()}function
|
|
8
|
+
deps: ${r}}`};var iU={keyword:"dependencies",type:"object",schemaType:"object",error:er.error,code(t){let[e,r]=sU(t);CP(t,e),PP(t,r)}};function sU({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function CP(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let i=r.let("missing");for(let s in e){let a=e[s];if(a.length===0)continue;let c=(0,Ys.propertyInData)(r,n,s,o.opts.ownProperties);t.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ys.checkReportMissingProp)(t,u)}):(r.if((0,wh._)`${c} && (${(0,Ys.checkMissingProp)(t,a,i)})`),(0,Ys.reportMissingProp)(t,i),r.else())}}er.validatePropertyDeps=CP;function PP(t,e=t.schema){let{gen:r,data:n,keyword:o,it:i}=t,s=r.name("valid");for(let a in e)(0,oU.alwaysValidSchema)(i,e[a])||(r.if((0,Ys.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},s);t.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),t.ok(s))}er.validateSchemaDeps=PP;er.default=iU});var kP=P(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var xP=j(),aU=B(),cU={message:"property name must be valid",params:({params:t})=>(0,xP._)`{propertyName: ${t.propertyName}}`},uU={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:cU,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,aU.alwaysValidSchema)(o,r))return;let i=e.name("valid");e.forIn("key",n,s=>{t.setParams({propertyName:s}),t.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),e.if((0,xP.not)(i),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(i)}};bh.default=uU});var Ch=P(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var cu=Ct(),jt=j(),dU=Sr(),uu=B(),lU={message:"must NOT have additional properties",params:({params:t})=>(0,jt._)`{additionalProperty: ${t.additionalProperty}}`},fU={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:lU,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=t;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,uu.alwaysValidSchema)(s,r))return;let u=(0,cu.allSchemaProperties)(n.properties),d=(0,cu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,jt._)`${i} === ${dU.default.errors}`);function l(){e.forIn("key",o,m=>{!u.length&&!d.length?h(m):e.if(f(m),()=>h(m))})}function f(m){let v;if(u.length>8){let w=(0,uu.schemaRefOrVal)(s,n.properties,"properties");v=(0,cu.isOwnProperty)(e,w,m)}else u.length?v=(0,jt.or)(...u.map(w=>(0,jt._)`${m} === ${w}`)):v=jt.nil;return d.length&&(v=(0,jt.or)(v,...d.map(w=>(0,jt._)`${(0,cu.usePattern)(t,w)}.test(${m})`))),(0,jt.not)(v)}function p(m){e.code((0,jt._)`delete ${o}[${m}]`)}function h(m){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(m);return}if(r===!1){t.setParams({additionalProperty:m}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,uu.alwaysValidSchema)(s,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(m,v,!1),e.if((0,jt.not)(v),()=>{t.reset(),p(m)})):(g(m,v),a||e.if((0,jt.not)(v),()=>e.break()))}}function g(m,v,w){let b={keyword:"additionalProperties",dataProp:m,dataPropType:uu.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};Rh.default=fU});var MP=P(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var pU=Ds(),TP=Ct(),Ph=B(),AP=Ch(),hU={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:i}=t;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&AP.default.code(new pU.KeywordCxt(i,AP.default,"additionalProperties"));let s=(0,TP.allSchemaProperties)(r);for(let l of s)i.definedProperties.add(l);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Ph.mergeEvaluated.props(e,(0,Ph.toHash)(s),i.props));let a=s.filter(l=>!(0,Ph.alwaysValidSchema)(i,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,TP.propertyInData)(e,o,l,i.opts.ownProperties)),d(l),i.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return i.opts.useDefaults&&!i.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};Eh.default=hU});var zP=P(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var $P=Ct(),du=j(),IP=B(),OP=B(),mU={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:i}=t,{opts:s}=i,a=(0,$P.allSchemaProperties)(r),c=a.filter(g=>(0,IP.alwaysValidSchema)(i,r[g]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&o.properties,d=e.name("valid");i.props!==!0&&!(i.props instanceof du.Name)&&(i.props=(0,OP.evaluatedPropsToName)(e,i.props));let{props:l}=i;f();function f(){for(let g of a)u&&p(g),i.allErrors?h(g):(e.var(d,!0),h(g),e.if(d))}function p(g){for(let m in u)new RegExp(g).test(m)&&(0,IP.checkStrictMode)(i,`property ${m} matches pattern ${g} (use allowMatchingProperties)`)}function h(g){e.forIn("key",n,m=>{e.if((0,du._)`${(0,$P.usePattern)(t,g)}.test(${m})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:m,dataPropType:OP.Type.Str},d),i.opts.unevaluated&&l!==!0?e.assign((0,du._)`${l}[${m}]`,!0):!v&&!i.allErrors&&e.if((0,du.not)(d),()=>e.break())})})}}};xh.default=mU});var NP=P(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var gU=B(),yU={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,gU.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};kh.default=yU});var DP=P(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var vU=Ct(),_U={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:vU.validateUnion,error:{message:"must match a schema in anyOf"}};Th.default=_U});var LP=P(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var lu=j(),SU=B(),wU={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,lu._)`{passingSchemas: ${t.passing}}`},bU={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wU,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(s,()=>t.reset(),()=>t.error(!0));function u(){i.forEach((d,l)=>{let f;(0,SU.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,lu._)`${c} && ${s}`).assign(s,!1).assign(a,(0,lu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(s,!0),e.assign(a,l),f&&t.mergeEvaluated(f,lu.Name)})})}}};Ah.default=bU});var jP=P(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var RU=B(),CU={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((i,s)=>{if((0,RU.alwaysValidSchema)(n,i))return;let a=t.subschema({keyword:"allOf",schemaProp:s},o);t.ok(o),t.mergeEvaluated(a)})}};Mh.default=CU});var qP=P($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var fu=j(),UP=B(),PU={message:({params:t})=>(0,fu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,fu._)`{failingKeyword: ${t.ifClause}}`},EU={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:PU,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,UP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=FP(n,"then"),i=FP(n,"else");if(!o&&!i)return;let s=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&i){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,fu.not)(a),u("else"));t.pass(s,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},a);e.assign(s,a),t.mergeValidEvaluated(f,s),l?e.assign(l,(0,fu._)`${d}`):t.setParams({ifClause:d})}}}};function FP(t,e){let r=t.schema[e];return r!==void 0&&!(0,UP.alwaysValidSchema)(t,r)}$h.default=EU});var HP=P(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var xU=B(),kU={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,xU.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ih.default=kU});var GP=P(Oh=>{"use strict";Object.defineProperty(Oh,"__esModule",{value:!0});var TU=gh(),AU=SP(),MU=yh(),$U=bP(),IU=RP(),OU=EP(),zU=kP(),NU=Ch(),DU=MP(),LU=zP(),jU=NP(),FU=DP(),UU=LP(),qU=jP(),HU=qP(),GU=HP();function ZU(t=!1){let e=[jU.default,FU.default,UU.default,qU.default,HU.default,GU.default,zU.default,NU.default,OU.default,DU.default,LU.default];return t?e.push(AU.default,$U.default):e.push(TU.default,MU.default),e.push(IU.default),e}Oh.default=ZU});var ZP=P(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var Pe=j(),BU={message:({schemaCode:t})=>(0,Pe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Pe._)`{format: ${t}}`},WU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BU,code(t,e){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),g=r.const("fDef",(0,Pe._)`${h}[${s}]`),m=r.let("fType"),v=r.let("format");r.if((0,Pe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(m,(0,Pe._)`${g}.type || "string"`).assign(v,(0,Pe._)`${g}.validate`),()=>r.assign(m,(0,Pe._)`"string"`).assign(v,g)),t.fail$data((0,Pe.or)(w(),b()));function w(){return c.strictSchema===!1?Pe.nil:(0,Pe._)`${s} && !${v}`}function b(){let R=d.$async?(0,Pe._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Pe._)`${v}(${n})`,_=(0,Pe._)`(typeof ${v} == "function" ? ${R} : ${v}.test(${n}))`;return(0,Pe._)`${v} && ${v} !== true && ${m} === ${e} && !${_}`}}function p(){let h=l.formats[i];if(!h){w();return}if(h===!0)return;let[g,m,v]=b(h);g===e&&t.pass(R());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function b(_){let C=_ instanceof RegExp?(0,Pe.regexpCode)(_):c.code.formats?(0,Pe._)`${c.code.formats}${(0,Pe.getProperty)(i)}`:void 0,I=r.scopeValue("formats",{key:i,ref:_,code:C});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,Pe._)`${I}.validate`]:["string",_,I]}function R(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Pe._)`await ${v}(${n})`}return typeof m=="function"?(0,Pe._)`${v}(${n})`:(0,Pe._)`${v}.test(${n})`}}}};zh.default=WU});var BP=P(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var VU=ZP(),KU=[VU.default];Nh.default=KU});var WP=P(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.contentVocabulary=Zo.metadataVocabulary=void 0;Zo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var KP=P(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var JU=rP(),YU=gP(),XU=GP(),QU=BP(),VP=WP(),eq=[JU.default,YU.default,(0,XU.default)(),QU.default,VP.metadataVocabulary,VP.contentVocabulary];Dh.default=eq});var YP=P(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.DiscrError=void 0;var JP;(function(t){t.Tag="tag",t.Mapping="mapping"})(JP||(pu.DiscrError=JP={}))});var QP=P(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var Bo=j(),Lh=YP(),XP=Vc(),tq=Ls(),rq=B(),nq={message:({params:{discrError:t,tagName:e}})=>t===Lh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Bo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},oq={keyword:"discriminator",type:"object",schemaType:"object",error:nq,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:i}=t,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Bo._)`${r}${(0,Bo.getProperty)(a)}`);e.if((0,Bo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Lh.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Bo._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:Lh.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(g,Bo.Name),h}function f(){var p;let h={},g=v(o),m=!0;for(let R=0;R<s.length;R++){let _=s[R];if(_?.$ref&&!(0,rq.schemaHasRulesButRef)(_,i.self.RULES)){let I=_.$ref;if(_=XP.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,I),_ instanceof XP.SchemaEnv&&(_=_.schema),_===void 0)throw new tq.default(i.opts.uriResolver,i.baseId,I)}let C=(p=_?.properties)===null||p===void 0?void 0:p[a];if(typeof C!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);m=m&&(g||v(_)),w(C,R)}if(!m)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:R}){return Array.isArray(R)&&R.includes(a)}function w(R,_){if(R.const)b(R.const,_);else if(R.enum)for(let C of R.enum)b(C,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(R,_){if(typeof R!="string"||R in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[R]=_}}}};jh.default=oq});var eE=P((UY,iq)=>{iq.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Uh=P((le,Fh)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var sq=JC(),aq=KP(),cq=QP(),tE=eE(),uq=["/properties"],hu="http://json-schema.org/draft-07/schema",Wo=class extends sq.default{_addVocabularies(){super._addVocabularies(),aq.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(cq.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(tE,uq):tE;this.addMetaSchema(e,hu,!1),this.refs["http://json-schema.org/schema"]=hu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hu)?hu:void 0)}};le.Ajv=Wo;Fh.exports=le=Wo;Fh.exports.Ajv=Wo;Object.defineProperty(le,"__esModule",{value:!0});le.default=Wo;var dq=Ds();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return dq.KeywordCxt}});var Vo=j();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var lq=Bc();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return lq.default}});var fq=Ls();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return fq.default}})});var uE=P(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.formatNames=rr.fastFormats=rr.fullFormats=void 0;function tr(t,e){return{validate:t,compare:e}}rr.fullFormats={date:tr(iE,Zh),time:tr(Hh(!0),Bh),"date-time":tr(rE(!0),aE),"iso-time":tr(Hh(),sE),"iso-date-time":tr(rE(),cE),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:vq,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:Pq,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_q,int32:{type:"number",validate:bq},int64:{type:"number",validate:Rq},float:{type:"number",validate:oE},double:{type:"number",validate:oE},password:!0,binary:!0};rr.fastFormats={...rr.fullFormats,date:tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zh),time:tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Bh),"date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,aE),"iso-time":tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,sE),"iso-date-time":tr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,cE),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};rr.formatNames=Object.keys(rr.fullFormats);function pq(t){return t%4===0&&(t%100!==0||t%400===0)}var hq=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,mq=[0,31,28,31,30,31,30,31,31,30,31,30,31];function iE(t){let e=hq.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&pq(r)?29:mq[n])}function Zh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var qh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hh(t){return function(r){let n=qh.exec(r);if(!n)return!1;let o=+n[1],i=+n[2],s=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let l=i-d*c,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&s<61}}function Bh(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function sE(t,e){if(!(t&&e))return;let r=qh.exec(t),n=qh.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Gh=/t|\s/i;function rE(t){let e=Hh(t);return function(n){let o=n.split(Gh);return o.length===2&&iE(o[0])&&e(o[1])}}function aE(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function cE(t,e){if(!(t&&e))return;let[r,n]=t.split(Gh),[o,i]=e.split(Gh),s=Zh(r,o);if(s!==void 0)return s||Bh(n,i)}var gq=/\/|:/,yq=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function vq(t){return gq.test(t)&&yq.test(t)}var nE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function _q(t){return nE.lastIndex=0,nE.test(t)}var Sq=-(2**31),wq=2**31-1;function bq(t){return Number.isInteger(t)&&t<=wq&&t>=Sq}function Rq(t){return Number.isInteger(t)}function oE(){return!0}var Cq=/[^\\]\\Z/;function Pq(t){if(Cq.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var dE=P(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.formatLimitDefinition=void 0;var Eq=Uh(),Ft=j(),on=Ft.operators,mu={formatMaximum:{okStr:"<=",ok:on.LTE,fail:on.GT},formatMinimum:{okStr:">=",ok:on.GTE,fail:on.LT},formatExclusiveMaximum:{okStr:"<",ok:on.LT,fail:on.GTE},formatExclusiveMinimum:{okStr:">",ok:on.GT,fail:on.LTE}},xq={message:({keyword:t,schemaCode:e})=>(0,Ft.str)`should be ${mu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ft._)`{comparison: ${mu[t].okStr}, limit: ${e}}`};Ko.formatLimitDefinition={keyword:Object.keys(mu),type:"string",schemaType:"string",$data:!0,error:xq,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:i}=t,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new Eq.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=e.const("fmt",(0,Ft._)`${f}[${c.schemaCode}]`);t.fail$data((0,Ft.or)((0,Ft._)`typeof ${p} != "object"`,(0,Ft._)`${p} instanceof RegExp`,(0,Ft._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:s.code.formats?(0,Ft._)`${s.code.formats}${(0,Ft.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,Ft._)`${f}.compare(${r}, ${n}) ${mu[o].fail} 0`}},dependencies:["format"]};var kq=t=>(t.addKeyword(Ko.formatLimitDefinition),t);Ko.default=kq});var hE=P((Xs,pE)=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var Jo=uE(),Tq=dE(),Wh=j(),lE=new Wh.Name("fullFormats"),Aq=new Wh.Name("fastFormats"),Vh=(t,e={keywords:!0})=>{if(Array.isArray(e))return fE(t,e,Jo.fullFormats,lE),t;let[r,n]=e.mode==="fast"?[Jo.fastFormats,Aq]:[Jo.fullFormats,lE],o=e.formats||Jo.formatNames;return fE(t,o,r,n),e.keywords&&(0,Tq.default)(t),t};Vh.get=(t,e="full")=>{let n=(e==="fast"?Jo.fastFormats:Jo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function fE(t,e,r,n){var o,i;(o=(i=t.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,Wh._)`require("ajv-formats/dist/formats").${n}`);for(let s of e)t.addFormat(s,r[s])}pE.exports=Xs=Vh;Object.defineProperty(Xs,"__esModule",{value:!0});Xs.default=Vh});var RE=P((t7,bE)=>{bE.exports=wE;wE.sync=Oq;var _E=Er("fs");function Iq(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var n=0;n<r.length;n++){var o=r[n].toLowerCase();if(o&&t.substr(-o.length).toLowerCase()===o)return!0}return!1}function SE(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:Iq(e,r)}function wE(t,e,r){_E.stat(t,function(n,o){r(n,n?!1:SE(o,t,e))})}function Oq(t,e){return SE(_E.statSync(t),t,e)}});var kE=P((r7,xE)=>{xE.exports=PE;PE.sync=zq;var CE=Er("fs");function PE(t,e,r){CE.stat(t,function(n,o){r(n,n?!1:EE(o,e))})}function zq(t,e){return EE(CE.statSync(t),e)}function EE(t,e){return t.isFile()&&Nq(t,e)}function Nq(t,e){var r=t.mode,n=t.uid,o=t.gid,i=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),s=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),a=parseInt("100",8),c=parseInt("010",8),u=parseInt("001",8),d=a|c,l=r&u||r&c&&o===s||r&a&&n===i||r&d&&i===0;return l}});var AE=P((o7,TE)=>{var n7=Er("fs"),Su;process.platform==="win32"||global.TESTING_WINDOWS?Su=RE():Su=kE();TE.exports=Kh;Kh.sync=Dq;function Kh(t,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(n,o){Kh(t,e||{},function(i,s){i?o(i):n(s)})})}Su(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function Dq(t,e){try{return Su.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var DE=P((i7,NE)=>{var Yo=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",ME=Er("path"),Lq=Yo?";":":",$E=AE(),IE=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),OE=(t,e)=>{let r=e.colon||Lq,n=t.match(/\//)||Yo&&t.match(/\\/)?[""]:[...Yo?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Yo?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",i=Yo?o.split(r):[""];return Yo&&t.indexOf(".")!==-1&&i[0]!==""&&i.unshift(""),{pathEnv:n,pathExt:i,pathExtExe:o}},zE=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:i}=OE(t,e),s=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&s.length?d(s):l(IE(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=ME.join(p,t),g=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(g,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];$E(u+h,{pathExt:i},(g,m)=>{if(!g&&m)if(e.all)s.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},jq=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=OE(t,e),i=[];for(let s=0;s<r.length;s++){let a=r[s],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=ME.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if($E.sync(f,{pathExt:o}))if(e.all)i.push(f);else return f}catch{}}}if(e.all&&i.length)return i;if(e.nothrow)return null;throw IE(t)};NE.exports=zE;zE.sync=jq});var jE=P((s7,Jh)=>{"use strict";var LE=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Jh.exports=LE;Jh.exports.default=LE});var HE=P((a7,qE)=>{"use strict";var FE=Er("path"),Fq=DE(),Uq=jE();function UE(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,i=o&&process.chdir!==void 0&&!process.chdir.disabled;if(i)try{process.chdir(t.options.cwd)}catch{}let s;try{s=Fq.sync(t.command,{path:r[Uq({env:r})],pathExt:e?FE.delimiter:void 0})}catch{}finally{i&&process.chdir(n)}return s&&(s=FE.resolve(o?t.options.cwd:"",s)),s}function qq(t){return UE(t)||UE(t,!0)}qE.exports=qq});var GE=P((c7,Xh)=>{"use strict";var Yh=/([()\][%!^"`<>&|;, *?])/g;function Hq(t){return t=t.replace(Yh,"^$1"),t}function Gq(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Yh,"^$1"),e&&(t=t.replace(Yh,"^$1")),t}Xh.exports.command=Hq;Xh.exports.argument=Gq});var BE=P((u7,ZE)=>{"use strict";ZE.exports=/^#!(.*)/});var VE=P((d7,WE)=>{"use strict";var Zq=BE();WE.exports=(t="")=>{let e=t.match(Zq);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var JE=P((l7,KE)=>{"use strict";var Qh=Er("fs"),Bq=VE();function Wq(t){let r=Buffer.alloc(150),n;try{n=Qh.openSync(t,"r"),Qh.readSync(n,r,0,150,0),Qh.closeSync(n)}catch{}return Bq(r.toString())}KE.exports=Wq});var ex=P((f7,QE)=>{"use strict";var Vq=Er("path"),YE=HE(),XE=GE(),Kq=JE(),Jq=process.platform==="win32",Yq=/\.(?:com|exe)$/i,Xq=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Qq(t){t.file=YE(t);let e=t.file&&Kq(t.file);return e?(t.args.unshift(t.file),t.command=e,YE(t)):t.file}function eH(t){if(!Jq)return t;let e=Qq(t),r=!Yq.test(e);if(t.options.forceShell||r){let n=Xq.test(e);t.command=Vq.normalize(t.command),t.command=XE.command(t.command),t.args=t.args.map(i=>XE.argument(i,n));let o=[t.command].concat(t.args).join(" ");t.args=["/d","/s","/c",`"${o}"`],t.command=process.env.comspec||"cmd.exe",t.options.windowsVerbatimArguments=!0}return t}function tH(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let n={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?n:eH(n)}QE.exports=tH});var nx=P((p7,rx)=>{"use strict";var em=process.platform==="win32";function tm(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function rH(t,e){if(!em)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let i=tx(o,e);if(i)return r.call(t,"error",i)}return r.apply(t,arguments)}}function tx(t,e){return em&&t===1&&!e.file?tm(e.original,"spawn"):null}function nH(t,e){return em&&t===1&&!e.file?tm(e.original,"spawnSync"):null}rx.exports={hookChildProcess:rH,verifyENOENT:tx,verifyENOENTSync:nH,notFoundError:tm}});var sx=P((h7,Xo)=>{"use strict";var ox=Er("child_process"),rm=ex(),nm=nx();function ix(t,e,r){let n=rm(t,e,r),o=ox.spawn(n.command,n.args,n.options);return nm.hookChildProcess(o,n),o}function oH(t,e,r){let n=rm(t,e,r),o=ox.spawnSync(n.command,n.args,n.options);return o.error=o.error||nm.verifyENOENTSync(o.status,n),o}Xo.exports=ix;Xo.exports.spawn=ix;Xo.exports.sync=oH;Xo.exports._parse=rm;Xo.exports._enoent=nm});import{logger as SB}from"@hermes/logger";import{logger as QG,logPublic as nk}from"@hermes/logger";var tA="mcp-auth";function Se(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(tA,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as RG}from"@augmentcode/auggie-v2";import{logger as CG}from"@hermes/logger";import{logger as NA}from"@hermes/logger";import{logger as nA}from"@hermes/logger";function rA(t,e,r){let n=r?.get(t.name);return n!==void 0?n.host===t&&n.owner.kind==="plugin":e?.get(t.name)===t}function xr(t,e,r){let n=r?.get(t.name);if(n?.host===t)return n.owner.kind;let o=t.config;return o?.vfsSource!==void 0?"vfs":o?.registrySource!==void 0?"registry":rA(t,e,r)?"plugin":"local"}function oA(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var rg=nA.child({prefix:"pi-mcp"}),iA="augment:mcp-status-report";function ct(t,e,r){let n=t.servers.get(e),o=n?.hostedCredentialProvenance;if(o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0)return{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain};let i=n?.targetCredentialProvenance?n.targetCredentialProvenance.credential:t.credentialRevisions?.get(e);return{serverGeneration:t.serverGenerations?.get(e)??0,mcpConfigId:r??n?.config.id,credentialRevision:i?.revision,credentialRevisionDomain:i?.domain}}function ci(t,e,r,n){let o=ct(t,e);return o.serverGeneration!==n.serverGeneration||o.mcpConfigId!==n.mcpConfigId||o.credentialRevision!==n.credentialRevision||o.credentialRevisionDomain!==n.credentialRevisionDomain?!1:(t.statusFailureCategories??=new Map,t.statusFailureCategories.set(e,{category:r,...n}),!0)}function ut(t,e,r){if(r){let o=ct(t,e);if(o.serverGeneration!==r.serverGeneration||o.mcpConfigId!==r.mcpConfigId||o.credentialRevision!==r.credentialRevision||o.credentialRevisionDomain!==r.credentialRevisionDomain)return!1}let n=t.statusFailureCategories?.get(e);return t.statusFailureCategories?.delete(e),typeof n=="object"&&n.category==="auth_refresh_needed"&&t.authRefreshNeededReportKeys?.delete(e),!0}function sA(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=ct(t,e);if(r?.serverGeneration===n.serverGeneration&&r.mcpConfigId===n.mcpConfigId&&r.credentialRevision===n.credentialRevision&&r.credentialRevisionDomain===n.credentialRevisionDomain)return r.category;t.statusFailureCategories.delete(e),t.authRefreshNeededReportKeys?.delete(e)}var ua=3e4;function aA(t){switch(t.status){case"success":return"connected";case"failed":case"auth_required":return"failed";case"initializing":{let e=t.connectStartedAt;return e!==void 0&&Date.now()-e>=ua?"failed":void 0}default:return}}var ng="authentication required",cA="Authentication refresh is pending in the backend; retry shortly.",uA="timed out connecting after 30s",dA="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",lA="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",fA="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",pA="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",hA="Server requires re-authentication \u2014 its saved credential is no longer valid. Reconnect it from the session MCP panel.",mA="Server was not started: its credential is temporarily unavailable. Re-initialize it in a moment.",gA=new Map([["manager_unavailable","retry"],["managed_provider_unavailable","retry"],["refresh_retryable","retry"],["reauth_required","reconnect"],["auth_terminal","reconnect"],["policy_excluded","blocked"],["share_identity_excluded","blocked"]]),yA="Server was not started: this session is not allowed to use it.",vA="Server was not started: this session's Space policy does not allow it.",_A="Server was not started: its shared credential is not available to this session's identity.",SA="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function wA(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),i=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),s=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=s(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?lA:dA,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=s(a);i.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...CA({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}bA({state:t,servers:e,liveConfigIds:r,reportedConfigIds:n,reportedNames:o,idlessReportedNames:i})}function bA(t){let{state:e,servers:r,liveConfigIds:n,reportedConfigIds:o,reportedNames:i,idlessReportedNames:s}=t;for(let[a,c]of e.oauthFailureCategoriesByConfigId??[]){if(n.has(a)||o.has(a)||e.sessionRemovedConfigIds.has(a))continue;let u=sg(e,a)??RA(e,c);if(u===void 0)continue;let d=e.registryConfigNamesById.get(a)??c.serverName;s.has(d)||(o.add(a),r.push({name:d,source:"registry",status:"failed",...u,mcpConfigId:a}),i.add(d))}}function og(t){switch(t.disposition){case"retry":case"reconnect":case"blocked":return t.disposition;case void 0:return gA.get(t.category);default:return}}function RA(t,e){if(!(t.selectedRegistryConfigIds===void 0||og(e)!=="retry"))return{errorMessage:mA,failureCategory:"transient"}}function ig(t,e){let r=new Map;for(let[n,o]of Object.entries(e)){if(!o||typeof o!="object")continue;let i=o;typeof i.category=="string"&&typeof i.config_id=="string"&&i.config_id!==""&&r.set(i.config_id,{category:i.category,serverName:n,...typeof i.disposition=="string"?{disposition:i.disposition}:{}})}t.oauthFailureCategoriesByConfigId=r}function sg(t,e){let r=t.oauthFailureCategoriesByConfigId?.get(e);if(r!==void 0)switch(og(r)){case"reconnect":return{errorMessage:hA,failureCategory:"auth_terminal"};case"blocked":return r.category==="share_identity_excluded"?{errorMessage:_A,failureCategory:"share_identity_excluded"}:{errorMessage:r.category==="policy_excluded"?vA:yA,failureCategory:"policy_excluded"};default:return}}function CA(t){let{state:e,id:r,name:n,reportedNames:o}=t;if(e.authFallbackDisplacedConfigIds.has(r))return{errorMessage:SA,failureCategory:"auth_terminal"};let i=sg(e,r);return i!==void 0?i:{errorMessage:o.has(n)?pA:fA,failureCategory:"configuration"}}function PA(t,e){return e!==void 0?e.isAuthError?ng:e.error:t.status==="initializing"?uA:t.lastError??(t.status==="auth_required"?ng:void 0)}function ag(t,e){if(t.targetCredentialProvenance)return t.targetCredentialProvenance.credential;let r=e.statusFailureCategories?.get(t.name);return typeof r=="object"?{revision:r.credentialRevision,domain:r.credentialRevisionDomain}:e.credentialRevisions?.get(t.name)}function EA(t,e,r){if(ag(t,e)?.domain?.startsWith("recipient:"))return ct(e,t.name).serverGeneration;let n=e.statusFailureCategories?.get(t.name);if(r&&typeof n=="object")return n.serverGeneration;let o=ct(e,t.name).serverGeneration;return o>0?o:void 0}function xA(t,e){return e!==void 0?e.isAuthError?"auth":void 0:t.status==="initializing"?"timeout":t.lastErrorClass}function kA(t,e){let r=aA(t);if(r===void 0)return;let n=sA(e,t.name),o=r==="connected"?oA(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let i={name:t.name,source:xr(t,e.pluginServerHosts,e.hostLeases),status:r,transport:t.config.type,tools:t.suppressesProviderDiagnostics?[]:t.tools.map(u=>u.name)},s=t.config.id;s!==void 0&&(i.mcpConfigId=s,e.dynamicallyAddedConfigIds.has(s)&&(i.dynamicallyAdded=!0));let a=ag(t,e);a?.revision!==void 0&&a.domain!==void 0&&(i.credentialRevision=a.revision,i.credentialRevisionDomain=a.domain);let c=EA(t,e,r==="failed");if(c!==void 0&&(i.serverGeneration=c),r==="failed"){i.errorMessage=n==="auth_refresh_needed"?cA:PA(t,o),i.failureCategory=n??(t.status==="auth_required"||o?.isAuthError===!0?"auth_terminal":"transport_transient");let u=xA(t,o);u!==void 0&&(i.errorClass=u)}return i}function TA(t){let e=[];for(let r of t.servers.values()){let n=kA(r,t);n!==void 0&&e.push(n)}return wA(t,e),e}function N(t,e){try{let r=TA(e),n=JSON.stringify(r);if(n===e.lastStatusReport)return;e.lastStatusReport=n,e.statusHostGeneration??=1,e.statusReportSequence=(e.statusReportSequence??0)+1;let o={servers:r,observedAtMs:Date.now(),hostGeneration:e.statusHostGeneration,reportSequence:e.statusReportSequence};t.events.emit(iA,o),rg.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){rg.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var da={local:4,registry:3,plugin:2,vfs:1};function Ht(t){return t.hostLeases??=new Map,t.hostLeases}function AA(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function ui(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function di(t,e){return t.kind===e.kind&&t.identity===e.identity}function cg(t){if(!t.host)return t.retirement;let e=()=>{},r=new Promise(n=>{e=n});return{incumbent:{owner:t.owner,revision:t.revision,host:t.host},teardown:r,settled:!1,resolve:e}}function td(t,e){let r=AA(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function la(t,e,r){if(r.kind==="registry"){ui(t).set(e,{kind:"domain",domain:r.identity});return}ui(t).set(e,{kind:"blocked"})}function rd(t,e,r){r&&t.servers.get(e)===r&&t.servers.delete(e),r&&t.pluginServerHosts.get(e)===r&&(t.pluginServerHosts.delete(e),t.pluginServerNames.delete(e))}function kr(t,e){return t.registrySource!==void 0?{kind:"registry",identity:`user:${t.id??t.name}`}:t.vfsSource!==void 0?{kind:"vfs",identity:t.id??t.name}:{kind:e??"local",identity:t.id??t.name}}function te(t,e,r){let n=Ht(t),o=n.get(e);if(o)return o;let i=t.pluginServerHosts.get(e)===r?"plugin":void 0,s=r.config,a=s?kr(s,i):{kind:i??"local",identity:e},c={owner:a,revision:td(t,e),host:r,connectionEpoch:t.mcpConnectionEpoch};return n.set(e,c),la(t,e,a),c}function ug(t){let{state:e,name:r,host:n}=t,o=Ht(e),i=o.get(r);if(!i||i.host!==n||i.owner.kind!=="local"||e.servers.get(r)!==n)return;let s={owner:{kind:"plugin",identity:n.config.id??r},revision:td(e,r),host:n};return o.set(r,s),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),la(e,r,s.owner),s}function li(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:i}=t,s=Ht(e),a=s.get(r);if(a){if(a.retirement?.settled)return;let l=da[n.kind]>da[a.owner.kind],f=da[n.kind]===da[a.owner.kind],p=o===a.revision&&(i===void 0||i===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?cg(a):void 0;rd(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,connectionEpoch:e.mcpConnectionEpoch,revision:td(e,r),host:void 0,...u?{retirement:u}:{}};return s.set(r,d),la(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function nd(t){if(!t)return;let e=await t.teardown;if(e.status==="failed")throw e.error instanceof Error?e.error:new Error(String(e.error))}function _e(t){let{state:e,name:r,retirement:n,result:o}=t;if(n.settled)return!1;n.settled=!0,n.result=o;let s=Ht(e).get(r);return s?.retirement===n&&(o.status==="failed"?(s.host=void 0,ui(e).set(r,{kind:"blocked"})):s.retirement=void 0),n.resolve(o),!0}function fa(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e).get(r);return!s||s.revision!==o||!di(s.owner,n)||s.host!==void 0||s.retirement!==void 0?!1:(s.host=i,e.servers.set(r,i),n.kind==="plugin"?(e.pluginServerNames.add(r),e.pluginServerHosts.set(r,i)):(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),!0)}function dt(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e).get(r);if(!s||s.revision!==o||!di(s.owner,n)||s.host!==i||s.retirement!==void 0)return;let a=cg(s);if(a)return rd(e,r,i),s.host=void 0,s.retirement=a,a}function dg(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,i=Ht(e),s=i.get(r),a=o.result;return!s||s.retirement!==o||s.host!==void 0||!o.settled||!di(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(s.retirement=void 0,!di(s.owner,n)||s.revision!==o.incumbent.revision?(la(e,r,s.owner),!0):(i.delete(r),ui(e).set(r,{kind:"blocked"}),!0))}function xe(t){let{state:e,name:r,owner:n,revision:o,host:i}=t,s=Ht(e),a=s.get(r);return!a||a.revision!==o||!di(a.owner,n)||a.host!==i||a.retirement!==void 0?!1:(rd(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),s.delete(r),ui(e).set(r,{kind:"blocked"}),!0)}function D(t,e){return Ht(t).get(e)}function od(t,e,r){let n=Ht(t).get(e);return n?.host===r&&(n.owner.kind!=="registry"||n.connectionEpoch===t.mcpConnectionEpoch)}function lg(t){if(t!==void 0)try{return new URL(t).toString()}catch{return t}}function Tr(t,e){return!t||!e?!1:t.id===e.id&&t.name===e.name&&t.type===e.type&&lg(t.url)===lg(e.url)&&t.registrySource===e.registrySource&&t.vfsSource===e.vfsSource}var Qn=class{constructor(){this._tokens=new Map;this._authRequired=new Set;this._retiredCredentials=new Set;this._credentialRetirementGenerations=new Map;this._credentialIdentities=new Map}get(e){return this._tokens.get(e)}commit(e,r,n){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e),n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e)}hasCredentialIdentity(e,r){return Tr(this._credentialIdentities.get(e),r)}reconcileCredentialIdentity(e,r,n){return this._tokens.get(e)!==r||this._retiredCredentials.has(e)?!1:(n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e),!0)}set(e,r,n){this.commit(e,r,n)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,i,s){return this.persist(e,n,s)}restoreAfterSupersededRefresh(e,r,n,o,i,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,i,s)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations),credentialIdentities:new Map([...this._credentialIdentities].map(([e,r])=>[e,{...r}]))}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n);for(let[r,n]of e.credentialIdentities??[])this._credentialIdentities.set(r,{...n})}delete(e,r){this._tokens.delete(e),this._credentialIdentities.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._credentialIdentities.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};function pi(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function id(t){try{return new URL(t).toString()}catch{return t}}function fi(t){if(!(t.type!=="http"&&t.type!=="sse"))return{id:t.id,name:t.name,type:t.type,url:id(t.url),auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Gt(t,e){return fi(e.config)}function mt(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:id(t.url)===id(e.url)}function sd(t,e){let r=fi(t),n=fi(e);return!r||!n?mt(t,e):Tr(r,n)}function Ie(t){return/^secret:(private|shared):.+/.test(t)}function ad(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function pa(t,e,r){if(r===void 0||!Ie(r))return r;let n=t.credentialRevisions?.get(e);return n?.domain===r?n.ownerDomain:void 0}function MA(t){let{state:e,name:r,expectedRegistryConfigId:n,expectedConfig:o,currentConfig:i}=t;if(o)return o;let s=n?e.registryCredentialConfigsById?.get(n):void 0;if(s?.name===r)return s;let a=e.registryCredentialConfigs?.get(r);if(a?.id===n)return a;if(i?.id===n)return i}function $A(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!mt(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function fg(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!ad(e,r):n!==void 0&&e!==n}function pg(t,e,r){return r&&e!==void 0&&t!==void 0&&ad(t,e)}function IA(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(i=>i!==void 0&&!ad(i,n))}function hg(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:i,expectedFence:s,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if($A({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&i!==void 0&&(i.owner.kind!=="registry"||fg({identity:i.owner.identity,...l}))||o&&s?.kind==="domain"&&fg({identity:s.domain,...l})?!0:IA({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function OA(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return fi(r);if(n!==void 0)return{id:n,name:e}}function zA(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:i}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!i||!fi(i)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...i}))}async function mg(t,e,r,n,o){let i=t.oauthCredentialDomains?.get(e),s=t.credentialRevisions?.get(e)?.domain,a=pa(t,e,i),c=pa(t,e,s),u=t.servers?.get(e)?.config,d=MA({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:u}),l=d?.id??r,f=d?.registrySource!==void 0||d===void 0&&r!==void 0,p=d?.registrySource===void 0?void 0:`user:${d.id??d.name}`,h=hg({currentConfig:u,retiredConfig:d,expectedRegistryConfigId:r,retiresRegistryIdentity:f,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:l,retiredOwnerIdentity:p,acceptedDomain:a,currentDomain:c}),g=pg(a,l,f),m=pg(c,l,f),v=!h,w=t.tokens?.get(e)!==void 0&&i===void 0&&s===void 0,R=h&&!(v||g||m||w);if(o==="durable"){let ee=OA({name:e,retiredConfig:d,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,ee,{preserveNameState:R})}let _=hg({currentConfig:t.servers?.get(e)?.config,retiredConfig:d,expectedRegistryConfigId:r,retiresRegistryIdentity:f,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:l,retiredOwnerIdentity:p,acceptedDomain:pa(t,e,t.oauthCredentialDomains?.get(e)),currentDomain:pa(t,e,t.credentialRevisions?.get(e)?.domain)}),C=v&&!_,I=!1;return t.equalRevisionRebindDomains?.delete(e),(C||g)&&t.oauthCredentialDomains?.get(e)===i&&(t.oauthCredentialDomains.delete(e),I=!0),(C||m)&&t.credentialRevisions?.get(e)?.domain===s&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),I=!0),C&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),zA({state:t,name:e,mode:o,stillOwnsNameScopedRevision:C,retiredConfig:d}),I&&(pi(t,e),ut(t,e),t.authRefreshNeededReportKeys?.delete(e)),C}function gt(t,e,r,n){return mg(t,e,r,n,"durable")}function hi(t,e,r,n){return mg(t,e,r,n,"session")}function ha(t){let e=[];if(Object.hasOwn(t,"credential_owner_domain")&&e.push(t.credential_owner_domain),Object.hasOwn(t,"credentialOwnerDomain")&&e.push(t.credentialOwnerDomain),e.length===0)return{kind:"absent"};if(e.some(n=>typeof n!="string"||!/^user:.+/.test(n)))return{kind:"invalid"};let r=e[0];return e.every(n=>n===r)?{kind:"valid",ownerDomain:r}:{kind:"invalid"}}function Ar(t,e){let r=t.replace(/^0+(?=\d)/,""),n=e.replace(/^0+(?=\d)/,"");return r.length!==n.length?r.length<n.length?-1:1:r===n?0:r<n?-1:1}var gg="augment:mcp-oauth-credentials",yg=300*1e3,DA=256,cd=NA.child({prefix:"pi-mcp"}),Tt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function Ge(t){return`user:${t}`}function pn(t){let{state:e,name:r,revision:n}=t;if(e.credentialRevisions??=new Map,e.oauthCredentialRevisions??=new Map,e.oauthCredentialDomains??=new Map,e.hostedCredentialOwnership?.delete(r),n===void 0){e.credentialRevisions.delete(r),e.oauthCredentialDomains.delete(r),e.authRefreshNeededReportKeys?.delete(r);return}let o={...n,revision:n.revision.replace(/^0+(?=\d)/,"")},i=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(i?.revision!==o.revision||i?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let s=e.oauthCredentialRevisions.get(o.domain);(s===void 0||Ar(o.revision,s)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function Mr(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="recipient"&&r!=="user"&&r!=="tenant"?t:Ge(t.slice(e+1))}function hn(t){return t.ownerDomain??Mr(t.domain)}function vg(t,e,r){let n=Ge(e);return r!==void 0?r===n:Ie(t)||Mr(t)===n}function LA(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function jA(t,e,r){return{acceptedDomain:t.oauthCredentialDomains.get(e),credentialRevision:t.credentialRevisions.get(e),expectedDomain:t.expectedCredentialDomains.get(e),failure:t.statusFailureCategories.get(e),restoreFailure:r}}function FA(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function UA(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&LA(t.credentialRevisions.get(e),r.credentialRevision)&&FA(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function qA(t){return JSON.stringify({id:t.id,name:t.name,type:t.type,url:t.type==="stdio"?void 0:t.url,auth:t.type==="stdio"?void 0:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource})}function HA(t){let{state:e,config:r,domain:n}=t,o=r.id===void 0?void 0:e.registryCredentialConfigsById.get(r.id);return!o||e.sessionRemovedConfigIds.has(r.id??"")||!mt(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function $r(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function cr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function _g(t){$r(t);let e=new Set([...t.registryCredentialConfigs.keys(),...t.registryConfigNamesById.values(),...t.oauthCredentialDomains.keys(),...t.credentialRevisions.keys(),...t.preservedCredentialIdentities?.keys()??[],...[...t.bootOAuthCredentialBuffer?.values()??[]].map(n=>n.serverName),...[...t.registryCredentialIntents.values()].flatMap(n=>n.configName?[n.configName]:[])]);for(let[n,o]of t.hostLeases)o.owner.kind==="registry"&&e.add(n);for(let n of e){let o=t.hostLeases.get(n);if(o&&o.owner.kind!=="registry")continue;t.tokens.clearLocalCredential(n);let i=t.oauthCredentialDomains.get(n);i&&t.oauthCredentialRevisions.delete(i),t.oauthCredentialDomains.delete(n),t.credentialRevisions.delete(n),t.hostedCredentialOwnership?.delete(n),t.preservedCredentialIdentities?.delete(n),t.expectedCredentialDomains.set(n,{kind:"blocked"}),t.authRefreshNeededReportKeys?.delete(n)}let r=new Set(t.oauthCredentialDomains.values());for(let n of t.oauthCredentialRevisions.keys())r.has(n)||t.oauthCredentialRevisions.delete(n);for(let n of t.bootOAuthCredentialBuffer?.keys()??[])cr(t,n);t.registryCredentialIntents.clear(),t.pendingRegistryCredentialDomains.clear(),t.stagedOAuthCredentials.clear(),t.equalRevisionRebindDomains.clear(),t.registryCredentialConfigs.clear(),t.registryCredentialConfigsById.clear(),t.registryConfigNamesById.clear(),t.mcpRestartState.clear()}function Sg(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)(o.connectionEpoch!==t.mcpConnectionEpoch||e-o.insertedAtMs>=yg)&&cr(t,n)}function GA(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&cr(t,e)}function wg(t,e){let r=t?.credential_revision_domain??t?.credentialRevisionDomain;if(!(r!==e&&(Ie(e)||typeof r=="string"&&Ie(r))))return t?.credential_revision??t?.credentialRevision}function bg(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:i}=t;$r(e),e.bootOAuthCredentialBuffer??=new Map;let s=e.bootOAuthCredentialBuffer,a=Date.now();Sg(e,a);let c=hn(n),u=Ie(c)?`${c}\0${r}`:c,d=s.get(u),l=wg(d?.credential,n.domain);if(typeof l=="string"&&Ar(n.revision,l)<=0)return;!d&&s.size>=DA&&GA(e),cr(e,u);let f={serverName:r,credential:o,suppressReconnect:i,insertedAtMs:a,connectionEpoch:e.mcpConnectionEpoch,expiryTimer:void 0};s.set(u,f),f.expiryTimer=setTimeout(()=>{s.get(u)===f&&cr(e,u)},yg),f.expiryTimer.unref?.(),cd.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function ZA(t,e){$r(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function Ye(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:i=!1}=t;$r(e);let s=e.registryCredentialIntents.get(r);if(!(n!==void 0&&s?.epoch!==n)){if(!o&&s?.configName){let a=e.expectedCredentialDomains.get(s.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(s.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),i||cr(e,r)}}function ma(t){let{state:e,domain:r,forceNew:n=!1}=t;$r(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let i=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Ye({state:e,domain:r,epoch:o.epoch});let s={epoch:ZA(e,r),configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0};return e.registryCredentialIntents.set(r,s),i!==void 0&&i.configFingerprint===void 0&&e.stagedOAuthCredentials.set(r,{...i,intentEpoch:s.epoch}),e.pendingRegistryCredentialDomains.add(r),{domain:r,...s}}function Rg(t,e){$r(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Ye({state:t,domain:r,epoch:n.epoch});for(let r of t.pendingRegistryCredentialDomains)e.has(r)||(t.pendingRegistryCredentialDomains.delete(r),t.stagedOAuthCredentials.delete(r));for(let r of t.stagedOAuthCredentials.keys())e.has(r)||t.stagedOAuthCredentials.delete(r);for(let r of t.bootOAuthCredentialBuffer?.keys()??[]){let n=r.split("\0",1)[0];!e.has(r)&&!Ie(n)&&cr(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);ma({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function BA(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||D(e,r.name)?.owner.kind==="local")return;$r(e);let n=Ge(r.id),o=qA(r),i=HA({state:e,config:r,domain:n});i||e.equalRevisionRebindDomains.delete(r.name);let s=e.registryCredentialIntents.get(n);if(s&&s.configFingerprint===void 0){s.configFingerprint=o,s.configName=r.name,s.allowEqualRevisionRebind=i;let a=e.stagedOAuthCredentials.get(n);a?.intentEpoch===s.epoch&&(a.configFingerprint=o)}else s&&s.configFingerprint!==o?(Ye({state:e,domain:n,epoch:s.epoch}),s=void 0):s&&(s.allowEqualRevisionRebind=i);if(!s){let a=ma({state:e,domain:n});if(s=e.registryCredentialIntents.get(n),!s||s.epoch!==a.epoch)return;s.configFingerprint=o,s.configName=r.name,s.allowEqualRevisionRebind=i}return e.pendingRegistryCredentialDomains.add(n),WA({state:e,config:r,domain:n}),{domain:n,...s}}function Cg(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;$r(e);let i=hn(r),s=e.registryCredentialIntents.get(i);if(!s||!e.pendingRegistryCredentialDomains.has(i))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(i),d=c?.intentEpoch===s.epoch&&c.configFingerprint===s.configFingerprint?wg(c.credential,r.domain):void 0,l=a===void 0?void 0:Ar(r.revision,a),f=l===0;l!==void 0&&l<0||f&&s.configFingerprint!==void 0&&!s.allowEqualRevisionRebind||typeof d=="string"&&Ar(r.revision,d)<=0||e.stagedOAuthCredentials.set(i,{credential:n,suppressReconnect:o,intentEpoch:s.epoch,configFingerprint:s.configFingerprint,requiresEqualRevisionRebind:f})}function WA(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n});let i=e.credentialRevisions.get(r.name);(o===void 0||i?.ownerDomain!==void 0&&i.ownerDomain!==n||i?.ownerDomain===void 0&&!Ie(o)&&Mr(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),ut(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function VA(t){let{state:e,config:r,pi:n,intent:o}=t,i=e.stagedOAuthCredentials.get(o.domain);if(!i||i.intentEpoch!==o.epoch||i.configFingerprint!==o.configFingerprint||i.requiresEqualRevisionRebind&&!o.allowEqualRevisionRebind)return;e.stagedOAuthCredentials.delete(o.domain),i.requiresEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),Ye({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let s={[r.name]:i.credential};n.events.emit(gg,i.suppressReconnect?{credentials:s,suppressReconnect:!0}:s)}function KA(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();Sg(e,o);let i=e.bootOAuthCredentialBuffer?.get(r);if(i)return cr(e,r),i;for(let[s,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&Ie(s.split("\0",1)[0]))return cr(e,s),a}function JA(t){let{config:e,pi:r,buffered:n}=t;cd.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),cd.info("MCP OAuth boot credential replayed",{hasRegistryConfigId:e.id!==void 0,registryOwned:e.registrySource!==void 0,visibility:"public"});let o={[e.name]:n.credential};r.events.emit(gg,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function YA(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(mt(n,r)){if(n.name===r.name)return;await hi(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await gt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function XA(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:i}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=UA(e,r.name,o);Ye({state:e,domain:n.domain,epoch:n.epoch,preserveFence:!c}),c&&(e.expectedCredentialDomains.set(r.name,{kind:"blocked"}),o.restoreFailure!==void 0&&e.statusFailureCategories.set(r.name,o.restoreFailure))}let a=`Registry credential replacement failed for ${r.name}: ${i instanceof Error?i.message:String(i)}`;return e.diagnostics.push({server:r.name,message:a,origin:"registry"}),new Tt(a)}async function QA(t){let{state:e,config:r,pi:n,intent:o,previousConfig:i,rollbackSnapshot:s}=t,a=e.registryCredentialIntents.get(o.domain);if(a?.epoch!==o.epoch||a.configFingerprint!==o.configFingerprint)return!1;e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let c;try{c=await YA({state:e,config:r,previousConfig:i})}catch(h){throw XA({state:e,config:r,intent:o,rollbackSnapshot:s,cause:h})}let u=e.registryCredentialIntents.get(o.domain);c&&u?.epoch===o.epoch&&e.expectedCredentialDomains.get(r.name)===c&&e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let d=e.expectedCredentialDomains.get(r.name);if(u?.epoch!==o.epoch||u.configFingerprint!==o.configFingerprint||d?.kind!=="domain"||d.domain!==o.domain)return Ye({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),VA({state:e,config:r,pi:n,intent:o});let p=KA({state:e,domain:o.domain,serverName:r.name});return Ye({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&JA({config:r,pi:n,buffered:p}),!0}function Ir(t){let{state:e,config:r,pi:n}=t;if(r.id===void 0||r.registrySource===void 0)return Promise.resolve(!0);let o=e.statusFailureCategories.get(r.name),i=BA({state:e,config:r});if(!i)return Promise.resolve(!1);let s=e.registryCredentialIntents.get(i.domain);if(!s||s.epoch!==i.epoch)return Promise.resolve(!1);if(s.finalization)return s.finalization;let a=jA(e,r.name,o),u=(e.registryCredentialFinalizationsByName.get(r.name)??Promise.resolve(!0)).catch(()=>!1).then(()=>{let d=e.registryCredentialConfigs.get(r.name)??(r.id===void 0?void 0:e.registryCredentialConfigsById.get(r.id))??e.servers.get(r.name)?.config;return QA({state:e,config:r,pi:n,intent:i,previousConfig:d,rollbackSnapshot:a})});return e.registryCredentialFinalizationsByName.set(r.name,u),s.finalization=u,u.then(()=>{e.registryCredentialFinalizationsByName.get(r.name)===u&&e.registryCredentialFinalizationsByName.delete(r.name)},()=>{e.registryCredentialFinalizationsByName.get(r.name)===u&&e.registryCredentialFinalizationsByName.delete(r.name)}),u}import{SettingsManager as fM}from"@augmentcode/auggie-v2";import{homedir as Pg}from"node:os";import{sep as eM}from"node:path";var ud=class extends Error{constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},tM=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,rM=/\\\$\{/g,nM=new Set(["workspaceFolder","augmentToken"]),Eg="${workspaceFolder}";function xg(t,e){return t.includes(Eg)?t.split(Eg).join(e):t}function kg(t,e){return t.includes("${")?t.replace(tM,(n,o,i)=>{if(nM.has(o))return n;let s=e[o];if(s!==void 0)return s;if(i!==void 0)return i;throw new ud(o)}).replace(rM,"${"):t}function oM(t){return t.startsWith("~")?t==="~"?Pg():t.startsWith("~/")||t.startsWith(`~${eM}`)?Pg()+t.slice(1):t:t}function dd(t,e,r){return oM(kg(xg(t,e),r))}function eo(t,e,r){return kg(xg(t,e),r)}function Tg(t,e,r){let n={};for(let[o,i]of Object.entries(t))n[o]=eo(i,e,r);return n}var iM="$augment-";function sM(t,e,r){if(!t)return;let n={};for(let[o,i]of Object.entries(t))n[o]=i.startsWith(iM)?i:eo(i,e,r);return n}function Zt(t,e){let r=process.env;return{...t,url:eo(t.url,e,r),headers:sM(t.headers,e,r)}}function Bt(t,e){let r=process.env;return{...t,command:dd(t.command,e,r),args:t.args.map(n=>eo(n,e,r)),env:t.env?Tg(t.env,e,r):void 0,cwd:t.cwd?dd(t.cwd,e,r):e}}import{readFileSync as cM}from"node:fs";var At=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function to(t){if(t.type==="stdio"||t.type==="http"||t.type==="sse")return t.type;if(t.url)return"http";if(t.command)return"stdio"}function aM(t){if(!t)return;let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=String(n));return Object.keys(e).length>0?e:void 0}function ro(t,e){let r=to(e);if(!r)throw new At(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new At(`MCP server "${t}" has type "${r}" but no 'url' property`);let a=typeof e.clientId=="string"?e.clientId.trim():void 0;return{type:r,name:e.name??t,disabled:e.disabled,url:e.url,headers:e.headers,auth:e.auth==="oauth"?"oauth":void 0,...a?{clientId:a}:{},timeoutMs:e.timeoutMs}}let n=e.command;if(!n)throw new At(`MCP server "${t}" has type "stdio" but no 'command' property`);let o=(e.args??[]).map(a=>String(a)),i=e.useShellInterpolation??!0,s=i&&o.length>0?`${n} ${o.join(" ")}`:n;return{type:"stdio",name:e.name??t,disabled:e.disabled,command:s,args:i?[]:o,env:aM(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:i}}var $g=t=>cM(t,"utf8");function ga(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ag(t){return ga(t)&&("command"in t||"url"in t)}function fd(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function Mg(t,e){return fd(t.name)??e}function ld(t,e){let r=to(t);if(r==="http"||r==="sse")return fd(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return fd(t.name,t.title,n)??e}function uM(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[ld(n,String(r)),n]});if(ga(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,i)=>{let s=o;return[ld(s,String(i)),s]})}for(let r of["servers","mcpServers"]){let n=t[r];if(ga(n))return Object.entries(n).map(([o,i])=>{let s=i;return[Mg(s,o),s]})}if(Ag(t)){let r=t;return[[ld(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(Ag))return Object.entries(t).map(([r,n])=>{if(!ga(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[Mg(o,r),o]})}throw new Error("unrecognized MCP config JSON shape (expected an array of servers, a { servers|mcpServers } array/record, a single server object, or a Claude-Desktop-style record)")}function pd(t){return t instanceof Error?t.message:String(t)}function dM(t,e,r,n,o){if(r)return e;try{return n(t)}catch(i){o.push({message:`Failed to read --mcp-config file "${t}": ${pd(i)}`});return}}function lM(t,e,r){let n=t.trim();if(n.length===0)return[];let o=n.startsWith("[")||n.startsWith("{"),i=o?"inline JSON":`file "${t}"`,s=dM(t,n,o,e,r);if(s===void 0)return[];let a;try{a=JSON.parse(s)}catch(c){return r.push({message:`Failed to parse --mcp-config ${i}: ${pd(c)}`}),[]}try{return uM(a)}catch(c){return r.push({message:`Invalid --mcp-config ${i}: ${pd(c)}`}),[]}}function hd(t,e=$g){let r={},n=[];for(let o of t)for(let[i,s]of lM(o,e,n))r[i]=s;return{servers:r,diagnostics:n}}function md(t,e=$g){return!t||t.length===0?new Set:new Set(Object.keys(hd(t,e).servers))}var pM=["global","project","local","managed"];function hM(t,e){switch(e){case"global":return t.getGlobalSettings().mcpServers;case"project":return t.getProjectSettings().mcpServers;case"local":return t.getLocalSettings().mcpServers;case"managed":return t.getManagedSettings().mcpServers}}function mM(t){let e={};for(let r of t)if(r)for(let[n,o]of Object.entries(r)){if(o===null){delete e[n];continue}o&&(e[n]=structuredClone(o))}return e}function gM(t,e,r){let n=hd(t);r.push(...n.diagnostics);let o=n.servers;if(!e||e.size===0)return o;for(let[i,s]of Object.entries(o)){let a=e.get(i);a!==void 0&&(o[i]={...s,disabled:a})}return o}function yM(t,e,r){let n=fM.create(t,e);for(let{scope:o,error:i}of n.drainErrors()){let s=i.message.includes("parse settings JSON")?"parse":"read";r.push({message:`Failed to ${s} ${o} settings.json: ${i.message}`})}return mM(pM.map(o=>hM(n,o)))}function no(t,e,r,n){let o=[],i=r!==void 0&&r.length>0,s=i?gM(r,n,o):yM(t,e,o),a=[];for(let[c,u]of Object.entries(s))try{let d=ro(c,i?u:{...u,name:c});a.push(d.type==="stdio"?Bt(d,t):Zt(d,t))}catch(d){let l=d instanceof At?d.message:`Failed to normalize MCP server "${c}": ${d instanceof Error?d.message:String(d)}`;o.push({server:c,message:l})}return{servers:a,diagnostics:o}}import{recordToolCallMcpServer as TM,setToolSource as Fg}from"@augmentcode/auggie-v2";import{logger as AM}from"@hermes/logger";import{Type as MM}from"@sinclair/typebox";var ya=Symbol.for("__pi_mcp_state__");function vM(t,e){return t.id!==e.id||t.type!==e.type||t.type==="stdio"||e.type==="stdio"||t.auth!=="oauth"||e.auth!=="oauth"?!1:t.url===e.url&&t.auth===e.auth}function _M(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function SM(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([s,a])=>s!==r.name&&a.id===e&&vM(a,r)).map(([s])=>s),o=n.some(s=>{let a=t.oauthCredentialDomains.get(s);return a!==void 0&&_M(a,e)}),i=t.expectedCredentialDomains.get(r.name);if(!(!o||t.sessionRemovedConfigIds.has(e)||t.oauthCredentialDomains.has(r.name)||i?.kind!=="domain"||i.domain!==`user:${e}`)){t.equalRevisionRebindDomains.set(r.name,i.domain);for(let s of n)t.tokens.clearLocalCredential(s),t.oauthCredentialDomains.delete(s),t.credentialRevisions.delete(s),t.hostedCredentialOwnership?.delete(s),t.preservedCredentialIdentities?.delete(s),t.statusFailureCategories?.delete(s),t.authRefreshNeededReportKeys?.delete(s),t.expectedCredentialDomains.set(s,{kind:"blocked"})}}}function wM(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.initialConnectPromise??=null,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.transientReconnects??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let i=n;i.intentEpoch??=o.epoch,i.configFingerprint??=o.configFingerprint,i.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&SM(t),t.authenticationGeneration??=0,t.authenticatingServerName??=void 0,t.liveEditGenerations??=new Map,t.blockedVfsMcpNames??=new Set,t.pluginServerHosts||(t.pluginServerHosts=new Map),t.toolRegistrationsByPi??=new WeakMap,t.hostLeases??=new Map,t.hostLeaseRevisions??=new Map,t.expectedCredentialDomains??=new Map;for(let[r,n]of t.servers)n.config!==void 0&&te(t,r,n);t.pluginReconcileQueue??=Promise.resolve(),t.mcpAttachDisabled??=!1,t.mcpAttachCloudSignaled??=!1,t.attachResolvers??=new Map,t.attachResultListenerBound??=!1,t.cloudModeListenerBound??=!1,t.attachmentCommandGenerations??=new Map,t.attachmentCommandInFlightGenerations??=new Map,t.attachmentCommandAppliedGenerations??=new Map}async function mi(t,e){for(;;){let r=t.missingHostRemovals.get(e);if(!r)return;try{await r.promise}catch{}if(t.missingHostRemovals.get(e)===r)return}}function oo(t){let{state:e,configId:r,generation:n}=t;e.attachmentCommandGenerations??=new Map,e.attachmentCommandInFlightGenerations??=new Map,e.attachmentCommandAppliedGenerations??=new Map;let o=e.attachmentCommandGenerations.get(r)??0;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o===0:n<o||n===e.attachmentCommandInFlightGenerations.get(r)||n===e.attachmentCommandAppliedGenerations.get(r)?!1:(e.attachmentCommandGenerations.set(r,n),e.attachmentCommandInFlightGenerations.set(r,n),!0)}function gd(t){let{state:e,configId:r,generation:n}=t;typeof n!="number"||n<=0||(e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r),e.attachmentCommandGenerations?.get(r)===n&&(e.attachmentCommandAppliedGenerations??=new Map,e.attachmentCommandAppliedGenerations.set(r,n)))}function va(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function _a(t){let{state:e,configId:r,generation:n,operation:o,wasApplied:i}=t;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o:o.then(s=>(i()?gd({state:e,configId:r,generation:n}):va({state:e,configId:r,generation:n}),s),s=>{throw va({state:e,configId:r,generation:n}),s})}function Y(){let t=globalThis;if(t[ya])return wM(t[ya]),t[ya];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Qn,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations:new Map,transientReconnects:new Map,serverGenerations:new Map,configRevisions:new Map,configDesiredRevisions:new Map,configDesiredSources:new Map,credentialRevisions:new Map,oauthCredentialRevisions:new Map,oauthCredentialDomains:new Map,equalRevisionRebindDomains:new Map,preservedCredentialIdentities:new Map,stagedOAuthCredentials:new Map,bootOAuthCredentialBuffer:new Map,pendingRegistryCredentialDomains:new Set,registryCredentialIntents:new Map,registryCredentialIntentEpochs:new Map,registryCredentialFinalizationsByName:new Map,statusHostGeneration:1,statusReportSequence:0,statusFailureCategories:new Map,authRefreshNeededReportKeys:new Map,hostedCredentialOwnership:new Map,shouldProactivelyRefreshTokens:!0,backgroundRefreshIntervalId:void 0,credsListenerBound:!1,configIdsListenerBound:!1,registryGeneration:0,liveEditGenerations:new Map,attachmentCommandGenerations:new Map,attachmentCommandInFlightGenerations:new Map,attachmentCommandAppliedGenerations:new Map,mcpConfigsListenerBound:!1,embeddedRegistryConfigs:void 0,vfsListenerBound:!1,addServerListenerBound:!1,restartServerListenerBound:!1,removeServerListenerBound:!1,mcpRestartState:new Map,vfsGeneration:0,lastSuccessfulVfsMcpSignature:void 0,blockedVfsMcpNames:new Set,credentials:void 0,secretsClient:void 0,headerSecrets:{},headerSecretFailures:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,initialConnectPromise:null,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,authFallbackDisplacedConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,oauthFailureCategoriesByConfigId:void 0,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1,isCloudMode:void 0,cloudModeListenerBound:!1};return t[ya]=e,e}var Ig=Symbol.for("__hermes_mcp_tool_registry__"),Og=Symbol.for("__hermes_mcp_tool_server_registry__"),bM=Symbol.for("__hermes_mcp_extension_factory__");function vd(){let t=globalThis;return t[Ig]??=new Map,t[Ig]}function yd(){let t=globalThis;return t[Og]??=new Map,t[Og]}function zg(t){return vd().get(t)}function Or(t,e){vd().set(t.name,t),e===void 0?yd().delete(t.name):yd().set(t.name,e)}function io(t,e){let r=vd();(e===void 0||r.get(t)===e)&&(r.delete(t),yd().delete(t))}function Ng(t){Reflect.set(t,bM,!0)}import{recordToolCallFacts as Lg}from"@augmentcode/auggie-v2";function Sa(t,e,r,n){return r.includes(t)?n.includes(t)?`"${t}" is a built-in tool, not an MCP server. Call it directly.`:`Built-in tool "${t}" is not available (disabled).`:`MCP server "${t}" is not available (status: ${e??"unknown"}).`}function RM(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function CM(t){let e=[];for(let r of t)r.type==="text"?e.push({type:"text",text:r.text}):e.push({type:"image",mimeType:r.mimeType,data:r.data});return e}function PM(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
|
|
9
|
+
`).trim()}function _d(t,e,r){if(t.isError){let o=PM(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=CM(t.content);if(n.length>0)return{content:n,details:void 0};if(t.rawItemCount>0)throw new Error(`MCP server "${e}" returned a result with no usable content (${t.rawItemCount} content item(s), none in a recognized shape). This may indicate the server failed to produce output (e.g. missing credentials).`);return{content:[{type:"text",text:`[MCP tool "${e}/${r}" returned no content]`}],details:void 0}}function Dg(t){let e=t.total===void 0?"":`/${t.total}`,r=t.message?` - ${t.message}`:"";return`Progress: ${t.progress}${e}${r}`}var EM={reconnecting:"Reconnecting to the MCP server",reauthorizing:"Refreshing the MCP server sign-in"};function wa(t,e){if(!t)return;let r,n="running",o=i=>t({content:[{type:"text",text:i}],details:{kind:"mcp_tool_update",server:e,phase:n,...r===void 0?{}:{progress:r.progress,...r.total===void 0?{}:{total:r.total},...r.message?{message:r.message}:{}}}});return{onProgress:i=>{r=i,n="running",o(Dg(i))},onPhase:i=>{if(i!==n){if(n=i,i!=="running"){o(EM[i]);return}o(r?Dg(r):"Resumed")}}}}async function Sd(t,e,r){let n=Y(),o=n.servers.get(t),i=o?.status!=="success"&&n.reconnects?.has(t)===!0;if(!n.recoverTransientServer||!i&&(o?.status!=="failed"||!o.lastFailureTransient))return!1;r?.onPhase?.("reconnecting");let s=await n.recoverTransientServer(t,e);return s&&r?.onPhase?.("running"),s}function ba(t,e){return e===void 0?t:{...t,onFacts:r=>Lg(e,r)}}async function jg(t){let e=ba(wa(t.onUpdate,t.serverName),t.toolCallId),r=t.getHost();if(r?.status!=="success"&&await Sd(t.serverName,t.signal,e)&&(r=t.getHost()),!r||r.status!=="success")throw t.toolCallId!==void 0&&Lg(t.toolCallId,{errorType:"unavailable"}),new Error(Sa(t.serverName,r?.status,t.getAllToolNames(),t.getActiveToolNames()));let n=t.map.resolve(t.namespaced),o=RM(t.params),i=await r.callTool(n,o,t.signal,{toolCallId:t.toolCallId},e);return _d(i,t.serverName,n)}var xM=/[^a-zA-Z0-9_-]/g;function wd(t){return t.replace(xM,"_")}function kM(t,e){let r=wd(e),n=wd(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var zr=class{constructor(e){this._map=new Map;this._serverName=e}put(e){let r=kM(this._serverName,e),n=this._map.get(r),o=n!==void 0&&n!==e;return n===void 0&&this._map.set(r,e),{namespaced:r,collision:o}}resolve(e){let r=this._map.get(e);if(r)return r;let n=`_${wd(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Ra=AM.child({prefix:"pi-mcp"});function Ca(){return Y().toolRegistrationsByPi}function Ug(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:i}=t,s;try{s=MM.Unsafe(n.inputSchema??{})}catch(c){if(t.suppressDiagnostics){Ra.warn("Skipping MCP stdio tool with invalid input schema; provider diagnostics are suppressed");return}Ra.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>Y().servers.get(r);return{name:i,label:n.name,description:n.description??"",parameters:s,execute:(c,u,d,l,f)=>(TM(c,r),jg({serverName:r,namespaced:i,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(p=>p.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d,toolCallId:c,onUpdate:l}))}}function bd(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n),i=r.definitionsByName?.get(n);e.ownerByToolName.delete(n),t.unregisterTool(n),io(n,i),r.definitionsByName?.delete(n),$M(t,e,n,r,o)}function $M(t,e,r,n,o){let i=Y();for(let[s,a]of e.byServer){if(a===n||!a.registeredNames.has(r))continue;let c=i.servers.get(s);if(c===void 0||c!==a.host||c.status!=="success"||i.serverGenerations?.get(s)!==a.generation)continue;let u=new zr(s);for(let d of c.listTools()){let{namespaced:l,collision:f}=u.put(d.name);if(f||l!==r)continue;let p=Ug({pi:t,serverName:s,tool:d,map:u,namespaced:l,suppressDiagnostics:c.suppressesProviderDiagnostics});if(!p)return;Fg(r,"mcp",s),t.registerTool(p),Or(p,s),a.definitionsByName??=new Map,a.definitionsByName.set(r,p),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function IM(t,e){let r=Ca(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=Y().serverGenerations?.get(e.name),i=n.byServer.get(e.name);if(i?.host===e&&i.generation===o)return{registration:i,replaced:!1};if(i)for(let a of i.registeredNames)bd(t,n,i,a);let s={generation:o,host:e,map:new zr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,s),{registration:s,replaced:i!==void 0}}function Rd(t,e){let{registration:r,replaced:n}=IM(t,e),o=new Set(r.registeredNames),i=new zr(e.name);r.map=i,r.registeredNames.clear();let s=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:f}=i.put(d.name);if(f){let h=i.resolve(l),g=e.suppressesProviderDiagnostics?"MCP stdio tool name collision; provider diagnostics are suppressed. Only the first tool will be available.":`Tool name collision detected in MCP server "${s}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,m=Y();m.diagnostics.some(w=>w.server===s&&(w.message===g||w.message.includes(`both map to "${l}"`)))||(Ra.warn(g),m.diagnostics.push({server:s,message:g}));continue}let p=Ug({pi:t,serverName:s,tool:d,map:i,namespaced:l,suppressDiagnostics:e.suppressesProviderDiagnostics});p&&(Fg(l,"mcp",s),t.registerTool(p),Or(p,s),r.definitionsByName??=new Map,r.definitionsByName.set(l,p),Ca().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Ca().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&bd(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Ra.info(`Registered ${a} MCP tool(s) from server "${s}"`)}function Cd(t,e,r){let n=Ca().get(t);if(!n)return!1;let o=n.byServer.get(e.name);if(!o||o.host!==e||o.generation!==r)return!1;for(let i of o.registeredNames)bd(t,n,o,i);return n.byServer.delete(e.name),!0}function qg(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&Rd(t,r)}import{getToolSource as qM}from"@augmentcode/auggie-v2";import{Type as OM}from"@sinclair/typebox";var zM=!1,Hg=2e4;function NM(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function DM(t){let e=0;for(let r of t.servers.values())e+=LM(r);return e}function LM(t){if(t.status!=="success")return 0;let e=new zr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||jM(n.inputSchema)&&(r+=NM(n))}return r}function jM(t){try{return OM.Unsafe(t??{}),!0}catch{return!1}}function FM(t){let e=t.featureFlags?.flags.cliMcpToolSearchAutoEnable;return typeof e=="boolean"?e:zM}function UM(t){let e=t.featureFlags?.flags.cliMcpToolSearchTokenThreshold;if(typeof e=="bigint"){let r=Number(e);return Number.isFinite(r)&&r>0?r:Hg}return typeof e=="number"&&Number.isFinite(e)&&e>0?e:Hg}function Gg(t){return FM(t)?DM(t)>=UM(t):!1}var Zg="AUGGIE_ENABLE_TOOL_SEARCH",HM=new Set(["find-tool","execute-tool","attach-mcp-server"]);function gi(){return process.env[Zg]==="1"}function Pd(t){return process.env[Zg]!=="0"&&t.featureFlags?.flags.cliMcpToolSearchAutoEnable===!0}function Nr(t){return gi()?!0:Pd(t)?t.toolSearchLatched?!0:Gg(t)?(t.toolSearchLatched=!0,!0):!1:!1}function Pa(t){let e=t.getActiveTools(),r=e.filter(n=>!GM(n)||HM.has(n));r.length!==e.length&&t.setActiveTools(r)}function GM(t){return qM(t)==="mcp"}import{recordToolCallFacts as d0,recordToolCallMcpServer as l0,setToolSource as Qg}from"@augmentcode/auggie-v2";import{logger as f0}from"@hermes/logger";import{Type as ey}from"@sinclair/typebox";import{logger as ZM}from"@hermes/logger";var yi={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Dr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Bg=ZM.child({prefix:"pi-mcp"}),BM=5e3,WM=1,VM=2,KM=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),JM=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function YM(t){if(typeof t=="number")return t===2||t===3;if(typeof t=="string"){let e=t.toUpperCase();return e.includes("OAUTH")||e.includes("API_KEY")}return!1}function XM(t){return t===WM||typeof t=="string"&&KM.has(t)?"available":t===VM||typeof t=="string"&&JM.has(t)?"opt_in_required":"unknown"}function QM(t){if(!(typeof t.id!="string"||t.id.length===0))return{id:t.id,name:typeof t.name=="string"&&t.name.length>0?t.name:t.id,description:typeof t.description=="string"?t.description:"",requiresAuth:YM(t.auth_type),state:XM(t.state)}}function Ed(t,e){if(t.servers.has(e.name))return!0;for(let r of t.servers.values())if(r.config?.id===e.id)return!0;return!1}function Ea(t){return t.featureFlags?.flags.cosmosMcpAgentAttach===!0&&!t.mcpAttachDisabled}function mn(t){return Ea(t)?(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Ed(t,r)):[]}async function Wg(t,e,r){let n=t.apiUrl.replace(/\/+$/,""),o=e??fetch;try{let i=await o(`${n}/settings/get-mcp-catalog-metadata`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({product_type:Dr.UNSPECIFIED}),signal:AbortSignal.timeout(r??BM)});if(!i.ok)return Bg.debug(`MCP catalog fetch failed with ${i.status}; treating catalog as empty`),{ok:!1,disable:i.status===404};let s=await i.json(),a=[];for(let c of s.entries??[]){let u=QM(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(i){return Bg.debug(`MCP catalog fetch failed: ${i instanceof Error?i.message:String(i)}`),{ok:!1,disable:!1}}}var e0="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",t0=`You are a tool search assistant. Given a user's query and a list of available tools, identify the single best matching tool.
|
|
10
10
|
|
|
11
11
|
<user_query>{{query}}</user_query>
|
|
12
12
|
|
|
13
13
|
Available tools on MCP server "{{server_name}}":
|
|
14
14
|
{{tool_list}}
|
|
15
15
|
|
|
16
|
-
Respond with ONLY the tool name (no markdown, no explanation).`,
|
|
17
|
-
`)}function
|
|
16
|
+
Respond with ONLY the tool name (no markdown, no explanation).`,r0=/[\n\r]/g,n0=/</g,o0=/>/g;function gn(t){return t.replace(r0," ").replace(n0,"\u2039").replace(o0,"\u203A").trim()}function i0(){let t=process.env[e0];return t?.trim()?t:t0}var s0=/\{\{(query|server_name|tool_list)\}\}/g;function Vg(t,e,r){let n={"{{query}}":gn(t),"{{server_name}}":gn(e),"{{tool_list}}":r};return i0().replace(s0,o=>n[o]??o)}function Ee(t){return{content:[{type:"text",text:t}],details:void 0}}function Kg(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function xd(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function xa(t,e,r){let n={mcp_server:t,tools:Kg(e).map(xd),note:r};return Ee(JSON.stringify(n,null,2))}function Jg(t){return Kg(t).map(e=>{let r=gn(e.name),n=gn(e.description??"");return`- ${r}: ${n}`}).join(`
|
|
17
|
+
`)}function Yg(t){let e=t.trim();try{let r=JSON.parse(e);if(typeof r.tool_name=="string")return r.tool_name}catch{}return e}import{complete as a0}from"@earendil-works/pi-ai";var c0="augment:tool-search-usage";function u0(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Xg(t,e,r){let n=e.model;if(!n)return;let o=await e.modelRegistry.getApiKeyAndHeaders(n);if(!(o.ok&&o.apiKey))return;let i={role:"user",content:[{type:"text",text:r}],timestamp:Date.now()},s=await a0(o.baseUrl?{...n,baseUrl:o.baseUrl}:n,{messages:[i]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:s.model,usage:s.usage};return t.events.emit(c0,a),u0(s)}var ry=f0.child({prefix:"pi-mcp"}),so="find-tool",Lr="execute-tool",p0=10,ty=15,h0=20,m0={type:"object",properties:{query:{type:"string",description:"Detailed description of the task you need a tool for: the action (create, read, search, delete, \u2026), the target resource, and relevant context (field names, filters). More specific queries match better."},mcp_server:{type:"string",description:"Name of the MCP server to search."}},required:["query","mcp_server"]},g0={type:"object",properties:{mcp_server:{type:"string",description:"Name of the MCP server hosting the tool."},tool_name:{type:"string",description:"Original MCP tool name returned by find-tool."},arguments:{type:"object",description:"Arguments object to pass to the tool."}},required:["mcp_server","tool_name","arguments"]};function vi(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ").trim().replace(/\s+/g," ")}function y0(t){let e=[...Y().servers.values()].filter(c=>c.status==="success"),r=e.find(c=>c.name===t);if(r)return{server:r,name:r.name};let n=vi(t),o=e.filter(c=>n.length>0&&vi(c.name)===n);if(o.length===1){let[c]=o;return{server:c,name:c.name}}let i=n.split(" ").filter(Boolean),s=e.filter(c=>{let u=new Set(vi(c.name).split(" "));return n.length>0&&i.every(d=>u.has(d))});if(s.length===1){let[c]=s;return{server:c,name:c.name}}let a=[...o,...s].map(c=>c.name).filter((c,u,d)=>d.indexOf(c)===u).sort();if(a.length>1){let c=e.map(u=>u.name).sort();throw new Error(`MCP server name "${t}" is ambiguous. Matching servers: ${a.join(", ")}. Use an exact server name. Available servers: ${c.join(", ")}.`)}}function ny(t,e){let r=Y(),n=t.getAllTools().map(u=>u.name);if(!n.includes(e)){let u=e.trim().toLowerCase(),d=mn(r).find(l=>l.id===e.trim()||l.name.toLowerCase()===u);if(d)throw new Error(`MCP server "${d.name}" is available but not attached. Call attach-mcp-server now with config_id "${d.id}"; it attaches directly without requiring user approval.`)}let o=n.includes(e)?void 0:y0(e);if(o)return o;let i=t.getActiveTools(),s=r.servers.get(e),a=[...r.servers.values()].filter(u=>u.status==="success").map(u=>u.name).sort(),c=Sa(e,s?.status,n,i);throw new Error(`${c} Available servers: ${a.join(", ")||"none"}.`)}function v0(t){let e=Y(),r=new Set([...[...e.servers.values()].filter(i=>i.status!=="success").map(i=>i.name),...[...e.reconnects?.keys()??[]].filter(i=>e.servers.get(i)?.status!=="success")]);if(r.has(t))return t;let n=vi(t),o=[...r].filter(i=>n.length>0&&vi(i)===n);return o.length===1?o[0]:void 0}function _0(t){if(t==null)throw new Error(`${Lr} requires an "arguments" object with the tool's parameters.`);if(typeof t!="object"||Array.isArray(t)){let e=Array.isArray(t)?"an array":typeof t;throw new Error(`${Lr} "arguments" must be an object, not ${e}.`)}return t}async function S0(t,e,r,n,o){let i=Vg(r,n,Jg(o)),s=await Xg(t,e,i);if(!s)return;let a=Yg(s);return o.find(c=>c.name===a)}async function w0(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${so} requires string "query" and "mcp_server" parameters.`);let i=ny(t,o),s=i.server.listTools();if(s.length===0)throw new Error(`No tools available on MCP server "${i.name}".`);if(s.length<=p0)return xa(i.name,s,"All tools on this server.");try{let a=await S0(t,e,n,i.name,s);return a?Ee(JSON.stringify(xd(a),null,2)):xa(i.name,s,"No single best match; all tools listed.")}catch(a){return ry.warn(`${so} LLM match failed: ${a instanceof Error?a.message:String(a)}`),xa(i.name,s,"Search failed; all tools listed.")}}async function b0(t,e,r,n,o){let{mcp_server:i,tool_name:s,arguments:a}=e??{};if(typeof i!="string"||typeof s!="string")throw new Error(`${Lr} requires string "mcp_server" and "tool_name" parameters.`);let c=_0(a),u=v0(i),d=u?ba(wa(o,u),n.toolCallId):void 0;u&&await Sd(u,r,d);let l;try{l=ny(t,i)}catch(p){throw d0(n.toolCallId,{errorType:"unavailable"}),p}l0(n.toolCallId,l.name);let f=await l.server.callTool(s,c,r,n,d??ba(wa(o,l.name),n.toolCallId));return _d(f,l.name,s)}function R0(){let t=Y(),e=[...t.servers.values()].filter(i=>i.status==="success"),r=`Search for the right MCP tool. Call with a natural-language query and the target MCP server name to get the best-matching tool, then run it with ${Lr}. When this gateway is present, MCP tools may intentionally be absent as top-level tools. Before reporting an expected MCP capability unavailable, search its attached server with ${so}, then invoke it with ${Lr}.`,n=[];if(e.length===0)n.push(`${r} No MCP servers are currently connected.`);else{let i=e.map(s=>{let a=s.listTools().map(d=>d.name),c=a.slice(0,ty).join(", "),u=a.length>ty?", \u2026":"";return`- ${s.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
|
|
18
18
|
${i.join(`
|
|
19
|
-
`)}`)}let o=
|
|
19
|
+
`)}`)}let o=mn(t).slice(0,h0);if(o.length>0){let i=o.map(s=>{let a=gn(s.description),c=s.requiresAuth?" [requires auth]":"";return`- ${s.name}${a?` \u2014 ${a}`:""}${c}`});n.push(`Available but not attached (use attach-mcp-server to enable):
|
|
20
20
|
${i.join(`
|
|
21
21
|
`)}
|
|
22
22
|
When the user's request requires one of these servers, call attach-mcp-server immediately; it attaches directly without requiring user approval.`)}return n.join(`
|
|
23
23
|
|
|
24
|
-
`)}function Wt(t){let e={name:io,label:io,description:f0(),parameters:Jg.Unsafe(o0),execute:(n,o,i,s,a)=>d0(t,a,o)},r={name:Dr,label:Dr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:Jg.Unsafe(i0),execute:(n,o,i,s)=>l0(t,o,i,{toolCallId:n},s)};Kg(io,"mcp"),Kg(Dr,"mcp"),t.registerTool(e),t.registerTool(r),Ir(e),Ir(r),Xg.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{redactSecrets as kE}from"@augmentcode/auggie-v2";import{logger as oH,logPublic as iH}from"@hermes/logger";import{logger as S0}from"@hermes/logger";import{logger as p0}from"@hermes/logger";function hn(t){return new Promise(e=>setTimeout(e,t))}var ey=p0.child({prefix:"pi-mcp"}),vi={maxTries:3,initialMs:500,mult:2,maxMs:2e3},xd=3e4,cr=200,gt=class extends Error{constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function Ed(t){return t instanceof gt?t.statusCode>=500:!0}async function mn(t){let e;for(let r=0;r<vi.maxTries;r++)try{return await t()}catch(n){if(e=n,!Ed(n))throw n;if(r<vi.maxTries-1){let o=Math.min(vi.initialMs*vi.mult**r,vi.maxMs);await hn(o)}}throw e}var Ea=class{constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??xd}async callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:r===void 0?"{}":JSON.stringify({product_type:r}),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>""),s=i.length>cr?`${i.slice(0,cr)}\u2026[truncated]`:i;throw new gt(o.status,o.statusText,s)}return await o.json()}getMcpTenantConfigs(e){return mn(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return mn(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function ty(t,e){let r=[],[n,o]=await Promise.allSettled([t.getMcpTenantConfigs(e),t.getMcpUserConfigs(e)]),i={},s={};if(n.status==="fulfilled")i=n.value;else{let a=`Failed to fetch tenant MCP configs: ${String(n.reason)}`;ey.warn(a),r.push({message:a})}if(o.status==="fulfilled")s=o.value;else{let a=`Failed to fetch user MCP configs: ${String(o.reason)}`;ey.warn(a),r.push({message:a})}return{tenant:i,user:s,diagnostics:r}}function h0(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var ry=32;function m0(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>ry&&(e=e.slice(0,ry)),e=e.replace(/_+$/,""),e}function ny(t,e){let r=e?m0(e):"",n=h0(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function oy(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var g0=1e12,y0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function v0(t){let e=y0.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),i=Number(e[4]),s=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||i>23||s>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function _0(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<g0?t*1e3:t;if(typeof t=="string")return v0(t)}function iy(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:_0(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Vt=S0.child({prefix:"pi-mcp"}),Z=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},ao=class extends Error{},ay=[100,500],w0=ay.length+1,b0=t=>new Promise(e=>{setTimeout(e,t)});function sy(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Td="augment.mcp-access-token.",R0=JSON.stringify({retired:!0}),ka=3;function Kt(t){return`${Td}${t}`}function Ta(t){return`legacy:${t}`}function At(t){return t?.id?ny(t.id,t.name):void 0}function wi(t){if(t)return{type:t.type??null,id:t.id??null,name:t.name??null,url:cy(t.url),auth:null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function cy(t){if(typeof t!="string")return null;try{return new URL(t).toString()}catch{return t}}function bi(t){if(typeof t=="string")try{return bi(JSON.parse(t))??t}catch{return t}if(typeof t!="object"||t===null||Array.isArray(t))return t===void 0?void 0:JSON.stringify(t);let e=t;return JSON.stringify({type:e.type??null,id:e.id??null,name:e.name??null,url:cy(e.url),auth:null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function Mt(t){return bi(wi(t))}function C0(t){return bi(wi(t))}function P0(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function so(t){try{let e=JSON.parse(t);return{credentialIdentity:bi(e.credentialIdentity),state:P0(e)}}catch{return{}}}function _i(t,e){let r={...t,type:"oauth",credentialIdentity:wi(e)};return JSON.stringify(r)}function gn(t,e){let r=oy({accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.client.client_secret,expiresAt:t.expiresAt,resource:t.resource,serverMetadata:t.serverMetadata,client:t.client});return JSON.stringify({...JSON.parse(r),credentialIdentity:wi(e),credentialState:"active"})}function x0(t){return JSON.stringify({credentialIdentity:wi(t),credentialState:"retired",retired:!0})}function E0(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=C0(e),i=bi(n.credentialIdentity);if(!(o&&(i===void 0?e?.auth!=="oauth":i!==o))&&!(typeof n.accessToken!="string"||n.accessToken.length===0||typeof n.serverMetadata!="object"||n.serverMetadata===null||typeof n.client!="object"||n.client===null))return{identityMatched:o!==void 0&&i===o,token:n}}function kd(t){try{let e=iy(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:void 0,authorization_endpoint:typeof r.authorization_endpoint=="string"?r.authorization_endpoint:void 0,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var Si=class{constructor(e,r,n,o=b0){this._memory=new Xn;this._dirtyGenerations=new Map;this._durableQueues=new Map;this._registryMemoryWriteGenerations=new Map;this._registryMemoryAuthorities=new Map;this._registryMemoryCommittedAuthorities=new Map;this._nextGeneration=0;if(this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"){this._memory.seed(n);for(let[i,s]of n.credentialIdentities??[]){let a=Mt(s);a&&this._registryMemoryCommittedAuthorities.set(i,a)}}}get(e){return this._memory.get(e)}commit(e,r,n){this._memory.commit(e,r,n);let o=Mt(n);o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e)}hasCredentialIdentity(e,r){return this._memory.hasCredentialIdentity(e,r)}reconcileCredentialIdentity(e,r,n){if(!this._memory.reconcileCredentialIdentity(e,r,n))return!1;let o=Mt(n);return o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e),!0}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,n,o)}).catch(()=>{Vt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).then(o=>{o&&this._memory.get(e)===r&&this.commit(e,r,n)}).catch(()=>{Vt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let i=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,n,i)});return}let o=await this._persist(e,r,n,!1);this.commit(e,r,o?n:void 0)}_beginRegistryMemoryWrite(e,r){let n=Mt(r);if(!n)throw new Z;let o=(this._registryMemoryWriteGenerations.get(e)??0)+1;return this._registryMemoryWriteGenerations.set(e,o),this._registryMemoryAuthorities.set(e,n),{generation:o,identity:n,retirementGeneration:this._memory.credentialRetirementGeneration(e)}}_commitRegistryMemoryWrite(e,r,n,o){this._registryMemoryWriteGenerations.get(e)!==o.generation||this._registryMemoryAuthorities.get(e)!==o.identity||this._memory.credentialRetirementGeneration(e)!==o.retirementGeneration||(this._memory.commit(e,r,n),this._registryMemoryCommittedAuthorities.set(e,o.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=At(e),n=Mt(e),o=this._getClient();if(!(!r||!n||!o||!e))try{return await this._enqueueWrite(r,()=>this._captureAuthenticatedIdentityVersion({client:o,key:r,identity:n,registry:e}))}catch{throw new Z}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<ka;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new Z}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:i}=e,s=await r.getUserSecretWithVersion(n);if(!s)return"0";let a=so(s.value);if(a.state==="retired")return s.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new Z;if(a.credentialIdentity===o&&a.state==="active")return s.version;let c=kd(s.value);if(!c)throw new Z;try{await r.upsertUserSecret(n,gn(c,i),s.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=At(e),n=Mt(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new Z;return}try{return await this._enqueueWrite(r,async()=>{let i=await o.getUserSecretWithVersion(r);if(!i)throw new Z;let s=so(i.value);if(s.state!=="active"||s.credentialIdentity!==n||!kd(i.value))throw new Z;return i.version})}catch{throw new Z}}persistAuthenticated(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}persistRefresh(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}async _persistAuthenticated(e,r,n,o){let i=this._getClient(),s=At(n),a=n&&s&&i&&o!==void 0?this._enqueueWrite(s,()=>i.upsertUserSecret(s,gn(r,n),o)):void 0,c=this._shouldPersist()&&i?()=>this._writeLegacyKey(e,r,!1,n):void 0;if(a)return this._drainRegistryWrites(e,a,c,void 0,n);if(n?.id||this._shouldPersist()&&!i)throw new Z;if(c)return{revision:await this._asPersistenceResult(c()),domain:Ta(e)}}restoreAfterSupersededRefresh(e,r,n,o,i,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,i,s)}async restoreAfterSupersededAuthentication(e,r,n,o,i,s=o){let a=this._getClient(),c=At(o),u;if(c&&o){if(!a||!s||i?.domain!==`private:${o.id}`||At(s)!==c)throw new Z;if(u=await this._enqueueWrite(c,()=>this._restoreRegistryCredential({client:a,key:c,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s,persistedRevision:i})),!u)return}if(!c&&At(s))throw new Z;if(!this._shouldPersist())return u;if(!a)throw new Z;if(c&&o){try{await this._enqueueWrite(Kt(e),()=>this._restoreLegacyCredential({client:a,key:Kt(e),persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s}))}catch{Vt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return u}if(i?.domain!==Ta(e))throw new Z;try{return await this._enqueueWrite(Kt(e),()=>this._restoreLegacyCredentialExact({client:a,key:Kt(e),serverName:e,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s,persistedRevision:i}))}catch{throw new Z}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:i,currentToken:s,persistedIdentity:a,currentIdentity:c,persistedRevision:u}=e,d=await r.getUserSecretWithVersion(n);if(!(!d||d.version!==u.revision||d.value!==_i(i,a)))try{return{revision:await r.upsertUserSecret(n,_i(s,c),u.revision),domain:Ta(o)}}catch(l){if(this._isVersionConflict(l))return;throw l}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:i,persistedIdentity:s,currentIdentity:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==gn(o,s)))try{return{revision:await r.upsertUserSecret(n,gn(i,a),c.revision),domain:`private:${a.id}`}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:i,persistedIdentity:s,currentIdentity:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.value!==_i(o,s)))try{await r.upsertUserSecret(n,_i(i,a),c.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async _drainRegistryWrites(e,r,n,o,i){let s;try{s=await r}catch{throw new Z}if(o?.(),i?.id&&!s)throw new Z;try{await n?.()}catch{Vt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return i?.id&&s?{revision:s,domain:`private:${i.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let i=Mt(o);if(!i)throw new Z;for(let s=0;s<ka;s+=1){let a=await e.getUserSecretWithVersion(r),c=a?so(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==i)throw new Z;try{return await this._upsertUserSecretOnce(e,r,gn(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new Z}async _retireRegistryCredential(e,r,n){let o=Mt(n);if(!o)throw new Z;for(let i=0;i<ka;i+=1){let s=await e.getUserSecretWithVersion(r),a=s?so(s.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(s&&a.credentialIdentity===void 0)throw new Z;try{await this._upsertUserSecretOnce(e,r,x0(n),s?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new Z}_isVersionConflict(e){return e instanceof gt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,i){let s=this._getClient(),a=At(n),c=a&&n&&s?this._enqueueWrite(a,()=>{let d=this._getClient();if(!d)throw new Error("MCP secrets client unavailable");return this._writeRegistryCredential(d,a,r,n)},{credentialShape:"registry",operation:"write"}):void 0,u=this._shouldPersist()&&s?()=>this._writeLegacyKey(e,r,o,n):void 0;if(c)return this._drainRegistryWrites(e,c,u,i,n);if(n?.id||this._shouldPersist()&&!s)throw new Z;if(u)return{revision:await this._asPersistenceResult(u()),domain:Ta(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new Z}}_enqueueWrite(e,r,n){let o=sy(e),i=++this._nextGeneration;n?.onGeneration?.(i);let s=this._durableQueues.get(o),a=s??{latestGeneration:i,latestMutationGeneration:n?i:0,tail:Promise.resolve()};a.latestGeneration=i,n&&(a.latestMutationGeneration=i),s||this._durableQueues.set(o,a);let c=()=>this._runPersistence(a,i,r,n),u=s?a.tail.catch(()=>{}).then(c):c();return a.tail=u,u.finally(()=>{a.latestGeneration===i&&this._durableQueues.get(o)?.tail===u&&this._durableQueues.delete(o)}).catch(()=>{}),u}async _runPersistence(e,r,n,o){let i=o?w0:1;for(let s=0;s<i;s+=1){if(this._isLegacyPersistenceGateClosed(o))throw new ao;try{return await n()}catch(a){this._throwIfPersistenceCanceled(e,r,o);let c=this._persistenceRetryDelay(a,s,o);if(c===void 0)throw a;await this._delay(c)}}throw new Z}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new ao}_persistenceRetryDelay(e,r,n){let o=n?ay[r]:void 0,i=!(e instanceof Z)&&Ed(e);if(o===void 0||!i){n&&Vt.warn("MCP OAuth credential persistence exhausted retries",{attempts:r+1,credentialShape:n.credentialShape,operation:n.operation});return}return o}_upsertUserSecretOnce(e,r,n,o){return typeof e.upsertUserSecretOnce=="function"?e.upsertUserSecretOnce(r,n,o):e.upsertUserSecret(r,n,o)}_deleteUserSecretOnce(e,r){return typeof e.deleteUserSecretOnce=="function"?e.deleteUserSecretOnce(r):e.deleteUserSecret(r)}_writeLegacyKey(e,r,n,o){let i=0,s=this._enqueueWrite(Kt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,Kt(e),_i(r,o));return this._dirtyGenerations.get(e)===i&&this._dirtyGenerations.delete(e),c},{credentialShape:"legacy",operation:"write",onGeneration:a=>{i=a,this._dirtyGenerations.set(e,a)}});return s.catch(a=>{(a instanceof ao||!n)&&this._dirtyGenerations.get(e)===i&&this._dirtyGenerations.delete(e)}),s}retireCredential(e,r,n){let o=Mt(r),i=this._registryMemoryCommittedAuthorities.get(e),s=n?.preserveNameState===!0&&(i===void 0||i!==o),a=(this._registryMemoryWriteGenerations.get(e)??0)+1;this._registryMemoryWriteGenerations.set(e,a),this._registryMemoryAuthorities.delete(e);let c=this._getClient(),u=At(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new Z));let l=this._shouldPersist()&&!s,f;return l&&(c?f=this._enqueueWrite(Kt(e),async()=>{let p=await c.upsertUserSecret(Kt(e),R0)}):f=Promise.reject(new Z)),this._awaitRetirements(e,d,f).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:s}),s||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,i]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Vt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),i.status==="rejected"&&Vt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(i.status==="rejected")throw i.reason}delete(e,r){if(this._memory.delete(e),this._memory.clearAuthRequired(e),this._dirtyGenerations.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._retireRegistryKey(r),!this._shouldPersist()){this._dirtyGenerations.delete(e);return}let n=Kt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let s=this._getClient();if(!s)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(s,n)},{credentialShape:"legacy",operation:"delete",onGeneration:s=>{o=s,this._dirtyGenerations.set(e,s)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(s=>{s instanceof ao&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=At(e);!r||!e||!this._canScheduleDurableOperation(r)||this._enqueueWrite(r,async()=>{let n=this._getClient();if(!n)throw new Error("MCP secrets client unavailable");await this._retireRegistryCredential(n,r,e)},{credentialShape:"registry",operation:"delete"}).catch(()=>{Vt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(sy(e)))}markAuthRequired(e){this._memory.markAuthRequired(e)}isAuthRequired(e){return this._memory.isAuthRequired(e)}clearAuthRequired(e){this._memory.clearAuthRequired(e)}hasInFlightWrite(e){return this._dirtyGenerations.has(e)}async _loadRegistryToken(e,r){let n=At(r),o=Mt(r);if(!n||!o||!r)return{identityRejected:!1};try{return await this._enqueueWrite(n,()=>this._readRegistryToken({client:e,key:n,expectedIdentity:o,registry:r}))}catch{return{identityRejected:!0}}}async _readRegistryToken(e){for(let r=0;r<ka;r+=1){let n=await this._readRegistryTokenAttempt(e);if(n!==void 0)return n}return{identityRejected:!0}}async _readRegistryTokenAttempt(e){let{client:r,key:n,expectedIdentity:o,registry:i}=e,s=await r.getUserSecretWithVersion(n);if(!s)return{identityRejected:!1,authorityVersion:"0"};let a=so(s.value);if(a.state==="retired"||(a.credentialIdentity===void 0?i.auth!=="oauth":a.credentialIdentity!==o))return{identityRejected:!0};let c=kd(s.value);if(!c)return{identityRejected:!0};if(a.credentialIdentity===o&&a.state==="active")return{identityRejected:!1,token:c};try{return await r.upsertUserSecret(n,gn(c,i),s.version),{identityRejected:!1,token:c}}catch(u){return this._isVersionConflict(u)?void 0:{identityRejected:!0}}}async _importLegacyToken(e,r,n,o){let i=At(n),s=Mt(n);if(!i||!s||!n||o===void 0)return;let a=await this._loadLegacyToken(e,r,n);if(a)try{return await this._enqueueWrite(i,async()=>{let c=await e.getUserSecretWithVersion(i);if((c?.version??"0")===o){if(c){let u=so(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==s)return}return await e.upsertUserSecret(i,gn(a.token,n),o),{identityMatched:!0,token:a.token}}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(Kt(r));return o?E0(o,n):void 0}catch{return}}async ensureLoaded(e,r){if(this._memory.get(e)||!this._shouldPersist()||this.hasInFlightWrite(e))return;let o=this._getClient();if(!o)return;let i=this._memory.credentialRetirementGeneration(e),s=await this._loadRegistryToken(o,r);if(s.identityRejected)return;let a=s.token?{identityMatched:!0,token:s.token}:void 0;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==i)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,s.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Vt.debug(`Backend secret for MCP server "${e}" is not a usable OAuth token; ignoring`);return}this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==i||(this.commit(e,a.token,a.identityMatched?r:void 0),Vt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var uy="Augment Code",dy="https://augmentcode.com",ly="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var T0=1e3,A0=500;function Md(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Ri(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Ad=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function fy(t){return new URLSearchParams({k:t}).toString().slice(2)}function M0(t,e){let r=`${fy(t)}:${fy(e)}`;return`Basic ${btoa(r)}`}function gy(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function $0(t){return t.client.token_endpoint_auth_method==="none"||!gy(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function I0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function O0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var z0=401,yy=500;function $d(t,...e){return t.status<yy&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function py(t){return $d(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===z0}async function hy(t,e,r){let n={"Content-Type":"application/x-www-form-urlencoded"},o=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken});r&&o.set("resource",r);let i=gy(t);e==="basic"&&i?n.Authorization=M0(t.client.client_id,i):(o.set("client_id",t.client.client_id),e==="body"&&i&&o.set("client_secret",i));let s=await fetch(t.serverMetadata.token_endpoint,{method:"POST",headers:n,body:o.toString(),signal:AbortSignal.timeout(1e4)});if(!s.ok){let c=await s.text().catch(()=>""),u=O0(c),d=c.slice(0,A0);throw new yn(s.status,s.statusText,d,u)}let a=await s.json();if(!a.access_token)throw new Ad;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*T0:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function my(t,e){try{return await hy(t,e,t.resource)}catch(r){if(r instanceof yn&&t.resource&&$d(r,"invalid_target"))return await hy(t,e,void 0);throw r}}var yn=class t extends Error{constructor(e,r,n,o,i=!1){super(`Token refresh failed: ${e} ${r}${n?` \u2014 ${n}`:""}`),this.name="RefreshHttpError",this.status=e,this.statusText=r,this.body=n,this.oauthErrorCode=o,this.clientAuthPlacementsExhausted=i}withClientAuthPlacementsExhausted(){return new t(this.status,this.statusText,this.body,this.oauthErrorCode,!0)}};function Id(t){return!(t instanceof yn)||t.status>=yy?!1:$d(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Od(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=$0(t);try{return await my(e,r)}catch(n){let o=I0(r);if(!(n instanceof yn)||!o||!py(n))throw n;try{return await my(e,o)}catch(i){throw i instanceof yn&&py(i)?i.withClientAuthPlacementsExhausted():i}}}import{logger as T$}from"@hermes/logger";var Dd;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Dd="oauth4webapi/v3.8.6");function fo(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Jt="ERR_INVALID_ARG_VALUE",Xe="ERR_INVALID_ARG_TYPE";function he(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var qd=Symbol(),N0=Symbol(),D0=Symbol(),_n=Symbol();var vy=Symbol();var L0=new TextEncoder,j0=new TextDecoder;function Ld(t){return typeof t=="string"?L0.encode(t):j0.decode(t)}var jd;Uint8Array.prototype.toBase64?jd=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):jd=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let n=0;n<e.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var Fd;Uint8Array.fromBase64?Fd=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw he("The input to be decoded is not correctly encoded.",Jt,e)}}:Fd=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw he("The input to be decoded is not correctly encoded.",Jt,e)}};function Ma(t){return typeof t=="string"?Fd(t):jd(t)}var uo=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=y$,Error.captureStackTrace?.(this,this.constructor)}},Ci=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new Ci(t,{code:e,cause:r})}function $a(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Hd(t){fo(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Dd&&!e.has("user-agent")&&e.set("user-agent",Dd),e.has("authorization"))throw he('"options.headers" must not include the "authorization" header name',Jt);return e}function Gd(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw he('"options.signal" must return or be an instance of AbortSignal',Xe);return e}}function F0(t){return t.includes("//")?t.replace("//","/"):t}function U0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=F0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function q0(t,e,r,n){if(!(t instanceof URL))throw he(`"${e}" must be an instance of URL`,Xe);Ty(t,n?.[qd]!==!0);let o=r(new URL(t.href)),i=Hd(n?.headers);return i.set("accept","application/json"),(n?.[_n]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Gd(o,n?.signal)})}function co(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw he(`${r} must be a number`,Xe,o);if(t>0)return;if(e){if(t!==0)throw he(`${r} must be a non-negative number`,Jt,o);return}throw he(`${r} must be a positive number`,Jt,o)}catch(i){throw n?O(i.message,n,o):i}}function $e(t,e,r,n){try{if(typeof t!="string")throw he(`${e} must be a string`,Xe,n);if(t.length===0)throw he(`${e} must not be empty`,Jt,n)}catch(o){throw r?O(o.message,r,n):o}}async function wy(t,e){let r=t;if(!(r instanceof URL)&&r!==za)throw he('"expectedIssuerIdentifier" must be an instance of URL',Xe);if(!fo(e,Response))throw he('"response" must be an instance of Response',Xe);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Xd,e);Ei(e);let n=await ja(e);if($e(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==za&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',Da,{expected:r.href,body:n,attribute:"issuer"});return n}function by(t){G0(t,"application/json")}function H0(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,_$,t)}function G0(t,e){if(r$(t)!==e)throw H0(t,e)}function Zd(){return Ma(crypto.getRandomValues(new Uint8Array(32)))}function Ry(){return Zd()}function Cy(){return Zd()}function Py(){return Zd()}async function xy(t){return $e(t,"codeVerifier"),Ma(await crypto.subtle.digest("SHA-256",Ld(t)))}function Bd(t){let e=t?.[N0];return typeof e=="number"&&Number.isFinite(e)?e:0}function Wd(t){let e=t?.[D0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Vd(){return Math.floor(Date.now()/1e3)}function Na(t){if(typeof t!="object"||t===null)throw he('"as" must be an object',Xe);$e(t.issuer,'"as.issuer"')}function Kd(t){if(typeof t!="object"||t===null)throw he('"client" must be an object',Xe);$e(t.client_id,'"client.client_id"')}function _y(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Jd(t){return $e(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function Ey(t){return $e(t,'"clientSecret"'),(e,r,n,o)=>{let i=_y(r.client_id),s=_y(t),a=btoa(`${i}:${s}`);o.set("authorization",`Basic ${a}`)}}function ky(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var Z0=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function Ty(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",S$,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",w$,t)}function Sy(t,e,r,n){let o;if(typeof t!="string"||!(o=Z0(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?b$:R$,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return Ty(o,n),o}function Ay(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Sy(t.mtls_endpoint_aliases[e],e,r,n):Sy(t[e],e,r,n)}var lo=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=g$,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Pi=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=v$,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},xi=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=m$,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ia="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",B0="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",W0='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',V0="("+Ia+")\\s*=\\s*"+W0,K0="("+Ia+")\\s*=\\s*("+Ia+")",J0=new RegExp("^[,\\s]*("+Ia+")"),Y0=new RegExp("^[,\\s]*"+V0+"[,\\s]*(.*)"),X0=new RegExp("^[,\\s]*"+K0+"[,\\s]*(.*)"),Q0=new RegExp("^("+B0+")(?:$|[,\\s])(.*)");function e$(t){if(!fo(t,Response))throw he('"response" must be an instance of Response',Xe);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(J0),i=o?.[1].toLowerCase();if(!i)return;let s=n.substring(o[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let f,p;if(o=n.match(Y0)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(X0)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match(Q0)){if(Object.keys(u).length)break;[,d,n]=o;break}return}else n=s||void 0;let l={scheme:i,parameters:u};d&&(l.token68=d),r.push(l)}if(r.length)return r}async function t$(t){if(t.status>399&&t.status<500){Ei(t),by(t);try{let e=await t.clone().json();if($a(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function My(t,e,r){if(t.status!==e){s$(t);let n;throw(n=await t$(t))?(await t.body?.cancel(),new lo("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Xd,t)}}function $y(t){if(!Yd.has(t))throw he('"options.DPoP" is not a valid DPoPHandle',Jt)}function r$(t){return t.headers.get("content-type")?.split(";")[0]}async function n$(t,e,r,n,o,i,s){return await r(t,e,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[_n]||fetch)(n.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Gd(n,s?.signal)})}async function o$(t,e,r,n,o,i){let s=Ay(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[qd]!==!0);o.set("grant_type",n);let a=Hd(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&($y(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await n$(t,e,r,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}var Iy=new WeakMap,i$=new WeakMap;function Oy(t){if(!t.id_token)return;let e=Iy.get(t);if(!e)throw he('"ref" was already garbage collected or did not resolve from the proper sources',Jt);return e}async function zy(t,e,r,n,o,i){if(Na(t),Kd(e),!fo(r,Response))throw he('"response" must be an instance of Response',Xe);await My(r,200,"Token Endpoint"),Ei(r);let s=await ja(r);if($e(s.access_token,'"response" body "access_token" property',V,{body:s}),$e(s.token_type,'"response" body "token_type" property',V,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;co(a,!0,'"response" body "expires_in" property',V,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$e(s.refresh_token,'"response" body "refresh_token" property',V,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw O('"response" body "scope" property must be a string',V,{body:s});if(s.id_token!==void 0){$e(s.id_token,'"response" body "id_token" property',V,{body:s});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(co(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await C$(s.id_token,P$.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Bd(e),Wd(e),o).then(f$.bind(void 0,a)).then(c$.bind(void 0,t)).then(a$.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',Lr,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',Lr,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&co(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),i$.set(r,u),Iy.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new uo("unsupported `token_type` value",{cause:{body:s}});return s}function s$(t){let e;if(e=e$(t))throw new xi("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function a$(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',Lr,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',Lr,{expected:t,claims:e.claims,claim:"aud"});return e}function c$(t,e){let r=t[k$]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',Lr,{expected:r,claims:e.claims,claim:"iss"});return e}var Yd=new WeakSet;function u$(t){return Yd.add(t),t}var d$=Symbol();async function Ny(t,e,r,n,o,i,s){if(Na(t),Kd(e),!Yd.has(n))throw he('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Jt);$e(o,'"redirectUri"');let a=vn(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),i!==d$&&($e(i,'"codeVerifier"'),c.set("code_verifier",i)),o$(t,e,r,"authorization_code",c,s)}var l$={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function f$(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${l$[r]}) claim missing`,V,{claims:e.claims});return e}var zd=Symbol(),Nd=Symbol();async function Dy(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?p$(t,e,r,n.expectedNonce,n.maxAge,n[vy],n.recognizedTokenTypes):h$(t,e,r,n?.[vy],n?.recognizedTokenTypes)}async function p$(t,e,r,n,o,i,s){let a=[];switch(n){case void 0:n=zd;break;case zd:break;default:$e(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Nd;break;case Nd:break;default:co(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await zy(t,e,r,a,i,s);$e(c.id_token,'"response" body "id_token" property',V,{body:c});let u=Oy(c);if(o!==Nd){let d=Vd()+Bd(e),l=Wd(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",Oa,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===zd){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Lr,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',Lr,{expected:n,claims:u,claim:"nonce"});return c}async function h$(t,e,r,n,o){let i=await zy(t,e,r,void 0,n,o),s=Oy(i);if(s){if(e.default_max_age!==void 0){co(e.default_max_age,!0,'"client.default_max_age"');let a=Vd()+Bd(e),c=Wd(e);if(s.auth_time+e.default_max_age<a-c)throw O("too much time has elapsed since the last End-User authentication",Oa,{claims:s,now:a,tolerance:c,claim:"auth_time"})}if(s.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Lr,{expected:void 0,claims:s,claim:"nonce"})}return i}var m$="OAUTH_WWW_AUTHENTICATE_CHALLENGE",g$="OAUTH_RESPONSE_BODY_ERROR",y$="OAUTH_UNSUPPORTED_OPERATION",v$="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Ud="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var _$="OAUTH_RESPONSE_IS_NOT_JSON",Xd="OAUTH_RESPONSE_IS_NOT_CONFORM",S$="OAUTH_HTTP_REQUEST_FORBIDDEN",w$="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Oa="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Lr="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Da="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var b$="OAUTH_MISSING_SERVER_METADATA",R$="OAUTH_INVALID_SERVER_METADATA";function Ei(t){if(t.bodyUsed)throw he('"response" body has been used already',Jt)}async function C$(t,e,r,n,o){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:i,1:s,length:a}=t.split(".");else throw new uo("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",V,t);let c;try{c=JSON.parse(Ld(Ma(i)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",Ud,l)}if(!$a(c))throw O("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new uo('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Ld(Ma(s)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",Ud,l)}if(!$a(u))throw O("JWT Payload must be a top level object",V,t);let d=Vd()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Oa,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',Oa,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function P$(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function vn(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,V);return r}var x$=Symbol(),E$=Symbol();function Ly(t,e,r,n){if(Na(t),Kd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw he('"parameters" must be an instance of URLSearchParams, or URL',Xe);if(vn(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=vn(r,"iss"),i=vn(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case E$:if(i!==void 0)throw O('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case x$:break;default:if($e(n,'"expectedState" argument'),i!==n)throw O(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(vn(r,"error"))throw new Pi("authorization response from the server is an error",{cause:r});let a=vn(r,"id_token"),c=vn(r,"token");if(a!==void 0||c!==void 0)throw new uo("implicit and hybrid flows are not supported");return u$(new URLSearchParams(r))}async function jy(t,e,r){Na(t);let n=Ay(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[qd]!==!0),o=Hd(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let i="POST";r?.DPoP&&($y(r.DPoP),await r.DPoP.addProof(n,o,i,r.initialAccessToken)),r?.initialAccessToken&&o.set("authorization",`${o.has("dpop")?"DPoP":"Bearer"} ${r.initialAccessToken}`);let s=await(r?.[_n]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:i,redirect:"manual",signal:Gd(n,r?.signal)});return r?.DPoP?.cacheNonce(s,n),s}async function Fy(t){if(!fo(t,Response))throw he('"response" must be an instance of Response',Xe);await My(t,201,"Dynamic Client Registration Endpoint"),Ei(t);let e=await ja(t);return $e(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&$e(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&co(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function Uy(t,e){return q0(t,"resourceIdentifier",r=>(U0(r,".well-known/oauth-protected-resource",!0),r),e)}async function La(t,e){let r=t;if(!(r instanceof URL)&&r!==za)throw he('"expectedResourceIdentifier" must be an instance of URL',Xe);if(!fo(e,Response))throw he('"response" must be an instance of Response',Xe);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',Xd,e);Ei(e);let n=await ja(e);if($e(n.resource,'"response" body "resource" property',V,{body:n}),r!==za&&new URL(n.resource).href!==r.href)throw O('"response" body "resource" property does not match the expected value',Da,{expected:r.href,body:n,attribute:"resource"});return n}async function ja(t,e=by){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',Ud,n)}if(!$a(r))throw O('"response" body must be a top level object',V,{body:r});return r}var za=Symbol(),k$=Symbol();var ki="TLS certificate not trusted. Configure system trust or NODE_EXTRA_CA_CERTS.",qy={UNABLE_TO_GET_ISSUER_CERT:ki,UNABLE_TO_GET_ISSUER_CERT_LOCALLY:ki,UNABLE_TO_VERIFY_LEAF_SIGNATURE:ki,DEPTH_ZERO_SELF_SIGNED_CERT:ki,SELF_SIGNED_CERT_IN_CHAIN:ki,CERT_HAS_EXPIRED:"TLS certificate expired. Check the system clock or contact the server administrator.",ERR_TLS_CERT_ALTNAME_INVALID:"TLS certificate hostname mismatch. Verify the server URL or contact the network administrator."};function Ti(t){let e=new Set,r=t,n;for(let o=0;o<16&&!(typeof r!="object"||r===null||e.has(r));o++){if(e.add(r),"name"in r&&(r.name==="AbortError"||r.name==="TimeoutError")||"code"in r&&r.code==="ABORT_ERR")return;"code"in r&&typeof r.code=="string"&&Object.hasOwn(qy,r.code)&&(n??=r.code),r="cause"in r?r.cause:void 0}return n}function Ai(t){return Object.assign(new Error(qy[t]),{code:t})}var Zy=T$.child({prefix:"pi-mcp"}),Mi=1e4,A$=1e3,M$=401,Hy=200,$$="accounts.google.com",I$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,O$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,By;function po(){return By??globalThis.fetch}function Wy(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Vy(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function el(t){let e=Vy(t),r,n=o=>{r??=Ti(o)};try{let o=await z$(e,n),i=o?.authorization_servers?.map(s=>new URL(s))??[e];for(let s of i){let a=await F$(s,n);if(a)return Object.assign(a,{resourceScopes:o?.scopes_supported,resourceIdentifier:o?.resource})}}catch(o){throw qa(o)}throw r?Ai(r):new Error("Failed to discover metadata URL")}async function z$(t,e){try{let r=await Uy(t,{signal:AbortSignal.timeout(Mi),[_n]:By??void 0});return r.ok?await La(t,r):(r.body?.cancel().catch(()=>{}),await Ky(t,r.headers.get("www-authenticate"),e)??await Gy(t,e))}catch(r){return e(r),await Gy(t,e)}}async function Gy(t,e){for(let r of["HEAD","GET"])try{let n=await po()(t,{method:r,signal:AbortSignal.timeout(Mi)});n.body?.cancel().catch(()=>{});let o=await Ky(t,n.headers.get("www-authenticate"),e);if(o)return o}catch(n){e(n)}}async function Ky(t,e,r){let n=j$(e);if(n)try{let o=await po()(n,{signal:AbortSignal.timeout(Mi)});return await N$(t,o)}catch(o){r(o);return}}async function N$(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await La(t,new Response(r,n))}catch(o){if(!(o instanceof Ci)||o.code!==Da)throw o;let i=D$(r);if(!i||!L$(i,t))throw o;return await La(i,new Response(r,n))}}function D$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function L$(t,e){if(t.origin!==e.origin)return!1;let r=t.pathname.replace(/\/+$/,""),n=e.pathname.replace(/\/+$/,"");return r===n||n.startsWith(`${r}/`)}function j$(t){if(!t)return;let e=t.match(I$),r=t.match(O$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function F$(t,e){for(let r of U$(t))try{let n=new URL(r,t),o=await po()(n,{signal:AbortSignal.timeout(Mi)});if(o.body?.cancel().catch(()=>{}),!o.ok)continue;return n}catch(n){e(n)}}function U$(t){let e=t.pathname.startsWith("/")?t.pathname.slice(1):t.pathname;return[...e.length>0?[new URL(`/.well-known/oauth-authorization-server/${e}`,t),new URL(`/.well-known/openid-configuration/${e}`,t),new URL(`/${e}/.well-known/openid-configuration`,t)]:[],new URL("/.well-known/oauth-authorization-server",t),new URL("/.well-known/openid-configuration",t)]}async function tl(t){try{let e=await po()(t,{signal:AbortSignal.timeout(Mi)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await q$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await wy(o,new Response(r,n))}catch(e){throw qa(e)}}async function q$(t){if(!t.ok)throw new Error("Invalid status code from discovery response");let e=await t.json();if(!e.issuer||typeof e.issuer!="string")throw new Error("Invalid issuer from discovery response");return new URL(e.issuer)}var Qd=class extends Error{constructor(e){super(`This MCP server's authorization server (\`${e}\`) does not support Dynamic Client Registration. Configure a static OAuth Client ID and Secret in the Advanced section.`),this.name="McpOAuthDcrUnsupportedError",this.issuer=e}};function H$(t){if(!t.clientId)throw new Error("clientId is required to build client from config");let e=t.clientSecret?.trim();return{client_id:t.clientId,...e?{client_secret:e}:{}}}async function rl({config:t,serverMetadata:e,redirectUris:r,preferStaticClient:n=!1}){let o=t.clientId?.trim(),i=t.clientSecret?.trim();if(!!o&&(n||!!i||!e.registration_endpoint))return H$({...t,clientId:o});if(!e.registration_endpoint)throw new Qd(e.issuer);return await G$(e,r)}async function G$(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await jy(t,{client_name:uy,client_uri:dy,logo_uri:ly,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[_n]:Z$});return n.ok||Zy.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Fy(n)}catch(r){throw qa(r)}}async function Z$(t,e){let r=await po()(t,Wy(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Zy.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${W$(n)}`),r.status===200&&(o.status=201,o.statusText="Created"),o.status===201)try{let i=JSON.parse(n);i.client_secret_expires_at||(i.client_secret_expires_at=0),"client_secret"in i&&!i.client_secret&&(i.client_secret=void 0),n=JSON.stringify(i)}catch{}return new Response(n,o)}function B$(t,e){let r=new Headers(e?.headers),n=r.get("content-type"),o=e;return n?.toLowerCase().startsWith("application/x-www-form-urlencoded;")&&(r.set("content-type","application/x-www-form-urlencoded"),o={...e,headers:r}),po()(t,Wy(o))}function W$(t){try{let e=JSON.parse(t);for(let r of Object.keys(e))/secret|token/i.test(r)&&(e[r]="[REDACTED]");return JSON.stringify(e)}catch{return t.length>Hy?`${t.slice(0,Hy)}\u2026`:t}}async function Fa(t,e,r,n,o,i,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=Ry(),c=await xy(a),u=Cy(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!s?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=Vy(i??t).toString(),m=new URL(r.authorization_endpoint);return m.searchParams.set("response_type","code"),m.searchParams.set("client_id",e.client_id),m.searchParams.set("code_challenge",c),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("redirect_uri",n),m.searchParams.set("resource",h),m.searchParams.set("state",u),p&&m.searchParams.set("scope",p),l?.includes("offline_access")&&m.searchParams.set("prompt","consent"),m.hostname===$$&&(m.searchParams.set("access_type","offline"),m.searchParams.set("prompt","consent")),r.code_challenge_methods_supported?.includes("S256")||(d=Py(),m.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:m}}function Ua(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function nl(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await Fa(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function V$(t,e,r){let n=await Ny(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[_n]:B$,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Dy(t.serverMetadata,t.client,await K$(n))}async function ol(t,e){try{let r=Ly(e.serverMetadata,e.client,t,e.state),n=await Y$(e.client,o=>V$(e,r,o));return eI(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw qa(r)}}async function K$(t){let e=await t.text(),r={status:t.status,statusText:t.statusText,headers:t.headers};try{let n=JSON.parse(e);if("id_token"in n)return n.id_token=void 0,new Response(JSON.stringify(n),r)}catch{}return new Response(e,r)}function Jy(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function J$(t){let e=Jy(t);return e===void 0?ky():t.token_endpoint_auth_method==="client_secret_basic"?Ey(e):Jd(e)}async function Y$(t,e){try{return await e(J$(t))}catch(r){let n=X$(t);if(n&&Q$(r))return await e(n);throw r}}function X$(t){let e=Jy(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return Jd(e)}function Q$(t){return t instanceof lo?t.error==="invalid_client"||t.error==="unauthorized":t instanceof xi?t.status===M$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function eI(t,e,r,n,o){if(!t.access_token)throw new Error("OAuth token response contained no access token");return{accessToken:t.access_token,refreshToken:t.refresh_token||n,expiresAt:t.expires_in?Date.now()+t.expires_in*A$:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function qa(t){let e=Ti(t);if(e)return Ai(e);if(t instanceof lo||t instanceof Pi){let r=t.error_description?` (${t.error_description})`:"";return new Error(`${t.message}${r}`,{cause:t})}return t instanceof Error?t:new Error(String(t))}var tI=/(authorization|auth[_-]?token|access[_-]?token|refresh[_-]?token|\btoken\b|secret|password|passwd|\bpwd\b|api[_-]?key|apikey|client[_-]?secret|private[_-]?key|cookie|session[_-]?id|credential|bearer)/i,Yy=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,Xy=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,Qy=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Sn="[redacted]",rI=/[.*+?^${}()|[\]\\]/g;function il(t,e){return e.chars-=t.length,e.chars<0?e.marker:e.redactText(t)}function nI(t,e,r){try{let n=Array.isArray(t);if(n&&t.length>r.nodes)return r.marker;let o=Object.getPrototypeOf(t);if(!n&&o!==null&&o!==Object.prototype)return r.marker;r.active.add(t);let i=Object.keys(t);if(i.length>r.nodes)return r.marker;let s=n?[]:Object.create(null);for(let a of i){if(n&&!/^(0|[1-9]\d*)$/.test(a))continue;let c=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,n?a:il(a,r),{value:c&&"value"in c?ev(c.value,e+1,r):r.marker,enumerable:!0,configurable:!0,writable:!0})}return s}catch{return r.marker}finally{r.active.delete(t)}}function ev(t,e,r){if(--r.nodes<0||e>16)return r.marker;if(typeof t=="string")return il(t,r);if(t===void 0)return t;if(t===null||typeof t=="boolean"||typeof t=="number"){if(typeof t=="number"&&!Number.isFinite(t))return r.marker;let n=JSON.stringify(t);return il(n,r)===n?t:r.marker}return typeof t!="object"||r.active.has(t)?r.marker:nI(t,e,r)}function al(t){let e=[...new Set(t)].filter(Boolean);if(e.length>128||e.reduce((i,s)=>i+s.length,0)>262144)return{text:()=>"",value:()=>{}};let r=e.length?new RegExp(e.sort((i,s)=>s.length-i.length).map(i=>i.replace(rI,"\\$&")).join("|"),"g"):void 0,n=e.some(i=>Sn.includes(i))?"":Sn,o=i=>{if(i.length>262144)return n;let s=r?i.replace(r,()=>n):i;return e.some(a=>s.includes(a))?n:s};return{text:o,value:i=>ev(i,0,{redactText:o,marker:n,nodes:1e4,chars:262144,active:new WeakSet})}}var oI=500,iI=8192,sI=6;function aI(t){return Yy.test(t)||Xy.test(t)||Qy.test(t)}var cI=new RegExp(Yy.source,"g"),uI=new RegExp(Xy.source,"gi"),dI=new RegExp(Qy.source,"g");function tv(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function Ha(t){return t&&tv(t,iI).replace(cI,Sn).replace(uI,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Sn}`).replace(dI,Sn)}function sl(t,e,r){if(e)return Sn;if(typeof t=="string")return aI(t)?Sn:t;if(t===null||typeof t!="object")return t;if(r>=sI)return"[truncated]";if(Array.isArray(t))return t.map(o=>sl(o,!1,r+1));let n={};for(let[o,i]of Object.entries(t))n[o]=sl(i,tI.test(o),r+1);return n}function rv(t,e=oI){if(t==null)return;let r=sl(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return tv(n,e)}var ov={reportError:()=>{}},nv=Symbol.for("__pi_mcp_error_reporter_slot__");function iv(){let t=globalThis,e=t[nv];return e||(e={reporter:null},t[nv]=e),e}function sv(t){let e=iv(),r=e.reporter??ov;return e.reporter=t,r}function lI(){return iv().reporter??ov}function $i(t,e){try{lI().reportError(t,e)}catch{}}import{logger as fI}from"@hermes/logger";var cl=fI.child({prefix:"pi-mcp"});function av(t,e,r){let n=0,o=0,i=r?.authoritative?{}:{...t.headerSecrets};for(let[s,a]of Object.entries(e))typeof a=="string"&&a!==""?(i[s]=a,n++):a===null||a===""?s in i&&(delete i[s],o++):cl.warn(`Skipping malformed header-secret entry "${s}"`);t.headerSecrets=i,t.headerSecretFailures??={};for(let s of Object.keys(i))delete t.headerSecretFailures[s];cl.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function cv(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Td)){let o=t.headerSecrets[e];if(o!==void 0)return o;let i=t.headerSecretFailures[e];if(i==="missing"||i==="permission_denied")return{reason:i}}let r=t.secretsClient;if(r)try{let o=await r.getSecret(e);return o!==void 0?(delete t.headerSecretFailures[e],o):{reason:t.headerSecretFailures[e]??"missing"}}catch{return{reason:"transient"}}let n=t.headerSecretFailures[e];return n===void 0?void 0:{reason:n}}}function uv(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[i,s]of Object.entries(e))(s==="missing"||s==="permission_denied"||s==="transient")&&(n[i]=s,delete o[i]);t.headerSecrets=o,t.headerSecretFailures=n,cl.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function dv(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as pI}from"@hermes/logger";var Ii=pI.child({prefix:"pi-mcp"}),hI="$augment-",Oi=/\$augment-[a-zA-Z0-9_.-]+/g,mI=new RegExp(Oi.source);function jr(t){return mI.test(t)}function Ga(t){return t.slice(hI.length)}function zi(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(Oi))e.add(Ga(n[0]));return[...e].sort()}var gI=["permission_denied","missing","transient"];function lv(t){let e=new Set(t);return gI.find(r=>e.has(r))??"missing"}var yt=class extends Error{constructor(e,r,n,o=n===void 0?"missing":"transient"){super(`MCP server "${e}" not started: missing secret(s) ${r.join(", ")}`,n===void 0?void 0:{cause:n}),this.name="McpSecretResolutionError",this.serverName=e,this.missingKeys=r,this.reason=o}};async function fv(t,e,r,n,o,i,s){let a=[...t.matchAll(Oi)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=Ga(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),i.set(f,p===void 0?"missing":p.reason),Ii.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),Ii.warn(`Secret "${f}" resolved empty for "${e}"`));let m=c.slice(0,l),g=s?s(h,m):h;c=m+g+c.slice(l+d.length),Ii.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),i.set(f,"transient"),Ii.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function pv({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,i=new Set,s=new Map;for(let[a,c]of Object.entries(t)){if(!jr(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){Ii.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await fv(c,a,r,o,i,s)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...i].sort(),...s.size===0?{}:{failureReasons:Object.fromEntries([...s.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var yI=/["$`\\]/g;function vI(t){let e="unquoted",r=0;for(;r<t.length;){let n=t[r];if(e==="single"){n==="'"&&(e="unquoted"),r+=1;continue}if(e==="double"){if(n==="\\"){r+=2;continue}n==='"'&&(e="unquoted"),r+=1;continue}if(n==="\\"){r+=2;continue}n==="'"?e="single":n==='"'&&(e="double"),r+=1}return e}function _I(t,e){let r=vI(e);if(r==="double")return t.replace(yI,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function hv(t,e,r=!0){let n=new Set,o=new Set,i=new Map;return{resolved:await fv(t,"command",e,n,o,i,r?_I:void 0),unresolvedKeys:[...n].sort(),emptyKeys:[...o].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}import{AsyncLocalStorage as Qq}from"node:async_hooks";var mv,ul=Object.freeze({status:"aborted"});function S(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=s.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function s(a){var c;let u=r?.Parent?new i:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Yt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ho=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(mv=globalThis).__zod_globalConfig??(mv.__zod_globalConfig={});var mo=globalThis.__zod_globalConfig;function Qe(t){return t&&Object.assign(mo,t),mo}var H={};Xu(H,{BIGINT_FORMAT_RANGES:()=>_v,Class:()=>ll,NUMBER_FORMAT_RANGES:()=>yl,aborted:()=>qr,allowsEval:()=>hl,assert:()=>CI,assertEqual:()=>SI,assertIs:()=>bI,assertNever:()=>RI,assertNotEqual:()=>wI,assignProp:()=>Fr,base64ToUint8Array:()=>wv,base64urlToUint8Array:()=>UI,cached:()=>yo,captureStackTrace:()=>Wa,cleanEnum:()=>FI,cleanRegex:()=>ji,clone:()=>vt,cloneDef:()=>xI,createTransparentProxy:()=>$I,defineLazy:()=>X,esc:()=>Ba,escapeRegex:()=>dr,explicitlyAborted:()=>vl,extend:()=>zI,finalizeIssue:()=>_t,floatSafeRemainder:()=>fl,getElementAtPath:()=>EI,getEnumValues:()=>Di,getLengthableOrigin:()=>Fi,getParsedType:()=>MI,getSizableOrigin:()=>Sv,hexToUint8Array:()=>HI,isObject:()=>wn,isPlainObject:()=>Ur,issue:()=>vo,joinValues:()=>Za,jsonStringifyReplacer:()=>go,merge:()=>DI,mergeDefs:()=>ur,normalizeParams:()=>M,nullish:()=>Li,numKeys:()=>AI,objectClone:()=>PI,omit:()=>OI,optionalKeys:()=>gl,parsedType:()=>_l,partial:()=>LI,pick:()=>II,prefixIssues:()=>lr,primitiveTypes:()=>vv,promiseAllObject:()=>kI,propertyKeyTypes:()=>ml,randomString:()=>TI,required:()=>jI,safeExtend:()=>NI,shallowClone:()=>yv,slugify:()=>pl,stringifyPrimitive:()=>Va,uint8ArrayToBase64:()=>bv,uint8ArrayToBase64url:()=>qI,uint8ArrayToHex:()=>GI,unwrapMessage:()=>Ni});function SI(t){return t}function wI(t){return t}function bI(t){}function RI(t){throw new Error("Unexpected value in exhaustive check")}function CI(t){}function Di(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Za(t,e="|"){return t.map(r=>Va(r)).join(e)}function go(t,e){return typeof e=="bigint"?e.toString():e}function yo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Li(t){return t==null}function ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fl(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var gv=Symbol("evaluating");function X(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==gv)return n===void 0&&(n=gv,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function PI(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Fr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ur(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function xI(t){return ur(t._zod.def)}function EI(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function kI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function TI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Ba(t){return JSON.stringify(t)}function pl(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Wa="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function wn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hl=yo(()=>{if(mo.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Ur(t){if(wn(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(wn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yv(t){return Ur(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function AI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var MI=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},ml=new Set(["string","number","symbol"]),vv=new Set(["string","number","bigint","boolean","symbol","undefined"]);function dr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function vt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function M(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function $I(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Va(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var yl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},_v={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function II(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=ur(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return Fr(this,"shape",s),s},checks:[]});return vt(t,i)}function OI(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=ur(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Fr(this,"shape",s),s},checks:[]});return vt(t,i)}function zI(t,e){if(!Ur(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=ur(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return Fr(this,"shape",i),i}});return vt(t,o)}function NI(t,e){if(!Ur(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=ur(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Fr(this,"shape",n),n}});return vt(t,r)}function DI(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=ur(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Fr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return vt(t,r)}function LI(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=ur(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Fr(this,"shape",c),c},checks:[]});return vt(e,s)}function jI(t,e,r){let n=ur(e._zod.def,{get shape(){let o=e._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new t({type:"nonoptional",innerType:o[s]});return Fr(this,"shape",i),i}});return vt(e,n)}function qr(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vl(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function lr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ni(t){return typeof t=="string"?t:t?.message}function _t(t,e,r){let n=t.message?t.message:Ni(t.inst?._zod.def?.error?.(t))??Ni(e?.error?.(t))??Ni(r.customError?.(t))??Ni(r.localeError?.(t))??"Invalid input",{inst:o,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function Sv(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _l(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function vo(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function FI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function wv(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function bv(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function UI(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return wv(e+r)}function qI(t){return bv(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function HI(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function GI(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var ll=class{constructor(...e){}};var Rv=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,go,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ka=S("$ZodError",Rv),Sl=S("$ZodError",Rv,{Parent:Error});function wl(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function bl(t,e=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(s))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return n(t),r}var Ja=t=>(e,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Yt;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>_t(c,i,Qe())));throw Wa(a,o?.callee),a}return s.value};var Ya=t=>async(e,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>_t(c,i,Qe())));throw Wa(a,o?.callee),a}return s.value};var Ui=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Yt;return i.issues.length?{success:!1,error:new(t??Ka)(i.issues.map(s=>_t(s,o,Qe())))}:{success:!0,data:i.value}},qi=Ui(Sl),Hi=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>_t(s,o,Qe())))}:{success:!0,data:i.value}},Xa=Hi(Sl),Cv=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ja(t)(e,r,o)};var Pv=t=>(e,r,n)=>Ja(t)(e,r,n);var xv=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ya(t)(e,r,o)};var Ev=t=>async(e,r,n)=>Ya(t)(e,r,n);var kv=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ui(t)(e,r,o)};var Tv=t=>(e,r,n)=>Ui(t)(e,r,n);var Av=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Hi(t)(e,r,o)};var Mv=t=>async(e,r,n)=>Hi(t)(e,r,n);var $v=/^[cC][0-9a-z]{6,}$/,Iv=/^[0-9a-z]+$/,Ov=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,zv=/^[0-9a-vA-V]{20}$/,Nv=/^[A-Za-z0-9]{27}$/,Dv=/^[a-zA-Z0-9_-]{21}$/,Lv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var jv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Rl=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Fv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var BI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Uv(){return new RegExp(BI,"u")}var qv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Hv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Gv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Zv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Bv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Cl=/^[A-Za-z0-9_-]*$/;var Wv=/^https?$/,Vv=/^\+[1-9]\d{6,14}$/,Kv="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Jv=new RegExp(`^${Kv}$`);function Yv(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Xv(t){return new RegExp(`^${Yv(t)}$`)}function Qv(t){let e=Yv({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Kv}T(?:${n})$`)}var e_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},t_=/^-?\d+n?$/,r_=/^-?\d+$/,Pl=/^-?\d+(?:\.\d+)?$/,n_=/^(?:true|false)$/i,o_=/^null$/i;var i_=/^[^A-Z]*$/,s_=/^[^a-z]*$/;var Oe=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),a_={number:"number",bigint:"bigint",object:"date"},xl=S("$ZodCheckLessThan",(t,e)=>{Oe.init(t,e);let r=a_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),El=S("$ZodCheckGreaterThan",(t,e)=>{Oe.init(t,e);let r=a_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),c_=S("$ZodCheckMultipleOf",(t,e)=>{Oe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):fl(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),u_=S("$ZodCheckNumberFormat",(t,e)=>{Oe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=yl[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,r&&(a.pattern=r_)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}});var d_=S("$ZodCheckMaxLength",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let s=Fi(o);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),l_=S("$ZodCheckMinLength",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let s=Fi(o);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),f_=S("$ZodCheckLengthEquals",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,i=o.length;if(i===e.length)return;let s=Fi(o),a=i>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Zi=S("$ZodCheckStringFormat",(t,e)=>{var r,n;Oe.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),p_=S("$ZodCheckRegex",(t,e)=>{Zi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),h_=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=i_),Zi.init(t,e)}),m_=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=s_),Zi.init(t,e)}),g_=S("$ZodCheckIncludes",(t,e)=>{Oe.init(t,e);let r=dr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),y_=S("$ZodCheckStartsWith",(t,e)=>{Oe.init(t,e);let r=new RegExp(`^${dr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),v_=S("$ZodCheckEndsWith",(t,e)=>{Oe.init(t,e);let r=new RegExp(`.*${dr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var __=S("$ZodCheckOverwrite",(t,e)=>{Oe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Qa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
24
|
+
`)}function Wt(t){let e={name:so,label:so,description:R0(),parameters:ey.Unsafe(m0),execute:(n,o,i,s,a)=>w0(t,a,o)},r={name:Lr,label:Lr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:ey.Unsafe(g0),execute:(n,o,i,s)=>b0(t,o,i,{toolCallId:n},s)};Qg(so,"mcp"),Qg(Lr,"mcp"),t.registerTool(e),t.registerTool(r),Or(e),Or(r),ry.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{redactSecrets as Nx,traceparentForToolCall as xH}from"@augmentcode/auggie-v2";import{logger as kH,logPublic as TH}from"@hermes/logger";import{logger as M0}from"@hermes/logger";import{logger as C0}from"@hermes/logger";function yn(t){return new Promise(e=>setTimeout(e,t))}var oy=C0.child({prefix:"pi-mcp"}),_i={maxTries:3,initialMs:500,mult:2,maxMs:2e3},kd=3e4,ur=200,yt=class extends Error{constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function Td(t){return t instanceof yt?t.statusCode>=500:!0}async function vn(t){let e;for(let r=0;r<_i.maxTries;r++)try{return await t()}catch(n){if(e=n,!Td(n))throw n;if(r<_i.maxTries-1){let o=Math.min(_i.initialMs*_i.mult**r,_i.maxMs);await yn(o)}}throw e}var ka=class{constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??kd}async callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:r===void 0?"{}":JSON.stringify({product_type:r}),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>""),s=i.length>ur?`${i.slice(0,ur)}\u2026[truncated]`:i;throw new yt(o.status,o.statusText,s)}return await o.json()}getMcpTenantConfigs(e){return vn(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return vn(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function iy(t,e){let r=[],[n,o]=await Promise.allSettled([t.getMcpTenantConfigs(e),t.getMcpUserConfigs(e)]),i={},s={};if(n.status==="fulfilled")i=n.value;else{let a=`Failed to fetch tenant MCP configs: ${String(n.reason)}`;oy.warn(a),r.push({message:a})}if(o.status==="fulfilled")s=o.value;else{let a=`Failed to fetch user MCP configs: ${String(o.reason)}`;oy.warn(a),r.push({message:a})}return{tenant:i,user:s,diagnostics:r}}function P0(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var sy=32;function E0(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>sy&&(e=e.slice(0,sy)),e=e.replace(/_+$/,""),e}function ay(t,e){let r=e?E0(e):"",n=P0(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function cy(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var x0=1e12,k0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function T0(t){let e=k0.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),i=Number(e[4]),s=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||i>23||s>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function A0(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<x0?t*1e3:t;if(typeof t=="string")return T0(t)}function uy(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:A0(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Vt=M0.child({prefix:"pi-mcp"}),Z=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},co=class extends Error{},ly=[100,500],$0=ly.length+1,I0=t=>new Promise(e=>{setTimeout(e,t)});function dy(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Md="augment.mcp-access-token.",O0=JSON.stringify({retired:!0}),Ta=3;function Kt(t){return`${Md}${t}`}function Aa(t){return`legacy:${t}`}function Mt(t){return t?.id?ay(t.id,t.name):void 0}function bi(t){if(t)return{type:t.type??null,id:t.id??null,name:t.name??null,url:fy(t.url),auth:null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function fy(t){if(typeof t!="string")return null;try{return new URL(t).toString()}catch{return t}}function Ri(t){if(typeof t=="string")try{return Ri(JSON.parse(t))??t}catch{return t}if(typeof t!="object"||t===null||Array.isArray(t))return t===void 0?void 0:JSON.stringify(t);let e=t;return JSON.stringify({type:e.type??null,id:e.id??null,name:e.name??null,url:fy(e.url),auth:null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function $t(t){return Ri(bi(t))}function z0(t){return Ri(bi(t))}function N0(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function ao(t){try{let e=JSON.parse(t);return{credentialIdentity:Ri(e.credentialIdentity),state:N0(e)}}catch{return{}}}function Si(t,e){let r={...t,type:"oauth",credentialIdentity:bi(e)};return JSON.stringify(r)}function _n(t,e){let r=cy({accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.client.client_secret,expiresAt:t.expiresAt,resource:t.resource,serverMetadata:t.serverMetadata,client:t.client});return JSON.stringify({...JSON.parse(r),credentialIdentity:bi(e),credentialState:"active"})}function D0(t){return JSON.stringify({credentialIdentity:bi(t),credentialState:"retired",retired:!0})}function L0(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=z0(e),i=Ri(n.credentialIdentity);if(!(o&&(i===void 0?e?.auth!=="oauth":i!==o))&&!(typeof n.accessToken!="string"||n.accessToken.length===0||typeof n.serverMetadata!="object"||n.serverMetadata===null||typeof n.client!="object"||n.client===null))return{identityMatched:o!==void 0&&i===o,token:n}}function Ad(t){try{let e=uy(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:void 0,authorization_endpoint:typeof r.authorization_endpoint=="string"?r.authorization_endpoint:void 0,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var wi=class{constructor(e,r,n,o=I0){this._memory=new Qn;this._dirtyGenerations=new Map;this._durableQueues=new Map;this._registryMemoryWriteGenerations=new Map;this._registryMemoryAuthorities=new Map;this._registryMemoryCommittedAuthorities=new Map;this._nextGeneration=0;if(this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"){this._memory.seed(n);for(let[i,s]of n.credentialIdentities??[]){let a=$t(s);a&&this._registryMemoryCommittedAuthorities.set(i,a)}}}get(e){return this._memory.get(e)}commit(e,r,n){this._memory.commit(e,r,n);let o=$t(n);o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e)}hasCredentialIdentity(e,r){return this._memory.hasCredentialIdentity(e,r)}reconcileCredentialIdentity(e,r,n){if(!this._memory.reconcileCredentialIdentity(e,r,n))return!1;let o=$t(n);return o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e),!0}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,n,o)}).catch(()=>{Vt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).then(o=>{o&&this._memory.get(e)===r&&this.commit(e,r,n)}).catch(()=>{Vt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let i=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,n,i)});return}let o=await this._persist(e,r,n,!1);this.commit(e,r,o?n:void 0)}_beginRegistryMemoryWrite(e,r){let n=$t(r);if(!n)throw new Z;let o=(this._registryMemoryWriteGenerations.get(e)??0)+1;return this._registryMemoryWriteGenerations.set(e,o),this._registryMemoryAuthorities.set(e,n),{generation:o,identity:n,retirementGeneration:this._memory.credentialRetirementGeneration(e)}}_commitRegistryMemoryWrite(e,r,n,o){this._registryMemoryWriteGenerations.get(e)!==o.generation||this._registryMemoryAuthorities.get(e)!==o.identity||this._memory.credentialRetirementGeneration(e)!==o.retirementGeneration||(this._memory.commit(e,r,n),this._registryMemoryCommittedAuthorities.set(e,o.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=Mt(e),n=$t(e),o=this._getClient();if(!(!r||!n||!o||!e))try{return await this._enqueueWrite(r,()=>this._captureAuthenticatedIdentityVersion({client:o,key:r,identity:n,registry:e}))}catch{throw new Z}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<Ta;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new Z}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:i}=e,s=await r.getUserSecretWithVersion(n);if(!s)return"0";let a=ao(s.value);if(a.state==="retired")return s.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new Z;if(a.credentialIdentity===o&&a.state==="active")return s.version;let c=Ad(s.value);if(!c)throw new Z;try{await r.upsertUserSecret(n,_n(c,i),s.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Mt(e),n=$t(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new Z;return}try{return await this._enqueueWrite(r,async()=>{let i=await o.getUserSecretWithVersion(r);if(!i)throw new Z;let s=ao(i.value);if(s.state!=="active"||s.credentialIdentity!==n||!Ad(i.value))throw new Z;return i.version})}catch{throw new Z}}persistAuthenticated(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}persistRefresh(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}async _persistAuthenticated(e,r,n,o){let i=this._getClient(),s=Mt(n),a=n&&s&&i&&o!==void 0?this._enqueueWrite(s,()=>i.upsertUserSecret(s,_n(r,n),o)):void 0,c=this._shouldPersist()&&i?()=>this._writeLegacyKey(e,r,!1,n):void 0;if(a)return this._drainRegistryWrites(e,a,c,void 0,n);if(n?.id||this._shouldPersist()&&!i)throw new Z;if(c)return{revision:await this._asPersistenceResult(c()),domain:Aa(e)}}restoreAfterSupersededRefresh(e,r,n,o,i,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,i,s)}async restoreAfterSupersededAuthentication(e,r,n,o,i,s=o){let a=this._getClient(),c=Mt(o),u;if(c&&o){if(!a||!s||i?.domain!==`private:${o.id}`||Mt(s)!==c)throw new Z;if(u=await this._enqueueWrite(c,()=>this._restoreRegistryCredential({client:a,key:c,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s,persistedRevision:i})),!u)return}if(!c&&Mt(s))throw new Z;if(!this._shouldPersist())return u;if(!a)throw new Z;if(c&&o){try{await this._enqueueWrite(Kt(e),()=>this._restoreLegacyCredential({client:a,key:Kt(e),persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s}))}catch{Vt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return u}if(i?.domain!==Aa(e))throw new Z;try{return await this._enqueueWrite(Kt(e),()=>this._restoreLegacyCredentialExact({client:a,key:Kt(e),serverName:e,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:s,persistedRevision:i}))}catch{throw new Z}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:i,currentToken:s,persistedIdentity:a,currentIdentity:c,persistedRevision:u}=e,d=await r.getUserSecretWithVersion(n);if(!(!d||d.version!==u.revision||d.value!==Si(i,a)))try{return{revision:await r.upsertUserSecret(n,Si(s,c),u.revision),domain:Aa(o)}}catch(l){if(this._isVersionConflict(l))return;throw l}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:i,persistedIdentity:s,currentIdentity:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==_n(o,s)))try{return{revision:await r.upsertUserSecret(n,_n(i,a),c.revision),domain:`private:${a.id}`}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:i,persistedIdentity:s,currentIdentity:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.value!==Si(o,s)))try{await r.upsertUserSecret(n,Si(i,a),c.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async _drainRegistryWrites(e,r,n,o,i){let s;try{s=await r}catch{throw new Z}if(o?.(),i?.id&&!s)throw new Z;try{await n?.()}catch{Vt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return i?.id&&s?{revision:s,domain:`private:${i.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let i=$t(o);if(!i)throw new Z;for(let s=0;s<Ta;s+=1){let a=await e.getUserSecretWithVersion(r),c=a?ao(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==i)throw new Z;try{return await this._upsertUserSecretOnce(e,r,_n(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new Z}async _retireRegistryCredential(e,r,n){let o=$t(n);if(!o)throw new Z;for(let i=0;i<Ta;i+=1){let s=await e.getUserSecretWithVersion(r),a=s?ao(s.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(s&&a.credentialIdentity===void 0)throw new Z;try{await this._upsertUserSecretOnce(e,r,D0(n),s?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new Z}_isVersionConflict(e){return e instanceof yt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,i){let s=this._getClient(),a=Mt(n),c=a&&n&&s?this._enqueueWrite(a,()=>{let d=this._getClient();if(!d)throw new Error("MCP secrets client unavailable");return this._writeRegistryCredential(d,a,r,n)},{credentialShape:"registry",operation:"write"}):void 0,u=this._shouldPersist()&&s?()=>this._writeLegacyKey(e,r,o,n):void 0;if(c)return this._drainRegistryWrites(e,c,u,i,n);if(n?.id||this._shouldPersist()&&!s)throw new Z;if(u)return{revision:await this._asPersistenceResult(u()),domain:Aa(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new Z}}_enqueueWrite(e,r,n){let o=dy(e),i=++this._nextGeneration;n?.onGeneration?.(i);let s=this._durableQueues.get(o),a=s??{latestGeneration:i,latestMutationGeneration:n?i:0,tail:Promise.resolve()};a.latestGeneration=i,n&&(a.latestMutationGeneration=i),s||this._durableQueues.set(o,a);let c=()=>this._runPersistence(a,i,r,n),u=s?a.tail.catch(()=>{}).then(c):c();return a.tail=u,u.finally(()=>{a.latestGeneration===i&&this._durableQueues.get(o)?.tail===u&&this._durableQueues.delete(o)}).catch(()=>{}),u}async _runPersistence(e,r,n,o){let i=o?$0:1;for(let s=0;s<i;s+=1){if(this._isLegacyPersistenceGateClosed(o))throw new co;try{return await n()}catch(a){this._throwIfPersistenceCanceled(e,r,o);let c=this._persistenceRetryDelay(a,s,o);if(c===void 0)throw a;await this._delay(c)}}throw new Z}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new co}_persistenceRetryDelay(e,r,n){let o=n?ly[r]:void 0,i=!(e instanceof Z)&&Td(e);if(o===void 0||!i){n&&Vt.warn("MCP OAuth credential persistence exhausted retries",{attempts:r+1,credentialShape:n.credentialShape,operation:n.operation});return}return o}_upsertUserSecretOnce(e,r,n,o){return typeof e.upsertUserSecretOnce=="function"?e.upsertUserSecretOnce(r,n,o):e.upsertUserSecret(r,n,o)}_deleteUserSecretOnce(e,r){return typeof e.deleteUserSecretOnce=="function"?e.deleteUserSecretOnce(r):e.deleteUserSecret(r)}_writeLegacyKey(e,r,n,o){let i=0,s=this._enqueueWrite(Kt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,Kt(e),Si(r,o));return this._dirtyGenerations.get(e)===i&&this._dirtyGenerations.delete(e),c},{credentialShape:"legacy",operation:"write",onGeneration:a=>{i=a,this._dirtyGenerations.set(e,a)}});return s.catch(a=>{(a instanceof co||!n)&&this._dirtyGenerations.get(e)===i&&this._dirtyGenerations.delete(e)}),s}retireCredential(e,r,n){let o=$t(r),i=this._registryMemoryCommittedAuthorities.get(e),s=n?.preserveNameState===!0&&(i===void 0||i!==o),a=(this._registryMemoryWriteGenerations.get(e)??0)+1;this._registryMemoryWriteGenerations.set(e,a),this._registryMemoryAuthorities.delete(e);let c=this._getClient(),u=Mt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new Z));let l=this._shouldPersist()&&!s,f;return l&&(c?f=this._enqueueWrite(Kt(e),async()=>{let p=await c.upsertUserSecret(Kt(e),O0)}):f=Promise.reject(new Z)),this._awaitRetirements(e,d,f).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:s}),s||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,i]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Vt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),i.status==="rejected"&&Vt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(i.status==="rejected")throw i.reason}delete(e,r){if(this._memory.delete(e),this._memory.clearAuthRequired(e),this._dirtyGenerations.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._retireRegistryKey(r),!this._shouldPersist()){this._dirtyGenerations.delete(e);return}let n=Kt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let s=this._getClient();if(!s)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(s,n)},{credentialShape:"legacy",operation:"delete",onGeneration:s=>{o=s,this._dirtyGenerations.set(e,s)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(s=>{s instanceof co&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Mt(e);!r||!e||!this._canScheduleDurableOperation(r)||this._enqueueWrite(r,async()=>{let n=this._getClient();if(!n)throw new Error("MCP secrets client unavailable");await this._retireRegistryCredential(n,r,e)},{credentialShape:"registry",operation:"delete"}).catch(()=>{Vt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(dy(e)))}markAuthRequired(e){this._memory.markAuthRequired(e)}isAuthRequired(e){return this._memory.isAuthRequired(e)}clearAuthRequired(e){this._memory.clearAuthRequired(e)}hasInFlightWrite(e){return this._dirtyGenerations.has(e)}async _loadRegistryToken(e,r){let n=Mt(r),o=$t(r);if(!n||!o||!r)return{identityRejected:!1};try{return await this._enqueueWrite(n,()=>this._readRegistryToken({client:e,key:n,expectedIdentity:o,registry:r}))}catch{return{identityRejected:!0}}}async _readRegistryToken(e){for(let r=0;r<Ta;r+=1){let n=await this._readRegistryTokenAttempt(e);if(n!==void 0)return n}return{identityRejected:!0}}async _readRegistryTokenAttempt(e){let{client:r,key:n,expectedIdentity:o,registry:i}=e,s=await r.getUserSecretWithVersion(n);if(!s)return{identityRejected:!1,authorityVersion:"0"};let a=ao(s.value);if(a.state==="retired"||(a.credentialIdentity===void 0?i.auth!=="oauth":a.credentialIdentity!==o))return{identityRejected:!0};let c=Ad(s.value);if(!c)return{identityRejected:!0};if(a.credentialIdentity===o&&a.state==="active")return{identityRejected:!1,token:c};try{return await r.upsertUserSecret(n,_n(c,i),s.version),{identityRejected:!1,token:c}}catch(u){return this._isVersionConflict(u)?void 0:{identityRejected:!0}}}async _importLegacyToken(e,r,n,o){let i=Mt(n),s=$t(n);if(!i||!s||!n||o===void 0)return;let a=await this._loadLegacyToken(e,r,n);if(a)try{return await this._enqueueWrite(i,async()=>{let c=await e.getUserSecretWithVersion(i);if((c?.version??"0")===o){if(c){let u=ao(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==s)return}return await e.upsertUserSecret(i,_n(a.token,n),o),{identityMatched:!0,token:a.token}}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(Kt(r));return o?L0(o,n):void 0}catch{return}}async ensureLoaded(e,r){if(this._memory.get(e)||!this._shouldPersist()||this.hasInFlightWrite(e))return;let o=this._getClient();if(!o)return;let i=this._memory.credentialRetirementGeneration(e),s=await this._loadRegistryToken(o,r);if(s.identityRejected)return;let a=s.token?{identityMatched:!0,token:s.token}:void 0;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==i)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,s.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Vt.debug(`Backend secret for MCP server "${e}" is not a usable OAuth token; ignoring`);return}this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==i||(this.commit(e,a.token,a.identityMatched?r:void 0),Vt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var py="Augment Code",hy="https://augmentcode.com",my="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var F0=1e3,U0=500;function Id(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Ci(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var $d=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function gy(t){return new URLSearchParams({k:t}).toString().slice(2)}function q0(t,e){let r=`${gy(t)}:${gy(e)}`;return`Basic ${btoa(r)}`}function Sy(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function H0(t){return t.client.token_endpoint_auth_method==="none"||!Sy(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function G0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function Z0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var B0=401,wy=500;function Od(t,...e){return t.status<wy&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function yy(t){return Od(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===B0}async function vy(t,e,r){let n={"Content-Type":"application/x-www-form-urlencoded"},o=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken});r&&o.set("resource",r);let i=Sy(t);e==="basic"&&i?n.Authorization=q0(t.client.client_id,i):(o.set("client_id",t.client.client_id),e==="body"&&i&&o.set("client_secret",i));let s=await fetch(t.serverMetadata.token_endpoint,{method:"POST",headers:n,body:o.toString(),signal:AbortSignal.timeout(1e4)});if(!s.ok){let c=await s.text().catch(()=>""),u=Z0(c),d=c.slice(0,U0);throw new Sn(s.status,s.statusText,d,u)}let a=await s.json();if(!a.access_token)throw new $d;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*F0:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function _y(t,e){try{return await vy(t,e,t.resource)}catch(r){if(r instanceof Sn&&t.resource&&Od(r,"invalid_target"))return await vy(t,e,void 0);throw r}}var Sn=class t extends Error{constructor(e,r,n,o,i=!1){super(`Token refresh failed: ${e} ${r}${n?` \u2014 ${n}`:""}`),this.name="RefreshHttpError",this.status=e,this.statusText=r,this.body=n,this.oauthErrorCode=o,this.clientAuthPlacementsExhausted=i}withClientAuthPlacementsExhausted(){return new t(this.status,this.statusText,this.body,this.oauthErrorCode,!0)}};function zd(t){return!(t instanceof Sn)||t.status>=wy?!1:Od(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Nd(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=H0(t);try{return await _y(e,r)}catch(n){let o=G0(r);if(!(n instanceof Sn)||!o||!yy(n))throw n;try{return await _y(e,o)}catch(i){throw i instanceof Sn&&yy(i)?i.withClientAuthPlacementsExhausted():i}}}import{logger as F$}from"@hermes/logger";var jd;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(jd="oauth4webapi/v3.8.6");function po(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Jt="ERR_INVALID_ARG_VALUE",Xe="ERR_INVALID_ARG_TYPE";function he(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var Gd=Symbol(),W0=Symbol(),V0=Symbol(),bn=Symbol();var by=Symbol();var K0=new TextEncoder,J0=new TextDecoder;function Fd(t){return typeof t=="string"?K0.encode(t):J0.decode(t)}var Ud;Uint8Array.prototype.toBase64?Ud=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Ud=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let n=0;n<e.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var qd;Uint8Array.fromBase64?qd=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw he("The input to be decoded is not correctly encoded.",Jt,e)}}:qd=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw he("The input to be decoded is not correctly encoded.",Jt,e)}};function $a(t){return typeof t=="string"?qd(t):Ud(t)}var lo=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=k$,Error.captureStackTrace?.(this,this.constructor)}},Pi=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new Pi(t,{code:e,cause:r})}function Ia(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Zd(t){po(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(jd&&!e.has("user-agent")&&e.set("user-agent",jd),e.has("authorization"))throw he('"options.headers" must not include the "authorization" header name',Jt);return e}function Bd(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw he('"options.signal" must return or be an instance of AbortSignal',Xe);return e}}function Y0(t){return t.includes("//")?t.replace("//","/"):t}function X0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=Y0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function Q0(t,e,r,n){if(!(t instanceof URL))throw he(`"${e}" must be an instance of URL`,Xe);Iy(t,n?.[Gd]!==!0);let o=r(new URL(t.href)),i=Zd(n?.headers);return i.set("accept","application/json"),(n?.[bn]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Bd(o,n?.signal)})}function uo(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw he(`${r} must be a number`,Xe,o);if(t>0)return;if(e){if(t!==0)throw he(`${r} must be a non-negative number`,Jt,o);return}throw he(`${r} must be a positive number`,Jt,o)}catch(i){throw n?O(i.message,n,o):i}}function $e(t,e,r,n){try{if(typeof t!="string")throw he(`${e} must be a string`,Xe,n);if(t.length===0)throw he(`${e} must not be empty`,Jt,n)}catch(o){throw r?O(o.message,r,n):o}}async function Py(t,e){let r=t;if(!(r instanceof URL)&&r!==Na)throw he('"expectedIssuerIdentifier" must be an instance of URL',Xe);if(!po(e,Response))throw he('"response" must be an instance of Response',Xe);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',el,e);ki(e);let n=await Fa(e);if($e(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==Na&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',La,{expected:r.href,body:n,attribute:"issuer"});return n}function Ey(t){t$(t,"application/json")}function e$(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,A$,t)}function t$(t,e){if(p$(t)!==e)throw e$(t,e)}function Wd(){return $a(crypto.getRandomValues(new Uint8Array(32)))}function xy(){return Wd()}function ky(){return Wd()}function Ty(){return Wd()}async function Ay(t){return $e(t,"codeVerifier"),$a(await crypto.subtle.digest("SHA-256",Fd(t)))}function Vd(t){let e=t?.[W0];return typeof e=="number"&&Number.isFinite(e)?e:0}function Kd(t){let e=t?.[V0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Jd(){return Math.floor(Date.now()/1e3)}function Da(t){if(typeof t!="object"||t===null)throw he('"as" must be an object',Xe);$e(t.issuer,'"as.issuer"')}function Yd(t){if(typeof t!="object"||t===null)throw he('"client" must be an object',Xe);$e(t.client_id,'"client.client_id"')}function Ry(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Xd(t){return $e(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function My(t){return $e(t,'"clientSecret"'),(e,r,n,o)=>{let i=Ry(r.client_id),s=Ry(t),a=btoa(`${i}:${s}`);o.set("authorization",`Basic ${a}`)}}function $y(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var r$=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function Iy(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",M$,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",$$,t)}function Cy(t,e,r,n){let o;if(typeof t!="string"||!(o=r$(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?I$:O$,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return Iy(o,n),o}function Oy(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Cy(t.mtls_endpoint_aliases[e],e,r,n):Cy(t[e],e,r,n)}var fo=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=x$,this.cause=r.cause,this.error=r.cause.error,this.status=r.response.status,this.error_description=r.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:r.response}),Error.captureStackTrace?.(this,this.constructor)}},Ei=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=T$,this.cause=r.cause,this.error=r.cause.get("error"),this.error_description=r.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},xi=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=E$,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Oa="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",n$="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",o$='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',i$="("+Oa+")\\s*=\\s*"+o$,s$="("+Oa+")\\s*=\\s*("+Oa+")",a$=new RegExp("^[,\\s]*("+Oa+")"),c$=new RegExp("^[,\\s]*"+i$+"[,\\s]*(.*)"),u$=new RegExp("^[,\\s]*"+s$+"[,\\s]*(.*)"),d$=new RegExp("^("+n$+")(?:$|[,\\s])(.*)");function l$(t){if(!po(t,Response))throw he('"response" must be an instance of Response',Xe);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(a$),i=o?.[1].toLowerCase();if(!i)return;let s=n.substring(o[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let f,p;if(o=n.match(c$)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(u$)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match(d$)){if(Object.keys(u).length)break;[,d,n]=o;break}return}else n=s||void 0;let l={scheme:i,parameters:u};d&&(l.token68=d),r.push(l)}if(r.length)return r}async function f$(t){if(t.status>399&&t.status<500){ki(t),Ey(t);try{let e=await t.clone().json();if(Ia(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function zy(t,e,r){if(t.status!==e){y$(t);let n;throw(n=await f$(t))?(await t.body?.cancel(),new fo("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,el,t)}}function Ny(t){if(!Qd.has(t))throw he('"options.DPoP" is not a valid DPoPHandle',Jt)}function p$(t){return t.headers.get("content-type")?.split(";")[0]}async function h$(t,e,r,n,o,i,s){return await r(t,e,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[bn]||fetch)(n.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Bd(n,s?.signal)})}async function m$(t,e,r,n,o,i){let s=Oy(t,"token_endpoint",e.use_mtls_endpoint_aliases,i?.[Gd]!==!0);o.set("grant_type",n);let a=Zd(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(Ny(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await h$(t,e,r,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}var Dy=new WeakMap,g$=new WeakMap;function Ly(t){if(!t.id_token)return;let e=Dy.get(t);if(!e)throw he('"ref" was already garbage collected or did not resolve from the proper sources',Jt);return e}async function jy(t,e,r,n,o,i){if(Da(t),Yd(e),!po(r,Response))throw he('"response" must be an instance of Response',Xe);await zy(r,200,"Token Endpoint"),ki(r);let s=await Fa(r);if($e(s.access_token,'"response" body "access_token" property',V,{body:s}),$e(s.token_type,'"response" body "token_type" property',V,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;uo(a,!0,'"response" body "expires_in" property',V,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&$e(s.refresh_token,'"response" body "refresh_token" property',V,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw O('"response" body "scope" property must be a string',V,{body:s});if(s.id_token!==void 0){$e(s.id_token,'"response" body "id_token" property',V,{body:s});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(uo(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await z$(s.id_token,N$.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Vd(e),Kd(e),o).then(R$.bind(void 0,a)).then(_$.bind(void 0,t)).then(v$.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',jr,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',jr,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&uo(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),g$.set(r,u),Dy.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](r,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new lo("unsupported `token_type` value",{cause:{body:s}});return s}function y$(t){let e;if(e=l$(t))throw new xi("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function v$(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',jr,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',jr,{expected:t,claims:e.claims,claim:"aud"});return e}function _$(t,e){let r=t[j$]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',jr,{expected:r,claims:e.claims,claim:"iss"});return e}var Qd=new WeakSet;function S$(t){return Qd.add(t),t}var w$=Symbol();async function Fy(t,e,r,n,o,i,s){if(Da(t),Yd(e),!Qd.has(n))throw he('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Jt);$e(o,'"redirectUri"');let a=wn(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),i!==w$&&($e(i,'"codeVerifier"'),c.set("code_verifier",i)),m$(t,e,r,"authorization_code",c,s)}var b$={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function R$(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${b$[r]}) claim missing`,V,{claims:e.claims});return e}var Dd=Symbol(),Ld=Symbol();async function Uy(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?C$(t,e,r,n.expectedNonce,n.maxAge,n[by],n.recognizedTokenTypes):P$(t,e,r,n?.[by],n?.recognizedTokenTypes)}async function C$(t,e,r,n,o,i,s){let a=[];switch(n){case void 0:n=Dd;break;case Dd:break;default:$e(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Ld;break;case Ld:break;default:uo(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await jy(t,e,r,a,i,s);$e(c.id_token,'"response" body "id_token" property',V,{body:c});let u=Ly(c);if(o!==Ld){let d=Jd()+Vd(e),l=Kd(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",za,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===Dd){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',jr,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',jr,{expected:n,claims:u,claim:"nonce"});return c}async function P$(t,e,r,n,o){let i=await jy(t,e,r,void 0,n,o),s=Ly(i);if(s){if(e.default_max_age!==void 0){uo(e.default_max_age,!0,'"client.default_max_age"');let a=Jd()+Vd(e),c=Kd(e);if(s.auth_time+e.default_max_age<a-c)throw O("too much time has elapsed since the last End-User authentication",za,{claims:s,now:a,tolerance:c,claim:"auth_time"})}if(s.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',jr,{expected:void 0,claims:s,claim:"nonce"})}return i}var E$="OAUTH_WWW_AUTHENTICATE_CHALLENGE",x$="OAUTH_RESPONSE_BODY_ERROR",k$="OAUTH_UNSUPPORTED_OPERATION",T$="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Hd="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var A$="OAUTH_RESPONSE_IS_NOT_JSON",el="OAUTH_RESPONSE_IS_NOT_CONFORM",M$="OAUTH_HTTP_REQUEST_FORBIDDEN",$$="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",za="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",jr="OAUTH_JWT_CLAIM_COMPARISON_FAILED",La="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var I$="OAUTH_MISSING_SERVER_METADATA",O$="OAUTH_INVALID_SERVER_METADATA";function ki(t){if(t.bodyUsed)throw he('"response" body has been used already',Jt)}async function z$(t,e,r,n,o){let{0:i,1:s,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:i,1:s,length:a}=t.split(".");else throw new lo("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",V,t);let c;try{c=JSON.parse(Fd($a(i)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",Hd,l)}if(!Ia(c))throw O("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new lo('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Fd($a(s)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",Hd,l)}if(!Ia(u))throw O("JWT Payload must be a top level object",V,t);let d=Jd()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',za,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',za,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function N$(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function wn(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,V);return r}var D$=Symbol(),L$=Symbol();function qy(t,e,r,n){if(Da(t),Yd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw he('"parameters" must be an instance of URLSearchParams, or URL',Xe);if(wn(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=wn(r,"iss"),i=wn(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case L$:if(i!==void 0)throw O('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case D$:break;default:if($e(n,'"expectedState" argument'),i!==n)throw O(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(wn(r,"error"))throw new Ei("authorization response from the server is an error",{cause:r});let a=wn(r,"id_token"),c=wn(r,"token");if(a!==void 0||c!==void 0)throw new lo("implicit and hybrid flows are not supported");return S$(new URLSearchParams(r))}async function Hy(t,e,r){Da(t);let n=Oy(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[Gd]!==!0),o=Zd(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let i="POST";r?.DPoP&&(Ny(r.DPoP),await r.DPoP.addProof(n,o,i,r.initialAccessToken)),r?.initialAccessToken&&o.set("authorization",`${o.has("dpop")?"DPoP":"Bearer"} ${r.initialAccessToken}`);let s=await(r?.[bn]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:i,redirect:"manual",signal:Bd(n,r?.signal)});return r?.DPoP?.cacheNonce(s,n),s}async function Gy(t){if(!po(t,Response))throw he('"response" must be an instance of Response',Xe);await zy(t,201,"Dynamic Client Registration Endpoint"),ki(t);let e=await Fa(t);return $e(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&$e(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&uo(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function Zy(t,e){return Q0(t,"resourceIdentifier",r=>(X0(r,".well-known/oauth-protected-resource",!0),r),e)}async function ja(t,e){let r=t;if(!(r instanceof URL)&&r!==Na)throw he('"expectedResourceIdentifier" must be an instance of URL',Xe);if(!po(e,Response))throw he('"response" must be an instance of Response',Xe);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',el,e);ki(e);let n=await Fa(e);if($e(n.resource,'"response" body "resource" property',V,{body:n}),r!==Na&&new URL(n.resource).href!==r.href)throw O('"response" body "resource" property does not match the expected value',La,{expected:r.href,body:n,attribute:"resource"});return n}async function Fa(t,e=Ey){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',Hd,n)}if(!Ia(r))throw O('"response" body must be a top level object',V,{body:r});return r}var Na=Symbol(),j$=Symbol();var Ti="TLS certificate not trusted. Configure system trust or NODE_EXTRA_CA_CERTS.",By={UNABLE_TO_GET_ISSUER_CERT:Ti,UNABLE_TO_GET_ISSUER_CERT_LOCALLY:Ti,UNABLE_TO_VERIFY_LEAF_SIGNATURE:Ti,DEPTH_ZERO_SELF_SIGNED_CERT:Ti,SELF_SIGNED_CERT_IN_CHAIN:Ti,CERT_HAS_EXPIRED:"TLS certificate expired. Check the system clock or contact the server administrator.",ERR_TLS_CERT_ALTNAME_INVALID:"TLS certificate hostname mismatch. Verify the server URL or contact the network administrator."};function Ai(t){let e=new Set,r=t,n;for(let o=0;o<16&&!(typeof r!="object"||r===null||e.has(r));o++){if(e.add(r),"name"in r&&(r.name==="AbortError"||r.name==="TimeoutError")||"code"in r&&r.code==="ABORT_ERR")return;"code"in r&&typeof r.code=="string"&&Object.hasOwn(By,r.code)&&(n??=r.code),r="cause"in r?r.cause:void 0}return n}function Mi(t){return Object.assign(new Error(By[t]),{code:t})}var Ky=F$.child({prefix:"pi-mcp"}),$i=1e4,U$=1e3,q$=401,Wy=200,H$="accounts.google.com",G$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,Z$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Jy;function ho(){return Jy??globalThis.fetch}function Yy(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Xy(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function rl(t){let e=Xy(t),r,n=o=>{r??=Ai(o)};try{let o=await B$(e,n),i=o?.authorization_servers?.map(s=>new URL(s))??[e];for(let s of i){let a=await Y$(s,n);if(a)return Object.assign(a,{resourceScopes:o?.scopes_supported,resourceIdentifier:o?.resource})}}catch(o){throw Ha(o)}throw r?Mi(r):new Error("Failed to discover metadata URL")}async function B$(t,e){try{let r=await Zy(t,{signal:AbortSignal.timeout($i),[bn]:Jy??void 0});return r.ok?await ja(t,r):(r.body?.cancel().catch(()=>{}),await Qy(t,r.headers.get("www-authenticate"),e)??await Vy(t,e))}catch(r){return e(r),await Vy(t,e)}}async function Vy(t,e){for(let r of["HEAD","GET"])try{let n=await ho()(t,{method:r,signal:AbortSignal.timeout($i)});n.body?.cancel().catch(()=>{});let o=await Qy(t,n.headers.get("www-authenticate"),e);if(o)return o}catch(n){e(n)}}async function Qy(t,e,r){let n=J$(e);if(n)try{let o=await ho()(n,{signal:AbortSignal.timeout($i)});return await W$(t,o)}catch(o){r(o);return}}async function W$(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await ja(t,new Response(r,n))}catch(o){if(!(o instanceof Pi)||o.code!==La)throw o;let i=V$(r);if(!i||!K$(i,t))throw o;return await ja(i,new Response(r,n))}}function V$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function K$(t,e){if(t.origin!==e.origin)return!1;let r=t.pathname.replace(/\/+$/,""),n=e.pathname.replace(/\/+$/,"");return r===n||n.startsWith(`${r}/`)}function J$(t){if(!t)return;let e=t.match(G$),r=t.match(Z$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function Y$(t,e){for(let r of X$(t))try{let n=new URL(r,t),o=await ho()(n,{signal:AbortSignal.timeout($i)});if(o.body?.cancel().catch(()=>{}),!o.ok)continue;return n}catch(n){e(n)}}function X$(t){let e=t.pathname.startsWith("/")?t.pathname.slice(1):t.pathname;return[...e.length>0?[new URL(`/.well-known/oauth-authorization-server/${e}`,t),new URL(`/.well-known/openid-configuration/${e}`,t),new URL(`/${e}/.well-known/openid-configuration`,t)]:[],new URL("/.well-known/oauth-authorization-server",t),new URL("/.well-known/openid-configuration",t)]}async function nl(t){try{let e=await ho()(t,{signal:AbortSignal.timeout($i)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await Q$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await Py(o,new Response(r,n))}catch(e){throw Ha(e)}}async function Q$(t){if(!t.ok)throw new Error("Invalid status code from discovery response");let e=await t.json();if(!e.issuer||typeof e.issuer!="string")throw new Error("Invalid issuer from discovery response");return new URL(e.issuer)}var tl=class extends Error{constructor(e){super(`This MCP server's authorization server (\`${e}\`) does not support Dynamic Client Registration. Configure a static OAuth Client ID and Secret in the Advanced section.`),this.name="McpOAuthDcrUnsupportedError",this.issuer=e}};function eI(t){if(!t.clientId)throw new Error("clientId is required to build client from config");let e=t.clientSecret?.trim();return{client_id:t.clientId,...e?{client_secret:e}:{}}}async function ol({config:t,serverMetadata:e,redirectUris:r,preferStaticClient:n=!1}){let o=t.clientId?.trim(),i=t.clientSecret?.trim();if(!!o&&(n||!!i||!e.registration_endpoint))return eI({...t,clientId:o});if(!e.registration_endpoint)throw new tl(e.issuer);return await tI(e,r)}async function tI(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Hy(t,{client_name:py,client_uri:hy,logo_uri:my,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[bn]:rI});return n.ok||Ky.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Gy(n)}catch(r){throw Ha(r)}}async function rI(t,e){let r=await ho()(t,Yy(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Ky.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${oI(n)}`),r.status===200&&(o.status=201,o.statusText="Created"),o.status===201)try{let i=JSON.parse(n);i.client_secret_expires_at||(i.client_secret_expires_at=0),"client_secret"in i&&!i.client_secret&&(i.client_secret=void 0),n=JSON.stringify(i)}catch{}return new Response(n,o)}function nI(t,e){let r=new Headers(e?.headers),n=r.get("content-type"),o=e;return n?.toLowerCase().startsWith("application/x-www-form-urlencoded;")&&(r.set("content-type","application/x-www-form-urlencoded"),o={...e,headers:r}),ho()(t,Yy(o))}function oI(t){try{let e=JSON.parse(t);for(let r of Object.keys(e))/secret|token/i.test(r)&&(e[r]="[REDACTED]");return JSON.stringify(e)}catch{return t.length>Wy?`${t.slice(0,Wy)}\u2026`:t}}async function Ua(t,e,r,n,o,i,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=xy(),c=await Ay(a),u=ky(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!s?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=Xy(i??t).toString(),g=new URL(r.authorization_endpoint);return g.searchParams.set("response_type","code"),g.searchParams.set("client_id",e.client_id),g.searchParams.set("code_challenge",c),g.searchParams.set("code_challenge_method","S256"),g.searchParams.set("redirect_uri",n),g.searchParams.set("resource",h),g.searchParams.set("state",u),p&&g.searchParams.set("scope",p),l?.includes("offline_access")&&g.searchParams.set("prompt","consent"),g.hostname===H$&&(g.searchParams.set("access_type","offline"),g.searchParams.set("prompt","consent")),r.code_challenge_methods_supported?.includes("S256")||(d=Ty(),g.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:g}}function qa(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function il(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await Ua(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function iI(t,e,r){let n=await Fy(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[bn]:nI,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Uy(t.serverMetadata,t.client,await sI(n))}async function sl(t,e){try{let r=qy(e.serverMetadata,e.client,t,e.state),n=await cI(e.client,o=>iI(e,r,o));return lI(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw Ha(r)}}async function sI(t){let e=await t.text(),r={status:t.status,statusText:t.statusText,headers:t.headers};try{let n=JSON.parse(e);if("id_token"in n)return n.id_token=void 0,new Response(JSON.stringify(n),r)}catch{}return new Response(e,r)}function ev(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function aI(t){let e=ev(t);return e===void 0?$y():t.token_endpoint_auth_method==="client_secret_basic"?My(e):Xd(e)}async function cI(t,e){try{return await e(aI(t))}catch(r){let n=uI(t);if(n&&dI(r))return await e(n);throw r}}function uI(t){let e=ev(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return Xd(e)}function dI(t){return t instanceof fo?t.error==="invalid_client"||t.error==="unauthorized":t instanceof xi?t.status===q$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function lI(t,e,r,n,o){if(!t.access_token)throw new Error("OAuth token response contained no access token");return{accessToken:t.access_token,refreshToken:t.refresh_token||n,expiresAt:t.expires_in?Date.now()+t.expires_in*U$:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function Ha(t){let e=Ai(t);if(e)return Mi(e);if(t instanceof fo||t instanceof Ei){let r=t.error_description?` (${t.error_description})`:"";return new Error(`${t.message}${r}`,{cause:t})}return t instanceof Error?t:new Error(String(t))}var fI=/(authorization|auth[_-]?token|access[_-]?token|refresh[_-]?token|\btoken\b|secret|password|passwd|\bpwd\b|api[_-]?key|apikey|client[_-]?secret|private[_-]?key|cookie|session[_-]?id|credential|bearer)/i,tv=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,rv=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,nv=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Rn="[redacted]",pI=/[.*+?^${}()|[\]\\]/g;function al(t,e){return e.chars-=t.length,e.chars<0?e.marker:e.redactText(t)}function hI(t,e,r){try{let n=Array.isArray(t);if(n&&t.length>r.nodes)return r.marker;let o=Object.getPrototypeOf(t);if(!n&&o!==null&&o!==Object.prototype)return r.marker;r.active.add(t);let i=Object.keys(t);if(i.length>r.nodes)return r.marker;let s=n?[]:Object.create(null);for(let a of i){if(n&&!/^(0|[1-9]\d*)$/.test(a))continue;let c=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(s,n?a:al(a,r),{value:c&&"value"in c?ov(c.value,e+1,r):r.marker,enumerable:!0,configurable:!0,writable:!0})}return s}catch{return r.marker}finally{r.active.delete(t)}}function ov(t,e,r){if(--r.nodes<0||e>16)return r.marker;if(typeof t=="string")return al(t,r);if(t===void 0)return t;if(t===null||typeof t=="boolean"||typeof t=="number"){if(typeof t=="number"&&!Number.isFinite(t))return r.marker;let n=JSON.stringify(t);return al(n,r)===n?t:r.marker}return typeof t!="object"||r.active.has(t)?r.marker:hI(t,e,r)}function ul(t){let e=[...new Set(t)].filter(Boolean);if(e.length>128||e.reduce((i,s)=>i+s.length,0)>262144)return{text:()=>"",value:()=>{}};let r=e.length?new RegExp(e.sort((i,s)=>s.length-i.length).map(i=>i.replace(pI,"\\$&")).join("|"),"g"):void 0,n=e.some(i=>Rn.includes(i))?"":Rn,o=i=>{if(i.length>262144)return n;let s=r?i.replace(r,()=>n):i;return e.some(a=>s.includes(a))?n:s};return{text:o,value:i=>ov(i,0,{redactText:o,marker:n,nodes:1e4,chars:262144,active:new WeakSet})}}var mI=500,gI=8192,yI=6;function vI(t){return tv.test(t)||rv.test(t)||nv.test(t)}var _I=new RegExp(tv.source,"g"),SI=new RegExp(rv.source,"gi"),wI=new RegExp(nv.source,"g");function iv(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function Ga(t){return t&&iv(t,gI).replace(_I,Rn).replace(SI,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Rn}`).replace(wI,Rn)}function cl(t,e,r){if(e)return Rn;if(typeof t=="string")return vI(t)?Rn:t;if(t===null||typeof t!="object")return t;if(r>=yI)return"[truncated]";if(Array.isArray(t))return t.map(o=>cl(o,!1,r+1));let n={};for(let[o,i]of Object.entries(t))n[o]=cl(i,fI.test(o),r+1);return n}function sv(t,e=mI){if(t==null)return;let r=cl(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return iv(n,e)}var cv={reportError:()=>{}},av=Symbol.for("__pi_mcp_error_reporter_slot__");function uv(){let t=globalThis,e=t[av];return e||(e={reporter:null},t[av]=e),e}function dv(t){let e=uv(),r=e.reporter??cv;return e.reporter=t,r}function bI(){return uv().reporter??cv}function Ii(t,e){try{bI().reportError(t,e)}catch{}}import{logger as RI}from"@hermes/logger";var dl=RI.child({prefix:"pi-mcp"});function lv(t,e,r){let n=0,o=0,i=r?.authoritative?{}:{...t.headerSecrets};for(let[s,a]of Object.entries(e))typeof a=="string"&&a!==""?(i[s]=a,n++):a===null||a===""?s in i&&(delete i[s],o++):dl.warn(`Skipping malformed header-secret entry "${s}"`);t.headerSecrets=i,t.headerSecretFailures??={};for(let s of Object.keys(i))delete t.headerSecretFailures[s];dl.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function fv(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Md)){let o=t.headerSecrets[e];if(o!==void 0)return o;let i=t.headerSecretFailures[e];if(i==="missing"||i==="permission_denied")return{reason:i}}let r=t.secretsClient;if(r)try{let o=await r.getSecret(e);return o!==void 0?(delete t.headerSecretFailures[e],o):{reason:t.headerSecretFailures[e]??"missing"}}catch{return{reason:"transient"}}let n=t.headerSecretFailures[e];return n===void 0?void 0:{reason:n}}}function pv(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[i,s]of Object.entries(e))(s==="missing"||s==="permission_denied"||s==="transient")&&(n[i]=s,delete o[i]);t.headerSecrets=o,t.headerSecretFailures=n,dl.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function hv(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as CI}from"@hermes/logger";var Oi=CI.child({prefix:"pi-mcp"}),PI="$augment-",zi=/\$augment-[a-zA-Z0-9_.-]+/g,EI=new RegExp(zi.source);function Fr(t){return EI.test(t)}function Za(t){return t.slice(PI.length)}function Ni(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(zi))e.add(Za(n[0]));return[...e].sort()}var xI=["permission_denied","missing","transient"];function mv(t){let e=new Set(t);return xI.find(r=>e.has(r))??"missing"}var vt=class extends Error{constructor(e,r,n,o=n===void 0?"missing":"transient"){super(`MCP server "${e}" not started: missing secret(s) ${r.join(", ")}`,n===void 0?void 0:{cause:n}),this.name="McpSecretResolutionError",this.serverName=e,this.missingKeys=r,this.reason=o}};async function gv(t,e,r,n,o,i,s){let a=[...t.matchAll(zi)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=Za(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),i.set(f,p===void 0?"missing":p.reason),Oi.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),Oi.warn(`Secret "${f}" resolved empty for "${e}"`));let g=c.slice(0,l),m=s?s(h,g):h;c=g+m+c.slice(l+d.length),Oi.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),i.set(f,"transient"),Oi.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function yv({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,i=new Set,s=new Map;for(let[a,c]of Object.entries(t)){if(!Fr(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){Oi.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await gv(c,a,r,o,i,s)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...i].sort(),...s.size===0?{}:{failureReasons:Object.fromEntries([...s.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var kI=/["$`\\]/g;function TI(t){let e="unquoted",r=0;for(;r<t.length;){let n=t[r];if(e==="single"){n==="'"&&(e="unquoted"),r+=1;continue}if(e==="double"){if(n==="\\"){r+=2;continue}n==='"'&&(e="unquoted"),r+=1;continue}if(n==="\\"){r+=2;continue}n==="'"?e="single":n==='"'&&(e="double"),r+=1}return e}function AI(t,e){let r=TI(e);if(r==="double")return t.replace(kI,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function vv(t,e,r=!0){let n=new Set,o=new Set,i=new Map;return{resolved:await gv(t,"command",e,n,o,i,r?AI:void 0),unresolvedKeys:[...n].sort(),emptyKeys:[...o].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var ll;ll=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function MI(t){return(await ll).getRandomValues(new Uint8Array(t))}async function $I(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await MI(t-n.length);for(let i of o)i<r&&(n+=e[i%e.length])}return n}async function II(t){return await $I(t)}async function OI(t){let e=await(await ll).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function fl(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await II(t),r=await OI(e);return{code_verifier:e,code_challenge:r}}var _v,pl=Object.freeze({status:"aborted"});function S(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=s.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function s(a){var c;let u=r?.Parent?new i:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}var Yt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},mo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(_v=globalThis).__zod_globalConfig??(_v.__zod_globalConfig={});var go=globalThis.__zod_globalConfig;function Qe(t){return t&&Object.assign(go,t),go}var H={};ed(H,{BIGINT_FORMAT_RANGES:()=>Rv,Class:()=>ml,NUMBER_FORMAT_RANGES:()=>wl,aborted:()=>Hr,allowsEval:()=>vl,assert:()=>jI,assertEqual:()=>zI,assertIs:()=>DI,assertNever:()=>LI,assertNotEqual:()=>NI,assignProp:()=>Ur,base64ToUint8Array:()=>Pv,base64urlToUint8Array:()=>rO,cached:()=>vo,captureStackTrace:()=>Va,cleanEnum:()=>tO,cleanRegex:()=>Fi,clone:()=>_t,cloneDef:()=>UI,createTransparentProxy:()=>WI,defineLazy:()=>X,esc:()=>Wa,escapeRegex:()=>lr,explicitlyAborted:()=>bl,extend:()=>JI,finalizeIssue:()=>St,floatSafeRemainder:()=>gl,getElementAtPath:()=>qI,getEnumValues:()=>Li,getLengthableOrigin:()=>Ui,getParsedType:()=>BI,getSizableOrigin:()=>Cv,hexToUint8Array:()=>oO,isObject:()=>Cn,isPlainObject:()=>qr,issue:()=>_o,joinValues:()=>Ba,jsonStringifyReplacer:()=>yo,merge:()=>XI,mergeDefs:()=>dr,normalizeParams:()=>$,nullish:()=>ji,numKeys:()=>ZI,objectClone:()=>FI,omit:()=>KI,optionalKeys:()=>Sl,parsedType:()=>Rl,partial:()=>QI,pick:()=>VI,prefixIssues:()=>fr,primitiveTypes:()=>bv,promiseAllObject:()=>HI,propertyKeyTypes:()=>_l,randomString:()=>GI,required:()=>eO,safeExtend:()=>YI,shallowClone:()=>wv,slugify:()=>yl,stringifyPrimitive:()=>Ka,uint8ArrayToBase64:()=>Ev,uint8ArrayToBase64url:()=>nO,uint8ArrayToHex:()=>iO,unwrapMessage:()=>Di});function zI(t){return t}function NI(t){return t}function DI(t){}function LI(t){throw new Error("Unexpected value in exhaustive check")}function jI(t){}function Li(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ba(t,e="|"){return t.map(r=>Ka(r)).join(e)}function yo(t,e){return typeof e=="bigint"?e.toString():e}function vo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ji(t){return t==null}function Fi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function gl(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var Sv=Symbol("evaluating");function X(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Sv)return n===void 0&&(n=Sv,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function FI(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Ur(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function dr(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function UI(t){return dr(t._zod.def)}function qI(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function HI(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=n[i];return o})}function GI(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Wa(t){return JSON.stringify(t)}function yl(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Va="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var vl=vo(()=>{if(go.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function qr(t){if(Cn(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Cn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wv(t){return qr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function ZI(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var BI=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},_l=new Set(["string","number","symbol"]),bv=new Set(["string","number","bigint","boolean","symbol","undefined"]);function lr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _t(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function $(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function WI(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,i){return e??(e=t()),Reflect.set(e,n,o,i)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ka(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Sl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var wl={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Rv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function VI(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=dr(t._zod.def,{get shape(){let s={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=r.shape[a])}return Ur(this,"shape",s),s},checks:[]});return _t(t,i)}function KI(t,e){let r=t._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=dr(t._zod.def,{get shape(){let s={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Ur(this,"shape",s),s},checks:[]});return _t(t,i)}function JI(t,e){if(!qr(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let i=t._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=dr(t._zod.def,{get shape(){let i={...t._zod.def.shape,...e};return Ur(this,"shape",i),i}});return _t(t,o)}function YI(t,e){if(!qr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=dr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Ur(this,"shape",n),n}});return _t(t,r)}function XI(t,e){if(t._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=dr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Ur(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return _t(t,r)}function QI(t,e,r){let o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=dr(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Ur(this,"shape",c),c},checks:[]});return _t(e,s)}function eO(t,e,r){let n=dr(e._zod.def,{get shape(){let o=e._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new t({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new t({type:"nonoptional",innerType:o[s]});return Ur(this,"shape",i),i}});return _t(e,n)}function Hr(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function bl(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue===!1)return!0;return!1}function fr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Di(t){return typeof t=="string"?t:t?.message}function St(t,e,r){let n=t.message?t.message:Di(t.inst?._zod.def?.error?.(t))??Di(e?.error?.(t))??Di(r.customError?.(t))??Di(r.localeError?.(t))??"Invalid input",{inst:o,continue:i,input:s,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function Cv(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ui(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Rl(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function _o(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function tO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Pv(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function Ev(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function rO(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Pv(e+r)}function nO(t){return Ev(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function oO(t){let e=t.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.slice(n,n+2),16);return r}function iO(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var ml=class{constructor(...e){}};var xv=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,yo,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ja=S("$ZodError",xv),Cl=S("$ZodError",xv,{Parent:Error});function Pl(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function El(t,e=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(e(s));else{let c=r,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(s))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return n(t),r}var Ya=t=>(e,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Yt;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>St(c,i,Qe())));throw Va(a,o?.callee),a}return s.value};var Xa=t=>async(e,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(c=>St(c,i,Qe())));throw Va(a,o?.callee),a}return s.value};var qi=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Yt;return i.issues.length?{success:!1,error:new(t??Ja)(i.issues.map(s=>St(s,o,Qe())))}:{success:!0,data:i.value}},Hi=qi(Cl),Gi=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>St(s,o,Qe())))}:{success:!0,data:i.value}},Qa=Gi(Cl),kv=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ya(t)(e,r,o)};var Tv=t=>(e,r,n)=>Ya(t)(e,r,n);var Av=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Xa(t)(e,r,o)};var Mv=t=>async(e,r,n)=>Xa(t)(e,r,n);var $v=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return qi(t)(e,r,o)};var Iv=t=>(e,r,n)=>qi(t)(e,r,n);var Ov=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Gi(t)(e,r,o)};var zv=t=>async(e,r,n)=>Gi(t)(e,r,n);var Nv=/^[cC][0-9a-z]{6,}$/,Dv=/^[0-9a-z]+$/,Lv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jv=/^[0-9a-vA-V]{20}$/,Fv=/^[A-Za-z0-9]{27}$/,Uv=/^[a-zA-Z0-9_-]{21}$/,qv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Hv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,xl=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var Gv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var aO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Zv(){return new RegExp(aO,"u")}var Bv=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var Vv=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Kv=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kl=/^[A-Za-z0-9_-]*$/;var Yv=/^https?$/,Xv=/^\+[1-9]\d{6,14}$/,Qv="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",e_=new RegExp(`^${Qv}$`);function t_(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function r_(t){return new RegExp(`^${t_(t)}$`)}function n_(t){let e=t_({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Qv}T(?:${n})$`)}var o_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},i_=/^-?\d+n?$/,s_=/^-?\d+$/,Tl=/^-?\d+(?:\.\d+)?$/,a_=/^(?:true|false)$/i,c_=/^null$/i;var u_=/^[^A-Z]*$/,d_=/^[^a-z]*$/;var Oe=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),l_={number:"number",bigint:"bigint",object:"date"},Al=S("$ZodCheckLessThan",(t,e)=>{Oe.init(t,e);let r=l_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ml=S("$ZodCheckGreaterThan",(t,e)=>{Oe.init(t,e);let r=l_[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),f_=S("$ZodCheckMultipleOf",(t,e)=>{Oe.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):gl(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),p_=S("$ZodCheckNumberFormat",(t,e)=>{Oe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,i]=wl[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,r&&(a.pattern=s_)}),t._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:t,continue:!e.abort})}});var h_=S("$ZodCheckMaxLength",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ji(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let s=Ui(o);n.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),m_=S("$ZodCheckMinLength",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ji(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let s=Ui(o);n.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),g_=S("$ZodCheckLengthEquals",(t,e)=>{var r;Oe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ji(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,i=o.length;if(i===e.length)return;let s=Ui(o),a=i>e.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Bi=S("$ZodCheckStringFormat",(t,e)=>{var r,n;Oe.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),y_=S("$ZodCheckRegex",(t,e)=>{Bi.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),v_=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=u_),Bi.init(t,e)}),__=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=d_),Bi.init(t,e)}),S_=S("$ZodCheckIncludes",(t,e)=>{Oe.init(t,e);let r=lr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),w_=S("$ZodCheckStartsWith",(t,e)=>{Oe.init(t,e);let r=new RegExp(`^${lr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),b_=S("$ZodCheckEndsWith",(t,e)=>{Oe.init(t,e);let r=new RegExp(`.*${lr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var R_=S("$ZodCheckOverwrite",(t,e)=>{Oe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ec=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
25
25
|
`).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new e(...r,o.join(`
|
|
26
|
-
`))}};var w_={major:4,minor:4,patch:3};var re=S("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=w_;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,a,c)=>{let u=qr(s),d;for(let l of a){if(l._zod.def.when){if(vl(s)||!l._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&c?.async===!1)throw new Yt;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(u||(u=qr(s,f)))});else{if(s.issues.length===f)continue;u||(u=qr(s,f))}}return d?d.then(()=>s):s},i=(s,a,c)=>{if(qr(s))return s.aborted=!0,s;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Yt;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let u=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>i(d,s,a)):i(u,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Yt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}X(t,"~standard",()=>({validate:o=>{try{let i=qi(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Xa(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),rc=S("$ZodString",(t,e)=>{re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??e_(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=S("$ZodStringFormat",(t,e)=>{Zi.init(t,e),rc.init(t,e)}),A_=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jv),ce.init(t,e)}),M_=S("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Rl(n))}else e.pattern??(e.pattern=Rl());ce.init(t,e)}),$_=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Fv),ce.init(t,e)}),I_=S("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Wv.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),O_=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Uv()),ce.init(t,e)}),z_=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Dv),ce.init(t,e)}),N_=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$v),ce.init(t,e)}),D_=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Iv),ce.init(t,e)}),L_=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ov),ce.init(t,e)}),j_=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=zv),ce.init(t,e)}),F_=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Nv),ce.init(t,e)}),U_=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Qv(e)),ce.init(t,e)}),q_=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Jv),ce.init(t,e)}),H_=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Xv(e)),ce.init(t,e)}),G_=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Lv),ce.init(t,e)}),Z_=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=qv),ce.init(t,e),t._zod.bag.format="ipv4"}),B_=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Hv),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var W_=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Gv),ce.init(t,e)}),V_=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Zv),ce.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function K_(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var J_=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Bv),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{K_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function KI(t){if(!Cl.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return K_(r)}var Y_=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Cl),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{KI(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),X_=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vv),ce.init(t,e)});function JI(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var Q_=S("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{JI(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Tl=S("$ZodNumber",(t,e)=>{re.init(t,e),t._zod.pattern=t._zod.bag.pattern??Pl,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),r}}),eS=S("$ZodNumberFormat",(t,e)=>{u_.init(t,e),Tl.init(t,e)}),tS=S("$ZodBoolean",(t,e)=>{re.init(t,e),t._zod.pattern=n_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),rS=S("$ZodBigInt",(t,e)=>{re.init(t,e),t._zod.pattern=t_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var nS=S("$ZodNull",(t,e)=>{re.init(t,e),t._zod.pattern=o_,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),oS=S("$ZodAny",(t,e)=>{re.init(t,e),t._zod.parse=r=>r}),iS=S("$ZodUnknown",(t,e)=>{re.init(t,e),t._zod.parse=r=>r}),sS=S("$ZodNever",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var aS=S("$ZodDate",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),r}});function b_(t,e,r){t.issues.length&&e.issues.push(...lr(r,t.issues)),e.value[r]=t.value}var cS=S("$ZodArray",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(u=>b_(u,r,s))):b_(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function tc(t,e,r,n,o,i){let s=r in n;if(t.issues.length){if(o&&i&&!s)return;e.issues.push(...lr(r,t.issues))}if(!s&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?s&&(e.value[r]=void 0):e.value[r]=t.value}function uS(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=gl(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function dS(t,e,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){s.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>tc(h,r,f,e,d,l))):tc(p,r,f,e,d,l)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>r):r}var YI=S("$ZodObject",(t,e)=>{if(re.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=yo(()=>uS(e));X(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=wn,i=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=s.shape;for(let f of s.keys){let p=l[f],h=p._zod.optin==="optional",m=p._zod.optout==="optional",g=p._zod.run({value:u[f],issues:[]},c);g instanceof Promise?d.push(g.then(v=>tc(v,a,f,u,h,m))):tc(g,a,f,u,h,m)}return i?dS(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),lS=S("$ZodObjectJIT",(t,e)=>{YI.init(t,e);let r=t._zod.parse,n=yo(()=>uS(e)),o=f=>{let p=new Qa(["shape","payload","ctx"]),h=n.value,m=b=>{let R=Ba(b);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),v=0;for(let b of h.keys)g[b]=`key_${v++}`;p.write("const newResult = {};");for(let b of h.keys){let R=g[b],_=Ba(b),C=f[b],I=C?._zod?.optin==="optional",ee=C?._zod?.optout==="optional";p.write(`const ${R} = ${m(b)};`),I&&ee?p.write(`
|
|
26
|
+
`))}};var P_={major:4,minor:4,patch:3};var re=S("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=P_;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let i of o._zod.onattach)i(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,a,c)=>{let u=Hr(s),d;for(let l of a){if(l._zod.def.when){if(bl(s)||!l._zod.def.when(s))continue}else if(u)continue;let f=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&c?.async===!1)throw new Yt;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(u||(u=Hr(s,f)))});else{if(s.issues.length===f)continue;u||(u=Hr(s,f))}}return d?d.then(()=>s):s},i=(s,a,c)=>{if(Hr(s))return s.aborted=!0,s;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Yt;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(s,a)=>{if(a.skipChecks)return t._zod.parse(s,a);if(a.direction==="backward"){let u=t._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>i(d,s,a)):i(u,s,a)}let c=t._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Yt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}X(t,"~standard",()=>({validate:o=>{try{let i=Hi(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Qa(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),nc=S("$ZodString",(t,e)=>{re.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??o_(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=S("$ZodStringFormat",(t,e)=>{Bi.init(t,e),nc.init(t,e)}),O_=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Hv),ce.init(t,e)}),z_=S("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=xl(n))}else e.pattern??(e.pattern=xl());ce.init(t,e)}),N_=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Gv),ce.init(t,e)}),D_=S("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Yv.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:t,continue:!e.abort});return}let o=new URL(n);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),e.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),L_=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Zv()),ce.init(t,e)}),j_=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Uv),ce.init(t,e)}),F_=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Nv),ce.init(t,e)}),U_=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Dv),ce.init(t,e)}),q_=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Lv),ce.init(t,e)}),H_=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=jv),ce.init(t,e)}),G_=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Fv),ce.init(t,e)}),Z_=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=n_(e)),ce.init(t,e)}),B_=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=e_),ce.init(t,e)}),W_=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=r_(e)),ce.init(t,e)}),V_=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=qv),ce.init(t,e)}),K_=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Bv),ce.init(t,e),t._zod.bag.format="ipv4"}),J_=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Wv),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var Y_=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Vv),ce.init(t,e)}),X_=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Kv),ce.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Q_(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var eS=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Jv),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Q_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function dO(t){if(!kl.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Q_(r)}var tS=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kl),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{dO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),rS=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Xv),ce.init(t,e)});function lO(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var nS=S("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{lO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Il=S("$ZodNumber",(t,e)=>{re.init(t,e),t._zod.pattern=t._zod.bag.pattern??Tl,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),r}}),oS=S("$ZodNumberFormat",(t,e)=>{p_.init(t,e),Il.init(t,e)}),iS=S("$ZodBoolean",(t,e)=>{re.init(t,e),t._zod.pattern=a_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),sS=S("$ZodBigInt",(t,e)=>{re.init(t,e),t._zod.pattern=i_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:t}),r}});var aS=S("$ZodNull",(t,e)=>{re.init(t,e),t._zod.pattern=c_,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),cS=S("$ZodAny",(t,e)=>{re.init(t,e),t._zod.parse=r=>r}),uS=S("$ZodUnknown",(t,e)=>{re.init(t,e),t._zod.parse=r=>r}),dS=S("$ZodNever",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var lS=S("$ZodDate",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),r}});function E_(t,e,r){t.issues.length&&e.issues.push(...fr(r,t.issues)),e.value[r]=t.value}var fS=S("$ZodArray",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(u=>E_(u,r,s))):E_(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});function rc(t,e,r,n,o,i){let s=r in n;if(t.issues.length){if(o&&i&&!s)return;e.issues.push(...fr(r,t.issues))}if(!s&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?s&&(e.value[r]=void 0):e.value[r]=t.value}function pS(t){let e=Object.keys(t.shape);for(let n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=Sl(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function hS(t,e,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){s.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>rc(h,r,f,e,d,l))):rc(p,r,f,e,d,l)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),t.length?Promise.all(t).then(()=>r):r}var fO=S("$ZodObject",(t,e)=>{if(re.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=vo(()=>pS(e));X(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=Cn,i=e.catchall,s;t._zod.parse=(a,c)=>{s??(s=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=s.shape;for(let f of s.keys){let p=l[f],h=p._zod.optin==="optional",g=p._zod.optout==="optional",m=p._zod.run({value:u[f],issues:[]},c);m instanceof Promise?d.push(m.then(v=>rc(v,a,f,u,h,g))):rc(m,a,f,u,h,g)}return i?hS(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),mS=S("$ZodObjectJIT",(t,e)=>{fO.init(t,e);let r=t._zod.parse,n=vo(()=>pS(e)),o=f=>{let p=new ec(["shape","payload","ctx"]),h=n.value,g=b=>{let R=Wa(b);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};p.write("const input = payload.value;");let m=Object.create(null),v=0;for(let b of h.keys)m[b]=`key_${v++}`;p.write("const newResult = {};");for(let b of h.keys){let R=m[b],_=Wa(b),C=f[b],I=C?._zod?.optin==="optional",ee=C?._zod?.optout==="optional";p.write(`const ${R} = ${g(b)};`),I&&ee?p.write(`
|
|
27
27
|
if (${R}.issues.length) {
|
|
28
28
|
if (${_} in input) {
|
|
29
29
|
payload.issues = payload.issues.concat(${R}.issues.map(iss => ({
|
|
@@ -82,23 +82,23 @@ When the user's request requires one of these servers, call attach-mcp-server im
|
|
|
82
82
|
}
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,R)=>w(f,b,R)},i,s=wn,a=!mo.jitless,u=a&&hl.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return s(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(i||(i=o(e.shape)),f=i(f,p),d?dS([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function R_(t,e,r,n){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let o=t.filter(i=>!qr(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>_t(s,n,Qe())))}),e)}var Al=S("$ZodUnion",(t,e)=>{re.init(t,e),X(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),X(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),X(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),X(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>ji(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>R_(a,n,t,o)):R_(s,n,t,o)}});var fS=S("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Al.init(t,e);let r=t._zod.parse;X(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=yo(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!wn(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback||i.direction==="backward"?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:s,path:[e.discriminator],inst:t}),o)}}),pS=S("$ZodIntersection",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),s=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>C_(r,c,u)):C_(r,i,s)}});function kl(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ur(t)&&Ur(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let s=kl(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],s=kl(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function C_(t,e,r){let n=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else t.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&t.issues.push({...o,keys:i}),qr(t))return t;let s=kl(e.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var hS=S("$ZodRecord",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Ur(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let i=[],s=e.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>_t(p,n,Qe())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?i.push(f.then(p=>{p.issues.length&&r.issues.push(...lr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...lr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Pl.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>_t(l,n,Qe())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?i.push(d.then(l=>{l.issues.length&&r.issues.push(...lr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...lr(a,d.issues)),r.value[c.value]=d.value)}}return i.length?Promise.all(i).then(()=>r):r}});var mS=S("$ZodEnum",(t,e)=>{re.init(t,e);let r=Di(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>ml.has(typeof o)).map(o=>typeof o=="string"?dr(o):o.toString()).join("|")})$`),t._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:t}),o}}),gS=S("$ZodLiteral",(t,e)=>{if(re.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?dr(n):n?dr(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}});var yS=S("$ZodTransform",(t,e)=>{re.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ho(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new Yt;return r.value=o,r.fallback=!0,r}});function P_(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Ml=S("$ZodOptional",(t,e)=>{re.init(t,e),t._zod.optin="optional",t._zod.optout="optional",X(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),X(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ji(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>P_(s,o)):P_(i,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),vS=S("$ZodExactOptional",(t,e)=>{Ml.init(t,e),X(t._zod,"values",()=>e.innerType._zod.values),X(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),_S=S("$ZodNullable",(t,e)=>{re.init(t,e),X(t._zod,"optin",()=>e.innerType._zod.optin),X(t._zod,"optout",()=>e.innerType._zod.optout),X(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ji(r.source)}|null)$`):void 0}),X(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),SS=S("$ZodDefault",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>x_(i,e)):x_(o,e)}});function x_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var wS=S("$ZodPrefault",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),bS=S("$ZodNonOptional",(t,e)=>{re.init(t,e),X(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>E_(i,t)):E_(o,t)}});function E_(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var RS=S("$ZodCatch",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"optout",()=>e.innerType._zod.optout),X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>_t(s,n,Qe()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>_t(i,n,Qe()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var $l=S("$ZodPipe",(t,e)=>{re.init(t,e),X(t._zod,"values",()=>e.in._zod.values),X(t._zod,"optin",()=>e.in._zod.optin),X(t._zod,"optout",()=>e.out._zod.optout),X(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=e.out._zod.run(r,n);return i instanceof Promise?i.then(s=>ec(s,e.in,n)):ec(i,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(i=>ec(i,e.out,n)):ec(o,e.out,n)}});function ec(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var CS=S("$ZodPreprocess",(t,e)=>{$l.init(t,e)}),PS=S("$ZodReadonly",(t,e)=>{re.init(t,e),X(t._zod,"propValues",()=>e.innerType._zod.propValues),X(t._zod,"values",()=>e.innerType._zod.values),X(t._zod,"optin",()=>e.innerType?._zod?.optin),X(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(k_):k_(o)}});function k_(t){return t.value=Object.freeze(t.value),t}var xS=S("$ZodCustom",(t,e)=>{Oe.init(t,e),re.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>T_(i,r,n,t));T_(o,r,n,t)}});function T_(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(vo(o))}}var XI=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,s=_l(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Va(o.values[0])}`:`Invalid option: expected one of ${Za(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Za(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function ES(){return{localeError:XI()}}var kS;var Il=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function TS(){return new Il}(kS=globalThis).__zod_globalRegistry??(kS.__zod_globalRegistry=TS());var Hr=globalThis.__zod_globalRegistry;function AS(t,e){return new t({type:"string",...M(e)})}function MS(t,e){return new t({type:"string",coerce:!0,...M(e)})}function $S(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...M(e)})}function Ol(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...M(e)})}function IS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...M(e)})}function OS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(e)})}function zS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(e)})}function NS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(e)})}function zl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...M(e)})}function DS(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...M(e)})}function LS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(e)})}function jS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...M(e)})}function FS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(e)})}function US(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...M(e)})}function qS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...M(e)})}function HS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(e)})}function GS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(e)})}function ZS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(e)})}function BS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(e)})}function WS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(e)})}function VS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...M(e)})}function KS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...M(e)})}function JS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...M(e)})}function YS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...M(e)})}function XS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(e)})}function QS(t,e){return new t({type:"string",format:"date",check:"string_format",...M(e)})}function ew(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...M(e)})}function tw(t,e){return new t({type:"string",format:"duration",check:"string_format",...M(e)})}function rw(t,e){return new t({type:"number",checks:[],...M(e)})}function nw(t,e){return new t({type:"number",coerce:!0,checks:[],...M(e)})}function ow(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...M(e)})}function iw(t,e){return new t({type:"boolean",...M(e)})}function sw(t,e){return new t({type:"boolean",coerce:!0,...M(e)})}function aw(t,e){return new t({type:"bigint",coerce:!0,...M(e)})}function cw(t,e){return new t({type:"null",...M(e)})}function uw(t){return new t({type:"any"})}function dw(t){return new t({type:"unknown"})}function lw(t,e){return new t({type:"never",...M(e)})}function fw(t,e){return new t({type:"date",coerce:!0,...M(e)})}function _o(t,e){return new xl({check:"less_than",...M(e),value:t,inclusive:!1})}function fr(t,e){return new xl({check:"less_than",...M(e),value:t,inclusive:!0})}function So(t,e){return new El({check:"greater_than",...M(e),value:t,inclusive:!1})}function $t(t,e){return new El({check:"greater_than",...M(e),value:t,inclusive:!0})}function Bi(t,e){return new c_({check:"multiple_of",...M(e),value:t})}function nc(t,e){return new d_({check:"max_length",...M(e),maximum:t})}function wo(t,e){return new l_({check:"min_length",...M(e),minimum:t})}function oc(t,e){return new f_({check:"length_equals",...M(e),length:t})}function Nl(t,e){return new p_({check:"string_format",format:"regex",...M(e),pattern:t})}function Dl(t){return new h_({check:"string_format",format:"lowercase",...M(t)})}function Ll(t){return new m_({check:"string_format",format:"uppercase",...M(t)})}function jl(t,e){return new g_({check:"string_format",format:"includes",...M(e),includes:t})}function Fl(t,e){return new y_({check:"string_format",format:"starts_with",...M(e),prefix:t})}function Ul(t,e){return new v_({check:"string_format",format:"ends_with",...M(e),suffix:t})}function Gr(t){return new __({check:"overwrite",tx:t})}function ql(t){return Gr(e=>e.normalize(t))}function Hl(){return Gr(t=>t.trim())}function Gl(){return Gr(t=>t.toLowerCase())}function Zl(){return Gr(t=>t.toUpperCase())}function Bl(){return Gr(t=>pl(t))}function pw(t,e,r){return new t({type:"array",element:e,...M(r)})}function hw(t,e,r){let n=M(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function mw(t,e,r){return new t({type:"custom",check:"custom",fn:e,...M(r)})}function gw(t,e){let r=QI(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(vo(o,n.value,r._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(vo(i))}},t(n.value,n)),e);return r}function QI(t,e){let r=new Oe({check:"custom",...M(e)});return r._zod.check=t,r}function Wl(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Hr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function Re(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s);let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,d);else{let f=s.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(s.ref||(s.ref=l),Re(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),e.io==="input"&&Ge(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function Vl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(s[0])?.id,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(s[1]===r)return{ref:"#"};let u=`#/${a}/`,d=s[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=o(s);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
85
|
+
`)}p.write("payload.value = newResult;"),p.write("return payload;");let w=p.compile();return(b,R)=>w(f,b,R)},i,s=Cn,a=!go.jitless,u=a&&vl.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return s(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(i||(i=o(e.shape)),f=i(f,p),d?hS([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function x_(t,e,r,n){for(let i of t)if(i.issues.length===0)return e.value=i.value,e;let o=t.filter(i=>!Hr(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(i=>i.issues.map(s=>St(s,n,Qe())))}),e)}var Ol=S("$ZodUnion",(t,e)=>{re.init(t,e),X(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),X(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),X(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),X(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>Fi(o.source)).join("|")})$`)}});let r=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>x_(a,n,t,o)):x_(s,n,t,o)}});var gS=S("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ol.init(t,e);let r=t._zod.parse;X(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=vo(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!Cn(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=n.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback||i.direction==="backward"?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:s,path:[e.discriminator],inst:t}),o)}}),yS=S("$ZodIntersection",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,i=e.left._zod.run({value:o,issues:[]},n),s=e.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>k_(r,c,u)):k_(r,i,s)}});function $l(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(qr(t)&&qr(e)){let r=Object.keys(e),n=Object.keys(t).filter(i=>r.indexOf(i)!==-1),o={...t,...e};for(let i of n){let s=$l(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],i=e[n],s=$l(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function k_(t,e,r){let n=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else t.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&t.issues.push({...o,keys:i}),Hr(t))return t;let s=$l(e.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return t.value=s.data,t}var vS=S("$ZodRecord",(t,e)=>{re.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!qr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let i=[],s=e.keyType._zod.values;if(s){r.value={};let a=new Set;for(let u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>St(p,n,Qe())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?i.push(f.then(p=>{p.issues.length&&r.issues.push(...fr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...fr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Tl.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>St(l,n,Qe())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?i.push(d.then(l=>{l.issues.length&&r.issues.push(...fr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...fr(a,d.issues)),r.value[c.value]=d.value)}}return i.length?Promise.all(i).then(()=>r):r}});var _S=S("$ZodEnum",(t,e)=>{re.init(t,e);let r=Li(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>_l.has(typeof o)).map(o=>typeof o=="string"?lr(o):o.toString()).join("|")})$`),t._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:t}),o}}),SS=S("$ZodLiteral",(t,e)=>{if(re.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?lr(n):n?lr(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:e.values,input:i,inst:t}),n}});var wS=S("$ZodTransform",(t,e)=>{re.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new mo(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r.fallback=!0,r));if(o instanceof Promise)throw new Yt;return r.value=o,r.fallback=!0,r}});function T_(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var zl=S("$ZodOptional",(t,e)=>{re.init(t,e),t._zod.optin="optional",t._zod.optout="optional",X(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),X(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fi(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,i=e.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>T_(s,o)):T_(i,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),bS=S("$ZodExactOptional",(t,e)=>{zl.init(t,e),X(t._zod,"values",()=>e.innerType._zod.values),X(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),RS=S("$ZodNullable",(t,e)=>{re.init(t,e),X(t._zod,"optin",()=>e.innerType._zod.optin),X(t._zod,"optout",()=>e.innerType._zod.optout),X(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Fi(r.source)}|null)$`):void 0}),X(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),CS=S("$ZodDefault",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>A_(i,e)):A_(o,e)}});function A_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var PS=S("$ZodPrefault",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),ES=S("$ZodNonOptional",(t,e)=>{re.init(t,e),X(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>M_(i,t)):M_(o,t)}});function M_(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var xS=S("$ZodCatch",(t,e)=>{re.init(t,e),t._zod.optin="optional",X(t._zod,"optout",()=>e.innerType._zod.optout),X(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=e.catchValue({...r,error:{issues:i.issues.map(s=>St(s,n,Qe()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>St(i,n,Qe()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Nl=S("$ZodPipe",(t,e)=>{re.init(t,e),X(t._zod,"values",()=>e.in._zod.values),X(t._zod,"optin",()=>e.in._zod.optin),X(t._zod,"optout",()=>e.out._zod.optout),X(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=e.out._zod.run(r,n);return i instanceof Promise?i.then(s=>tc(s,e.in,n)):tc(i,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(i=>tc(i,e.out,n)):tc(o,e.out,n)}});function tc(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var kS=S("$ZodPreprocess",(t,e)=>{Nl.init(t,e)}),TS=S("$ZodReadonly",(t,e)=>{re.init(t,e),X(t._zod,"propValues",()=>e.innerType._zod.propValues),X(t._zod,"values",()=>e.innerType._zod.values),X(t._zod,"optin",()=>e.innerType?._zod?.optin),X(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then($_):$_(o)}});function $_(t){return t.value=Object.freeze(t.value),t}var AS=S("$ZodCustom",(t,e)=>{Oe.init(t,e),re.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>I_(i,r,n,t));I_(o,r,n,t)}});function I_(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(_o(o))}}var pO=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(o){return t[o]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};return o=>{switch(o.code){case"invalid_type":{let i=n[o.expected]??o.expected,s=Rl(o.input),a=n[s]??s;return`Invalid input: expected ${i}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${Ka(o.values[0])}`:`Invalid option: expected one of ${Ba(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Too big: expected ${o.origin??"value"} to have ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Too small: expected ${o.origin} to have ${i}${o.minimum.toString()} ${s.unit}`:`Too small: expected ${o.origin} to be ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${Ba(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(s=>`'${s}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function MS(){return{localeError:pO()}}var $S;var Dl=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function IS(){return new Dl}($S=globalThis).__zod_globalRegistry??($S.__zod_globalRegistry=IS());var Gr=globalThis.__zod_globalRegistry;function OS(t,e){return new t({type:"string",...$(e)})}function zS(t,e){return new t({type:"string",coerce:!0,...$(e)})}function NS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...$(e)})}function Ll(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...$(e)})}function DS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...$(e)})}function LS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(e)})}function jS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(e)})}function FS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(e)})}function jl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...$(e)})}function US(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...$(e)})}function qS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(e)})}function HS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...$(e)})}function GS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(e)})}function ZS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...$(e)})}function BS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...$(e)})}function WS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(e)})}function VS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(e)})}function KS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(e)})}function JS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(e)})}function YS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(e)})}function XS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...$(e)})}function QS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...$(e)})}function ew(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...$(e)})}function tw(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...$(e)})}function rw(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(e)})}function nw(t,e){return new t({type:"string",format:"date",check:"string_format",...$(e)})}function ow(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...$(e)})}function iw(t,e){return new t({type:"string",format:"duration",check:"string_format",...$(e)})}function sw(t,e){return new t({type:"number",checks:[],...$(e)})}function aw(t,e){return new t({type:"number",coerce:!0,checks:[],...$(e)})}function cw(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...$(e)})}function uw(t,e){return new t({type:"boolean",...$(e)})}function dw(t,e){return new t({type:"boolean",coerce:!0,...$(e)})}function lw(t,e){return new t({type:"bigint",coerce:!0,...$(e)})}function fw(t,e){return new t({type:"null",...$(e)})}function pw(t){return new t({type:"any"})}function hw(t){return new t({type:"unknown"})}function mw(t,e){return new t({type:"never",...$(e)})}function gw(t,e){return new t({type:"date",coerce:!0,...$(e)})}function So(t,e){return new Al({check:"less_than",...$(e),value:t,inclusive:!1})}function pr(t,e){return new Al({check:"less_than",...$(e),value:t,inclusive:!0})}function wo(t,e){return new Ml({check:"greater_than",...$(e),value:t,inclusive:!1})}function It(t,e){return new Ml({check:"greater_than",...$(e),value:t,inclusive:!0})}function Wi(t,e){return new f_({check:"multiple_of",...$(e),value:t})}function oc(t,e){return new h_({check:"max_length",...$(e),maximum:t})}function bo(t,e){return new m_({check:"min_length",...$(e),minimum:t})}function ic(t,e){return new g_({check:"length_equals",...$(e),length:t})}function Fl(t,e){return new y_({check:"string_format",format:"regex",...$(e),pattern:t})}function Ul(t){return new v_({check:"string_format",format:"lowercase",...$(t)})}function ql(t){return new __({check:"string_format",format:"uppercase",...$(t)})}function Hl(t,e){return new S_({check:"string_format",format:"includes",...$(e),includes:t})}function Gl(t,e){return new w_({check:"string_format",format:"starts_with",...$(e),prefix:t})}function Zl(t,e){return new b_({check:"string_format",format:"ends_with",...$(e),suffix:t})}function Zr(t){return new R_({check:"overwrite",tx:t})}function Bl(t){return Zr(e=>e.normalize(t))}function Wl(){return Zr(t=>t.trim())}function Vl(){return Zr(t=>t.toLowerCase())}function Kl(){return Zr(t=>t.toUpperCase())}function Jl(){return Zr(t=>yl(t))}function yw(t,e,r){return new t({type:"array",element:e,...$(r)})}function vw(t,e,r){let n=$(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function _w(t,e,r){return new t({type:"custom",check:"custom",fn:e,...$(r)})}function Sw(t,e){let r=hO(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(_o(o,n.value,r._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(_o(i))}},t(n.value,n)),e);return r}function hO(t,e){let r=new Oe({check:"custom",...$(e)});return r._zod.check=t,r}function Yl(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Gr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function Re(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,i=e.seen.get(t);if(i)return i.count++,r.schemaPath.includes(t)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,s);let a=t._zod.toJSONSchema?.();if(a)s.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,s.schema,d);else{let f=s.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(s.ref||(s.ref=l),Re(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(s.schema,c),e.io==="input"&&Ze(t)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(t).schema}function Xl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let s of t.seen.entries()){let a=t.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=s=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(s[0])?.id,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=s[1].defId??s[1].schema.id??`schema${t.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(s[1]===r)return{ref:"#"};let u=`#/${a}/`,d=s[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=o(s);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let s of t.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
86
86
|
|
|
87
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function Kl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let g in u)g==="$ref"||g==="allOf"||g in d||delete u[g];if(h.$ref&&p.def)for(let g in u)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(u[g])===JSON.stringify(p.def[g])&&delete u[g]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Wi(e,"input",t.processors),output:Wi(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ge(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ge(n.element,r);if(n.type==="set")return Ge(n.valueType,r);if(n.type==="lazy")return Ge(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ge(n.innerType,r);if(n.type==="intersection")return Ge(n.left,r)||Ge(n.right,r);if(n.type==="record"||n.type==="map")return Ge(n.keyType,r)||Ge(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Ge(n.in,r)||Ge(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ge(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ge(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ge(o,r))return!0;return!!(n.rest&&Ge(n.rest,r))}return!1}var yw=(t,e={})=>r=>{let n=Wl({...r,processors:e});return Re(t,n),Vl(n,t),Kl(n,t)},Wi=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},s=Wl({...o??{},target:i,io:e,processors:r});return Re(t,s),Vl(s,t),Kl(s,t)};var eO={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},vw=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=eO[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},_w=(t,e,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof i=="number"&&(o.minimum=i),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof s=="number"&&(o.maximum=s),typeof c=="number"&&(o.multipleOf=c)},Sw=(t,e,r,n)=>{r.type="boolean"},ww=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var bw=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var Rw=(t,e,r,n)=>{r.not={}},Cw=(t,e,r,n)=>{},Pw=(t,e,r,n)=>{},xw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Ew=(t,e,r,n)=>{let o=t._zod.def,i=Di(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},kw=(t,e,r,n)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i};var Tw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Aw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var Mw=(t,e,r,n)=>{let o=r,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Re(i.element,e,{...n,path:[...n.path,"items"]})},$w=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let u in s)o.properties[u]=Re(s[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(u=>{let d=i.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Re(i.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Iw=(t,e,r,n)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Re(a,e,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},Ow=(t,e,r,n)=>{let o=t._zod.def,i=Re(o.left,e,{...n,path:[...n.path,"allOf",0]}),s=Re(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c};var zw=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=Re(i.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Re(i.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=Re(i.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=s._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},Nw=(t,e,r,n)=>{let o=t._zod.def,i=Re(o.innerType,e,n),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Dw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},Lw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},jw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Fw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Uw=(t,e,r,n)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Re(s,e,n);let a=e.seen.get(t);a.ref=s},qw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.readOnly=!0};var Jl=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType};function ic(t){return!!t._zod}function It(t,e){return ic(t)?qi(t,e):t.safeParse(e)}function sc(t){if(!t)return;let e;if(ic(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function ac(t){if(ic(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Vi={};Xu(Vi,{ZodISODate:()=>Gw,ZodISODateTime:()=>Hw,ZodISODuration:()=>Bw,ZodISOTime:()=>Zw,date:()=>Xl,datetime:()=>Yl,duration:()=>ef,time:()=>Ql});var Hw=S("ZodISODateTime",(t,e)=>{U_.init(t,e),me.init(t,e)});function Yl(t){return XS(Hw,t)}var Gw=S("ZodISODate",(t,e)=>{q_.init(t,e),me.init(t,e)});function Xl(t){return QS(Gw,t)}var Zw=S("ZodISOTime",(t,e)=>{H_.init(t,e),me.init(t,e)});function Ql(t){return ew(Zw,t)}var Bw=S("ZodISODuration",(t,e)=>{G_.init(t,e),me.init(t,e)});function ef(t){return tw(Bw,t)}var cO=(t,e)=>{Ka.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bl(t,r)},flatten:{value:r=>wl(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,go,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,go,2)}},isEmpty:{get(){return t.issues.length===0}}})};var dt=S("ZodError",cO,{Parent:Error});var Vw=Ja(dt),Kw=Ya(dt),Jw=Ui(dt),Yw=Hi(dt),Xw=Cv(dt),Qw=Pv(dt),eb=xv(dt),tb=Ev(dt),rb=kv(dt),nb=Tv(dt),ob=Av(dt),ib=Mv(dt);var sb=new WeakMap;function Ki(t,e,r){let n=Object.getPrototypeOf(t),o=sb.get(n);if(o||(o=new Set,sb.set(n,o)),!o.has(e)){o.add(e);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=S("ZodType",(t,e)=>(re.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Wi(t,"input"),output:Wi(t,"output")}}),t.toJSONSchema=yw(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>Vw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Jw(t,r,n),t.parseAsync=async(r,n)=>Kw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Yw(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Xw(t,r,n),t.decode=(r,n)=>Qw(t,r,n),t.encodeAsync=async(r,n)=>eb(t,r,n),t.decodeAsync=async(r,n)=>tb(t,r,n),t.safeEncode=(r,n)=>rb(t,r,n),t.safeDecode=(r,n)=>nb(t,r,n),t.safeEncodeAsync=async(r,n)=>ob(t,r,n),t.safeDecodeAsync=async(r,n)=>ib(t,r,n),Ki(t,"ZodType",{check(...r){let n=this.def;return this.clone(H.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return vt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(JO(r,n))},superRefine(r,n){return this.check(YO(r,n))},overwrite(r){return this.check(Gr(r))},optional(){return ye(this)},exactOptional(){return LO(this)},nullable(){return db(this)},nullish(){return ye(db(this))},nonoptional(r){return GO(this,r)},array(){return x(this)},or(r){return ue([this,r])},and(r){return dc(this,r)},transform(r){return lb(this,wb(r))},default(r){return UO(this,r)},prefault(r){return HO(this,r)},catch(r){return BO(this,r)},pipe(r){return lb(this,r)},readonly(){return KO(this)},describe(r){let n=this.clone();return Hr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Hr.get(this);let n=this.clone();return Hr.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Hr.get(t)?.description},configurable:!0}),t)),fb=S("_ZodString",(t,e)=>{rc.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>vw(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Ki(t,"_ZodString",{regex(...n){return this.check(Nl(...n))},includes(...n){return this.check(jl(...n))},startsWith(...n){return this.check(Fl(...n))},endsWith(...n){return this.check(Ul(...n))},min(...n){return this.check(wo(...n))},max(...n){return this.check(nc(...n))},length(...n){return this.check(oc(...n))},nonempty(...n){return this.check(wo(1,...n))},lowercase(n){return this.check(Dl(n))},uppercase(n){return this.check(Ll(n))},trim(){return this.check(Hl())},normalize(...n){return this.check(ql(...n))},toLowerCase(){return this.check(Gl())},toUpperCase(){return this.check(Zl())},slugify(){return this.check(Bl())}})}),rf=S("ZodString",(t,e)=>{rc.init(t,e),fb.init(t,e),t.email=r=>t.check($S(dO,r)),t.url=r=>t.check(zl(pb,r)),t.jwt=r=>t.check(YS(PO,r)),t.emoji=r=>t.check(DS(lO,r)),t.guid=r=>t.check(Ol(ab,r)),t.uuid=r=>t.check(IS(cc,r)),t.uuidv4=r=>t.check(OS(cc,r)),t.uuidv6=r=>t.check(zS(cc,r)),t.uuidv7=r=>t.check(NS(cc,r)),t.nanoid=r=>t.check(LS(fO,r)),t.guid=r=>t.check(Ol(ab,r)),t.cuid=r=>t.check(jS(pO,r)),t.cuid2=r=>t.check(FS(hO,r)),t.ulid=r=>t.check(US(mO,r)),t.base64=r=>t.check(VS(bO,r)),t.base64url=r=>t.check(KS(RO,r)),t.xid=r=>t.check(qS(gO,r)),t.ksuid=r=>t.check(HS(yO,r)),t.ipv4=r=>t.check(GS(vO,r)),t.ipv6=r=>t.check(ZS(_O,r)),t.cidrv4=r=>t.check(BS(SO,r)),t.cidrv6=r=>t.check(WS(wO,r)),t.e164=r=>t.check(JS(CO,r)),t.datetime=r=>t.check(Yl(r)),t.date=r=>t.check(Xl(r)),t.time=r=>t.check(Ql(r)),t.duration=r=>t.check(ef(r))});function y(t){return AS(rf,t)}var me=S("ZodStringFormat",(t,e)=>{ce.init(t,e),fb.init(t,e)}),dO=S("ZodEmail",(t,e)=>{$_.init(t,e),me.init(t,e)});var ab=S("ZodGUID",(t,e)=>{A_.init(t,e),me.init(t,e)});var cc=S("ZodUUID",(t,e)=>{M_.init(t,e),me.init(t,e)});var pb=S("ZodURL",(t,e)=>{I_.init(t,e),me.init(t,e)});function hb(t){return zl(pb,t)}var lO=S("ZodEmoji",(t,e)=>{O_.init(t,e),me.init(t,e)});var fO=S("ZodNanoID",(t,e)=>{z_.init(t,e),me.init(t,e)});var pO=S("ZodCUID",(t,e)=>{N_.init(t,e),me.init(t,e)});var hO=S("ZodCUID2",(t,e)=>{D_.init(t,e),me.init(t,e)});var mO=S("ZodULID",(t,e)=>{L_.init(t,e),me.init(t,e)});var gO=S("ZodXID",(t,e)=>{j_.init(t,e),me.init(t,e)});var yO=S("ZodKSUID",(t,e)=>{F_.init(t,e),me.init(t,e)});var vO=S("ZodIPv4",(t,e)=>{Z_.init(t,e),me.init(t,e)});var _O=S("ZodIPv6",(t,e)=>{B_.init(t,e),me.init(t,e)});var SO=S("ZodCIDRv4",(t,e)=>{W_.init(t,e),me.init(t,e)});var wO=S("ZodCIDRv6",(t,e)=>{V_.init(t,e),me.init(t,e)});var bO=S("ZodBase64",(t,e)=>{J_.init(t,e),me.init(t,e)});var RO=S("ZodBase64URL",(t,e)=>{Y_.init(t,e),me.init(t,e)});var CO=S("ZodE164",(t,e)=>{X_.init(t,e),me.init(t,e)});var PO=S("ZodJWT",(t,e)=>{Q_.init(t,e),me.init(t,e)});var uc=S("ZodNumber",(t,e)=>{Tl.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>_w(t,n,o,i),Ki(t,"ZodNumber",{gt(n,o){return this.check(So(n,o))},gte(n,o){return this.check($t(n,o))},min(n,o){return this.check($t(n,o))},lt(n,o){return this.check(_o(n,o))},lte(n,o){return this.check(fr(n,o))},max(n,o){return this.check(fr(n,o))},int(n){return this.check(cb(n))},safe(n){return this.check(cb(n))},positive(n){return this.check(So(0,n))},nonnegative(n){return this.check($t(0,n))},negative(n){return this.check(_o(0,n))},nonpositive(n){return this.check(fr(0,n))},multipleOf(n,o){return this.check(Bi(n,o))},step(n,o){return this.check(Bi(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function K(t){return rw(uc,t)}var xO=S("ZodNumberFormat",(t,e)=>{eS.init(t,e),uc.init(t,e)});function cb(t){return ow(xO,t)}var nf=S("ZodBoolean",(t,e)=>{tS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Sw(t,r,n,o)});function ie(t){return iw(nf,t)}var mb=S("ZodBigInt",(t,e)=>{rS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>ww(t,n,o,i),t.gte=(n,o)=>t.check($t(n,o)),t.min=(n,o)=>t.check($t(n,o)),t.gt=(n,o)=>t.check(So(n,o)),t.gte=(n,o)=>t.check($t(n,o)),t.min=(n,o)=>t.check($t(n,o)),t.lt=(n,o)=>t.check(_o(n,o)),t.lte=(n,o)=>t.check(fr(n,o)),t.max=(n,o)=>t.check(fr(n,o)),t.positive=n=>t.check(So(BigInt(0),n)),t.negative=n=>t.check(_o(BigInt(0),n)),t.nonpositive=n=>t.check(fr(BigInt(0),n)),t.nonnegative=n=>t.check($t(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Bi(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var EO=S("ZodNull",(t,e)=>{nS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bw(t,r,n,o)});function gb(t){return cw(EO,t)}var kO=S("ZodAny",(t,e)=>{oS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Cw(t,r,n,o)});function yb(){return uw(kO)}var TO=S("ZodUnknown",(t,e)=>{iS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Pw(t,r,n,o)});function ge(){return dw(TO)}var AO=S("ZodNever",(t,e)=>{sS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Rw(t,r,n,o)});function MO(t){return lw(AO,t)}var vb=S("ZodDate",(t,e)=>{aS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>xw(t,n,o,i),t.min=(n,o)=>t.check($t(n,o)),t.max=(n,o)=>t.check(fr(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var $O=S("ZodArray",(t,e)=>{cS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mw(t,r,n,o),t.element=e.element,Ki(t,"ZodArray",{min(r,n){return this.check(wo(r,n))},nonempty(r){return this.check(wo(1,r))},max(r,n){return this.check(nc(r,n))},length(r,n){return this.check(oc(r,n))},unwrap(){return this.element}})});function x(t,e){return pw($O,t,e)}var _b=S("ZodObject",(t,e)=>{lS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$w(t,r,n,o),H.defineLazy(t,"shape",()=>e.shape),Ki(t,"ZodObject",{keyof(){return et(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ge()})},loose(){return this.clone({...this._zod.def,catchall:ge()})},strict(){return this.clone({...this._zod.def,catchall:MO()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return H.extend(this,r)},safeExtend(r){return H.safeExtend(this,r)},merge(r){return H.merge(this,r)},pick(r){return H.pick(this,r)},omit(r){return H.omit(this,r)},partial(...r){return H.partial(bb,this,r[0])},required(...r){return H.required(Rb,this,r[0])}})});function E(t,e){let r={type:"object",shape:t??{},...H.normalizeParams(e)};return new _b(r)}function ke(t,e){return new _b({type:"object",shape:t,catchall:ge(),...H.normalizeParams(e)})}var Sb=S("ZodUnion",(t,e)=>{Al.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Iw(t,r,n,o),t.options=e.options});function ue(t,e){return new Sb({type:"union",options:t,...H.normalizeParams(e)})}var IO=S("ZodDiscriminatedUnion",(t,e)=>{Sb.init(t,e),fS.init(t,e)});function of(t,e,r){return new IO({type:"union",options:e,discriminator:t,...H.normalizeParams(r)})}var OO=S("ZodIntersection",(t,e)=>{pS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ow(t,r,n,o)});function dc(t,e){return new OO({type:"intersection",left:t,right:e})}var ub=S("ZodRecord",(t,e)=>{hS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>zw(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new ub({type:"record",keyType:y(),valueType:t,...H.normalizeParams(e)}):new ub({type:"record",keyType:t,valueType:e,...H.normalizeParams(r)})}var tf=S("ZodEnum",(t,e)=>{mS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Ew(t,n,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new tf({...e,checks:[],...H.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new tf({...e,checks:[],...H.normalizeParams(o),entries:i})}});function et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new tf({type:"enum",entries:r,...H.normalizeParams(e)})}var zO=S("ZodLiteral",(t,e)=>{gS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kw(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function k(t,e){return new zO({type:"literal",values:Array.isArray(t)?t:[t],...H.normalizeParams(e)})}var NO=S("ZodTransform",(t,e)=>{yS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Aw(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new ho(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(H.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(H.issue(s))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function wb(t){return new NO({type:"transform",transform:t})}var bb=S("ZodOptional",(t,e)=>{Ml.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ye(t){return new bb({type:"optional",innerType:t})}var DO=S("ZodExactOptional",(t,e)=>{vS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function LO(t){return new DO({type:"optional",innerType:t})}var jO=S("ZodNullable",(t,e)=>{_S.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Nw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function db(t){return new jO({type:"nullable",innerType:t})}var FO=S("ZodDefault",(t,e)=>{SS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Lw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function UO(t,e){return new FO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var qO=S("ZodPrefault",(t,e)=>{wS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function HO(t,e){return new qO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var Rb=S("ZodNonOptional",(t,e)=>{bS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Dw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function GO(t,e){return new Rb({type:"nonoptional",innerType:t,...H.normalizeParams(e)})}var ZO=S("ZodCatch",(t,e)=>{RS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function BO(t,e){return new ZO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Cb=S("ZodPipe",(t,e)=>{$l.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Uw(t,r,n,o),t.in=e.in,t.out=e.out});function lb(t,e){return new Cb({type:"pipe",in:t,out:e})}var WO=S("ZodPreprocess",(t,e)=>{Cb.init(t,e),CS.init(t,e)}),VO=S("ZodReadonly",(t,e)=>{PS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function KO(t){return new VO({type:"readonly",innerType:t})}var Pb=S("ZodCustom",(t,e)=>{xS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Tw(t,r,n,o)});function xb(t,e){return hw(Pb,t??(()=>!0),e)}function JO(t,e={}){return mw(Pb,t,e)}function YO(t,e){return gw(t,e)}function sf(t,e){return new WO({type:"pipe",in:wb(t),out:e})}var kb={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Eb;Eb||(Eb={});var lc={};Xu(lc,{bigint:()=>tz,boolean:()=>ez,date:()=>rz,number:()=>QO,string:()=>XO});function XO(t){return MS(rf,t)}function QO(t){return nw(uc,t)}function ez(t){return sw(nf,t)}function tz(t){return aw(mb,t)}function rz(t){return fw(vb,t)}Qe(ES());var Co="2025-11-25";var Tb=[Co,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zr="io.modelcontextprotocol/related-task",pc="2.0",Te=xb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ab=ue([y(),K().int()]),Mb=y(),L6=ke({ttl:K().optional(),pollInterval:K().optional()}),oz=E({ttl:K().optional()}),iz=E({taskId:y()}),cf=ke({progressToken:Ab.optional(),[Zr]:iz.optional()}),lt=E({_meta:cf.optional()}),Ji=lt.extend({task:oz.optional()}),$b=t=>Ji.safeParse(t).success,ze=E({method:y(),params:lt.loose().optional()}),St=E({_meta:cf.optional()}),wt=E({method:y(),params:St.loose().optional()}),Ae=ke({_meta:cf.optional()}),hc=ue([y(),K().int()]),Ib=E({jsonrpc:k(pc),id:hc,...ze.shape}).strict(),Yi=t=>Ib.safeParse(t).success,Ob=E({jsonrpc:k(pc),...wt.shape}).strict(),zb=t=>Ob.safeParse(t).success,uf=E({jsonrpc:k(pc),id:hc,result:Ae}).strict(),bn=t=>uf.safeParse(t).success;var $;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})($||($={}));var df=E({jsonrpc:k(pc),id:hc.optional(),error:E({code:K().int(),message:y(),data:ge().optional()})}).strict();var Nb=t=>df.safeParse(t).success;var Br=ue([Ib,Ob,uf,df]),j6=ue([uf,df]),Rn=Ae.strict(),sz=St.extend({requestId:hc.optional(),reason:y().optional()}),mc=wt.extend({method:k("notifications/cancelled"),params:sz}),az=E({src:y(),mimeType:y().optional(),sizes:x(y()).optional(),theme:et(["light","dark"]).optional()}),Xi=E({icons:x(az).optional()}),Ro=E({name:y(),title:y().optional()}),Db=Ro.extend({...Ro.shape,...Xi.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),cz=dc(E({applyDefaults:ie().optional()}),ae(y(),ge())),uz=sf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,dc(E({form:cz.optional(),url:Te.optional()}),ae(y(),ge()).optional())),dz=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({sampling:ke({createMessage:Te.optional()}).optional(),elicitation:ke({create:Te.optional()}).optional()}).optional()}),lz=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({tools:ke({call:Te.optional()}).optional()}).optional()}),fz=E({experimental:ae(y(),Te).optional(),sampling:E({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:uz.optional(),roots:E({listChanged:ie().optional()}).optional(),tasks:dz.optional(),extensions:ae(y(),Te).optional()}),pz=lt.extend({protocolVersion:y(),capabilities:fz,clientInfo:Db}),hz=ze.extend({method:k("initialize"),params:pz});var mz=E({experimental:ae(y(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:E({listChanged:ie().optional()}).optional(),resources:E({subscribe:ie().optional(),listChanged:ie().optional()}).optional(),tools:E({listChanged:ie().optional()}).optional(),tasks:lz.optional(),extensions:ae(y(),Te).optional()}),lf=Ae.extend({protocolVersion:y(),capabilities:mz,serverInfo:Db,instructions:y().optional()}),Lb=wt.extend({method:k("notifications/initialized"),params:St.optional()}),jb=t=>Lb.safeParse(t).success,gc=ze.extend({method:k("ping"),params:lt.optional()}),gz=E({progress:K(),total:ye(K()),message:ye(y())}),yz=E({...St.shape,...gz.shape,progressToken:Ab}),yc=wt.extend({method:k("notifications/progress"),params:yz}),vz=lt.extend({cursor:Mb.optional()}),Qi=ze.extend({params:vz.optional()}),es=Ae.extend({nextCursor:Mb.optional()}),_z=et(["working","input_required","completed","failed","cancelled"]),ts=E({taskId:y(),status:_z,ttl:ue([K(),gb()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:ye(K()),statusMessage:ye(y())}),Cn=Ae.extend({task:ts}),Sz=St.merge(ts),rs=wt.extend({method:k("notifications/tasks/status"),params:Sz}),vc=ze.extend({method:k("tasks/get"),params:lt.extend({taskId:y()})}),_c=Ae.merge(ts),Sc=ze.extend({method:k("tasks/result"),params:lt.extend({taskId:y()})}),F6=Ae.loose(),wc=Qi.extend({method:k("tasks/list")}),bc=es.extend({tasks:x(ts)}),Rc=ze.extend({method:k("tasks/cancel"),params:lt.extend({taskId:y()})}),Fb=Ae.merge(ts),Ub=E({uri:y(),mimeType:ye(y()),_meta:ae(y(),ge()).optional()}),qb=Ub.extend({text:y()}),ff=y().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Hb=Ub.extend({blob:ff}),ns=et(["user","assistant"]),Po=E({audience:x(ns).optional(),priority:K().min(0).max(1).optional(),lastModified:Vi.datetime({offset:!0}).optional()}),Gb=E({...Ro.shape,...Xi.shape,uri:y(),description:ye(y()),mimeType:ye(y()),size:ye(K()),annotations:Po.optional(),_meta:ye(ke({}))}),wz=E({...Ro.shape,...Xi.shape,uriTemplate:y(),description:ye(y()),mimeType:ye(y()),annotations:Po.optional(),_meta:ye(ke({}))}),bz=Qi.extend({method:k("resources/list")}),pf=es.extend({resources:x(Gb)}),Rz=Qi.extend({method:k("resources/templates/list")}),hf=es.extend({resourceTemplates:x(wz)}),mf=lt.extend({uri:y()}),Cz=mf,Pz=ze.extend({method:k("resources/read"),params:Cz}),gf=Ae.extend({contents:x(ue([qb,Hb]))}),yf=wt.extend({method:k("notifications/resources/list_changed"),params:St.optional()}),xz=mf,Ez=ze.extend({method:k("resources/subscribe"),params:xz}),kz=mf,Tz=ze.extend({method:k("resources/unsubscribe"),params:kz}),Az=St.extend({uri:y()}),Mz=wt.extend({method:k("notifications/resources/updated"),params:Az}),$z=E({name:y(),description:ye(y()),required:ye(ie())}),Iz=E({...Ro.shape,...Xi.shape,description:ye(y()),arguments:ye(x($z)),_meta:ye(ke({}))}),Oz=Qi.extend({method:k("prompts/list")}),vf=es.extend({prompts:x(Iz)}),zz=lt.extend({name:y(),arguments:ae(y(),y()).optional()}),Nz=ze.extend({method:k("prompts/get"),params:zz}),_f=E({type:k("text"),text:y(),annotations:Po.optional(),_meta:ae(y(),ge()).optional()}),Sf=E({type:k("image"),data:ff,mimeType:y(),annotations:Po.optional(),_meta:ae(y(),ge()).optional()}),wf=E({type:k("audio"),data:ff,mimeType:y(),annotations:Po.optional(),_meta:ae(y(),ge()).optional()}),Dz=E({type:k("tool_use"),name:y(),id:y(),input:ae(y(),ge()),_meta:ae(y(),ge()).optional()}),Lz=E({type:k("resource"),resource:ue([qb,Hb]),annotations:Po.optional(),_meta:ae(y(),ge()).optional()}),jz=Gb.extend({type:k("resource_link")}),bf=ue([_f,Sf,wf,jz,Lz]),Fz=E({role:ns,content:bf}),Rf=Ae.extend({description:y().optional(),messages:x(Fz)}),Cf=wt.extend({method:k("notifications/prompts/list_changed"),params:St.optional()}),Uz=E({title:y().optional(),readOnlyHint:ie().optional(),destructiveHint:ie().optional(),idempotentHint:ie().optional(),openWorldHint:ie().optional()}),qz=E({taskSupport:et(["required","optional","forbidden"]).optional()}),Zb=E({...Ro.shape,...Xi.shape,description:y().optional(),inputSchema:E({type:k("object"),properties:ae(y(),Te).optional(),required:x(y()).optional()}).catchall(ge()),outputSchema:E({type:k("object"),properties:ae(y(),Te).optional(),required:x(y()).optional()}).catchall(ge()).optional(),annotations:Uz.optional(),execution:qz.optional(),_meta:ae(y(),ge()).optional()}),Hz=Qi.extend({method:k("tools/list")}),Pf=es.extend({tools:x(Zb)}),Pn=Ae.extend({content:x(bf).default([]),structuredContent:ae(y(),ge()).optional(),isError:ie().optional()}),U6=Pn.or(Ae.extend({toolResult:ge()})),Gz=Ji.extend({name:y(),arguments:ae(y(),ge()).optional()}),Zz=ze.extend({method:k("tools/call"),params:Gz}),os=wt.extend({method:k("notifications/tools/list_changed"),params:St.optional()}),Bb=E({autoRefresh:ie().default(!0),debounceMs:K().int().nonnegative().default(300)}),Wb=et(["debug","info","notice","warning","error","critical","alert","emergency"]),Bz=lt.extend({level:Wb}),Wz=ze.extend({method:k("logging/setLevel"),params:Bz}),Vz=St.extend({level:Wb,logger:y().optional(),data:ge()}),Kz=wt.extend({method:k("notifications/message"),params:Vz}),Jz=E({name:y().optional()}),Yz=E({hints:x(Jz).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),Xz=E({mode:et(["auto","required","none"]).optional()}),Qz=E({type:k("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:x(bf).default([]),structuredContent:E({}).loose().optional(),isError:ie().optional(),_meta:ae(y(),ge()).optional()}),eN=of("type",[_f,Sf,wf]),fc=of("type",[_f,Sf,wf,Dz,Qz]),tN=E({role:ns,content:ue([fc,x(fc)]),_meta:ae(y(),ge()).optional()}),rN=Ji.extend({messages:x(tN),modelPreferences:Yz.optional(),systemPrompt:y().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:x(y()).optional(),metadata:Te.optional(),tools:x(Zb).optional(),toolChoice:Xz.optional()}),xf=ze.extend({method:k("sampling/createMessage"),params:rN}),Ef=Ae.extend({model:y(),stopReason:ye(et(["endTurn","stopSequence","maxTokens"]).or(y())),role:ns,content:eN}),kf=Ae.extend({model:y(),stopReason:ye(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:ns,content:ue([fc,x(fc)])}),nN=E({type:k("boolean"),title:y().optional(),description:y().optional(),default:ie().optional()}),oN=E({type:k("string"),title:y().optional(),description:y().optional(),minLength:K().optional(),maxLength:K().optional(),format:et(["email","uri","date","date-time"]).optional(),default:y().optional()}),iN=E({type:et(["number","integer"]),title:y().optional(),description:y().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),sN=E({type:k("string"),title:y().optional(),description:y().optional(),enum:x(y()),default:y().optional()}),aN=E({type:k("string"),title:y().optional(),description:y().optional(),oneOf:x(E({const:y(),title:y()})),default:y().optional()}),cN=E({type:k("string"),title:y().optional(),description:y().optional(),enum:x(y()),enumNames:x(y()).optional(),default:y().optional()}),uN=ue([sN,aN]),dN=E({type:k("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:E({type:k("string"),enum:x(y())}),default:x(y()).optional()}),lN=E({type:k("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:E({anyOf:x(E({const:y(),title:y()}))}),default:x(y()).optional()}),fN=ue([dN,lN]),pN=ue([cN,uN,fN]),hN=ue([pN,nN,oN,iN]),mN=Ji.extend({mode:k("form").optional(),message:y(),requestedSchema:E({type:k("object"),properties:ae(y(),hN),required:x(y()).optional()})}),gN=Ji.extend({mode:k("url"),message:y(),elicitationId:y(),url:y().url()}),yN=ue([mN,gN]),Tf=ze.extend({method:k("elicitation/create"),params:yN}),vN=St.extend({elicitationId:y()}),_N=wt.extend({method:k("notifications/elicitation/complete"),params:vN}),Af=Ae.extend({action:et(["accept","decline","cancel"]),content:sf(t=>t===null?void 0:t,ae(y(),ue([y(),K(),ie(),x(y())])).optional())}),SN=E({type:k("ref/resource"),uri:y()});var wN=E({type:k("ref/prompt"),name:y()}),bN=lt.extend({ref:ue([wN,SN]),argument:E({name:y(),value:y()}),context:E({arguments:ae(y(),y()).optional()}).optional()}),RN=ze.extend({method:k("completion/complete"),params:bN});var Mf=Ae.extend({completion:ke({values:x(y()).max(100),total:ye(K().int()),hasMore:ye(ie())})}),CN=E({uri:y().startsWith("file://"),name:y().optional(),_meta:ae(y(),ge()).optional()}),PN=ze.extend({method:k("roots/list"),params:lt.optional()}),xN=Ae.extend({roots:x(CN)}),EN=wt.extend({method:k("notifications/roots/list_changed"),params:St.optional()}),q6=ue([gc,hz,RN,Wz,Nz,Oz,bz,Rz,Pz,Ez,Tz,Zz,Hz,vc,Sc,wc,Rc]),H6=ue([mc,yc,Lb,EN,rs]),G6=ue([Rn,Ef,kf,Af,xN,_c,bc,Cn]),Z6=ue([gc,xf,Tf,PN,vc,Sc,wc,Rc]),B6=ue([mc,yc,Kz,Mz,yf,os,Cf,rs,_N]),W6=ue([Rn,lf,Mf,Rf,vf,pf,hf,gf,Pn,Pf,_c,bc,Cn]),T=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===$.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new af(o.elicitations,r)}return new t(e,r,n)}},af=class extends T{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super($.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Wr(t){return t==="completed"||t==="failed"||t==="cancelled"}var xK=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $f(t){let r=sc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ac(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function If(t,e){let r=It(t,e);if(!r.success)throw r.error;return r.data}var IN=6e4,Cc=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(mc,r=>{this._oncancel(r)}),this.setNotificationHandler(yc,r=>{this._onprogress(r)}),this.setRequestHandler(gc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(vc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T($.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Sc,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,f=new T(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new T($.InvalidParams,`Task not found: ${i}`);if(!Wr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Wr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Zr]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(wc,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new T($.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Rc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new T($.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wr(o.status))throw new T($.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new T($.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof T?o:new T($.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),T.fromError($.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),bn(i)||Nb(i)?this._onresponse(i):Yi(i)?this._onrequest(i,s):zb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=T.fromError($.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Zr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:$.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=$b(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(s.signal.aborted)return;let l={relatedRequestId:e.id};i&&(l.relatedTask={taskId:i}),await this.notification(d,l)},sendRequest:async(d,l,f)=>{if(s.signal.aborted)throw new T($.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let h=p.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(s.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(s.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:$.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),bn(e))n(e);else{let s=new T(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(bn(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),bn(e))o(e);else{let s=T.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof T?s:new T($.InternalError,String(s))}}return}let i;try{let s=await this.request(e,Cn,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new T($.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Wr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new T($.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new T($.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof T?s:new T($.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=w=>{d(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){l(w);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Zr]:c}});let h=w=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(w)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let b=w instanceof T?w:new T($.RequestTimeout,String(w));d(b)};this._responseHandlers.set(f,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=It(r,w.result);b.success?u(b.data):d(b.error)}catch(b){d(b)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??IN,g=()=>h(T.fromError($.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let w=b=>{let R=this._responseHandlers.get(f);R?R(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,w),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),d(b)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(f),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},_c,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},bc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Fb,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Zr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Zr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Zr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=$f(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=If(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=$f(e);this._notificationHandlers.set(n,o=>{let i=If(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Yi(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new T($.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new T($.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new T($.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new T($.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=rs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Wr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new T($.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Wr(a.status))throw new T($.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=rs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Vb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Kb(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];Vb(s)&&Vb(i)?r[o]={...s,...i}:r[o]=i}return r}var jP=ca(_h(),1),FP=ca(LP(),1);function LU(){let t=new jP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,FP.default)(t),t}var au=class{constructor(e){this._ajv=e??LU()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var cu=class{constructor(e){this._client=e}async*callToolStream(e,r=Pn,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},r,i),a=o.getToolOutputValidator(e.name);for await(let c of s){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new T($.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let d=a(u.structuredContent);if(!d.valid){yield{type:"error",error:new T($.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof T){yield{type:"error",error:d};return}yield{type:"error",error:new T($.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function UP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function qP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function uu(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&uu(i,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&uu(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&uu(r,e)}}function jU(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var du=class extends Cc{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new au,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",os,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Cf,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",yf,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new cu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Kb(this._capabilities,e)}setRequestHandler(e,r){let o=sc(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i=ac(o);if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,u)=>{let d=It(Tf,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new T($.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=jU(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new T($.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new T($.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=It(Cn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new T($.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let m=It(Af,h);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new T($.InvalidParams,`Invalid elicitation result: ${w}`)}let g=m.data,v=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&g.action==="accept"&&g.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{uu(v,g.content)}catch{}return g};return super.setRequestHandler(e,a)}if(s==="sampling/createMessage"){let a=async(c,u)=>{let d=It(xf,c);if(!d.success){let g=d.error instanceof Error?d.error.message:String(d.error);throw new T($.InvalidParams,`Invalid sampling request: ${g}`)}let{params:l}=d.data,f=await Promise.resolve(r(c,u));if(l.task){let g=It(Cn,f);if(!g.success){let v=g.error instanceof Error?g.error.message:String(g.error);throw new T($.InvalidParams,`Invalid task creation result: ${v}`)}return g.data}let h=l.tools||l.toolChoice?kf:Ef,m=It(h,f);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new T($.InvalidParams,`Invalid sampling result: ${g}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Co,capabilities:this._capabilities,clientInfo:this._clientInfo}},lf,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Tb.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){UP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&qP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Rn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Mf,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Rn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Rf,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},vf,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},pf,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},hf,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},gf,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Rn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Rn,r)}async callTool(e,r=Pn,n){if(this.isToolTaskRequired(e.name))throw new T($.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!o.structuredContent&&!o.isError)throw new T($.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new T($.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof T?s:new T($.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},Pf,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let i=Bb.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,u=async()=>{if(!s){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var zs=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},HP=10,FU=13,Dn=32;function Eh(t){}function lu(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Eh,onError:r=Eh,onRetry:n=Eh,onComment:o,maxBufferSize:i}=t,s=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(_){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,_.charCodeAt(0)===239&&_.charCodeAt(1)===187&&_.charCodeAt(2)===191&&(_=_.slice(3))),s.length===0){let ee=g(_);ee!==""&&(s.push(ee),a=ee.length),m();return}if(_.indexOf(`
|
|
88
|
-
`)===-1&&_.indexOf("\r")===-1){s.push(_),a+=_.length,
|
|
87
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function Ql(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let m in u)m==="$ref"||m==="allOf"||m in d||delete u[m];if(h.$ref&&p.def)for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:Vi(e,"input",t.processors),output:Vi(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ze(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ze(n.element,r);if(n.type==="set")return Ze(n.valueType,r);if(n.type==="lazy")return Ze(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ze(n.innerType,r);if(n.type==="intersection")return Ze(n.left,r)||Ze(n.right,r);if(n.type==="record"||n.type==="map")return Ze(n.keyType,r)||Ze(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Ze(n.in,r)||Ze(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ze(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ze(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ze(o,r))return!0;return!!(n.rest&&Ze(n.rest,r))}return!1}var ww=(t,e={})=>r=>{let n=Yl({...r,processors:e});return Re(t,n),Xl(n,t),Ql(n,t)},Vi=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},s=Yl({...o??{},target:i,io:e,processors:r});return Re(t,s),Xl(s,t),Ql(s,t)};var mO={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bw=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=mO[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(l=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:l.source}))])}},Rw=(t,e,r,n)=>{let o=r,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof i=="number"&&(o.minimum=i),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof s=="number"&&(o.maximum=s),typeof c=="number"&&(o.multipleOf=c)},Cw=(t,e,r,n)=>{r.type="boolean"},Pw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var Ew=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var xw=(t,e,r,n)=>{r.not={}},kw=(t,e,r,n)=>{},Tw=(t,e,r,n)=>{},Aw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Mw=(t,e,r,n)=>{let o=t._zod.def,i=Li(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},$w=(t,e,r,n)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i};var Iw=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var Ow=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var zw=(t,e,r,n)=>{let o=r,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Re(i.element,e,{...n,path:[...n.path,"items"]})},Nw=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let u in s)o.properties[u]=Re(s[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(u=>{let d=i.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Re(i.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Dw=(t,e,r,n)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Re(a,e,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},Lw=(t,e,r,n)=>{let o=t._zod.def,i=Re(o.left,e,{...n,path:[...n.path,"allOf",0]}),s=Re(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c};var jw=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=Re(i.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Re(i.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=Re(i.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=s._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},Fw=(t,e,r,n)=>{let o=t._zod.def,i=Re(o.innerType,e,n),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},Uw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},qw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},Hw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},Gw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},Zw=(t,e,r,n)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Re(s,e,n);let a=e.seen.get(t);a.ref=s},Bw=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.readOnly=!0};var ef=(t,e,r,n)=>{let o=t._zod.def;Re(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType};var Ki={};ed(Ki,{ZodISODate:()=>Vw,ZodISODateTime:()=>Ww,ZodISODuration:()=>Jw,ZodISOTime:()=>Kw,date:()=>rf,datetime:()=>tf,duration:()=>of,time:()=>nf});var Ww=S("ZodISODateTime",(t,e)=>{Z_.init(t,e),me.init(t,e)});function tf(t){return rw(Ww,t)}var Vw=S("ZodISODate",(t,e)=>{B_.init(t,e),me.init(t,e)});function rf(t){return nw(Vw,t)}var Kw=S("ZodISOTime",(t,e)=>{W_.init(t,e),me.init(t,e)});function nf(t){return ow(Kw,t)}var Jw=S("ZodISODuration",(t,e)=>{V_.init(t,e),me.init(t,e)});function of(t){return iw(Jw,t)}var RO=(t,e)=>{Ja.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>El(t,r)},flatten:{value:r=>Pl(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,yo,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,yo,2)}},isEmpty:{get(){return t.issues.length===0}}})};var lt=S("ZodError",RO,{Parent:Error});var Xw=Ya(lt),Qw=Xa(lt),eb=qi(lt),tb=Gi(lt),rb=kv(lt),nb=Tv(lt),ob=Av(lt),ib=Mv(lt),sb=$v(lt),ab=Iv(lt),cb=Ov(lt),ub=zv(lt);var db=new WeakMap;function Ji(t,e,r){let n=Object.getPrototypeOf(t),o=db.get(n);if(o||(o=new Set,db.set(n,o)),!o.has(e)){o.add(e);for(let i in r){let s=r[i];Object.defineProperty(n,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var oe=S("ZodType",(t,e)=>(re.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Vi(t,"input"),output:Vi(t,"output")}}),t.toJSONSchema=ww(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>Xw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>eb(t,r,n),t.parseAsync=async(r,n)=>Qw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>tb(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>rb(t,r,n),t.decode=(r,n)=>nb(t,r,n),t.encodeAsync=async(r,n)=>ob(t,r,n),t.decodeAsync=async(r,n)=>ib(t,r,n),t.safeEncode=(r,n)=>sb(t,r,n),t.safeDecode=(r,n)=>ab(t,r,n),t.safeEncodeAsync=async(r,n)=>cb(t,r,n),t.safeDecodeAsync=async(r,n)=>ub(t,r,n),Ji(t,"ZodType",{check(...r){let n=this.def;return this.clone(H.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return _t(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(lz(r,n))},superRefine(r,n){return this.check(fz(r,n))},overwrite(r){return this.check(Zr(r))},optional(){return ye(this)},exactOptional(){return QO(this)},nullable(){return hb(this)},nullish(){return ye(hb(this))},nonoptional(r){return iz(this,r)},array(){return E(this)},or(r){return ue([this,r])},and(r){return cc(this,r)},transform(r){return mb(this,Pb(r))},default(r){return rz(this,r)},prefault(r){return oz(this,r)},catch(r){return az(this,r)},pipe(r){return mb(this,r)},readonly(){return dz(this)},describe(r){let n=this.clone();return Gr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Gr.get(this);let n=this.clone();return Gr.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t)),gb=S("_ZodString",(t,e)=>{nc.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>bw(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Ji(t,"_ZodString",{regex(...n){return this.check(Fl(...n))},includes(...n){return this.check(Hl(...n))},startsWith(...n){return this.check(Gl(...n))},endsWith(...n){return this.check(Zl(...n))},min(...n){return this.check(bo(...n))},max(...n){return this.check(oc(...n))},length(...n){return this.check(ic(...n))},nonempty(...n){return this.check(bo(1,...n))},lowercase(n){return this.check(Ul(n))},uppercase(n){return this.check(ql(n))},trim(){return this.check(Wl())},normalize(...n){return this.check(Bl(...n))},toLowerCase(){return this.check(Vl())},toUpperCase(){return this.check(Kl())},slugify(){return this.check(Jl())}})}),af=S("ZodString",(t,e)=>{nc.init(t,e),gb.init(t,e),t.email=r=>t.check(NS(PO,r)),t.url=r=>t.check(jl(yb,r)),t.jwt=r=>t.check(tw(FO,r)),t.emoji=r=>t.check(US(EO,r)),t.guid=r=>t.check(Ll(lb,r)),t.uuid=r=>t.check(DS(sc,r)),t.uuidv4=r=>t.check(LS(sc,r)),t.uuidv6=r=>t.check(jS(sc,r)),t.uuidv7=r=>t.check(FS(sc,r)),t.nanoid=r=>t.check(qS(xO,r)),t.guid=r=>t.check(Ll(lb,r)),t.cuid=r=>t.check(HS(kO,r)),t.cuid2=r=>t.check(GS(TO,r)),t.ulid=r=>t.check(ZS(AO,r)),t.base64=r=>t.check(XS(DO,r)),t.base64url=r=>t.check(QS(LO,r)),t.xid=r=>t.check(BS(MO,r)),t.ksuid=r=>t.check(WS($O,r)),t.ipv4=r=>t.check(VS(IO,r)),t.ipv6=r=>t.check(KS(OO,r)),t.cidrv4=r=>t.check(JS(zO,r)),t.cidrv6=r=>t.check(YS(NO,r)),t.e164=r=>t.check(ew(jO,r)),t.datetime=r=>t.check(tf(r)),t.date=r=>t.check(rf(r)),t.time=r=>t.check(nf(r)),t.duration=r=>t.check(of(r))});function y(t){return OS(af,t)}var me=S("ZodStringFormat",(t,e)=>{ce.init(t,e),gb.init(t,e)}),PO=S("ZodEmail",(t,e)=>{N_.init(t,e),me.init(t,e)});var lb=S("ZodGUID",(t,e)=>{O_.init(t,e),me.init(t,e)});var sc=S("ZodUUID",(t,e)=>{z_.init(t,e),me.init(t,e)});var yb=S("ZodURL",(t,e)=>{D_.init(t,e),me.init(t,e)});function vb(t){return jl(yb,t)}var EO=S("ZodEmoji",(t,e)=>{L_.init(t,e),me.init(t,e)});var xO=S("ZodNanoID",(t,e)=>{j_.init(t,e),me.init(t,e)});var kO=S("ZodCUID",(t,e)=>{F_.init(t,e),me.init(t,e)});var TO=S("ZodCUID2",(t,e)=>{U_.init(t,e),me.init(t,e)});var AO=S("ZodULID",(t,e)=>{q_.init(t,e),me.init(t,e)});var MO=S("ZodXID",(t,e)=>{H_.init(t,e),me.init(t,e)});var $O=S("ZodKSUID",(t,e)=>{G_.init(t,e),me.init(t,e)});var IO=S("ZodIPv4",(t,e)=>{K_.init(t,e),me.init(t,e)});var OO=S("ZodIPv6",(t,e)=>{J_.init(t,e),me.init(t,e)});var zO=S("ZodCIDRv4",(t,e)=>{Y_.init(t,e),me.init(t,e)});var NO=S("ZodCIDRv6",(t,e)=>{X_.init(t,e),me.init(t,e)});var DO=S("ZodBase64",(t,e)=>{eS.init(t,e),me.init(t,e)});var LO=S("ZodBase64URL",(t,e)=>{tS.init(t,e),me.init(t,e)});var jO=S("ZodE164",(t,e)=>{rS.init(t,e),me.init(t,e)});var FO=S("ZodJWT",(t,e)=>{nS.init(t,e),me.init(t,e)});var ac=S("ZodNumber",(t,e)=>{Il.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Rw(t,n,o,i),Ji(t,"ZodNumber",{gt(n,o){return this.check(wo(n,o))},gte(n,o){return this.check(It(n,o))},min(n,o){return this.check(It(n,o))},lt(n,o){return this.check(So(n,o))},lte(n,o){return this.check(pr(n,o))},max(n,o){return this.check(pr(n,o))},int(n){return this.check(fb(n))},safe(n){return this.check(fb(n))},positive(n){return this.check(wo(0,n))},nonnegative(n){return this.check(It(0,n))},negative(n){return this.check(So(0,n))},nonpositive(n){return this.check(pr(0,n))},multipleOf(n,o){return this.check(Wi(n,o))},step(n,o){return this.check(Wi(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function K(t){return sw(ac,t)}var UO=S("ZodNumberFormat",(t,e)=>{oS.init(t,e),ac.init(t,e)});function fb(t){return cw(UO,t)}var cf=S("ZodBoolean",(t,e)=>{iS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Cw(t,r,n,o)});function ie(t){return uw(cf,t)}var _b=S("ZodBigInt",(t,e)=>{sS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Pw(t,n,o,i),t.gte=(n,o)=>t.check(It(n,o)),t.min=(n,o)=>t.check(It(n,o)),t.gt=(n,o)=>t.check(wo(n,o)),t.gte=(n,o)=>t.check(It(n,o)),t.min=(n,o)=>t.check(It(n,o)),t.lt=(n,o)=>t.check(So(n,o)),t.lte=(n,o)=>t.check(pr(n,o)),t.max=(n,o)=>t.check(pr(n,o)),t.positive=n=>t.check(wo(BigInt(0),n)),t.negative=n=>t.check(So(BigInt(0),n)),t.nonpositive=n=>t.check(pr(BigInt(0),n)),t.nonnegative=n=>t.check(It(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(Wi(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var qO=S("ZodNull",(t,e)=>{aS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ew(t,r,n,o)});function Sb(t){return fw(qO,t)}var HO=S("ZodAny",(t,e)=>{cS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kw(t,r,n,o)});function wb(){return pw(HO)}var GO=S("ZodUnknown",(t,e)=>{uS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Tw(t,r,n,o)});function ge(){return hw(GO)}var ZO=S("ZodNever",(t,e)=>{dS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>xw(t,r,n,o)});function BO(t){return mw(ZO,t)}var bb=S("ZodDate",(t,e)=>{lS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Aw(t,n,o,i),t.min=(n,o)=>t.check(It(n,o)),t.max=(n,o)=>t.check(pr(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});var WO=S("ZodArray",(t,e)=>{fS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>zw(t,r,n,o),t.element=e.element,Ji(t,"ZodArray",{min(r,n){return this.check(bo(r,n))},nonempty(r){return this.check(bo(1,r))},max(r,n){return this.check(oc(r,n))},length(r,n){return this.check(ic(r,n))},unwrap(){return this.element}})});function E(t,e){return yw(WO,t,e)}var Rb=S("ZodObject",(t,e)=>{mS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Nw(t,r,n,o),H.defineLazy(t,"shape",()=>e.shape),Ji(t,"ZodObject",{keyof(){return et(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:ge()})},loose(){return this.clone({...this._zod.def,catchall:ge()})},strict(){return this.clone({...this._zod.def,catchall:BO()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return H.extend(this,r)},safeExtend(r){return H.safeExtend(this,r)},merge(r){return H.merge(this,r)},pick(r){return H.pick(this,r)},omit(r){return H.omit(this,r)},partial(...r){return H.partial(Eb,this,r[0])},required(...r){return H.required(xb,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...H.normalizeParams(e)};return new Rb(r)}function ke(t,e){return new Rb({type:"object",shape:t,catchall:ge(),...H.normalizeParams(e)})}var Cb=S("ZodUnion",(t,e)=>{Ol.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Dw(t,r,n,o),t.options=e.options});function ue(t,e){return new Cb({type:"union",options:t,...H.normalizeParams(e)})}var VO=S("ZodDiscriminatedUnion",(t,e)=>{Cb.init(t,e),gS.init(t,e)});function uf(t,e,r){return new VO({type:"union",options:e,discriminator:t,...H.normalizeParams(r)})}var KO=S("ZodIntersection",(t,e)=>{yS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Lw(t,r,n,o)});function cc(t,e){return new KO({type:"intersection",left:t,right:e})}var pb=S("ZodRecord",(t,e)=>{vS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jw(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new pb({type:"record",keyType:y(),valueType:t,...H.normalizeParams(e)}):new pb({type:"record",keyType:t,valueType:e,...H.normalizeParams(r)})}var sf=S("ZodEnum",(t,e)=>{_S.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Mw(t,n,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new sf({...e,checks:[],...H.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new sf({...e,checks:[],...H.normalizeParams(o),entries:i})}});function et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new sf({type:"enum",entries:r,...H.normalizeParams(e)})}var JO=S("ZodLiteral",(t,e)=>{SS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$w(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function T(t,e){return new JO({type:"literal",values:Array.isArray(t)?t:[t],...H.normalizeParams(e)})}var YO=S("ZodTransform",(t,e)=>{wS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ow(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new mo(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(H.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(H.issue(s))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Pb(t){return new YO({type:"transform",transform:t})}var Eb=S("ZodOptional",(t,e)=>{zl.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ye(t){return new Eb({type:"optional",innerType:t})}var XO=S("ZodExactOptional",(t,e)=>{bS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ef(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function QO(t){return new XO({type:"optional",innerType:t})}var ez=S("ZodNullable",(t,e)=>{RS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function hb(t){return new ez({type:"nullable",innerType:t})}var tz=S("ZodDefault",(t,e)=>{CS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function rz(t,e){return new tz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var nz=S("ZodPrefault",(t,e)=>{PS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function oz(t,e){return new nz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():H.shallowClone(e)}})}var xb=S("ZodNonOptional",(t,e)=>{ES.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Uw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function iz(t,e){return new xb({type:"nonoptional",innerType:t,...H.normalizeParams(e)})}var sz=S("ZodCatch",(t,e)=>{xS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Gw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function az(t,e){return new sz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var kb=S("ZodPipe",(t,e)=>{Nl.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Zw(t,r,n,o),t.in=e.in,t.out=e.out});function mb(t,e){return new kb({type:"pipe",in:t,out:e})}var cz=S("ZodPreprocess",(t,e)=>{kb.init(t,e),kS.init(t,e)}),uz=S("ZodReadonly",(t,e)=>{TS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bw(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function dz(t){return new uz({type:"readonly",innerType:t})}var Tb=S("ZodCustom",(t,e)=>{AS.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Iw(t,r,n,o)});function Ab(t,e){return vw(Tb,t??(()=>!0),e)}function lz(t,e={}){return _w(Tb,t,e)}function fz(t,e){return Sw(t,e)}function df(t,e){return new cz({type:"pipe",in:Pb(t),out:e})}var $b={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var Mb;Mb||(Mb={});var uc={};ed(uc,{bigint:()=>gz,boolean:()=>mz,date:()=>yz,number:()=>hz,string:()=>pz});function pz(t){return zS(af,t)}function hz(t){return aw(ac,t)}function mz(t){return dw(cf,t)}function gz(t){return lw(_b,t)}function yz(t){return gw(bb,t)}Qe(MS());var Po="2025-11-25";var Ib=[Po,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Br="io.modelcontextprotocol/related-task",lc="2.0",Te=Ab(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Ob=ue([y(),K().int()]),zb=y(),X6=ke({ttl:K().optional(),pollInterval:K().optional()}),_z=x({ttl:K().optional()}),Sz=x({taskId:y()}),ff=ke({progressToken:Ob.optional(),[Br]:Sz.optional()}),ft=x({_meta:ff.optional()}),Yi=ft.extend({task:_z.optional()}),Nb=t=>Yi.safeParse(t).success,ze=x({method:y(),params:ft.loose().optional()}),wt=x({_meta:ff.optional()}),bt=x({method:y(),params:wt.loose().optional()}),Ae=ke({_meta:ff.optional()}),fc=ue([y(),K().int()]),Db=x({jsonrpc:T(lc),id:fc,...ze.shape}).strict(),Xi=t=>Db.safeParse(t).success,Lb=x({jsonrpc:T(lc),...bt.shape}).strict(),jb=t=>Lb.safeParse(t).success,pf=x({jsonrpc:T(lc),id:fc,result:Ae}).strict(),Pn=t=>pf.safeParse(t).success;var A;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(A||(A={}));var hf=x({jsonrpc:T(lc),id:fc.optional(),error:x({code:K().int(),message:y(),data:ge().optional()})}).strict();var Fb=t=>hf.safeParse(t).success;var Wr=ue([Db,Lb,pf,hf]),Q6=ue([pf,hf]),En=Ae.strict(),wz=wt.extend({requestId:fc.optional(),reason:y().optional()}),pc=bt.extend({method:T("notifications/cancelled"),params:wz}),bz=x({src:y(),mimeType:y().optional(),sizes:E(y()).optional(),theme:et(["light","dark"]).optional()}),Qi=x({icons:E(bz).optional()}),Co=x({name:y(),title:y().optional()}),Ub=Co.extend({...Co.shape,...Qi.shape,version:y(),websiteUrl:y().optional(),description:y().optional()}),Rz=cc(x({applyDefaults:ie().optional()}),ae(y(),ge())),Cz=df(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cc(x({form:Rz.optional(),url:Te.optional()}),ae(y(),ge()).optional())),Pz=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({sampling:ke({createMessage:Te.optional()}).optional(),elicitation:ke({create:Te.optional()}).optional()}).optional()}),Ez=ke({list:Te.optional(),cancel:Te.optional(),requests:ke({tools:ke({call:Te.optional()}).optional()}).optional()}),xz=x({experimental:ae(y(),Te).optional(),sampling:x({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:Cz.optional(),roots:x({listChanged:ie().optional()}).optional(),tasks:Pz.optional(),extensions:ae(y(),Te).optional()}),kz=ft.extend({protocolVersion:y(),capabilities:xz,clientInfo:Ub}),Tz=ze.extend({method:T("initialize"),params:kz});var Az=x({experimental:ae(y(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:x({listChanged:ie().optional()}).optional(),resources:x({subscribe:ie().optional(),listChanged:ie().optional()}).optional(),tools:x({listChanged:ie().optional()}).optional(),tasks:Ez.optional(),extensions:ae(y(),Te).optional()}),mf=Ae.extend({protocolVersion:y(),capabilities:Az,serverInfo:Ub,instructions:y().optional()}),qb=bt.extend({method:T("notifications/initialized"),params:wt.optional()}),Hb=t=>qb.safeParse(t).success,hc=ze.extend({method:T("ping"),params:ft.optional()}),Mz=x({progress:K(),total:ye(K()),message:ye(y())}),$z=x({...wt.shape,...Mz.shape,progressToken:Ob}),mc=bt.extend({method:T("notifications/progress"),params:$z}),Iz=ft.extend({cursor:zb.optional()}),es=ze.extend({params:Iz.optional()}),ts=Ae.extend({nextCursor:zb.optional()}),Oz=et(["working","input_required","completed","failed","cancelled"]),rs=x({taskId:y(),status:Oz,ttl:ue([K(),Sb()]),createdAt:y(),lastUpdatedAt:y(),pollInterval:ye(K()),statusMessage:ye(y())}),xn=Ae.extend({task:rs}),zz=wt.merge(rs),ns=bt.extend({method:T("notifications/tasks/status"),params:zz}),gc=ze.extend({method:T("tasks/get"),params:ft.extend({taskId:y()})}),yc=Ae.merge(rs),vc=ze.extend({method:T("tasks/result"),params:ft.extend({taskId:y()})}),eK=Ae.loose(),_c=es.extend({method:T("tasks/list")}),Sc=ts.extend({tasks:E(rs)}),wc=ze.extend({method:T("tasks/cancel"),params:ft.extend({taskId:y()})}),Gb=Ae.merge(rs),Zb=x({uri:y(),mimeType:ye(y()),_meta:ae(y(),ge()).optional()}),Bb=Zb.extend({text:y()}),gf=y().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wb=Zb.extend({blob:gf}),os=et(["user","assistant"]),Eo=x({audience:E(os).optional(),priority:K().min(0).max(1).optional(),lastModified:Ki.datetime({offset:!0}).optional()}),Vb=x({...Co.shape,...Qi.shape,uri:y(),description:ye(y()),mimeType:ye(y()),size:ye(K()),annotations:Eo.optional(),_meta:ye(ke({}))}),Nz=x({...Co.shape,...Qi.shape,uriTemplate:y(),description:ye(y()),mimeType:ye(y()),annotations:Eo.optional(),_meta:ye(ke({}))}),Dz=es.extend({method:T("resources/list")}),yf=ts.extend({resources:E(Vb)}),Lz=es.extend({method:T("resources/templates/list")}),vf=ts.extend({resourceTemplates:E(Nz)}),_f=ft.extend({uri:y()}),jz=_f,Fz=ze.extend({method:T("resources/read"),params:jz}),Sf=Ae.extend({contents:E(ue([Bb,Wb]))}),wf=bt.extend({method:T("notifications/resources/list_changed"),params:wt.optional()}),Uz=_f,qz=ze.extend({method:T("resources/subscribe"),params:Uz}),Hz=_f,Gz=ze.extend({method:T("resources/unsubscribe"),params:Hz}),Zz=wt.extend({uri:y()}),Bz=bt.extend({method:T("notifications/resources/updated"),params:Zz}),Wz=x({name:y(),description:ye(y()),required:ye(ie())}),Vz=x({...Co.shape,...Qi.shape,description:ye(y()),arguments:ye(E(Wz)),_meta:ye(ke({}))}),Kz=es.extend({method:T("prompts/list")}),bf=ts.extend({prompts:E(Vz)}),Jz=ft.extend({name:y(),arguments:ae(y(),y()).optional()}),Yz=ze.extend({method:T("prompts/get"),params:Jz}),Rf=x({type:T("text"),text:y(),annotations:Eo.optional(),_meta:ae(y(),ge()).optional()}),Cf=x({type:T("image"),data:gf,mimeType:y(),annotations:Eo.optional(),_meta:ae(y(),ge()).optional()}),Pf=x({type:T("audio"),data:gf,mimeType:y(),annotations:Eo.optional(),_meta:ae(y(),ge()).optional()}),Xz=x({type:T("tool_use"),name:y(),id:y(),input:ae(y(),ge()),_meta:ae(y(),ge()).optional()}),Qz=x({type:T("resource"),resource:ue([Bb,Wb]),annotations:Eo.optional(),_meta:ae(y(),ge()).optional()}),eN=Vb.extend({type:T("resource_link")}),Ef=ue([Rf,Cf,Pf,eN,Qz]),tN=x({role:os,content:Ef}),xf=Ae.extend({description:y().optional(),messages:E(tN)}),kf=bt.extend({method:T("notifications/prompts/list_changed"),params:wt.optional()}),rN=x({title:y().optional(),readOnlyHint:ie().optional(),destructiveHint:ie().optional(),idempotentHint:ie().optional(),openWorldHint:ie().optional()}),nN=x({taskSupport:et(["required","optional","forbidden"]).optional()}),Kb=x({...Co.shape,...Qi.shape,description:y().optional(),inputSchema:x({type:T("object"),properties:ae(y(),Te).optional(),required:E(y()).optional()}).catchall(ge()),outputSchema:x({type:T("object"),properties:ae(y(),Te).optional(),required:E(y()).optional()}).catchall(ge()).optional(),annotations:rN.optional(),execution:nN.optional(),_meta:ae(y(),ge()).optional()}),oN=es.extend({method:T("tools/list")}),Tf=ts.extend({tools:E(Kb)}),kn=Ae.extend({content:E(Ef).default([]),structuredContent:ae(y(),ge()).optional(),isError:ie().optional()}),tK=kn.or(Ae.extend({toolResult:ge()})),iN=Yi.extend({name:y(),arguments:ae(y(),ge()).optional()}),sN=ze.extend({method:T("tools/call"),params:iN}),is=bt.extend({method:T("notifications/tools/list_changed"),params:wt.optional()}),Jb=x({autoRefresh:ie().default(!0),debounceMs:K().int().nonnegative().default(300)}),Yb=et(["debug","info","notice","warning","error","critical","alert","emergency"]),aN=ft.extend({level:Yb}),cN=ze.extend({method:T("logging/setLevel"),params:aN}),uN=wt.extend({level:Yb,logger:y().optional(),data:ge()}),dN=bt.extend({method:T("notifications/message"),params:uN}),lN=x({name:y().optional()}),fN=x({hints:E(lN).optional(),costPriority:K().min(0).max(1).optional(),speedPriority:K().min(0).max(1).optional(),intelligencePriority:K().min(0).max(1).optional()}),pN=x({mode:et(["auto","required","none"]).optional()}),hN=x({type:T("tool_result"),toolUseId:y().describe("The unique identifier for the corresponding tool call."),content:E(Ef).default([]),structuredContent:x({}).loose().optional(),isError:ie().optional(),_meta:ae(y(),ge()).optional()}),mN=uf("type",[Rf,Cf,Pf]),dc=uf("type",[Rf,Cf,Pf,Xz,hN]),gN=x({role:os,content:ue([dc,E(dc)]),_meta:ae(y(),ge()).optional()}),yN=Yi.extend({messages:E(gN),modelPreferences:fN.optional(),systemPrompt:y().optional(),includeContext:et(["none","thisServer","allServers"]).optional(),temperature:K().optional(),maxTokens:K().int(),stopSequences:E(y()).optional(),metadata:Te.optional(),tools:E(Kb).optional(),toolChoice:pN.optional()}),Af=ze.extend({method:T("sampling/createMessage"),params:yN}),Mf=Ae.extend({model:y(),stopReason:ye(et(["endTurn","stopSequence","maxTokens"]).or(y())),role:os,content:mN}),$f=Ae.extend({model:y(),stopReason:ye(et(["endTurn","stopSequence","maxTokens","toolUse"]).or(y())),role:os,content:ue([dc,E(dc)])}),vN=x({type:T("boolean"),title:y().optional(),description:y().optional(),default:ie().optional()}),_N=x({type:T("string"),title:y().optional(),description:y().optional(),minLength:K().optional(),maxLength:K().optional(),format:et(["email","uri","date","date-time"]).optional(),default:y().optional()}),SN=x({type:et(["number","integer"]),title:y().optional(),description:y().optional(),minimum:K().optional(),maximum:K().optional(),default:K().optional()}),wN=x({type:T("string"),title:y().optional(),description:y().optional(),enum:E(y()),default:y().optional()}),bN=x({type:T("string"),title:y().optional(),description:y().optional(),oneOf:E(x({const:y(),title:y()})),default:y().optional()}),RN=x({type:T("string"),title:y().optional(),description:y().optional(),enum:E(y()),enumNames:E(y()).optional(),default:y().optional()}),CN=ue([wN,bN]),PN=x({type:T("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:x({type:T("string"),enum:E(y())}),default:E(y()).optional()}),EN=x({type:T("array"),title:y().optional(),description:y().optional(),minItems:K().optional(),maxItems:K().optional(),items:x({anyOf:E(x({const:y(),title:y()}))}),default:E(y()).optional()}),xN=ue([PN,EN]),kN=ue([RN,CN,xN]),TN=ue([kN,vN,_N,SN]),AN=Yi.extend({mode:T("form").optional(),message:y(),requestedSchema:x({type:T("object"),properties:ae(y(),TN),required:E(y()).optional()})}),MN=Yi.extend({mode:T("url"),message:y(),elicitationId:y(),url:y().url()}),$N=ue([AN,MN]),If=ze.extend({method:T("elicitation/create"),params:$N}),IN=wt.extend({elicitationId:y()}),ON=bt.extend({method:T("notifications/elicitation/complete"),params:IN}),Of=Ae.extend({action:et(["accept","decline","cancel"]),content:df(t=>t===null?void 0:t,ae(y(),ue([y(),K(),ie(),E(y())])).optional())}),zN=x({type:T("ref/resource"),uri:y()});var NN=x({type:T("ref/prompt"),name:y()}),DN=ft.extend({ref:ue([NN,zN]),argument:x({name:y(),value:y()}),context:x({arguments:ae(y(),y()).optional()}).optional()}),LN=ze.extend({method:T("completion/complete"),params:DN});var zf=Ae.extend({completion:ke({values:E(y()).max(100),total:ye(K().int()),hasMore:ye(ie())})}),jN=x({uri:y().startsWith("file://"),name:y().optional(),_meta:ae(y(),ge()).optional()}),FN=ze.extend({method:T("roots/list"),params:ft.optional()}),UN=Ae.extend({roots:E(jN)}),qN=bt.extend({method:T("notifications/roots/list_changed"),params:wt.optional()}),rK=ue([hc,Tz,LN,cN,Yz,Kz,Dz,Lz,Fz,qz,Gz,sN,oN,gc,vc,_c,wc]),nK=ue([pc,mc,qb,qN,ns]),oK=ue([En,Mf,$f,Of,UN,yc,Sc,xn]),iK=ue([hc,Af,If,FN,gc,vc,_c,wc]),sK=ue([pc,mc,dN,Bz,wf,is,kf,ns,ON]),aK=ue([En,mf,zf,xf,bf,yf,vf,Sf,kn,Tf,yc,Sc,xn]),k=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===A.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new lf(o.elicitations,r)}return new t(e,r,n)}},lf=class extends k{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};var Ne=vb().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:$b.custom,message:"URL must be parseable",fatal:!0}),pl}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Qb=ke({resource:y().url(),authorization_servers:E(Ne).optional(),jwks_uri:y().url().optional(),scopes_supported:E(y()).optional(),bearer_methods_supported:E(y()).optional(),resource_signing_alg_values_supported:E(y()).optional(),resource_name:y().optional(),resource_documentation:y().optional(),resource_policy_uri:y().url().optional(),resource_tos_uri:y().url().optional(),tls_client_certificate_bound_access_tokens:ie().optional(),authorization_details_types_supported:E(y()).optional(),dpop_signing_alg_values_supported:E(y()).optional(),dpop_bound_access_tokens_required:ie().optional()}),Nf=ke({issuer:y(),authorization_endpoint:Ne,token_endpoint:Ne,registration_endpoint:Ne.optional(),scopes_supported:E(y()).optional(),response_types_supported:E(y()),response_modes_supported:E(y()).optional(),grant_types_supported:E(y()).optional(),token_endpoint_auth_methods_supported:E(y()).optional(),token_endpoint_auth_signing_alg_values_supported:E(y()).optional(),service_documentation:Ne.optional(),revocation_endpoint:Ne.optional(),revocation_endpoint_auth_methods_supported:E(y()).optional(),revocation_endpoint_auth_signing_alg_values_supported:E(y()).optional(),introspection_endpoint:y().optional(),introspection_endpoint_auth_methods_supported:E(y()).optional(),introspection_endpoint_auth_signing_alg_values_supported:E(y()).optional(),code_challenge_methods_supported:E(y()).optional(),client_id_metadata_document_supported:ie().optional()}),HN=ke({issuer:y(),authorization_endpoint:Ne,token_endpoint:Ne,userinfo_endpoint:Ne.optional(),jwks_uri:Ne,registration_endpoint:Ne.optional(),scopes_supported:E(y()).optional(),response_types_supported:E(y()),response_modes_supported:E(y()).optional(),grant_types_supported:E(y()).optional(),acr_values_supported:E(y()).optional(),subject_types_supported:E(y()),id_token_signing_alg_values_supported:E(y()),id_token_encryption_alg_values_supported:E(y()).optional(),id_token_encryption_enc_values_supported:E(y()).optional(),userinfo_signing_alg_values_supported:E(y()).optional(),userinfo_encryption_alg_values_supported:E(y()).optional(),userinfo_encryption_enc_values_supported:E(y()).optional(),request_object_signing_alg_values_supported:E(y()).optional(),request_object_encryption_alg_values_supported:E(y()).optional(),request_object_encryption_enc_values_supported:E(y()).optional(),token_endpoint_auth_methods_supported:E(y()).optional(),token_endpoint_auth_signing_alg_values_supported:E(y()).optional(),display_values_supported:E(y()).optional(),claim_types_supported:E(y()).optional(),claims_supported:E(y()).optional(),service_documentation:y().optional(),claims_locales_supported:E(y()).optional(),ui_locales_supported:E(y()).optional(),claims_parameter_supported:ie().optional(),request_parameter_supported:ie().optional(),request_uri_parameter_supported:ie().optional(),require_request_uri_registration:ie().optional(),op_policy_uri:Ne.optional(),op_tos_uri:Ne.optional(),client_id_metadata_document_supported:ie().optional()}),eR=x({...HN.shape,...Nf.pick({code_challenge_methods_supported:!0}).shape}),tR=x({access_token:y(),id_token:y().optional(),token_type:y(),expires_in:uc.number().optional(),scope:y().optional(),refresh_token:y().optional()}).strip(),rR=x({error:y(),error_description:y().optional(),error_uri:y().optional()}),Xb=Ne.optional().or(T("").transform(()=>{})),GN=x({redirect_uris:E(Ne),token_endpoint_auth_method:y().optional(),grant_types:E(y()).optional(),response_types:E(y()).optional(),client_name:y().optional(),client_uri:Ne.optional(),logo_uri:Xb,scope:y().optional(),contacts:E(y()).optional(),tos_uri:Xb,policy_uri:y().optional(),jwks_uri:Ne.optional(),jwks:wb().optional(),software_id:y().optional(),software_version:y().optional(),software_statement:y().optional()}).strip(),ZN=x({client_id:y(),client_secret:y().optional(),client_id_issued_at:K().optional(),client_secret_expires_at:K().optional()}).strip(),nR=GN.merge(ZN),uK=x({error:y(),error_description:y().optional()}).strip(),dK=x({token:y(),token_type_hint:y().optional()}).strip();function oR(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function iR({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var Ce=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},ss=class extends Ce{};ss.errorCode="invalid_request";var Tn=class extends Ce{};Tn.errorCode="invalid_client";var An=class extends Ce{};An.errorCode="invalid_grant";var Mn=class extends Ce{};Mn.errorCode="unauthorized_client";var as=class extends Ce{};as.errorCode="unsupported_grant_type";var cs=class extends Ce{};cs.errorCode="invalid_scope";var us=class extends Ce{};us.errorCode="access_denied";var hr=class extends Ce{};hr.errorCode="server_error";var ds=class extends Ce{};ds.errorCode="temporarily_unavailable";var ls=class extends Ce{};ls.errorCode="unsupported_response_type";var fs=class extends Ce{};fs.errorCode="unsupported_token_type";var ps=class extends Ce{};ps.errorCode="invalid_token";var hs=class extends Ce{};hs.errorCode="method_not_allowed";var ms=class extends Ce{};ms.errorCode="too_many_requests";var $n=class extends Ce{};$n.errorCode="invalid_client_metadata";var gs=class extends Ce{};gs.errorCode="insufficient_scope";var ys=class extends Ce{};ys.errorCode="invalid_target";var sR={[ss.errorCode]:ss,[Tn.errorCode]:Tn,[An.errorCode]:An,[Mn.errorCode]:Mn,[as.errorCode]:as,[cs.errorCode]:cs,[us.errorCode]:us,[hr.errorCode]:hr,[ds.errorCode]:ds,[ls.errorCode]:ls,[fs.errorCode]:fs,[ps.errorCode]:ps,[hs.errorCode]:hs,[ms.errorCode]:ms,[$n.errorCode]:$n,[gs.errorCode]:gs,[ys.errorCode]:ys};var De=class extends Error{constructor(e){super(e??"Unauthorized")}};function BN(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Df="code",Lf="S256";function WN(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&BN(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function VN(t,e,r,n){let{client_id:o,client_secret:i}=e;switch(t){case"client_secret_basic":KN(o,i,r);return;case"client_secret_post":JN(o,i,n);return;case"none":YN(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function KN(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function JN(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function YN(t,e){e.set("client_id",t)}async function cR(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=rR.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:s}=n,a=sR[o]||hr;return new a(i||"",s)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new hr(o)}}async function mr(t,e){try{return await jf(t,e)}catch(r){if(r instanceof Tn||r instanceof Mn)return await t.invalidateCredentials?.("all"),await jf(t,e);if(r instanceof An)return await t.invalidateCredentials?.("tokens"),await jf(t,e);throw r}}async function jf(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){let s=await t.discoveryState?.(),a,c,u,d=o;if(!d&&s?.resourceMetadataUrl&&(d=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(c=s.authorizationServerUrl,a=s.resourceMetadata,u=s.authorizationServerMetadata??await dR(c,{fetchFn:i}),!a)try{a=await uR(e,{resourceMetadataUrl:d},i)}catch{}(u!==s.authorizationServerMetadata||a!==s.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await oD(e,{resourceMetadataUrl:d,fetchFn:i});c=b.authorizationServerUrl,u=b.authorizationServerMetadata,a=b.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await QN(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=u?.client_id_metadata_document_supported===!0,R=t.clientMetadataUrl;if(R&&!XN(R))throw new $n(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${R}`);if(b&&R)p={client_id:R},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let C=await uD(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:i});await t.saveClientInformation(C),p=C}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await cD(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:i});return await t.saveTokens(b),"AUTHORIZED"}let g=await t.tokens();if(g?.refresh_token)try{let b=await aD(c,{metadata:u,clientInformation:p,refreshToken:g.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Ce)||b instanceof hr))throw b}let m=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:w}=await iD(c,{metadata:u,clientInformation:p,state:m,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(v),"REDIRECT"}function XN(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function QN(t,e,r){let n=oR(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!iR({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function xo(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Ff(t,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let s=Ff(t,"scope")||void 0,a=Ff(t,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:a}}function Ff(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function uR(t,e,r=fetch){let n=await rD(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return Qb.parse(await n.json())}async function Uf(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Uf(t,void 0,r):void 0;throw n}}function eD(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function aR(t,e,r=fetch){return await Uf(t,{"MCP-Protocol-Version":e},r)}function tD(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function rD(t,e,r,n){let o=new URL(t),i=n?.protocolVersion??Po,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let c=eD(e,o.pathname);s=new URL(c,n?.metadataServerUrl??o),s.search=o.search}let a=await aR(s,i,r);if(!n?.metadataUrl&&tD(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await aR(c,i,r)}return a}function nD(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function dR(t,{fetchFn:e=fetch,protocolVersion:r=Po}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=nD(t);for(let{url:i,type:s}of o){let a=await Uf(i,n,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?Nf.parse(await a.json()):eR.parse(await a.json())}}}async function oD(t,e){let r,n;try{r=await uR(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let o=await dR(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function iD(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Df))throw new Error(`Incompatible auth server: does not support response type ${Df}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Lf))throw new Error(`Incompatible auth server: does not support code challenge method ${Lf}`)}else a=new URL("/authorize",t);let c=await fl(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Df),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Lf),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:u}}function sD(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function lR(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),o)await o(c,r,a,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],l=WN(n,d);VN(l,n,c,r)}let u=await(s??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await cR(u);return tR.parse(await u.json())}async function aD(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await lR(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s});return{refresh_token:n,...c}}async function cD(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){let s=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(s)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();a=sD(o,u,t.redirectUrl)}let c=await t.clientInformation();return lR(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:i})}async function uD(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let s=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await cR(s);return nR.parse(await s.json())}var vs=class extends Error{constructor(e,r){super(e),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}},fR=10,dD=13,In=32;function qf(t){}function bc(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=qf,onError:r=qf,onRetry:n=qf,onComment:o,maxBufferSize:i}=t,s=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(_){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,_.charCodeAt(0)===239&&_.charCodeAt(1)===187&&_.charCodeAt(2)===191&&(_=_.slice(3))),s.length===0){let ee=m(_);ee!==""&&(s.push(ee),a=ee.length),g();return}if(_.indexOf(`
|
|
88
|
+
`)===-1&&_.indexOf("\r")===-1){s.push(_),a+=_.length,g();return}s.push(_);let C=s.join("");s.length=0,a=0;let I=m(C);I!==""&&(s.push(I),a=I.length),g()}function g(){i!==void 0&&(a+d.length<=i||(p=!0,s.length=0,a=0,u=void 0,d="",l=0,f=void 0,r(new vs(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function m(_){let C=0;if(_.indexOf("\r")===-1){let I=_.indexOf(`
|
|
89
89
|
`,C);for(;I!==-1;){if(C===I){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0,C=I+1,I=_.indexOf(`
|
|
90
|
-
`,C);continue}let ee=_.charCodeAt(C);if(
|
|
90
|
+
`,C);continue}let ee=_.charCodeAt(C);if(pR(_,C,ee)){let pe=_.charCodeAt(C+5)===In?C+6:C+5,be=_.slice(pe,I);if(l===0&&_.charCodeAt(I+1)===fR){e({id:u,event:f,data:be}),u=void 0,d="",f=void 0,C=I+2,I=_.indexOf(`
|
|
91
91
|
`,C);continue}d=l===0?be:`${d}
|
|
92
|
-
${be}`,l++}else
|
|
92
|
+
${be}`,l++}else hR(_,C,ee)?f=_.slice(_.charCodeAt(C+6)===In?C+7:C+6,I)||void 0:v(_,C,I);C=I+1,I=_.indexOf(`
|
|
93
93
|
`,C)}return _.slice(C)}for(;C<_.length;){let I=_.indexOf("\r",C),ee=_.indexOf(`
|
|
94
|
-
`,C),pe=-1;if(I!==-1&&ee!==-1?pe=I<ee?I:ee:I!==-1?I===_.length-1?pe=-1:pe=I:ee!==-1&&(pe=ee),pe===-1)break;v(_,C,pe),C=pe+1,_.charCodeAt(C-1)===
|
|
95
|
-
${
|
|
96
|
-
${C}`,l++;break;case"id":u=C.includes("\0")?void 0:C;break;case"retry":/^\d+$/.test(C)?n(parseInt(C,10)):r(new zs(`Invalid \`retry\` value: "${C}"`,{type:"invalid-retry",value:C,line:I}));break;default:r(new zs(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:C,line:I}));break}}function b(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function R(_={}){if(_.consume&&s.length>0){let C=s.join("");v(C,0,C.length)}c=!0,u=void 0,d="",l=0,f=void 0,s.length=0,a=0,p=!1}return{feed:h,reset:R}}function GP(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function ZP(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var pu=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(BP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(BP(this),r)}};function UU(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function kh(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(kh).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${kh(t.cause)}`:t.message:`${t}`}function BP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var VP=t=>{throw TypeError(t)},Nh=(t,e,r)=>e.has(t)||VP("Cannot "+r),q=(t,e,r)=>(Nh(t,e,"read from private field"),r?r.call(t):e.get(t)),Me=(t,e,r)=>e.has(t)?VP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ve=(t,e,r,n)=>(Nh(t,e,"write to private field"),e.set(t,r),r),vr=(t,e,r)=>(Nh(t,e,"access private method"),r),it,Ln,Ho,fu,hu,Ls,Bo,js,rn,Go,Wo,Zo,Ns,jt,Th,Ah,Mh,WP,$h,Ih,Ds,Oh,zh,jn=class extends EventTarget{constructor(e,r){var n,o;super(),Me(this,jt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Me(this,it),Me(this,Ln),Me(this,Ho),Me(this,fu),Me(this,hu),Me(this,Ls),Me(this,Bo),Me(this,js,null),Me(this,rn),Me(this,Go),Me(this,Wo,null),Me(this,Zo,null),Me(this,Ns,null),Me(this,Ah,async i=>{var s;q(this,Go).reset();let{body:a,redirected:c,status:u,headers:d}=i;if(u===204){vr(this,jt,Ds).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ve(this,Ho,new URL(i.url)):ve(this,Ho,void 0),u!==200){vr(this,jt,Ds).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){vr(this,jt,Ds).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(q(this,it)===this.CLOSED)return;ve(this,it,this.OPEN);let l=new Event("open");if((s=q(this,Ns))==null||s.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){vr(this,jt,Ds).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:m,value:g}=await p.read();g&&q(this,Go).feed(f.decode(g,{stream:!m})),m&&(h=!1,q(this,Go).reset(),vr(this,jt,Oh).call(this))}while(h)}),Me(this,Mh,i=>{ve(this,rn,void 0),!(i.name==="AbortError"||i.type==="aborted")&&vr(this,jt,Oh).call(this,kh(i))}),Me(this,$h,i=>{typeof i.id=="string"&&ve(this,js,i.id);let s=new MessageEvent(i.event||"message",{data:i.data,origin:q(this,Ho)?q(this,Ho).origin:q(this,Ln).origin,lastEventId:i.id||""});q(this,Zo)&&(!i.event||i.event==="message")&&q(this,Zo).call(this,s),this.dispatchEvent(s)}),Me(this,Ih,i=>{ve(this,Ls,i)}),Me(this,zh,()=>{ve(this,Bo,void 0),q(this,it)===this.CONNECTING&&vr(this,jt,Th).call(this)});try{if(e instanceof URL)ve(this,Ln,e);else if(typeof e=="string")ve(this,Ln,new URL(e,qU()));else throw new Error("Invalid URL")}catch{throw UU("An invalid or illegal string was specified")}ve(this,Go,lu({onEvent:q(this,$h),onRetry:q(this,Ih)})),ve(this,it,this.CONNECTING),ve(this,Ls,3e3),ve(this,hu,(n=r?.fetch)!=null?n:globalThis.fetch),ve(this,fu,(o=r?.withCredentials)!=null?o:!1),vr(this,jt,Th).call(this)}get readyState(){return q(this,it)}get url(){return q(this,Ln).href}get withCredentials(){return q(this,fu)}get onerror(){return q(this,Wo)}set onerror(e){ve(this,Wo,e)}get onmessage(){return q(this,Zo)}set onmessage(e){ve(this,Zo,e)}get onopen(){return q(this,Ns)}set onopen(e){ve(this,Ns,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){q(this,Bo)&&clearTimeout(q(this,Bo)),q(this,it)!==this.CLOSED&&(q(this,rn)&&q(this,rn).abort(),ve(this,it,this.CLOSED),ve(this,rn,void 0))}};it=new WeakMap,Ln=new WeakMap,Ho=new WeakMap,fu=new WeakMap,hu=new WeakMap,Ls=new WeakMap,Bo=new WeakMap,js=new WeakMap,rn=new WeakMap,Go=new WeakMap,Wo=new WeakMap,Zo=new WeakMap,Ns=new WeakMap,jt=new WeakSet,Th=function(){ve(this,it,this.CONNECTING),ve(this,rn,new AbortController),q(this,hu)(q(this,Ln),vr(this,jt,WP).call(this)).then(q(this,Ah)).catch(q(this,Mh))},Ah=new WeakMap,Mh=new WeakMap,WP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...q(this,js)?{"Last-Event-ID":q(this,js)}:void 0},cache:"no-store",signal:(t=q(this,rn))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},$h=new WeakMap,Ih=new WeakMap,Ds=function(t,e){var r;q(this,it)!==this.CLOSED&&ve(this,it,this.CLOSED);let n=new pu("error",{code:e,message:t});(r=q(this,Wo))==null||r.call(this,n),this.dispatchEvent(n)},Oh=function(t,e){var r;if(q(this,it)===this.CLOSED)return;ve(this,it,this.CONNECTING);let n=new pu("error",{code:e,message:t});(r=q(this,Wo))==null||r.call(this,n),this.dispatchEvent(n),ve(this,Bo,setTimeout(q(this,zh),q(this,Ls)))},zh=new WeakMap,jn.CONNECTING=0,jn.OPEN=1,jn.CLOSED=2;function qU(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Vo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function mu(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Vo(e.headers),...Vo(n.headers)}:e.headers};return t(r,o)}:t}var Dh;Dh=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function HU(t){return(await Dh).getRandomValues(new Uint8Array(t))}async function GU(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await HU(t-n.length);for(let i of o)i<r&&(n+=e[i%e.length])}return n}async function ZU(t){return await GU(t)}async function BU(t){let e=await(await Dh).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Lh(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await ZU(t),r=await BU(e);return{code_verifier:e,code_challenge:r}}var je=hb().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:kb.custom,message:"URL must be parseable",fatal:!0}),ul}).refine(t=>{let e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),JP=ke({resource:y().url(),authorization_servers:x(je).optional(),jwks_uri:y().url().optional(),scopes_supported:x(y()).optional(),bearer_methods_supported:x(y()).optional(),resource_signing_alg_values_supported:x(y()).optional(),resource_name:y().optional(),resource_documentation:y().optional(),resource_policy_uri:y().url().optional(),resource_tos_uri:y().url().optional(),tls_client_certificate_bound_access_tokens:ie().optional(),authorization_details_types_supported:x(y()).optional(),dpop_signing_alg_values_supported:x(y()).optional(),dpop_bound_access_tokens_required:ie().optional()}),jh=ke({issuer:y(),authorization_endpoint:je,token_endpoint:je,registration_endpoint:je.optional(),scopes_supported:x(y()).optional(),response_types_supported:x(y()),response_modes_supported:x(y()).optional(),grant_types_supported:x(y()).optional(),token_endpoint_auth_methods_supported:x(y()).optional(),token_endpoint_auth_signing_alg_values_supported:x(y()).optional(),service_documentation:je.optional(),revocation_endpoint:je.optional(),revocation_endpoint_auth_methods_supported:x(y()).optional(),revocation_endpoint_auth_signing_alg_values_supported:x(y()).optional(),introspection_endpoint:y().optional(),introspection_endpoint_auth_methods_supported:x(y()).optional(),introspection_endpoint_auth_signing_alg_values_supported:x(y()).optional(),code_challenge_methods_supported:x(y()).optional(),client_id_metadata_document_supported:ie().optional()}),WU=ke({issuer:y(),authorization_endpoint:je,token_endpoint:je,userinfo_endpoint:je.optional(),jwks_uri:je,registration_endpoint:je.optional(),scopes_supported:x(y()).optional(),response_types_supported:x(y()),response_modes_supported:x(y()).optional(),grant_types_supported:x(y()).optional(),acr_values_supported:x(y()).optional(),subject_types_supported:x(y()),id_token_signing_alg_values_supported:x(y()),id_token_encryption_alg_values_supported:x(y()).optional(),id_token_encryption_enc_values_supported:x(y()).optional(),userinfo_signing_alg_values_supported:x(y()).optional(),userinfo_encryption_alg_values_supported:x(y()).optional(),userinfo_encryption_enc_values_supported:x(y()).optional(),request_object_signing_alg_values_supported:x(y()).optional(),request_object_encryption_alg_values_supported:x(y()).optional(),request_object_encryption_enc_values_supported:x(y()).optional(),token_endpoint_auth_methods_supported:x(y()).optional(),token_endpoint_auth_signing_alg_values_supported:x(y()).optional(),display_values_supported:x(y()).optional(),claim_types_supported:x(y()).optional(),claims_supported:x(y()).optional(),service_documentation:y().optional(),claims_locales_supported:x(y()).optional(),ui_locales_supported:x(y()).optional(),claims_parameter_supported:ie().optional(),request_parameter_supported:ie().optional(),request_uri_parameter_supported:ie().optional(),require_request_uri_registration:ie().optional(),op_policy_uri:je.optional(),op_tos_uri:je.optional(),client_id_metadata_document_supported:ie().optional()}),YP=E({...WU.shape,...jh.pick({code_challenge_methods_supported:!0}).shape}),XP=E({access_token:y(),id_token:y().optional(),token_type:y(),expires_in:lc.number().optional(),scope:y().optional(),refresh_token:y().optional()}).strip(),QP=E({error:y(),error_description:y().optional(),error_uri:y().optional()}),KP=je.optional().or(k("").transform(()=>{})),VU=E({redirect_uris:x(je),token_endpoint_auth_method:y().optional(),grant_types:x(y()).optional(),response_types:x(y()).optional(),client_name:y().optional(),client_uri:je.optional(),logo_uri:KP,scope:y().optional(),contacts:x(y()).optional(),tos_uri:KP,policy_uri:y().optional(),jwks_uri:je.optional(),jwks:yb().optional(),software_id:y().optional(),software_version:y().optional(),software_statement:y().optional()}).strip(),KU=E({client_id:y(),client_secret:y().optional(),client_id_issued_at:K().optional(),client_secret_expires_at:K().optional()}).strip(),ex=VU.merge(KU),rY=E({error:y(),error_description:y().optional()}).strip(),nY=E({token:y(),token_type_hint:y().optional()}).strip();function tx(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function rx({requestedResource:t,configuredResource:e}){let r=typeof t=="string"?new URL(t):new URL(t.href),n=typeof e=="string"?new URL(e):new URL(e.href);if(r.origin!==n.origin||r.pathname.length<n.pathname.length)return!1;let o=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(i)}var Pe=class extends Error{constructor(e,r){super(e),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Fs=class extends Pe{};Fs.errorCode="invalid_request";var Fn=class extends Pe{};Fn.errorCode="invalid_client";var Un=class extends Pe{};Un.errorCode="invalid_grant";var qn=class extends Pe{};qn.errorCode="unauthorized_client";var Us=class extends Pe{};Us.errorCode="unsupported_grant_type";var qs=class extends Pe{};qs.errorCode="invalid_scope";var Hs=class extends Pe{};Hs.errorCode="access_denied";var _r=class extends Pe{};_r.errorCode="server_error";var Gs=class extends Pe{};Gs.errorCode="temporarily_unavailable";var Zs=class extends Pe{};Zs.errorCode="unsupported_response_type";var Bs=class extends Pe{};Bs.errorCode="unsupported_token_type";var Ws=class extends Pe{};Ws.errorCode="invalid_token";var Vs=class extends Pe{};Vs.errorCode="method_not_allowed";var Ks=class extends Pe{};Ks.errorCode="too_many_requests";var Hn=class extends Pe{};Hn.errorCode="invalid_client_metadata";var Js=class extends Pe{};Js.errorCode="insufficient_scope";var Ys=class extends Pe{};Ys.errorCode="invalid_target";var nx={[Fs.errorCode]:Fs,[Fn.errorCode]:Fn,[Un.errorCode]:Un,[qn.errorCode]:qn,[Us.errorCode]:Us,[qs.errorCode]:qs,[Hs.errorCode]:Hs,[_r.errorCode]:_r,[Gs.errorCode]:Gs,[Zs.errorCode]:Zs,[Bs.errorCode]:Bs,[Ws.errorCode]:Ws,[Vs.errorCode]:Vs,[Ks.errorCode]:Ks,[Hn.errorCode]:Hn,[Js.errorCode]:Js,[Ys.errorCode]:Ys};var We=class extends Error{constructor(e){super(e??"Unauthorized")}};function JU(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Fh="code",Uh="S256";function YU(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&JU(t.token_endpoint_auth_method)&&(e.length===0||e.includes(t.token_endpoint_auth_method))?t.token_endpoint_auth_method:e.length===0?r?"client_secret_basic":"none":r&&e.includes("client_secret_basic")?"client_secret_basic":r&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":r?"client_secret_post":"none"}function XU(t,e,r,n){let{client_id:o,client_secret:i}=e;switch(t){case"client_secret_basic":QU(o,i,r);return;case"client_secret_post":eq(o,i,n);return;case"none":tq(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function QU(t,e,r){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");let n=btoa(`${t}:${e}`);r.set("Authorization",`Basic ${n}`)}function eq(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function tq(t,e){e.set("client_id",t)}async function ix(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=QP.parse(JSON.parse(r)),{error:o,error_description:i,error_uri:s}=n,a=nx[o]||_r;return new a(i||"",s)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new _r(o)}}async function Sr(t,e){try{return await qh(t,e)}catch(r){if(r instanceof Fn||r instanceof qn)return await t.invalidateCredentials?.("all"),await qh(t,e);if(r instanceof Un)return await t.invalidateCredentials?.("tokens"),await qh(t,e);throw r}}async function qh(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:i}){let s=await t.discoveryState?.(),a,c,u,d=o;if(!d&&s?.resourceMetadataUrl&&(d=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(c=s.authorizationServerUrl,a=s.resourceMetadata,u=s.authorizationServerMetadata??await ax(c,{fetchFn:i}),!a)try{a=await sx(e,{resourceMetadataUrl:d},i)}catch{}(u!==s.authorizationServerMetadata||a!==s.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await cq(e,{resourceMetadataUrl:d,fetchFn:i});c=b.authorizationServerUrl,u=b.authorizationServerMetadata,a=b.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await nq(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=u?.client_id_metadata_document_supported===!0,R=t.clientMetadataUrl;if(R&&!rq(R))throw new Hn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${R}`);if(b&&R)p={client_id:R},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let C=await pq(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:i});await t.saveClientInformation(C),p=C}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await fq(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:i});return await t.saveTokens(b),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let b=await lq(c,{metadata:u,clientInformation:p,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Pe)||b instanceof _r))throw b}let g=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:w}=await uq(c,{metadata:u,clientInformation:p,state:g,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(v),"REDIRECT"}function rq(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function nq(t,e,r){let n=tx(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!rx({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ko(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Hh(t,"resource_metadata")||void 0,i;if(o)try{i=new URL(o)}catch{}let s=Hh(t,"scope")||void 0,a=Hh(t,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:a}}function Hh(t,e){let r=t.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${e}=(?:"([^"]+)"|([^\\s,]+))`),o=r.match(n);return o?o[1]||o[2]:null}async function sx(t,e,r=fetch){let n=await sq(t,"oauth-protected-resource",r,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!n||n.status===404)throw await n?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await n.body?.cancel(),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return JP.parse(await n.json())}async function Gh(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Gh(t,void 0,r):void 0;throw n}}function oq(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function ox(t,e,r=fetch){return await Gh(t,{"MCP-Protocol-Version":e},r)}function iq(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function sq(t,e,r,n){let o=new URL(t),i=n?.protocolVersion??Co,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let c=oq(e,o.pathname);s=new URL(c,n?.metadataServerUrl??o),s.search=o.search}let a=await ox(s,i,r);if(!n?.metadataUrl&&iq(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await ox(c,i,r)}return a}function aq(t){let e=typeof t=="string"?new URL(t):t,r=e.pathname!=="/",n=[];if(!r)return n.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),n.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),n;let o=e.pathname;return o.endsWith("/")&&(o=o.slice(0,-1)),n.push({url:new URL(`/.well-known/oauth-authorization-server${o}`,e.origin),type:"oauth"}),n.push({url:new URL(`/.well-known/openid-configuration${o}`,e.origin),type:"oidc"}),n.push({url:new URL(`${o}/.well-known/openid-configuration`,e.origin),type:"oidc"}),n}async function ax(t,{fetchFn:e=fetch,protocolVersion:r=Co}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=aq(t);for(let{url:i,type:s}of o){let a=await Gh(i,n,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?jh.parse(await a.json()):YP.parse(await a.json())}}}async function cq(t,e){let r,n;try{r=await sx(t,{resourceMetadataUrl:e?.resourceMetadataUrl},e?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}n||(n=String(new URL("/",t)));let o=await ax(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function uq(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:i,resource:s}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Fh))throw new Error(`Incompatible auth server: does not support response type ${Fh}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Uh))throw new Error(`Incompatible auth server: does not support code challenge method ${Uh}`)}else a=new URL("/authorize",t);let c=await Lh(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Fh),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Uh),a.searchParams.set("redirect_uri",String(n)),i&&a.searchParams.set("state",i),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",s.href),{authorizationUrl:a,codeVerifier:u}}function dq(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function cx(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:i,fetchFn:s}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),o)await o(c,r,a,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],l=YU(n,d);XU(l,n,c,r)}let u=await(s??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await ix(u);return XP.parse(await u.json())}async function lq(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:i,fetchFn:s}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await cx(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:i,resource:o,fetchFn:s});return{refresh_token:n,...c}}async function fq(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:i}={}){let s=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(s)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();a=dq(o,u,t.redirectUrl)}let c=await t.clientInformation();return cx(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:i})}async function pq(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let i;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(e.registration_endpoint)}else i=new URL("/register",t);let s=await(o??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!s.ok)throw await ix(s);return ex.parse(await s.json())}var Xs=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},gu=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=mu(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new We("No auth provider");let e;try{e=await Sr(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 We;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=Vo(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new jn(this._url.href,{...this._eventSourceInit,fetch:async(o,i)=>{let s=await this._commonHeaders();s.set("Accept","text/event-stream");let a=await e(o,{...i,headers:s});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=Ko(a);this._resourceMetadataUrl=c,this._scope=u}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let i=new Xs(o.code,o.message,o);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let i=o;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){n(s),this.onerror?.(s),this.close();return}r()}),this._eventSource.onmessage=o=>{let i=o,s;try{s=Br.parse(JSON.parse(i.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(s)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new We("No auth provider");if(await Sr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new We("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let i=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:s,scope:a}=Ko(o);if(this._resourceMetadataUrl=s,this._scope=a,await Sr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new We;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var Xx=ca(Jx(),1);import em from"node:process";import{PassThrough as qq}from"node:stream";var Fq=10*1024*1024,vu=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??Fq}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
97
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
98
|
-
`}var Hq=em.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Su(){let t={};for(let e of Hq){let r=em.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var _u=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new vu({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new qq)}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,Xx.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Su(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:em.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=Yx(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var nE=ca(rE(),1);function oE(t){if(t)try{return nE.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var wu=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let i;super({start(s){i=lu({onEvent:a=>{s.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&s.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(s){i.feed(s)}})}};var Xq={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ft=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},bu=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=mu(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??Xq}async _authThenStart(){if(!this._authProvider)throw new We("No auth provider");let e;try{e=await Sr(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 We;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=Vo(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 Ft(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(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:i}=r,s,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new wu({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(s=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Br.parse(JSON.parse(p.data));bn(m)&&(c=!0,i!==void 0&&(m.id=i)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:i},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:s,onresumptiontoken:o,replayMessageId:i},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 We("No auth provider");if(await Sr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new We("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:Yi(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ft(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=Ko(a);if(this._resourceMetadataUrl=h,this._scope=m,await Sr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new We;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:g}=Ko(a);if(g==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Ft(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=v??void 0,await Sr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new We;return this.send(e)}}throw new Ft(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),jb(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=oE(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(m=>Br.parse(m)):[Br.parse(p)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ft(-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 Ft(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 iE(t){if(!t.useShellInterpolation)return{command:t.command,args:t.args};let e=[t.command,...t.args].join(" ");return process.platform==="win32"?{command:"cmd.exe",args:["/c",e]}:{command:"/bin/sh",args:["-c",e]}}var eH={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 sE(t){return{...Su(),...eH,...t??{}}}function aE(){return Su()}var rm=class t extends _u{constructor(r,n=!1){super(r);this._captured=[];this._lineBuffer="";this._logHistory=[];this.suppressStderr=n}static{this.MAX_CAPTURED_LINES=100}static{this.MAX_LINE_BUFFER_CHARS=16384}static{this.MAX_LOG_HISTORY=1e3}async start(){await super.start();let r=this.stderr;r&&r.on("data",n=>this.ingestStderr(n))}ingestStderr(r){if(this.suppressStderr)return;this._lineBuffer+=r.toString();let n=this._lineBuffer.split(`
|
|
94
|
+
`,C),pe=-1;if(I!==-1&&ee!==-1?pe=I<ee?I:ee:I!==-1?I===_.length-1?pe=-1:pe=I:ee!==-1&&(pe=ee),pe===-1)break;v(_,C,pe),C=pe+1,_.charCodeAt(C-1)===dD&&_.charCodeAt(C)===fR&&C++}return _.slice(C)}function v(_,C,I){if(C===I){b();return}let ee=_.charCodeAt(C);if(pR(_,C,ee)){let Pr=_.charCodeAt(C+5)===In?C+6:C+5,tg=_.slice(Pr,I);d=l===0?tg:`${d}
|
|
95
|
+
${tg}`,l++;return}if(hR(_,C,ee)){f=_.slice(_.charCodeAt(C+6)===In?C+7:C+6,I)||void 0;return}if(ee===105&&_.charCodeAt(C+1)===100&&_.charCodeAt(C+2)===58){let Pr=_.slice(_.charCodeAt(C+3)===In?C+4:C+3,I);u=Pr.includes("\0")?void 0:Pr;return}if(ee===58){if(o){let Pr=_.slice(C,I);o(Pr.slice(_.charCodeAt(C+1)===In?2:1))}return}let pe=_.slice(C,I),be=pe.indexOf(":");if(be===-1){w(pe,"",pe);return}let qt=pe.slice(0,be),fn=pe.charCodeAt(be+1)===In?2:1,ht=pe.slice(be+fn);w(qt,ht,pe)}function w(_,C,I){switch(_){case"event":f=C||void 0;break;case"data":d=l===0?C:`${d}
|
|
96
|
+
${C}`,l++;break;case"id":u=C.includes("\0")?void 0:C;break;case"retry":/^\d+$/.test(C)?n(parseInt(C,10)):r(new vs(`Invalid \`retry\` value: "${C}"`,{type:"invalid-retry",value:C,line:I}));break;default:r(new vs(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:C,line:I}));break}}function b(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function R(_={}){if(_.consume&&s.length>0){let C=s.join("");v(C,0,C.length)}c=!0,u=void 0,d="",l=0,f=void 0,s.length=0,a=0,p=!1}return{feed:h,reset:R}}function pR(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function hR(t,e,r){return r===101&&t.charCodeAt(e+1)===118&&t.charCodeAt(e+2)===101&&t.charCodeAt(e+3)===110&&t.charCodeAt(e+4)===116&&t.charCodeAt(e+5)===58}var Cc=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(mR(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(mR(this),r)}};function lD(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Hf(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Hf).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Hf(t.cause)}`:t.message:`${t}`}function mR(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var yR=t=>{throw TypeError(t)},Yf=(t,e,r)=>e.has(t)||yR("Cannot "+r),q=(t,e,r)=>(Yf(t,e,"read from private field"),r?r.call(t):e.get(t)),Me=(t,e,r)=>e.has(t)?yR("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ve=(t,e,r,n)=>(Yf(t,e,"write to private field"),e.set(t,r),r),gr=(t,e,r)=>(Yf(t,e,"access private method"),r),tt,On,ko,Rc,Pc,ws,Mo,bs,Vr,To,$o,Ao,_s,Ot,Gf,Zf,Bf,gR,Wf,Vf,Ss,Kf,Jf,zn=class extends EventTarget{constructor(e,r){var n,o;super(),Me(this,Ot),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Me(this,tt),Me(this,On),Me(this,ko),Me(this,Rc),Me(this,Pc),Me(this,ws),Me(this,Mo),Me(this,bs,null),Me(this,Vr),Me(this,To),Me(this,$o,null),Me(this,Ao,null),Me(this,_s,null),Me(this,Zf,async i=>{var s;q(this,To).reset();let{body:a,redirected:c,status:u,headers:d}=i;if(u===204){gr(this,Ot,Ss).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ve(this,ko,new URL(i.url)):ve(this,ko,void 0),u!==200){gr(this,Ot,Ss).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){gr(this,Ot,Ss).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(q(this,tt)===this.CLOSED)return;ve(this,tt,this.OPEN);let l=new Event("open");if((s=q(this,_s))==null||s.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){gr(this,Ot,Ss).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:g,value:m}=await p.read();m&&q(this,To).feed(f.decode(m,{stream:!g})),g&&(h=!1,q(this,To).reset(),gr(this,Ot,Kf).call(this))}while(h)}),Me(this,Bf,i=>{ve(this,Vr,void 0),!(i.name==="AbortError"||i.type==="aborted")&&gr(this,Ot,Kf).call(this,Hf(i))}),Me(this,Wf,i=>{typeof i.id=="string"&&ve(this,bs,i.id);let s=new MessageEvent(i.event||"message",{data:i.data,origin:q(this,ko)?q(this,ko).origin:q(this,On).origin,lastEventId:i.id||""});q(this,Ao)&&(!i.event||i.event==="message")&&q(this,Ao).call(this,s),this.dispatchEvent(s)}),Me(this,Vf,i=>{ve(this,ws,i)}),Me(this,Jf,()=>{ve(this,Mo,void 0),q(this,tt)===this.CONNECTING&&gr(this,Ot,Gf).call(this)});try{if(e instanceof URL)ve(this,On,e);else if(typeof e=="string")ve(this,On,new URL(e,fD()));else throw new Error("Invalid URL")}catch{throw lD("An invalid or illegal string was specified")}ve(this,To,bc({onEvent:q(this,Wf),onRetry:q(this,Vf)})),ve(this,tt,this.CONNECTING),ve(this,ws,3e3),ve(this,Pc,(n=r?.fetch)!=null?n:globalThis.fetch),ve(this,Rc,(o=r?.withCredentials)!=null?o:!1),gr(this,Ot,Gf).call(this)}get readyState(){return q(this,tt)}get url(){return q(this,On).href}get withCredentials(){return q(this,Rc)}get onerror(){return q(this,$o)}set onerror(e){ve(this,$o,e)}get onmessage(){return q(this,Ao)}set onmessage(e){ve(this,Ao,e)}get onopen(){return q(this,_s)}set onopen(e){ve(this,_s,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){q(this,Mo)&&clearTimeout(q(this,Mo)),q(this,tt)!==this.CLOSED&&(q(this,Vr)&&q(this,Vr).abort(),ve(this,tt,this.CLOSED),ve(this,Vr,void 0))}};tt=new WeakMap,On=new WeakMap,ko=new WeakMap,Rc=new WeakMap,Pc=new WeakMap,ws=new WeakMap,Mo=new WeakMap,bs=new WeakMap,Vr=new WeakMap,To=new WeakMap,$o=new WeakMap,Ao=new WeakMap,_s=new WeakMap,Ot=new WeakSet,Gf=function(){ve(this,tt,this.CONNECTING),ve(this,Vr,new AbortController),q(this,Pc)(q(this,On),gr(this,Ot,gR).call(this)).then(q(this,Zf)).catch(q(this,Bf))},Zf=new WeakMap,Bf=new WeakMap,gR=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...q(this,bs)?{"Last-Event-ID":q(this,bs)}:void 0},cache:"no-store",signal:(t=q(this,Vr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Wf=new WeakMap,Vf=new WeakMap,Ss=function(t,e){var r;q(this,tt)!==this.CLOSED&&ve(this,tt,this.CLOSED);let n=new Cc("error",{code:e,message:t});(r=q(this,$o))==null||r.call(this,n),this.dispatchEvent(n)},Kf=function(t,e){var r;if(q(this,tt)===this.CLOSED)return;ve(this,tt,this.CONNECTING);let n=new Cc("error",{code:e,message:t});(r=q(this,$o))==null||r.call(this,n),this.dispatchEvent(n),ve(this,Mo,setTimeout(q(this,Jf),q(this,ws)))},Jf=new WeakMap,zn.CONNECTING=0,zn.OPEN=1,zn.CLOSED=2;function fD(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function Io(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Ec(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Io(e.headers),...Io(n.headers)}:e.headers};return t(r,o)}:t}var Kr=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},xc=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ec(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new De("No auth provider");let e;try{e=await mr(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 De;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=Io(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new zn(this._url.href,{...this._eventSourceInit,fetch:async(o,i)=>{let s=await this._commonHeaders();s.set("Accept","text/event-stream");let a=await e(o,{...i,headers:s});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=xo(a);this._resourceMetadataUrl=c,this._scope=u}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let i=new Kr(o.code,o.message,o);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let i=o;try{if(this._endpoint=new URL(i.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(s){n(s),this.onerror?.(s),this.close();return}r()}),this._eventSource.onmessage=o=>{let i=o,s;try{s=Wr.parse(JSON.parse(i.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(s)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new De("No auth provider");if(await mr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new De("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let i=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:s,scope:a}=xo(o);if(this._resourceMetadataUrl=s,this._scope=a,await mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new De;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${i}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var bR=ca(wR(),1);function RR(t){if(t)try{return bR.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var kc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let i;super({start(s){i=bc({onEvent:a=>{s.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&s.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(s){i.feed(s)}})}};var wD={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},rt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Tc=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=Ec(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??wD}async _authThenStart(){if(!this._authProvider)throw new De("No auth provider");let e;try{e=await mr(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 De;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=Io(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 rt(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(i=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:i}=r,s,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new kc({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(s=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let g=Wr.parse(JSON.parse(p.data));Pn(g)&&(c=!0,i!==void 0&&(g.id=i)),this.onmessage?.(g)}catch(g){this.onerror?.(g)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:o,replayMessageId:i},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:s,onresumptiontoken:o,replayMessageId:i},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}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 De("No auth provider");if(await mr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new De("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:Xi(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,s),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new rt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:g}=xo(a);if(this._resourceMetadataUrl=h,this._scope=g,await mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new De;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:g,error:m}=xo(a);if(m==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new rt(403,"Server returned 403 after trying upscoping");if(g&&(this._scope=g),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=v??void 0,await mr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new De;return this.send(e)}}throw new rt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Hb(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=RR(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(g=>Wr.parse(g)):[Wr.parse(p)];for(let g of h)this.onmessage?.(g)}else throw await a.body?.cancel(),new rt(-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 rt(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})}};import{AsyncLocalStorage as uH}from"node:async_hooks";function Ac(t){return!!t._zod}function zt(t,e){return Ac(t)?Hi(t,e):t.safeParse(e)}function Mc(t){if(!t)return;let e;if(Ac(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $c(t){if(Ac(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}function Jr(t){return t==="completed"||t==="failed"||t==="cancelled"}var AJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Qf(t){let r=Mc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$c(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ep(t,e){let r=zt(t,e);if(!r.success)throw r.error;return r.data}var tp=6e4,Ic=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(pc,r=>{this._oncancel(r)}),this.setNotificationHandler(mc,r=>{this._onprogress(r)}),this.setRequestHandler(hc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new k(A.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(vc,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,f=new k(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new k(A.InvalidParams,`Task not found: ${i}`);if(!Jr(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(Jr(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[Br]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(_c,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new k(A.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(wc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new k(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Jr(o.status))throw new k(A.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new k(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof k?o:new k(A.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),k.fromError(A.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),Pn(i)||Fb(i)?this._onresponse(i):Xi(i)?this._onrequest(i,s):jb(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=k.fromError(A.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Br]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:A.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let a=Nb(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(s.signal.aborted)return;let l={relatedRequestId:e.id};i&&(l.relatedTask={taskId:i}),await this.notification(d,l)},sendRequest:async(d,l,f)=>{if(s.signal.aborted)throw new k(A.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let h=p.relatedTask?.taskId??i;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(s.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(s.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:A.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===s&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Pn(e))n(e);else{let s=new k(e.error.code,e.error.message,e.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(Pn(e)&&e.result&&typeof e.result=="object"){let s=e.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),Pn(e))o(e);else{let s=k.fromError(e.error.code,e.error.message,e.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(s){yield{type:"error",error:s instanceof k?s:new k(A.InternalError,String(s))}}return}let i;try{let s=await this.request(e,xn,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new k(A.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Jr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new k(A.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new k(A.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof k?s:new k(A.InternalError,String(s))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=w=>{d(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){l(w);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Br]:c}});let h=w=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(w)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(R=>this._onerror(new Error(`Failed to send cancellation: ${R}`)));let b=w instanceof k?w:new k(A.RequestTimeout,String(w));d(b)};this._responseHandlers.set(f,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=zt(r,w.result);b.success?u(b.data):d(b.error)}catch(b){d(b)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??tp,m=()=>h(k.fromError(A.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(f,g,n?.maxTotalTimeout,m,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let w=b=>{let R=this._responseHandlers.get(f);R?R(b):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,w),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(f),d(b)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(w=>{this._cleanupTimeout(f),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},yc,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Sc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Gb,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Br]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Br]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Br]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(e,r){let n=Qf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=ep(e,o);return Promise.resolve(r(s,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Qf(e);this._notificationHandlers.set(n,o=>{let i=ep(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Xi(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new k(A.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new k(A.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new k(A.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new k(A.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=ns.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Jr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new k(A.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Jr(a.status))throw new k(A.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=ns.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Jr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function CR(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function PR(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let s=r[o];CR(s)&&CR(i)?r[o]={...s,...i}:r[o]=i}return r}var mE=ca(Uh(),1),gE=ca(hE(),1);function Mq(){let t=new mE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,gE.default)(t),t}var gu=class{constructor(e){this._ajv=e??Mq()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var yu=class{constructor(e){this._client=e}async*callToolStream(e,r=kn,n){let o=this._client,i={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},s=o.requestStream({method:"tools/call",params:e},r,i),a=o.getToolOutputValidator(e.name);for await(let c of s){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new k(A.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let d=a(u.structuredContent);if(!d.valid){yield{type:"error",error:new k(A.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof k){yield{type:"error",error:d};return}yield{type:"error",error:new k(A.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function yE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function vE(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function vu(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let i=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(r[o]=i.default),r[o]!==void 0&&vu(i,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&vu(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&vu(r,e)}}function $q(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var _u=class extends Ic{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new gu,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",is,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",kf,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",wf,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new yu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=PR(this._capabilities,e)}setRequestHandler(e,r){let o=Mc(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i=$c(o);if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let a=async(c,u)=>{let d=zt(If,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new k(A.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=$q(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new k(A.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new k(A.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=zt(xn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new k(A.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let g=zt(Of,h);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new k(A.InvalidParams,`Invalid elicitation result: ${w}`)}let m=g.data,v=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&m.action==="accept"&&m.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{vu(v,m.content)}catch{}return m};return super.setRequestHandler(e,a)}if(s==="sampling/createMessage"){let a=async(c,u)=>{let d=zt(Af,c);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new k(A.InvalidParams,`Invalid sampling request: ${m}`)}let{params:l}=d.data,f=await Promise.resolve(r(c,u));if(l.task){let m=zt(xn,f);if(!m.success){let v=m.error instanceof Error?m.error.message:String(m.error);throw new k(A.InvalidParams,`Invalid task creation result: ${v}`)}return m.data}let h=l.tools||l.toolChoice?$f:Mf,g=zt(h,f);if(!g.success){let m=g.error instanceof Error?g.error.message:String(g.error);throw new k(A.InvalidParams,`Invalid sampling result: ${m}`)}return g.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Po,capabilities:this._capabilities,clientInfo:this._clientInfo}},mf,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Ib.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){yE(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&vE(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},En,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},zf,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},En,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},xf,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},bf,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},yf,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},vf,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Sf,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},En,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},En,r)}async callTool(e,r=kn,n){if(this.isToolTaskRequired(e.name))throw new k(A.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),i=this.getToolOutputValidator(e.name);if(i){if(!o.structuredContent&&!o.isError)throw new k(A.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let s=i(o.structuredContent);if(!s.valid)throw new k(A.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof k?s:new k(A.InvalidParams,`Failed to validate structured content: ${s instanceof Error?s.message:String(s)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},Tf,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let i=Jb.safeParse(n);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:s,debounceMs:a}=i.data,{onChanged:c}=n,u=async()=>{if(!s){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var cx=ca(sx(),1);import om from"node:process";import{PassThrough as aH}from"node:stream";var iH=10*1024*1024,wu=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??iH}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
97
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),sH(r)}clear(){this._buffer=void 0}};function sH(t){return Wr.parse(JSON.parse(t))}function ax(t){return JSON.stringify(t)+`
|
|
98
|
+
`}var cH=om.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Ru(){let t={};for(let e of cH){let r=om.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var bu=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new wu({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new aH)}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,cx.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Ru(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:om.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=ax(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};function dx(t){if(!t.useShellInterpolation)return{command:t.command,args:t.args};let e=[t.command,...t.args].join(" ");return process.platform==="win32"?{command:"cmd.exe",args:["/c",e]}:{command:"/bin/sh",args:["-c",e]}}var dH={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 lx(t){return{...Ru(),...dH,...t??{}}}function fx(){return Ru()}var im=class t extends bu{constructor(r,n=!1){super(r);this._captured=[];this._lineBuffer="";this._logHistory=[];this.suppressStderr=n}static{this.MAX_CAPTURED_LINES=100}static{this.MAX_LINE_BUFFER_CHARS=16384}static{this.MAX_LOG_HISTORY=1e3}async start(){await super.start();let r=this.stderr;r&&r.on("data",n=>this.ingestStderr(n))}ingestStderr(r){if(this.suppressStderr)return;this._lineBuffer+=r.toString();let n=this._lineBuffer.split(`
|
|
99
99
|
`);this._lineBuffer=n.at(-1)??"",this._lineBuffer.length>t.MAX_LINE_BUFFER_CHARS&&(this._lineBuffer=this._lineBuffer.slice(-t.MAX_LINE_BUFFER_CHARS));for(let o of n.slice(0,-1))this.pushCapturedLine(`${o}
|
|
100
|
-
`)}pushCapturedLine(r){this._captured.push(r),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(r),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let r=this._captured.join("");return this._captured=[],r}getLogHistory(){return[...this._logHistory]}};function
|
|
101
|
-
`).map(i=>i.trim()).filter(i=>i.length>0),o=gH(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var vH=6e5,_H=18e5,wE=2147483647,SH=3e4,bE=1e4,AE=[250,1e3,2e3],Bn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},Qs=class extends Error{constructor(){super("MCP authentication refresh is pending in the backend; retry shortly");this.retryable=!0;this.name="BackendRefreshPendingError"}},wH=250,RE=3,bH=[200,500];function RH(t){for(let e of Object.values(t))if(jr(e))return!0;return!1}function um(t){let e=new Set;for(let r of t.matchAll(Oi))e.add(Ga(r[0]));return[...e].sort()}function dm(t){return[...new Set(t)].sort()}function CE(t,e){return lv(e.map(r=>t?.[r]??"missing"))}function CH({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n,args:o}){return dm([...e&&t?zi(t):[],...n&&r?um(r):[],...o.flatMap(um)])}var Ru="${augmentToken}";function PH(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 xH(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var ME="(unknown uri)",lm="unknown",PE=/=+$/,EH=/\s+/g,kH=/[-_]/g,TH=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Wn(t,e){return typeof t=="string"?t:e}function $E(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function AH(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function MH(t){let e=t.replace(EH,"").replace(kH,i=>i==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(PE,"");if(r.toString("base64").replace(PE,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function IE(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function $H(t){let e=IE(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Wn(e.uri,ME),n=Wn(e.mimeType,lm);if(typeof e.blob=="string"&&AH(n)){let i=MH(e.blob);if(i!==void 0)return i}let o=$E(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function IH(t){let e=Wn(t.type,"unknown");if(e==="resource")return $H(t);if(e==="audio"){let r=Wn(t.mimeType,lm),n=$E(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Wn(t.uri,ME),n=Wn(t.name,""),o=Wn(t.mimeType,lm);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function OH(t){if(t.type!=="resource")return;let e=IE(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&TH.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function zH(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=OH(t);return e||{type:"text",text:kE(IH(t))}}function NH(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(zH(n))}return e}function DH(t){return rv(t,lH)}function OE(t,e){let r=NH(t);if(r.length===0){let o=DH(e);o!==void 0&&r.push({type:"text",text:kE(o)})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}function LH(t,e){let r=OE(e?.value(t.content),e?.value(t.structuredContent)),n=r.content.flatMap(o=>o.type==="text"?[{type:"text",text:e?.text(o.text)??""}]:[]);return n.length===0&&n.push({type:"text",text:"MCP stdio tool failed; no usable secret-free diagnostic content"}),{isError:!0,content:n,rawItemCount:r.rawItemCount}}var zE=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),jH=new Set([502,503,504]),Xo=AE.length+1,FH=2;function UH(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 xE(t,e){if(ft(t)||cm(t)||t instanceof yt)return;if(e==="stdio"&&gE(t))return{totalAttempts:Xo};let r=t?.cause?.code;if(typeof r=="string")return zE.has(r)?{totalAttempts:Xo}:void 0;let n=t?.status??t?.code;return typeof n=="number"?n===524?{totalAttempts:FH}:jH.has(n)?{totalAttempts:Xo}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Xo}:void 0}var qH=80,HH=10,GH=/[^a-zA-Z0-9_.()-]/g,ZH=new Set(["Error","McpError","McpSecretResolutionError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Cu(t){return t.replace(GH,"_").slice(0,qH)||"unknown"}function BH(t){let e=UH(t);if(e!==void 0&&(/^\d{3}$/.test(e)||zE.has(e)))return e}function Ve(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=ZH.has(e)?e:"Error",n=BH(t);return n===void 0?r:`${r}(${n})`}function WH(t,e,r){return t instanceof yt?new yt(Cu(t.serverName),t.missingKeys.slice(0,HH).map(Cu),void 0,t.reason).message:t instanceof Gn?t.message:`MCP ${r} ${e} failed (${Ve(t)})`}function Zn(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Cu(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var fm={heartbeat_timeout:{tool:"The MCP server did not answer its heartbeat in time.",log:"MCP heartbeat timed out"},connection_closed:{tool:"The connection to the MCP server closed before the tool finished.",log:"MCP connection closed during tool execution"},heartbeat_failed:{tool:"The MCP heartbeat failed while the tool was running.",log:"MCP heartbeat failed during tool execution"}},VH="configured MCP server",KH=/^[A-Za-z][A-Za-z0-9 _.-]{0,79}$/,EE=/authorization|bearer|token|secret|password|passwd|api.?key|private.?key|cookie|credential|session/i,JH=/^(?:call_|toolu_)[A-Za-z0-9_-]{1,100}$/,Vn=class extends Error{constructor(e,r){super(fm[e].tool),this.category=e,this.serverDisplayName=r,this.stack=`Error: ${this.message}`}};function YH(t){return mE(t)?"heartbeat_timeout":am(t)?"connection_closed":"heartbeat_failed"}var Pu=class{constructor(e,r){this._lastFailureTransient=!1;this._tools=[];this._refreshPersisting=!1;this._disposing=!1;this._disposed=!1;this._inFlightCalls=new Set;this._wedgeRecoveryOwners=new Set;this._wedgePending=!1;this._wedgeRequired=!1;this._authEpoch=0;this._config=e,this._targetAuth=Y().targetMaterialStore?.auth(e),this._suppressStdioDiagnostics=e.type==="stdio"&&this._targetAuth?.credential!==void 0,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 targetCredentialProvenance(){return this._targetAuth?{credential:this._targetAuth.credential}:void 0}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get lastFailureTransient(){return this._lastFailureTransient}get isDisposed(){return this._disposing||this._disposed}get suppressesProviderDiagnostics(){return this._suppressStdioDiagnostics}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._suppressStdioDiagnostics?[]:this._stdioTransport?.getLogHistory().map(e=>Ha(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=>{Q.warn(`MCP server "${this.name}" connect failed (${Ve(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=this._connectFailureMessage(r,"connect"),o=this._config.type==="stdio"&&!this._suppressStdioDiagnostics&&!ft(r)?Ha(yH(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ve(r))}}async _connectWithRetries(){let e=Xo,r={available:!0};for(let n=1;n<=Xo;n++)try{let o=await this._attemptConnect(r);return n>1&&Q.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let i=xE(o,this._config.type);if(i===void 0||this._disposed||(e=Math.min(e,i.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let i=(AE[r-1]??0)+Math.floor(Math.random()*(wH+1));Q.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ve(e)}; retrying in ${i}ms`),await hn(i)}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){return ft(e)&&this.hasRefreshEligibleOAuthCredential()&&!!this._usableToken()?.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 Bn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let i=fE();this._client=i;let s;try{if(await om({operation:"connect",onFailure:u=>{s=u}},()=>i.connect(n)),this._disposed)return await this._closeFailedInitialization(i,n),o;i.setNotificationHandler(pE,()=>{Q.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(i,n),o;this._tools=this._safeTools(a.tools??[]),this._status="success",this._lastError=void 0,this._lastFailureTransient=!1,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=Y();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&ct(c,this.name),Q.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(i,n),s??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){Q.debug(`MCP server "${this.name}" close after failed connect attempt (${Ve(n)})`)}}}_connectFailureMessage(e,r){return this._suppressStdioDiagnostics?"MCP stdio connection failed; provider diagnostics are suppressed to protect credentials":WH(e,r,this._config.type)}_recordConnectFailure(e,r,n=this._connectFailureMessage(e,r)){if(this._lastFailureTransient=xE(e,this._config.type)!==void 0,e instanceof yt){this._status="failed";let o=Y();ai(o,this.name,e.reason,at(o,this.name,this._config.id))}else if(e instanceof Qs||e instanceof Bn)this._status="failed";else if(ft(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(ft(e)){this._status="auth_required";let o=Y(),i=o.servers.get(this.name);(i===void 0||i===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=this._connectFailureMessage(e,r);$i(Zn(o,Ve(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config,r=Y().targetMaterialStore;if(!this._targetAuth&&(r?.has(e.name)||e.id&&r?.has(e.id)))throw new Error("MCP target provenance is unavailable");switch(this._targetAuth?.headers(),e.type){case"stdio":{let n=iE({...e,command:this._resolvedCommand??e.command,args:this._resolvedArgs??e.args}),o=sE(this._resolvedEnv??e.env);return cE({command:n.command,args:n.args,env:o,cwd:e.cwd,...this._suppressStdioDiagnostics?{suppressStderr:!0}:{}})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return lE(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders(),...this._targetAuth?{validateUrl:this._targetAuth.validateUrl}:{}});default:return e}}_createHttpTransport(e,r){let n=dE(e,{headers:r,getHeaders:()=>this._buildAuthHeaders(),...this._targetAuth?{validateUrl:this._targetAuth.validateUrl}:{}});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?RH(r):!1,o=e.type==="stdio"&&jr(e.command),i=e.type==="stdio"?e.args:[],s=i.some(jr);if(!(n||o||s))return;let a=Y();if(!this._targetAuth&&!dv(a)){let u=CH({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o,args:i});throw new yt(this.name,u)}let c=this._targetAuth?.getSecret??cv(a);if(n&&r&&await this._resolveMapSecretRefs(r,c,e.type==="stdio"),o&&e.type==="stdio"&&(this._resolvedCommand=await this._resolveCommandSecretRefs(e.command,c,e.useShellInterpolation)),s){let u=[];for(let d of i)u.push(await this._resolveCommandSecretRefs(d,c,!1));this._resolvedArgs=u}}async _resolveMapSecretRefs(e,r,n){let o,i=new Set,s=async c=>{let u=await r(c);return this._suppressStdioDiagnostics&&typeof u=="string"&&i.add(u),u};try{o=await pv({configEnv:e,localEnv:n&&!this._targetAuth?aE():{},getSecret:s})}catch(c){throw Q.error(`MCP server "${this.name}" secret resolution failed (${Ve(c)})`),new yt(this.name,zi(e),c,"transient")}let a=dm([...o.unresolvedKeys,...o.emptyKeys]);if(a.length>0)throw new yt(this.name,a,void 0,CE(o.failureReasons,a));if(this._targetAuth){if(this._disposed)return;this._targetAuth.headers()}n?(this._suppressStdioDiagnostics&&(this._toolErrorRedactor=al(i)),this._resolvedEnv=o.resolved):this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r,n){let o;try{o=await hv(e,r,n)}catch(s){throw Q.error(`MCP server "${this.name}" command secret resolution failed (${Ve(s)})`),new yt(this.name,um(e),s,"transient")}let i=dm([...o.unresolvedKeys,...o.emptyKeys]);if(i.length>0)throw new yt(this.name,i,void 0,CE(o.failureReasons,i));return o.resolved}_expandAugmentToken(){if(this._targetAuth)return;let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(s=>s.includes(Ru)))return;let o;if(PH(e.url)){let s=Y().credentials?.apiKey;s?o=s:this._recordTokenDiagnostic(`${Ru} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Ru} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${xH(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let i={};for(let[s,a]of Object.entries(r))i[s]=a.replaceAll(Ru,o);this._resolvedHeaders=i}_recordTokenDiagnostic(e,r){let n=Y();if(n.diagnostics.some(s=>s.server===this.name&&s.message===e))return;n.diagnostics.push({server:this.name,message:e});let i=`MCP server "${this.name}": ${e}`;r==="error"?Q.error(i):Q.warn(i)}_usableToken(){let e=Y();if(this._targetAuth||e.targetMaterialStore?.has(this.name)||this._config.id&&e.targetMaterialStore?.has(this._config.id))return;let r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!ht(n,this._config)))return r}_buildAuthHeaders(){if(this._targetAuth)return this._targetAuth.headers();let e=this._usableToken();return e?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}hasRefreshEligibleOAuthCredential(){let{config:e}=this;if(e.type!=="http"&&e.type!=="sse"||e.disabled||this._hostedCredentialProvenance!==void 0||!this._usableToken())return!1;if(e.auth==="oauth")return!0;let r=Y();return r.tokens.hasCredentialIdentity?.(this.name,Gt(r,this))===!0}async _maybeProactiveRefresh(){let e=Y(),r=e.tokens,{config:n}=this;(n.type==="http"||n.type==="sse")&&await r.ensureLoaded?.(this.name,Gt(e,this));let i=this._usableToken();i&&this.hasRefreshEligibleOAuthCredential()&&(i.accessToken&&!Md(i)||e.shouldProactivelyRefreshTokens&&(i.refreshToken?await this._refreshTokenDeduped():Ri(i)&&e.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=Y(),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:at(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]),i=e.refreshes.get(o);if(i)return i.then(a=>a??{kind:"refreshed"});let s=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===s&&e.refreshes.delete(o),this._refreshPromise===s&&(this._refreshPromise=void 0)});return this._refreshPromise=s,e.refreshes.set(o,s),s}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=D(r,this.name)?.retirement?.incumbent.host,i=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&i&&(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 i=e.state.servers.get(this.name),s=e.state.tokens,a=s.get(this.name),c=e.state.credentialRevisions.get(this.name);if(s!==e.tokenStore||!i||!a||!ht(this._config,i.config))return;let u=Gt(e.state,i),d=n===void 0&&u===void 0||kr(n,u);try{if(a===e.token&&d){s.commit(this.name,r,n),dn({state:e.state,name:this.name,revision:o});return}let l=await s.restoreAfterSupersededRefresh(this.name,r,a,n,o,u);if(!l||e.state.tokens!==s||e.state.servers.get(this.name)!==i||s.get(this.name)!==a||!kr(Gt(e.state,i),u)||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain||s.reconcileCredentialIdentity?.(this.name,a,u)!==!0)return;dn({state:e.state,name:this.name,revision:l});let f=e.state.currentLoad?.latestPi;f&&N(f,e.state)}catch{Q.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof Z?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof Z)&&Id(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&ai(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),Q.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${Ve(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),ai(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=Gt(e.state,this),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Od(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let i=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,i),{kind:"transient_failure"};e.tokenStore.commit(this.name,o,r),dn({state:e.state,name:this.name,revision:i}),ct(e.state,this.name);let s=e.state.currentLoad?.latestPi;return s&&N(s,e.state),Q.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:cm(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}Q.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e,r){if(this._config.type!=="http")return e();try{return await e()}catch(n){let o=this._isSessionExpiredError(n),i=this._reinitializingPromise!==void 0;if(!(o||i))throw n;Q.info(o?`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`),r?.("reconnecting");try{await this._reinitializeSession()}catch(s){throw Q.error(`MCP server "${this.name}" session re-initialization failed (${Ve(s)})`),hH(n),n}return r?.("running"),await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Bn}async _withAuthRetry(e,r,n){let o=this._config,i=Y(),s=at(i,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),om({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||!ft(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new Qs;if(this._hostedCredentialProvenance!==void 0)throw new Bn;if(!this.hasRefreshEligibleOAuthCredential())throw this._markAuthRequired(d,s),d;if(l&&!l.available)throw this._markAuthRequired(d,s),d;Q.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`),n?.onPhase?.("reauthorizing");let f=i.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}this._authEpoch++,n?.onPhase?.("running");try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw ft(h)&&this._markAuthRequired(h,s),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._targetAuth?(this._config.type==="http"||this._config.type==="sse")&&this._config.auth==="oauth"&&this._targetAuth.credential!==void 0:this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=Y();ai(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ve(e)),Q.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed()},e.onerror=()=>{this._probeAfterError()})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},SH),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=Y(),r=at(e,this.name,this._config.id),n=await this._runProbe();for(let s=2;s<=RE&&n.outcome==="transient";s++)await hn(bH[s-2]??0),n=await this._runProbe();let o=at(e,this.name,this._config.id),i=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return i&&n.outcome==="alive"&&ct(e,this.name,r),i&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?Q.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&Q.debug(`MCP server "${this.name}" startup verification ping remained transient after ${RE} 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:bE})},"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 (${Ve(r)})`,i=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?Q.debug(i):Q.warn(i),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":im(e)||sm(e)?"alive":ft(e)?"authFailure":yE(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!e||this._disposed)return;let r=new Set(this._inFlightCalls),n=this._authEpoch;try{await e.ping({timeout:bE})}catch(o){if(this._reinitializingPromise||this._disposed||this._authEpoch!==n||sm(o)||im(o)||ft(o))return;this._failInFlightCalls(new Vn(YH(o),this._safeDiagnosticName()),!0,r)}}_probeAfterError(){if(this._errorProbe)return;let e=this._sendHeartbeat().finally(()=>{this._errorProbe===e&&(this._errorProbe=void 0)});this._errorProbe=e}_handleTransportClosed(){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(new Vn("connection_closed",this._safeDiagnosticName())))}_diagnosticRedactor(){let e=Y().tokens.get(this.name),r=this._config.type==="stdio"?this._config.env:this._config.headers;return al([...Object.values(r??{}),...Object.values(this._resolvedEnv??{}),...Object.values(this._resolvedHeaders??{}),e?.accessToken??"",e?.refreshToken??""])}_safeDiagnosticName(){let e=this.name;return!KH.test(e)||EE.test(e)||Ha(e)!==e||this._diagnosticRedactor().text(e)!==e||this._toolErrorRedactor&&this._toolErrorRedactor.text(e)!==e?VH:e}_safeCorrelationId(e){if(!(!e||!JH.test(e)||EE.test(e)||this._diagnosticRedactor().text(e)!==e||this._toolErrorRedactor&&this._toolErrorRedactor.text(e)!==e))return e}_wedgeRecoveryOwnership(e){let r=e.failure;return ft(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&&!ft(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,n){let o=[...this._inFlightCalls].filter(u=>!u.livenessRejected&&(!n||n.has(u)));if(o.length===0)return;if(!r){for(let u of o)u.livenessRejected=!0,u.reject(e);Q.warn(`MCP server "${this.name}" failing ${o.length} in-flight tool call(s)`);return}let i=o.map(u=>({call:u,state:this._wedgeRecoveryOwnership(u)})),s=i.some(({state:u})=>u==="recoverable"),a=!1;for(let{call:u,state:d}of i)d==="recoverable"||d==="owned"&&s||(u.livenessRejected=!0,a=!0,u.reject(e instanceof Vn?e:u.failure??e));let c=o.filter(u=>u.livenessRejected).length;this._logInFlightFailure({error:e,unsettled:o,failedCount:c}),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=a):a&&this.onWedged?.()}_logInFlightFailure({error:e,unsettled:r,failedCount:n}){if(!(e instanceof Vn)){Q.warn(`MCP server "${this.name}" failing ${n} in-flight tool call(s)`);return}if(n===0)return;let o=r.length===1?this._safeCorrelationId(r[0]?.correlationId):void 0;iH(fm[e.category].log,{failure_category:e.category,server_display_name:e.serverDisplayName,...o?{correlation_id:o}:{}})}_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=this._safeTools(e.tools??[]),n=!aH(this._tools,r);if(this._tools=r,n){Q.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){Q.warn(`MCP server "${this.name}" onToolsChanged handler threw (${Ve(o)})`)}}}catch(e){Q.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ve(e)}), keeping cached tools`)}}_safeTools(e){return this._suppressStdioDiagnostics?this._toolErrorRedactor?e.filter(r=>JSON.stringify(this._toolErrorRedactor?.value(r))===JSON.stringify(r)):[]:e}listTools(){return this._tools}async callTool(e,r,n,o,i){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>wE)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${wE}.`);let s=this._toolErrorRedactor,c={timeout:this._config.timeoutMs??vH,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??_H,onprogress:h=>{if(!this._suppressStdioDiagnostics){Q.debug(`MCP server "${this.name}" tool "${e}" progress: ${h.progress}${h.total===void 0?"":`/${h.total}`}${h.message?` - ${h.message}`:""}`);try{i?.onProgress?.(h)}catch{}}}},u=i?.onPhase?h=>{try{i.onPhase?.(h)}catch{}}:void 0,d,l=new Promise((h,m)=>{d={reject:m,livenessRejected:!1,sessionRecoveryOwned:!1,correlationId:this._safeCorrelationId(o?.toolCallId)}});l.catch(()=>{}),d&&this._inFlightCalls.add(d);let p=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??{}},hE,c)},"tool_call",{call:d,onPhase:u}),u).then(h=>(d&&this._settleInFlightCall(d,!0,void 0),h),h=>{throw d&&this._settleInFlightCall(d,!1,h),h});try{let h=await Promise.race([p,l]);if(this._suppressStdioDiagnostics&&h.isError===!0)return LH({content:h.content,structuredContent:h.structuredContent},s);let m=OE(h.content,h.structuredContent);return{isError:h.isError===!0,content:m.content,rawItemCount:m.rawItemCount}}catch(h){return(n?.aborted||h instanceof Error&&h.name==="AbortError")&&this._throwCallCancellation(h),this._reportAndThrowToolError(h,e)}finally{d&&!this._wedgeRecoveryOwners.has(d)&&(d.failure=void 0,this._inFlightCalls.delete(d))}}_throwCallCancellation(e){throw this._suppressStdioDiagnostics?Zn("MCP stdio tool call cancelled","AbortError"):e}_reportAndThrowToolError(e,r){if(e instanceof Vn){let c=Zn(fm[e.category].tool,"Error");throw this._disposed||$i(c,{server:e.serverDisplayName,op:"tool_call",transport:this._config.type}),c}if(this._suppressStdioDiagnostics){let c=Zn("MCP stdio tool call failed; provider diagnostics are suppressed to protect credentials","Error");throw this._disposed||$i(c,{server:this.name,op:"tool_call",transport:"stdio"}),c}if(e instanceof Bn||e instanceof Qs)throw e;if(ft(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Cu(r),i=Ve(e),s=vE(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 (${i}).${s}`;throw mH(e)||$i(Zn(a,i),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),Zn(a,i)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._toolErrorRedactor=void 0,this._targetAuth&&(this._resolvedHeaders=void 0,this._resolvedEnv=void 0,this._resolvedCommand=void 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(this._suppressStdioDiagnostics){let o=Zn("MCP stdio close failed","Error");if(Q.debug(o.message),e?.strict)throw o;return}if(Q.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var ea=QH.child({prefix:"pi-mcp"}),eG=3,tG=6e4;function rG(t,e){let r=Date.now(),n=r-tG,o=(t.restartHistory.get(e)??[]).filter(i=>i>=n);return o.length>=eG?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}var nG=2e3,oG=6e4,NE=20,iG=15e3,sG=.2;function pm(t){return t?.status==="failed"&&t.lastFailureTransient&&!t.isDisposed}function FE(t,e){let r=t.transientReconnects?.get(e);r?.timer&&clearTimeout(r.timer),t.transientReconnects?.delete(e)}function UE(t){for(let e of[...t.transientReconnects?.keys()??[]])FE(t,e)}function xu(t,e,r){e.transientReconnects??=new Map;let n=e.servers.get(t);if(!pm(n)){FE(e,t);return}let o=e.transientReconnects.get(t)??{attempt:0,timer:void 0};if(e.transientReconnects.set(t,o),o.timer&&o.host!==n&&(clearTimeout(o.timer),o.timer=void 0),o.timer||o.attempt>=NE){o.timer||ea.warn(`MCP server "${t}" transient reconnects exhausted; restart required`);return}let i=Math.min(oG,nG*2**o.attempt),s=1+(Math.random()*2-1)*sG,a=Math.round(i*s);o.attempt+=1;let c=o.attempt;o.host=n;let u=setTimeout(()=>{if(o.timer===u){if(o.timer=void 0,o.host=void 0,e.servers.get(t)!==n){xu(t,e,e.currentLoad?.latestPi??r);return}pm(n)&&(ea.info(`MCP server "${t}" reconnecting after transient failure (attempt ${c}/${NE})`),or(t,e,e.currentLoad?.latestPi??r))}},a);o.timer=u,typeof u.unref=="function"&&u.unref()}async function qE(t,e,r,n){if(n?.aborted)return!1;let o=e.reconnects?.get(t);if(o)return await DE(o.catch(()=>{}),n),e.servers.get(t)?.status==="success";if(!pm(e.servers.get(t)))return!1;let i=e.transientReconnects?.get(t);i?.timer&&(clearTimeout(i.timer),i.timer=void 0,i.host=void 0),ea.info(`MCP server "${t}" reconnecting on demand for a tool call`);let s=or(t,e,e.currentLoad?.latestPi??r).catch(()=>{});return await DE(s,n),e.servers.get(t)?.status==="success"}async function DE(t,e){let r,n,o=new Promise(i=>{r=setTimeout(i,iG),typeof r.unref=="function"&&r.unref(),n=()=>i(),e?.addEventListener("abort",n,{once:!0})});try{await Promise.race([t,o])}finally{r&&clearTimeout(r),n&&e?.removeEventListener("abort",n)}}function LE(t){Wt(t),Ca(t)}async function aG(t,e,r){if(!rG(e,t)){ea.warn(`MCP server "${t}" automatic restart rate-limited`);return}ea.warn(`MCP server "${t}" wedged; recycling transport`),await or(t,e,r)}function Eu(t,e,r){if(HE(e)){LE(t),N(t,e);return}wd(t,r),zr(e)&&LE(t),N(t,e)}function HE(t){return mi()||Rd(t)&&t.toolSearchLatched}function nr(t,e,r){return rd(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function hm(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,ct(t,e),t.authRefreshNeededReportKeys.delete(e),r}function cG(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),i=e.tokens.get(r.name),s=e.hostedCredentialOwnership?.get(r.name),a=o!==void 0&&s?.revision===o.revision,c=o!==void 0&&s?.domain===o.domain,u=o!==void 0&&s?.ownerDomain===o.ownerDomain,d=o!==void 0&&e.oauthCredentialDomains.get(r.name)===o.domain,l=o!==void 0&&mg(o.domain,r.id,o.ownerDomain);return o!==void 0&&i!==void 0&&s!==void 0&&a&&c&&u&&d&&l?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:s.accessTokenOnly}):s===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function mm(t){let{state:e,config:r,generation:n}=t;return new Pu(r,cG({state:e,config:r,hostGeneration:n}))}function Ke(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 gm(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 ym(t,e,r){return t.configDesiredRevisions.get(e)===r}function jE(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function vm(t,e,r,n){t.onStateChange=(a,c)=>{if(!nr(t,e,r))return;let u={server:t.name,state:a,...c===void 0?{}:{errorType:c}};n.events.emit(XH,u),(a==="failed"||a==="auth_required")&&HE(r)&&Wt(r.currentLoad?.latestPi??n)},t.onWedged=()=>{if(!nr(t,e,r))return;let a=r.currentLoad?.latestPi??n;aG(t.name,r,a)};let o=t.hostedCredentialProvenance,i=t.targetCredentialProvenance?.credential,s;i&&(t.config.type==="http"||t.config.type==="sse")&&t.config.auth==="oauth"?s={serverGeneration:e,mcpConfigId:t.config.id,credentialRevision:i.revision,credentialRevisionDomain:i.domain}:o?.kind==="accepted"&&o.hostedAccessTokenOnly&&(s={serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}),t.onAuthRefreshNeeded=()=>{if(!nr(t,e,r)||!s)return;let a=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==a&&(r.authRefreshNeededReportKeys.set(t.name,a),N(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!nr(t,e,r)||!s)return;let a=r.statusFailureCategories.get(t.name);typeof a=="object"&&a.category==="auth_refresh_needed"&&ct(r,t.name,s)&&N(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{nr(t,e,r)&&t.status==="success"&&Eu(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let a=r.currentLoad?.latestPi??n;bd(a,t,e),a!==n&&bd(n,t,e)}}async function GE(t,e,r,n){let o=setTimeout(()=>{nr(t,e,r)&&N(n(),r)},ua);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),nr(t,e,r)&&(N(n(),r),xu(t.name,r,n()))}}async function ZE(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function ku(t,e){if(e.status!=="installed")return!1;let r=D(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function uG(t){let{state:e,config:r,displaced:n,retirement:o}=t;gm(e,n.config),fi(e,r.name),n.beginDisposal?.();try{let i=od(n.config,r)?Promise.resolve():mt(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;_e({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(i){throw _e({state:e,name:r.name,retirement:o,result:{status:"failed",error:i}}),i}}async function dG(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,i=ut({state:e,name:r.name,owner:n,revision:o,host:r});if(i){r.beginDisposal?.();try{await r.dispose({strict:!0}),_e({state:e,name:r.name,retirement:i,result:{status:"retired"}}),Ee({state:e,name:r.name,owner:n,revision:o})}catch(s){throw _e({state:e,name:r.name,retirement:i,result:{status:"failed",error:s}}),s}}}async function lG(t){let{state:e,server:r,config:n,generation:o,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c}=t;return await r.connect(),nr(r,o,e)?a?.(n)===!1?(await dG({state:e,server:r,owner:i,leaseRevision:s}),{status:"superseded",config:n}):(r.status==="success"&&Eu(c(),e,r),N(c(),e),xu(r.name,e,c()),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:s}):{status:"superseded",config:n}}function fG(t){let{state:e,config:r,configRevision:n,pi:o,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c}=t,u=D(e,r.name);if(!ym(e,r.name,n)||u?.revision!==s||a?.(r)===!1)return Ee({state:e,name:r.name,owner:i,revision:s}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=hm(e,r.name),l=mm({state:e,config:r,generation:d});return vm(l,d,e,o),fa({state:e,name:r.name,owner:i,revision:s,host:l})?{connection:lG({state:e,server:l,config:r,generation:d,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c})}:(Ee({state:e,name:r.name,owner:i,revision:s}),{status:"superseded",config:r})}function pG(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:i,activePi:s}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!ym(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?te(r,a.name,u):D(r,a.name),l=Er(a,i),f=di({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>fG({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:s}),m=async()=>(f.displacedHost&&f.retirement?await uG({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await td(f.retirement),h());return f.retirement?m():h()}async function Je(t,e,r,n,o,i){let s=()=>e.currentLoad?.latestPi??r,a=t.map(d=>({config:d,revision:o?.get(d.name)??Ke(e,d.name)})),c=a.map(async d=>{try{let l=await pG({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:i,activePi:s});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(()=>{N(s(),e)},ua);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u);for(let d of a)xu(d.config.name,e,s())}}async function hG({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!jE(e,t,n))return!1;let i=o.config,s=te(e,t,o);if(!rd(e,t,o))return!1;gm(e,i),fi(e,t);let a=ut({state:e,name:t,owner:s.owner,revision:s.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),_e({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw _e({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(D(e,t)?.revision!==s.revision||!jE(e,t,n))return Ee({state:e,name:t,owner:s.owner,revision:s.revision}),!1;let c=hm(e,t),u=mm({state:e,config:i,generation:c});if(vm(u,c,e,r),!fa({state:e,name:t,owner:s.owner,revision:s.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await GE(u,c,e,d),nr(u,c,e)&&u.status==="success"&&Eu(d(),e,u),!0}function or(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 i=(async()=>{let s=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await hG({name:t,state:e,pi:r,configRevision:a}))return;s=c}while(s<(e.reconnectDesiredGenerations.get(t)??s))})().finally(()=>{e.reconnects.get(t)===i&&e.reconnects.delete(t)});return e.reconnects.set(t,i),i}async function mG(t){let{state:e,name:r,existing:n,config:o,retirement:i}=t;gm(e,n.config),fi(e,r),n.beginDisposal?.();try{let s=o!==void 0&&od(n.config,o)?Promise.resolve():mt(e,r,n.config.id,n.config),c=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;i&&_e({state:e,name:r,retirement:i,result:{status:"retired"}})}catch(s){throw i&&_e({state:e,name:r,retirement:i,result:{status:"failed",error:s}}),s}}async function BE(t,e,r,n,o){let i=()=>e.currentLoad?.latestPi??r,{servers:s}=ro(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=s.find(m=>m.name===t),c=Ke(e,t),u=e.servers.get(t),d=u?te(e,t,u):D(e,t),l={kind:"local",identity:a?.id??t},f=di({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await mG({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await td(f.retirement),D(e,t)?.revision!==f.lease.revision||!ym(e,t,c)){Ee({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){Ee({state:e,name:t,owner:l,revision:f.lease.revision}),N(i(),e);return}let p=hm(e,t),h=mm({state:e,config:a,generation:p});vm(h,p,e,r),fa({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await GE(h,p,e,i),nr(h,p,e)&&h.status==="success"&&Eu(i(),e,h))}async function ta(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>or(n,e,r)))}finally{e.reconnecting=!1}}var WE=Symbol.for("__pi_mcp_registry_ingress__");function Tu(t){return Object.defineProperty(t,WE,{value:!0}),t}function Kn(t){return Object.getOwnPropertyDescriptor(t,WE)?.value===!0}function nn(t){let{state:e,target:r,byConfigId:n=!1}=t;if(!r)return;let o=[...e.servers].filter(([u,d])=>d.config.id===r||!n&&u===r);if(o.length!==1)return;let i=o[0];if(!i)return;let[s,a]=i;if(a.config.id&&[...e.servers].some(([u,d])=>u!==s&&d.config.id===a.config.id))return;let c=D(e,s);if(!(c&&(c.host!==a||c.owner.kind==="registry"&&c.connectionEpoch!==e.mcpConnectionEpoch))&&!(!c&&e.mcpConnectionEpoch!==void 0&&a.config.registrySource!==void 0)&&!((n||s!==r)&&!Kn(a.config)&&!(c?.owner.kind==="registry"&&c.owner.identity===`user:${r}`)))return{name:s,server:a}}import{logger as gG}from"@hermes/logger";var yG=gG.child({prefix:"pi-mcp"}),vG=1e6,_G=1e3,SG=/^\d+$/;function VE(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function on(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"||!SG.test(e)||typeof r!="string"||r.length===0)return;let n=ha(t);if(n.kind!=="invalid")return{revision:e.replace(/^0+(?=\d)/,""),domain:VE(r),...n.kind==="valid"?{ownerDomain:n.ownerDomain}:{}}}function wG(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:Tr(o,n)>0?o:n}function bG(t,e,r){if(t===void 0)return!0;let n=VE(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain||r?.kind==="domain"&&(n.startsWith("private:")||n.startsWith("shared:"))&&e.domain.startsWith("recipient:")&&Ar(n)===r.domain&&Ar(e.domain)===r.domain?!0:r?.kind==="domain"&&!Ie(n)&&Ie(e.domain)&&Ar(n)===r.domain}function RG(t,e,r,n){let o=e.credential_revision??e.credentialRevision,i=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||i!==void 0)&&r===void 0)return yG.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let s=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||s!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";let a=Ar(r.domain);if(s?.kind==="blocked"||s?.kind==="domain"&&r.ownerDomain!==void 0&&r.ownerDomain!==s.domain||s?.kind==="domain"&&r.ownerDomain===void 0&&!Ie(r.domain)&&a!==s.domain)return"reject";let c=n?.acceptedDomains?.get(t);if(!bG(c,r,s))return"reject";let u=wG(n?.acceptedRevisions,r.domain,i);if(u===void 0)return"apply";let d=Tr(r.revision,u);return d>0||d===0&&c===void 0&&s?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===s.domain?"apply":d===0?"equal":"reject"}function CG(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 PG(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(typeof e.access_token!="string"||e.access_token.length===0||["refresh_token","token_type","scope","authorization_endpoint","token_endpoint","issuer","client_id","client_secret","token_endpoint_auth_method"].some(s=>e[s]!==void 0&&typeof e[s]!="string"))return!1;let n=e.access_token_expires_at;if(n===void 0)return!0;if(typeof n!="object"||n===null||Array.isArray(n))return!1;let{seconds:o,nanos:i}=n;return typeof o=="number"&&Number.isSafeInteger(o)&&typeof i=="number"&&Number.isInteger(i)&&i>=0&&i<1e9}function xG(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*_G+Math.floor(t.access_token_expires_at.nanos/vG):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 EG(t,e){return t?t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.expiresAt===e.expiresAt&&t.tokenType===e.tokenType&&t.scope===e.scope&&t.resource===e.resource&&t.serverMetadata?.issuer===e.serverMetadata?.issuer&&t.serverMetadata?.authorization_endpoint===e.serverMetadata?.authorization_endpoint&&t.serverMetadata?.token_endpoint===e.serverMetadata?.token_endpoint&&t.client?.client_id===e.client?.client_id&&t.client?.client_secret===e.client?.client_secret&&t.client?.token_endpoint_auth_method===e.client?.token_endpoint_auth_method:!1}function wr(t){let{store:e,serverName:r,proto:n,options:o}=t;if(!PG(n))return{decision:"reject"};let i=on(n),s=RG(r,n,i,o);if(s==="reject")return{decision:s};let a=xG(n);return s==="equal"&&o?.requireEqualMaterial===!0&&(o.acceptedDomains?.get(r)!==i?.domain||!EG(e.get(r),a))||s==="apply"&&CG(e,r,a,i)?{decision:"reject"}:{decision:s,token:a,revision:i}}function Au(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,i]of Object.entries(e)){let s=wr({store:t,serverName:o,proto:i,options:r});if(s.decision!=="apply"){n[s.decision==="equal"?"equal":"rejected"].push(o);continue}let{token:a,revision:c}=s;t.set(o,a),r?.equalRevisionRebindDomains?.delete(o),c!==void 0&&(r?.acceptedRevisions?.set(c.domain,c.revision),r?.acceptedDomains?.set(o,c.domain)),n.applied.push(o)}return n}var _m=kG.child({prefix:"pi-mcp"});function sn(t,e){_m.info(`Targeted MCP credential update for config ${t} skipped: ${e}`),KE("MCP targeted credential update skipped",{outcome:e})}function TG(t,e){let r=nn({state:t,target:e,byConfigId:!0});if(!r)return;let o=D(t,r.name)?.owner??Er(r.server.config);return o.kind==="registry"&&o.identity===`user:${e}`?r:void 0}function AG(t,e,r){let n=Object.entries(t).filter(([o,i])=>{let s=on(i);if(s===void 0)return!1;let a=ln(s);return s.ownerDomain!==void 0?a===`user:${e}`:o===r&&Ie(s.domain)||a===`user:${e}`});return n.length===1?n[0]?.[1]:void 0}async function JE(t){let{pi:e,state:r,update:n}=t;if(Object.keys(n.credentials).length!==1){_m.warn(`Targeted MCP credential update for config ${n.configId} must contain exactly one entry`),sn(n.configId,"invalid_payload");return}let o=TG(r,n.configId),i=o?AG(n.credentials,n.configId,o.server.config.name):void 0;if(!o){sn(n.configId,"no_live_host");return}if(!i){sn(n.configId,"credential_mismatch");return}let s=D(r,o.name),a=r.mcpConnectionEpoch;if(o.server.config.type==="stdio"||o.server.config.auth!=="oauth"){sn(n.configId,"unsupported_transport");return}let c=()=>({acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:!0}),u=()=>wr({store:r.tokens,serverName:o.name,proto:i,options:c()});if(u().decision==="reject"){sn(n.configId,"credential_rejected");return}let d=o.server.getRefreshInFlight?.();if(d&&await Promise.resolve(d).catch(()=>{}),r.mcpConnectionEpoch!==a||r.servers.get(o.name)!==o.server||D(r,o.name)!==s){sn(n.configId,"host_changed");return}if(u().decision==="reject"){sn(n.configId,"credential_rejected");return}te(r,o.name,o.server),r.shouldProactivelyRefreshTokens=!1;let l=Au(r.tokens,{[o.name]:i},c());if(!l.applied.includes(o.name)&&!l.equal.includes(o.name)){sn(n.configId,"not_applied");return}if(l.applied.includes(o.name)){let f=on(i);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,accessTokenOnly:i.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}await $G({pi:r.currentLoad?.latestPi??e,state:r,name:o.name,configId:n.configId,reconnect:t.reconnect??or,report:t.report??N})}function MG(t,e){return t?"restart_failed":e?"reconnected":"restart_not_connected"}async function $G(t){let{pi:e,state:r,name:n,configId:o}=t,i=!1;await t.reconnect(n,r,e).catch(a=>{i=!0,_m.warn(`Targeted MCP credential restart failed for config ${o}: ${a instanceof Error?a.name:"non-Error"}`)}),t.report(e,r),Se(r);let s=r.servers.get(n)?.status==="success";KE("MCP targeted credential update applied",{outcome:MG(i,s)})}import{logger as BG}from"@hermes/logger";import{randomUUID as IG}from"node:crypto";import{setToolSource as OG}from"@augmentcode/auggie-v2";import{logger as zG}from"@hermes/logger";import{Type as NG}from"@sinclair/typebox";var XE=zG.child({prefix:"pi-mcp"}),ir="attach-mcp-server",DG="augment:mcp-attach-request",LG=15e3,jG={type:"object",properties:{config_id:{type:"string",description:"Id (or name) of the MCP server to attach, as listed among the available unattached servers in find-tool's description."}},required:["config_id"]};function FG(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],i=o.find(l=>l.id===r);if(i)return{kind:"match",entry:i};let s=o.filter(l=>l.name.toLowerCase()===n),a=s.length===1?s[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(s.length===0)return{kind:"none"};let c=new Set(fn(t).map(l=>l.id)),u=s.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:s}}function UG(t,e){let r=e.name.toLowerCase();return fn(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function Sm(t,e){let r=UG(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function qG(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},LG);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function YE(t){let e=fn(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function HG(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return xe(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${Sm(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return xe(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.${Sm(r,e)}`)}function GG(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return xe(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,xe("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return xe(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return xe(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return xe(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return xe(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return xe(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${Sm(n,e)}`);case"NO_ACTIVE_VM":return xe(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return xe(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function ZG(t,e,r){if(e.mcpAttachDisabled)return xe("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${ir} requires a string "config_id" parameter. ${YE(e)}`);let o=FG(e,n);if(o.kind==="none")return xe(`No MCP server matching "${n}" is available to attach. ${YE(e)}`);if(o.kind==="ambiguous"){let l=o.candidates.map(f=>`"${f.name}" (id: ${f.id})`).join(", ");return xe(`Multiple MCP servers match the name "${n}": ${l}. Retry with the exact id of the intended server.`)}let i=o.entry,s=HG({entry:i,state:e});if(s!==void 0)return s;if(Cd(e,i))return xe(`MCP server "${i.name}" is already attached to this session. Use find-tool to discover its tools.`);if(i.state!=="available"&&i.state!=="opt_in_required")return xe(`MCP server "${i.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=IG();XE.info(`attach-mcp-server: requesting attach of "${i.name}" (config=${i.id} request=${a})`);let c=qG(e,a);t.events.emit(DG,{configId:i.id,requestId:a});let u=await c,d=GG({entry:i,result:u,state:e});return e.mcpAttachDisabled&&(e.mcpCatalog=void 0,t.unregisterTool(ir),oo(ir),zr(e)&&Wt(t)),d}function Mu(t,e){let r={name:ir,label:ir,description:"Attach an available MCP server to this session so its tools become usable. Only servers listed as available-but-not-attached in find-tool's description can be attached. Call this tool immediately when the user's request needs one of those servers; it attaches directly without requiring user approval.",parameters:NG.Unsafe(jG),execute:(n,o)=>ZG(t,e,o)};OG(ir,"mcp"),t.registerTool(r),Ir(r),XE.debug("Registered attach-mcp-server tool")}var $u=BG.child({prefix:"pi-mcp"}),wm="augment:mcp-attach-result";function QE(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(wm,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){$u.warn(`${wm} payload missing requestId`);return}let i=e.attachResolvers.get(o);if(!i){$u.debug(`${wm}: no pending resolver for request ${o} (already timed out?)`);return}let s={...typeof n?.status=="string"?{status:n.status}:{},...typeof n?.error=="string"?{error:WG(n.error)}:{}};i(s)}))}function WG(t){return t==="UNIMPLEMENTED"||t==="DENIED"?t:"TRANSPORT"}function Iu(t,e){if(e.mcpAttachCloudSignaled&&Pa(e)){Mu(t,e);return}e.mcpAttachCloudSignaled&&$g(ir)!==void 0&&(t.unregisterTool(ir),oo(ir))}function Qo(t,e){if(!e.mcpAttachCloudSignaled||!Pa(e)||!e.credentials)return Promise.resolve();if(e.catalogRefreshInFlight)return e.catalogRefreshInFlight;let r=e.credentials,n=e.mcpConnectionEpoch,o=(async()=>{let i=await Hg(r);if(e.mcpConnectionEpoch!==n||e.credentials!==r)return;i.ok?(e.mcpCatalog=i.entries,$u.debug(`MCP catalog refreshed: ${i.entries.length} entry(s)`)):i.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,$u.debug("MCP catalog endpoint unavailable (404); disabling attach for this session"));let s=e.currentLoad?.latestPi??t;Iu(s,e),zr(e)&&Wt(s)})().finally(()=>{e.catalogRefreshInFlight===o&&(e.catalogRefreshInFlight=void 0)});return e.catalogRefreshInFlight=o,o}import{logger as aZ}from"@hermes/logger";function VG(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case gi.OAUTH:return"oauth";case gi.API_KEY:return"header";default:return}let e=String(t).toLowerCase();if(e==="oauth"||e==="mcp_auth_type_oauth")return"oauth";if(e==="header"||e==="api_key"||e==="mcp_auth_type_api_key")return"header"}function KG(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Nr.CLI:return"cli";case Nr.CLOUD_AGENT:return"cloud_agent";default:return}switch(t){case"MCP_PRODUCT_TYPE_CLI":return"cli";case"MCP_PRODUCT_TYPE_CLOUD_AGENT":return"cloud_agent";default:return}}function Ou(t){if(t==null)return;if(t.length===0)return[];let e=t.map(KG).filter(r=>r!==void 0);return e.length===0?void 0:e}function zu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=VG(r.auth_type),o={name:r.name,type:r.type==="http"||r.type==="sse"||r.type==="stdio"?r.type:void 0,disabled:r.disabled,command:r.command,args:r.args,env:r.env,url:r.url,auth:n==="oauth"?"oauth":void 0,timeoutMs:r.timeout_ms,useShellInterpolation:r.use_shell_interpolation},i=eo(o);(i==="http"||i==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...to(r.name??t.id,o),id:t.id,registrySource:e}}}catch(s){return{ok:!1,reason:s instanceof Tt?s.message:String(s)}}}function JG(t){let e=t.config?.auth_type;return e===gi.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function YG(t){let e=t.name;return t.type==="stdio"?`stdio\0${e}\0${t.command}\0${t.args.join(" ")}`:`${t.type}\0${e}\0${t.url}`}function bm(t,e,r){let n=new Map;for(let o of t)r(o.id)&&n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()]}function XG(t,e,r){if(r!==void 0&&t.added_by===r)return Ou(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?Ou(n):[]}function QG(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:i,currentUserId:s}=t;if(i!=null&&i.length===0){let p=bm(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(i!=null){let p=new Set(i),h=bm(e,r,()=>!0),m=new Set(h.map(b=>b.id)),g=h.filter(b=>p.has(b.id)),v=h.filter(b=>!p.has(b.id)).map(b=>b.id),w=i.filter(b=>!m.has(b));return{selected:g,filteredOutIds:v,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=bm(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let m=!d.has(p.id)&&a.has(p.id)?XG(p,o,s):Ou(p.enabled_products),g=t.productType??"cloud_agent";m===void 0||m.includes(g)?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function eZ(t,e="cloud_agent"){if(t==null)return e==="cli"?Nr.CLI:Nr.CLOUD_AGENT}function tZ(t){return t.map(e=>({message:`Selected MCP config id "${e}" was not returned by the registry (not opted in to the shared server, deleted, or an unknown id)`}))}function ek(t,e,r,n){try{let o=t.type==="stdio"?Bt(t,n):Zt(t,n);return{ok:!0,server:Tu(o)}}catch(o){let i=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${i}`}}}}function rZ(t){let{payload:e,userIds:r,localServerNames:n,seenNames:o,workspaceRoot:i}=t;if(e.config?.disabled)return e.config.name?{kind:"retained",name:e.config.name}:{kind:"dropped"};let s=r.has(e.id)?"user":"tenant",a=zu(e,s);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${s}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${s}): a local server with the same name takes precedence`}};let d=ek(c,e.id,s,i);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${s}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=ek(c,e.id,s,i);return u.ok?(o.add(c.name),{kind:"connected",server:u.server}):{kind:"retained",name:c.name,diagnostic:u.diagnostic}}function nZ(t){let e=[],r=[],n=[];for(let o of t)JG(o)?(r.push(o.id),n.push({server:o.config?.name,message:`Skipped MCP server "${o.config?.name??o.id}" (id=${o.id}): OAuth authentication was never completed (no stored credentials), so it cannot connect`})):e.push(o);return{selected:e,droppedIds:r,diagnostics:n}}function oZ(t){let e=[],r=[],n=[],o=new Set;for(let i of t){let s=YG(i);if(o.has(s)){r.push(i.name),n.push({server:i.name,message:`Skipped duplicate MCP server "${i.name}" (id=${i.id}): byte-identical to another selected server`});continue}o.add(s),e.push(i)}return{servers:e,droppedNames:r,diagnostics:n}}function iZ(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function Nu(t){let e=t.productType??"cloud_agent",r=t.client??new Ea(t.creds),{tenant:n,user:o,diagnostics:i}=await ty(r,eZ(t.configIds,e)),s=o.mcp_configs??[],a=new Set(s.map(R=>R.id)),{selected:c,filteredOutIds:u,missingIds:d,retainedNames:l}=QG({tenantConfigs:n.mcp_configs??[],userConfigs:s,enabledSharedServerIds:o.enabled_shared_server_ids??[],serverProductPreferences:o.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId,productType:e}),f=nZ(c),p=f.selected;u.push(...f.droppedIds),i.push(...f.diagnostics),i.push(...tZ(d));let h=[],m=new Map,g=new Set(t.localServerNames),v=[...p.filter(R=>a.has(R.id)),...p.filter(R=>!a.has(R.id))];for(let R of v){let _=rZ({payload:R,userIds:a,localServerNames:t.localServerNames,seenNames:g,workspaceRoot:t.workspaceRoot});iZ(_,{servers:h,retainedNames:l,diagnostics:i,nameCollisionFallbacks:m})}let w=oZ(h);l.push(...w.droppedNames),i.push(...w.diagnostics);let b=new Map;for(let R of[...n.mcp_configs??[],...s])R.config?.name&&b.set(R.id,R.config.name);return{servers:w.servers,diagnostics:i,filteredOutIds:u,retainedNames:l,namesById:b,nameCollisionFallbacks:m}}import{logger as sZ}from"@hermes/logger";var ei=sZ.child({prefix:"pi-mcp"});function tk(t,e,r){let n=t;if(!n||typeof n!="object"||!n.id){ei.warn("Embedded MCP config is missing an id; ignoring");return}let o=r?.get(n.id);if(o)return o;let i=zu(n,"tenant");if(!i.ok){ei.warn(`Embedded MCP config '${n.id}' is not convertible; ignoring: ${i.reason}`);return}let s=e??process.cwd();try{return Tu(i.server.type==="stdio"?Bt(i.server,s):Zt(i.server,s))}catch(a){ei.warn(`Embedded MCP config '${n.id}' failed expansion; ignoring: ${a instanceof Error?a.message:String(a)}`);return}}function rk(t,e){let r;try{r=JSON.parse(t)}catch(n){ei.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return tk(r,e)}function ti(t,e,r){let n=t;if(typeof n=="string")try{n=JSON.parse(n)}catch(a){ei.warn(`Failed to parse embedded MCP configs: ${a instanceof Error?a.name:"non-Error thrown"}`);return}if(!Array.isArray(n)){ei.warn("Embedded MCP configs payload is not an array; ignoring");return}let o=[],i=new Map,s=!1;for(let a of n){let c=a,u=tk(a,e,r);if(c&&typeof c=="object"&&c.id&&c.config?.name&&i.set(c.id,{name:c.config.name,...u?{config:u}:{}}),c?.config?.disabled){s=!0;continue}u&&o.push(u)}if(!(o.length===0&&!s))return{servers:o,allConfigsById:i}}var xt=aZ.child({prefix:"pi-mcp"});function ok(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function ik(t){let{state:e,name:r,lease:n,host:o,isDeselected:i,selectionIsEmpty:s,replacementOwners:a}=t;if(s)return o?ut({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ke(e,r),"retiring"):void 0:(Ee({state:e,name:r,owner:n.owner,revision:n.revision}),Ke(e,r),"released");let c=a.get(r),u=di({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return i&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ke(e,r),leaseRevision:u.lease.revision}}function cZ(t){let{state:e,name:r,server:n,selectedIds:o,replacementOwners:i,slotReservations:s,processedNames:a}=t,c=te(e,r,n);if(c.owner.kind!=="registry"||c.host!==n)return;a.add(r);let u={...n.config};e.registryCredentialConfigs.set(r,u),n.config.id&&(e.registryConfigNamesById.set(n.config.id,r),e.registryCredentialConfigsById.set(n.config.id,u));let d=ik({state:e,name:r,lease:c,host:n,isDeselected:ok({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:i});if(d===void 0)return;d!=="released"&&d!=="retiring"&&s.set(r,d);let l=D(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&_e({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&Ee({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&_e({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function uZ(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:i,slotReservations:s}=t,a=ik({state:e,name:r,lease:n,isDeselected:ok({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:i});a&&a!=="released"&&a!=="retiring"&&s.set(r,a)}async function dZ(t,e,r){let n=e?new Set(e):void 0,o=new Map,i=[],s=new Set;for(let[a,c]of t.servers){let u=cZ({state:t,name:a,server:c,selectedIds:n,replacementOwners:r,slotReservations:o,processedNames:s});u&&i.push(u)}for(let[a,c]of t.hostLeases)s.has(a)||c.owner.kind!=="registry"||c.host!==void 0||uZ({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(i),o}async function sk(t,e,r,n,o){let i=[],s=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=s.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){s.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&i.push(mt(t,l,f.id,f))}try{await Promise.all(i)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new kt(f)}let d=new Map;for(let[l,f]of s){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),ht(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function lZ(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],i=[],s=[],a=[],c=new Set(r);for(let f of t.servers){if(n&&f.id!==void 0&&!n.has(f.id)){s.push(f.id);continue}if(c.has(f.name)){i.push({server:f.name,message:r.has(f.name)?`Skipped embedded MCP server "${f.name}" (id=${f.id}): a local server with the same name takes precedence`:`Skipped embedded MCP server "${f.name}" (id=${f.id}): another selected registry server with the same name takes precedence`}),a.push(f.name);continue}c.add(f.name),o.push(f)}let u=new Set(o.map(f=>f.name)),d=new Set(a),l=new Map;for(let[f,{name:p}]of t.allConfigsById)n&&!n.has(f)||(l.set(f,p),u.has(p)||d.has(p)||(d.add(p),a.push(p)));return{servers:o,diagnostics:i,filteredOutIds:s,retainedNames:a,namesById:l}}function fZ(t){let{state:e,configIds:r,admittedConfigs:n}=t,o=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,r?.length===0||Array.isArray(o)&&o.length===0)return{servers:[],allConfigsById:new Map};if(o!==void 0)return ti(o,e.workspaceRoot??process.cwd(),n)}async function pZ(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),i=[],s=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(He(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);i.push({id:a,name:c}),s.push(mt(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(s);for(let{id:a,name:c}of i)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new kt(c)}}function hZ(t){let e=new Map,r=t.configIds?new Set(t.configIds):void 0;for(let[n,{name:o}]of t.parsedEmbedded?.allConfigsById??[])(r===void 0||r.has(n))&&e.set(o,{kind:"registry",identity:`user:${n}`});return e}function mZ(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function gZ(t){let e=new Set;for(let[r,n]of t.servers){let o=te(t,r,n);o.owner.kind==="local"&&o.host===n&&e.add(r)}for(let[r,n]of t.hostLeases)n.owner.kind==="local"&&e.add(r);return e}function yZ(t){let{state:e,result:r,previousSelectedIds:n,selection:o}=t,i=new Set([...o??[],...r.servers.flatMap(s=>s.id===void 0?[]:[s.id]),...r.namesById?.keys()??[]]);return sk(e,r.servers,n,i,o!==void 0)}async function ak(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():hi(t,r.id)))}async function nk(t){return await ak(t.state,t.result),t.state.registryGeneration===t.generation&&await yZ(t),t.result}function vZ(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:i,previousSelectedIds:s,selection:a,generation:c,discover:u,productType:d}=t;if(n){xt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let f=lZ(n,r,i);return nk({state:e,result:f,previousSelectedIds:s,selection:a,generation:c})}return o?u({configIds:r,creds:o,currentUserId:o.userId,workspaceRoot:e.workspaceRoot??process.cwd(),localServerNames:i,productType:d}).then(f=>nk({state:e,result:f,previousSelectedIds:s,selection:a,generation:c})):void 0}function _Z(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),xt.warn(o.message);for(let[o,i]of r.namesById??[])e.registryConfigNamesById.set(o,i);r.filteredOutIds.length>0&&xt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function SZ(t){for(let e of t.servers){let r=`Skipped registry MCP server "${e.name}" (id=${e.id}): credential setup did not complete, likely because another server with the same name claimed it`;t.state.diagnostics.push({server:e.name,message:r,origin:"registry"}),xt.warn(r)}}function wZ(t){let{state:e,result:r}=t,n=r.servers.map(i=>{let s=e.sessionRegistryDisabledOverrides.get(i.name);return s===void 0?i:{...i,disabled:s}}),o=new Set([...n.map(i=>i.name),...r.retainedNames??[]]);for(let i of e.sessionRegistryDisabledOverrides.keys())o.has(i)||e.sessionRegistryDisabledOverrides.delete(i);return n}function ck(t){let{state:e,generation:r}=t;return n=>{if(e.registryGeneration!==r||n.id===void 0)return e.registryGeneration===r;let o=e.missingHostRemovalFences.get(n.id);return!e.sessionRemovedConfigIds.has(n.id)&&o?.registryGeneration!==r}}function Rm(t){let{state:e,result:r,selection:n,slotReservations:o}=t,i=new Set([...r.servers.map(s=>s.name),...r.retainedNames??[],...(n??[]).flatMap(s=>{let a=e.registryConfigNamesById.get(s);return a?[a]:[]})]);for(let[s,a]of o){if(i.has(s))continue;let c=D(e,s);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&Ee({state:e,name:s,owner:c.owner,revision:a.leaseRevision})}}async function bZ(t){let{state:e,result:r,selection:n,generation:o,connect:i,pi:s,slotReservations:a}=t;if(e.registryGeneration!==o){Rm({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),xt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await ak(e,r),e.registryGeneration!==o)return;let c=ck({state:e,generation:o}),u=r.servers.filter(c),d=await Promise.all(u.map(v=>$r({state:e,config:v,pi:s})));if(e.registryGeneration!==o)return;let l=u.filter((v,w)=>d[w]),f=u.filter((v,w)=>!d[w]);_Z({state:e,result:r,selection:n}),SZ({state:e,servers:f}),Rm({state:e,result:r,selection:n,slotReservations:a});let p=wZ({state:e,result:{...r,servers:l,retainedNames:[...r.retainedNames??[],...f.map(v=>v.name)]}});if(p.length===0)return;let h=p.filter(v=>{let w=e.servers.get(v.name);if((w?te(e,v.name,w):D(e,v.name))?.owner.kind==="local")return xt.info(`Registry install of "${v.name}" skipped: a local server claimed the name during discovery`),!1;let R=a.get(v.name)?.configRevision;if(R===void 0)return!0;let _=e.configDesiredRevisions.get(v.name);return _!==R?(xt.info(`Registry install of "${v.name}" skipped: slot revision advanced from ${R} to ${_} by a concurrent operation`),!1):!0});if(h.length===0)return;xt.info(`Registry discovery: connecting ${h.length} server(s)`);let g=(await i(h,e,e.currentLoad?.latestPi??s,c))?.find(v=>v.status==="failed");if(g)throw g.error instanceof Error?g.error:new Error(String(g.error));await RZ({state:e,pi:s,result:r,generation:o,connect:i})}async function RZ(t){let{state:e,pi:r,result:n,generation:o,connect:i}=t,s=n.nameCollisionFallbacks;if(!(!s||s.size===0))for(let[a,c]of s)for(let u of c){let d=await CZ({state:e,pi:r,generation:o,connect:i,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function CZ(t){let{state:e,pi:r,generation:n,connect:o,name:i,candidate:s}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(i);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===s.id)return"settled";if(!await $r({state:e,config:s,pi:r})||e.registryGeneration!==n)return"abort";xt.info(`MCP auth fallback: "${i}" (id=${c}) landed ${a.status}; connecting same-named config id=${s.id} in its place`),await o([s],e,e.currentLoad?.latestPi??r,ck({state:e,generation:n}));let d=e.servers.get(i);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===s.id&&d.status==="success"?"settled":"next"}async function PZ(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:i}=t,s=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;xt.warn(s),e.registryGeneration===n&&(await sk(e,[],o,new Set(i??[]),i!==void 0),e.selectedRegistryConfigIds=i,e.diagnostics.push({message:s,origin:"registry"}))}function xZ(t,e){for(let r of e??[]){let n=He(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Ye({state:t,domain:n,epoch:o?.epoch})}}async function EZ(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await bZ({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),Rm({state:t.resultArgs.state,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:t.resultArgs.state.registryGeneration===t.resultArgs.generation?t.resultArgs.selection:void 0,slotReservations:e}),r instanceof kt)throw xZ(t.resultArgs.state,t.resultArgs.selection),t.resultArgs.state.diagnostics.some(n=>n.message===r.message)||t.resultArgs.state.diagnostics.push({message:r.message,origin:"registry"}),r;await PZ({...t.resultArgs,error:r})}}function ra(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.discover??Nu,s=o?.connect??Je,a=n;if(!a||typeof a!="object"||Array.isArray(a))return xt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();let c=t.productType??a.productType??"cloud_agent";Array.isArray(a.configIds)&&Sg(r,new Set(a.configIds.map(He)));let u=fZ({state:r,configIds:a.configIds,admittedConfigs:t.admittedConfigs}),d=r.credentials;if(!(u||d)){xt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let w of a.configIds??[])Ye({state:r,domain:He(w)});return Promise.resolve()}let l=r.selectedRegistryConfigIds??[],f=pZ({state:r,previousSelectedIds:l,configIds:a.configIds}),p=hZ({parsedEmbedded:u,configIds:a.configIds}),h=++r.registryGeneration,m=Promise.all([dZ(r,a.configIds,p),f]).then(([w])=>w);mZ(r);let g=a.configIds?[...a.configIds]:void 0,v=vZ({state:r,configIds:a.configIds,parsedEmbedded:u,credentials:d,localServerNames:gZ(r),previousSelectedIds:l,selection:g,generation:h,discover:i,productType:c});return v?EZ({disposal:m,discovery:v,resultArgs:{state:r,previousSelectedIds:l,selection:g,generation:h,connect:s,pi:e}}):Promise.resolve()}import{logger as kZ}from"@hermes/logger";var an=kZ.child({prefix:"pi-mcp"});function TZ(t,e){Ye({state:t,domain:`user:${e}`}),t.liveEditGenerations??=new Map;let r=(t.liveEditGenerations.get(e)??0)+1;return t.liveEditGenerations.set(e,r),r}function AZ(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function fk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function MZ(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function uk(t){let{state:e,configId:r,fence:n,operation:o,retryPreviousFailureOnly:i=!1}=t,s=e.missingHostRemovals.get(r),a=(async()=>{let c=!1;if(s)try{await s.promise}catch{c=!0}i&&!c||await o()})().finally(()=>{e.missingHostRemovals.get(r)?.promise===a&&(MZ({state:e,configId:r,fence:n}),e.missingHostRemovals.delete(r))});return e.missingHostRemovals.set(r,{promise:a,liveEditGeneration:n.liveEditGeneration,registryGeneration:n.registryGeneration}),a}function pk(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function dk(t,e){for(let[r,n]of t.servers){if(t.targetMaterialStore?.has(e)&&!t.targetMaterialStore.trusts(n.config)&&!Kn(n.config))continue;let o=te(t,r,n);if(n.config.id===e&&o.owner.kind==="registry"&&o.host===n)return r}}function hk(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function $Z(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let i=D(e,r),s=n?Er(n):void 0;if(i===void 0){Ke(e,r);return}let a=i.host===void 0&&i.owner.kind==="registry"&&s?.kind==="registry"&&i.owner.identity===s.identity,c=o?.incumbent.owner.kind==="registry"&&s?.kind==="registry"&&o.incumbent.owner.identity===s.identity;if(!a&&!c)return;(o?.settled&&i.retirement===o?ag({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):Ee({state:e,name:r,owner:i.owner,revision:i.revision}))&&D(e,r)===void 0&&(hk(e,r),Ke(e,r))}async function Cm(t){let{state:e,configId:r,pi:n,report:o,sourceFence:i}=t,s=e.registryCredentialConfigsById.get(r),a=s?.name;if(!s||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw an.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=D(e,a),u=Er(s),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ke(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let g=D(e,a)?.retirement===d?d:void 0,v=g?.result;if(d&&v?.status==="failed"&&v.transportDisposed!==!0){let w=v.error instanceof Error?v.error:new Error(String(v.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw an.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await pi(e,a,r,s)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw an.warn(b),e.diagnostics.push({server:a,message:b}),w}fk({state:e,configId:r,fence:i})&&(pk(e,r),$Z({state:e,name:a,config:s,retirement:g})),an.info(`Live MCP remove-server: config id ${r} resolved to no live server (already removed or unknown id)`),o(e.currentLoad?.latestPi??n,e)}function lk(t){let{state:e,name:r,operation:n,result:o}=t;if(o.status!=="rejected")return;let i=`Live MCP remove-server failed to ${n} ${r}: ${o.reason instanceof Error?o.reason.message:String(o.reason)}`;an.warn(i),e.diagnostics.push({server:r,message:i})}async function IZ(t){let{state:e,name:r,configId:n,server:o}=t,[i]=await Promise.allSettled([o.dispose({strict:!0})]);if(lk({state:e,name:r,operation:"dispose",result:i}),i.status==="rejected")return{removed:!1,failure:i.reason,transportDisposed:!1};let[s]=await Promise.allSettled([pi(e,r,n,o.config)]);return lk({state:e,name:r,operation:"detach",result:s}),s.status==="fulfilled"?{removed:!0,failure:void 0,transportDisposed:!0}:{removed:!1,failure:s.reason,transportDisposed:!0}}async function OZ(t){let{state:e,configId:r,name:n,pi:o,report:i,sourceFence:s}=t,a=e.servers.get(n),c=a?te(e,n,a):D(e,n);if(!a||!c||c.owner.kind!=="registry"||c.host!==a)return;e.registryConfigNamesById.set(r,n),e.registryCredentialConfigsById.set(r,{...a.config});let u=e.configDesiredRevisions.get(n),d=e.configDesiredSources.get(n),l=Ke(e,n),f=ut({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),an.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:g}=await IZ({state:e,name:n,configId:r,server:a});if(h&&fk({state:e,configId:r,fence:s})?pk(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),_e({state:e,name:n,retirement:f,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:g}}),h&&Ee({state:e,name:n,owner:c.owner,revision:c.revision})&&hk(e,n),i(p,e),!h)throw m}function Du(t){let{pi:e,state:r,data:n,deps:o}=t,i=n,s=i&&typeof i.configId=="string"?i.configId:"";if(!s)return an.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!t.replacement&&!no({state:r,configId:s,generation:i?.attachmentGeneration}))return an.info(`Ignoring stale live MCP remove-server command for config id ${s}`),Promise.resolve();let a=g=>t.replacement?g:_a({state:r,configId:s,generation:i?.attachmentGeneration,operation:g,wasApplied:()=>!0}),c=o?.report??N,u=dk(r,s),d=r.registryCredentialConfigsById.get(s),l=d?.name?D(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(s),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(s);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let g=r.missingHostRemovalFences.get(s);if(g)return a(uk({state:r,configId:s,fence:g,retryPreviousFailureOnly:!0,operation:()=>Cm({state:r,configId:s,pi:e,report:c,sourceFence:g})}))}let h=TZ(r,s);if(u===void 0&&d===void 0)return a(Cm({state:r,configId:s,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=AZ({state:r,configId:s,liveEditGeneration:h});return a(uk({state:r,configId:s,fence:m,operation:()=>{let g=dk(r,s);return g===void 0?Cm({state:r,configId:s,pi:e,report:c,sourceFence:m}):OZ({state:r,configId:s,name:g,pi:e,report:c,sourceFence:m})}}))}import{createHash as zZ}from"node:crypto";var NZ=/^[1-9][0-9]*$/,DZ=/^[a-f0-9]{64}$/,LZ=new Set(["version","operation","config_id","server_name","transport","url","command","args","use_shell_interpolation","route_revision","binding_generation","ownership","auth_type","vm_id","connection_version","execution_principal_id","execution_principal_type","access_token","static_secrets"]);function fe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pm(t){return typeof t=="string"&&NZ.test(t)&&t.length<=19&&BigInt(t)<=9223372036854775807n}function Em(t){return fe(t)&&typeof t.vmId=="string"&&t.vmId.length>0&&t.vmId.length<=256&&t.vmId.trim()===t.vmId&&Pm(t.connectionVersion)}function jZ(t){if(t.version===2&&t.transport==="stdio")return(t.url===void 0||t.url==="")&&typeof t.command=="string"&&t.command.trim().length>0&&!jr(t.command)&&Array.isArray(t.args)&&t.args.every(e=>typeof e=="string"&&!jr(e))&&typeof t.use_shell_interpolation=="boolean"&&t.auth_type!=="oauth";if(t.version!==1||t.transport!=="http"&&t.transport!=="sse"||typeof t.url!="string"||t.command!==void 0||t.args!==void 0||t.use_shell_interpolation!==void 0)return!1;try{let e=new URL(t.url);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password&&!e.hash}catch{return!1}}function gk(t){if(!(!fe(t)||Object.keys(t).some(e=>!LZ.has(e)))&&!(!jZ(t)||t.operation!=="install"&&t.operation!=="retire"||t.auth_type!=="oauth"&&t.auth_type!=="static"&&t.auth_type!=="none")){for(let e of["config_id","server_name","vm_id","execution_principal_id"])if(typeof t[e]!="string"||t[e].length===0)return;if(!(typeof t.route_revision!="string"||!DZ.test(t.route_revision)||!Pm(t.connection_version))&&!(t.execution_principal_type!==void 0&&(typeof t.execution_principal_type!="number"||!Number.isInteger(t.execution_principal_type)||t.execution_principal_type<0||t.execution_principal_type>2147483647))&&!(t.ownership==="uncredentialed"?t.auth_type!=="none"||t.binding_generation!=="0":t.ownership!=="recipient"||t.auth_type==="none"||!Pm(t.binding_generation))){if(t.operation==="retire"||t.auth_type==="none"){if(t.access_token!==void 0||t.static_secrets!==void 0)return}else if(t.auth_type==="oauth"){if(typeof t.access_token!="string"||t.access_token.length===0||t.static_secrets!==void 0)return}else if(t.access_token!==void 0||!fe(t.static_secrets)||Object.keys(t.static_secrets).length===0||Object.values(t.static_secrets).some(e=>typeof e!="string"||e.trim().length===0))return;return{...t,execution_principal_type:t.execution_principal_type??0}}}}function xm(t,e){return t.execution_principal_id===e.execution_principal_id&&t.execution_principal_type===e.execution_principal_type}function FZ(t,e){return t.transport==="stdio"&&e.transport==="stdio"?t.command===e.command&&t.use_shell_interpolation===e.use_shell_interpolation&&t.args.length===e.args.length&&t.args.every((r,n)=>r===e.args[n]):t.transport===e.transport&&t.url===e.url}function UZ(t,e){return t.transport==="stdio"&&e.type==="stdio"?e.command===t.command&&e.useShellInterpolation===t.use_shell_interpolation&&e.args.length===t.args.length&&e.args.every((r,n)=>r===t.args[n]):e.type!=="stdio"&&t.transport===e.type&&e.url===t.url&&e.auth==="oauth"==(t.auth_type==="oauth")}function mk(t,e){return xm(t,e)&&t.config_id===e.config_id&&t.server_name===e.server_name&&FZ(t,e)&&t.route_revision===e.route_revision&&t.ownership===e.ownership&&t.auth_type===e.auth_type}function qZ(t,e){let r=Object.keys(t.static_secrets??{});return t.access_token===e.access_token&&r.length===Object.keys(e.static_secrets??{}).length&&r.every(n=>t.static_secrets?.[n]===e.static_secrets?.[n])}function HZ(t,e){let r=zi((e.type==="stdio"?e.env:e.headers)??{}),n=Object.keys(t.static_secrets??{});return t.auth_type==="static"?r.length>0&&r.length===n.length&&n.every(o=>r.includes(o)):r.length===0}var Lu=class{#t=new Map;#o=new WeakSet;#r=new WeakSet;#e;#n;#i=Symbol("mcp-connection");get epoch(){return this.#i}get hasConnection(){return this.#e!==void 0}revokeConnection(){this.#t.clear(),this.#r=new WeakSet,this.#n=void 0,this.#e=void 0,this.#i=Symbol("mcp-connection")}setConnection(e){return Em(e)?this.#e?.vmId===e.vmId&&this.#e.connectionVersion===e.connectionVersion?!1:(this.revokeConnection(),this.#e={...e},!0):(this.revokeConnection(),!0)}has(e){return this.#t.has(e)||[...this.#t.values()].some(r=>r.material.server_name===e)}hasTargetProvenance(e){return this.#o.has(e)}trusts(e){return this.#r.has(e)}retainSelection(e){for(let[r,n]of this.#t)e.has(r)||this.#r.delete(n.config)}config(e){return this.#t.get(e)?.config}validate(e,r,n){let o=this.#t.get(e.config_id);if(!this.#e||e.vm_id!==this.#e.vmId||e.connection_version!==this.#e.connectionVersion||this.#n&&!xm(e,this.#n))return!1;if(e.operation==="retire")return!n&&!!o&&this.#r.has(r)&&o.config===r&&xm(e,o.material)&&e.binding_generation===o.material.binding_generation;if(r.disabled||!r.registrySource||r.vfsSource||r.id!==e.config_id||r.name!==e.server_name||!UZ(e,r)||!n&&(!o||!this.#r.has(r)||!mk(e,o.material))||!HZ(e,r))return!1;if(!o)return!0;let i=BigInt(e.binding_generation)-BigInt(o.material.binding_generation);return i>=0n&&(i!==0n||o.material.operation==="install"&&mk(e,o.material)&&qZ(e,o.material))}commit(e,r){let n=Object.freeze({...e,...e.transport==="stdio"?{args:Object.freeze([...e.args])}:{},...e.static_secrets?{static_secrets:Object.freeze({...e.static_secrets})}:{}});this.#t.set(e.config_id,{material:n,config:r,epoch:Symbol("target-material")}),this.#r.add(r),this.#o.add(r),this.#n??={...n,access_token:void 0,static_secrets:void 0}}auth(e){if(!this.#r.has(e)||!e.id)return;let r=this.#t.get(e.id)?.epoch,n=()=>{let i=this.#t.get(e.id??"");if(!i||!this.#r.has(e)||i.epoch!==r||i.material.operation!=="install"||i.config!==e||i.material.vm_id!==this.#e?.vmId||i.material.connection_version!==this.#e.connectionVersion)throw new Error("MCP target material is unavailable");return i.material},o=n();return{...o.ownership==="recipient"?{credential:Object.freeze({revision:o.binding_generation,domain:`recipient:${o.config_id}`})}:{},validateUrl:i=>{let s=n();if(s.transport==="stdio")throw new Error("MCP target destination is unavailable");let a=new URL(i),c=new URL(s.url);if(a.username||a.password||a.hash||(s.transport==="sse"?a.origin!==c.origin:a.href!==c.href))throw new Error("MCP target destination is unavailable")},getSecret:async i=>n().static_secrets?.[i],headers:()=>{let i=n();return i.auth_type==="oauth"?{Authorization:`Bearer ${i.access_token}`}:{}}}}};function yk(t){return zZ("sha256").update(t).digest("hex")}function GZ(t,e){let r=Array.isArray(t.configIds)?new Set(t.configIds.filter(o=>typeof o=="string")):void 0,n=new Map;for(let o of e.values()){let i=JSON.parse(o);if(!(fe(i)&&fe(i.config))||typeof i.id!="string"||typeof i.config.name!="string"||r&&!r.has(i.id))continue;let s=n.get(i.config.name)??[];s.push(i.id),n.set(i.config.name,s)}return n}function ZZ(t,e){if(e.length<=1)return!0;let r=ha(t);return r.kind==="valid"&&e.filter(n=>He(n)===r.ownerDomain).length===1}function vk(t){let e=new Map;if(t===void 0)return e;if(typeof t!="string")throw new Error("Invalid MCP config map");let r=JSON.parse(t);if(!Array.isArray(r)||r.some(a=>!fe(a)||!fe(a.config)))throw new Error("Invalid MCP config map");let n=0,o=!1,i=!1,s=-1;for(let a=0;a<t.length;a++){let c=t[a];if(o){i?i=!1:c==="\\"?i=!0:c==='"'&&(o=!1);continue}if(c==='"'&&(o=!0),(c==="{"||c==="[")&&(n===1&&(s=a),n++),(c==="}"||c==="]")&&(n--,n===1&&s>=0)){let u=t.slice(s,a+1),d=JSON.parse(u);if(!fe(d)||typeof d.id!="string"||e.has(d.id))throw new Error("Invalid MCP config map");e.set(d.id,u),s=-1}}return e}function BZ(t,e){let r=t.args===void 0?[]:t.args,n=t.use_shell_interpolation===void 0?!1:t.use_shell_interpolation;return(t.url===void 0||t.url==="")&&t.command===e.command&&Array.isArray(r)&&r.length===e.args.length&&r.every((o,i)=>o===e.args[i])&&n===e.use_shell_interpolation}function WZ(t){return t.env!==void 0&&(!fe(t.env)||Object.values(t.env).some(e=>typeof e!="string"))?!1:t.timeout_ms===void 0||typeof t.timeout_ms=="number"&&Number.isSafeInteger(t.timeout_ms)&&t.timeout_ms>=0}function VZ(t,e,r){if(typeof t!="string"||yk(t)!==e.route_revision)return;let n=JSON.parse(t);if(!fe(n)||!fe(n.config)||n.id!==e.config_id||n.config.auth_type!=={oauth:2,static:3,none:1}[e.auth_type])return;let i=n.config;if(i.type!==void 0&&i.type!==e.transport||i.name!==e.server_name||i.disabled!==void 0&&i.disabled!==!1||!WZ(i))return;let s={id:e.config_id,name:e.server_name,registrySource:"tenant",...i.timeout_ms?{timeoutMs:i.timeout_ms}:{}},a=i.env?Object.freeze({...i.env}):void 0;if(e.transport==="stdio"){if(!BZ(i,e))return;let c=[...e.args];return Object.freeze(c),Object.freeze({...s,type:"stdio",command:e.command,args:c,useShellInterpolation:e.use_shell_interpolation,cwd:r??process.cwd(),env:a})}if(i.url===e.url)return Object.freeze({...s,type:e.transport,url:e.url,...e.auth_type==="oauth"?{auth:"oauth"}:{},...a?{headers:a}:{}})}function _k(t,e,r){if(!fe(e)||!fe(e.credentials))return;let n=t.targetMaterialStore;if(!n?.hasConnection)return;let o=Object.entries(e.credentials),i=e.kind==="boot";if(!i&&(e.version!==1||o.length!==1||e.kind!=="add"&&e.kind!=="restart"||e.hasLegacySecrets===!0))return;let s=i?vk(e.configsJson):new Map;if(i&&(e.headerSecrets!==void 0&&(!fe(e.headerSecrets)||Object.values(e.headerSecrets).some(l=>l!==null&&typeof l!="string"))||e.configIds!==void 0&&(!Array.isArray(e.configIds)||e.configIds.some(l=>typeof l!="string"||!l)||new Set(e.configIds).size!==e.configIds.length)))return;let a=i?GZ(e,s):void 0,c=[],u=new Set,d;for(let[l,f]of o){if(i&&!(fe(f)&&Object.hasOwn(f,"target_material"))){let b=a?.get(l)??[];(!fe(f)||b.length===0&&(e.configsJson!==void 0||e.configIds!==void 0)||!ZZ(f,b)||n.has(l)||wr({store:t.tokens,serverName:l,proto:f,options:{requireEqualMaterial:!0}}).decision==="reject")&&r?.add(l);continue}if(!fe(f)||Object.entries(f).some(([b,R])=>b!=="target_material"&&b!=="passive_install"&&R!==""))return;let p=gk(f.target_material);if(!p||p.server_name!==l||u.has(p.config_id))return;let h=JSON.stringify([p.execution_principal_id,p.execution_principal_type]);if(d!==void 0&&d!==h||(d=h,u.add(p.config_id),!i&&e.target!==(e.kind==="add"?p.config_id:l)))return;let m=i||e.kind==="add";if(m&&p.operation!=="install")return;let g=m?VZ(i?s.get(p.config_id):e.config,p,t.workspaceRoot):n.config(p.config_id);if(!g||!n.validate(p,g,m)||i&&Array.isArray(e.configIds)&&!e.configIds.includes(p.config_id))return;let v=t.servers.get(g.name),w=t.hostLeases.get(g.name);if(v&&!n.trusts(v.config)&&!Kn(v.config)&&!n.hasTargetProvenance(v.config)||v&&(v.config.registrySource===void 0||v.config.vfsSource!==void 0||v.config.id!==p.config_id)||v&&(!w||w.host!==v)||w&&(w.owner.kind!=="registry"||w.owner.identity!==`user:${p.config_id}`))return;if(Object.hasOwn(f,"passive_install")){let b=f.passive_install,R=at(t,g.name,g.id);if(e.kind!=="restart"||p.operation!=="install"||p.auth_type!=="oauth"||p.ownership!=="recipient"||!v||!fe(b)||!Number.isSafeInteger(b.host_generation)||Number(b.host_generation)<=0||R.serverGeneration!==b.host_generation||R.credentialRevisionDomain!==`recipient:${p.config_id}`||typeof b.observed_binding_generation!="string"||!/^[1-9][0-9]*$/.test(b.observed_binding_generation)||R.credentialRevision!==b.observed_binding_generation||BigInt(p.binding_generation)<=BigInt(b.observed_binding_generation))return}c.push({material:p,config:g})}if(!(i&&[...s.keys()].some(l=>n.has(l)&&!u.has(l)&&(!Array.isArray(e.configIds)||e.configIds.includes(l))))){if(i&&c.length>0){let l=ti(e.configsJson,t.workspaceRoot,new Map(c.map(({material:p,config:h})=>[p.config_id,h])));if(!l)return;let f=new Map;for(let{name:p}of l.allConfigsById.values())f.set(p,(f.get(p)??0)+1);for(let{material:p}of c){let h=l.allConfigsById.get(p.config_id);if(!h?.config||f.get(h.name)!==1)return}}return c}}async function KZ(t){let{pi:e,state:r,data:n}=t;if(!fe(n)||n.kind!=="boot")return!1;let o=r.targetMaterialStore;if(!o?.hasConnection)return!1;let i,s,a=new Set;try{i=_k(r,n,a);let h=n.configsJson===void 0?void 0:JSON.parse(n.configsJson);if(h!==void 0&&!Array.isArray(h))return!1;s=h}catch{return!1}if(!i)return!1;let c=o.epoch,u=()=>o.epoch===c,d=n.configIds;d===void 0&&s!==void 0&&(d=[...vk(n.configsJson).keys()]);let l=new Map(i.map(h=>[h.material.config_id,h.config]));o.retainSelection(new Set(l.keys()));for(let{material:h,config:m}of i)o.commit(h,m);r.mcpAttachCloudSignaled||(r.mcpAttachCloudSignaled=!0,Mu(r.currentLoad?.latestPi??e,r)),r.embeddedRegistryConfigs=s;let f=ra({pi:e,state:r,data:{configIds:d},admittedConfigs:l,deps:{connect:(h,m,g,v)=>{if(!u())return Promise.resolve([]);let w=h.map(b=>{let R=b.id?l.get(b.id):void 0;if(!R&&b.id&&o.has(b.id))throw new Error("MCP target material is unavailable");return R??b});return Je(w,m,g,b=>u()&&(v?.(b)??!0))}}});if(a.size>0&&r.diagnostics.push({origin:"registry",message:`Withheld ${a.size} MCP OAuth credential(s) that failed boot admission: ${[...a].join(", ")}`}),u()&&typeof n.onAdmitted=="function"&&n.onAdmitted(u,a),await f,!u())return!1;let p=r.currentLoad?.latestPi??e;return N(p,r),Se(r),Qo(p,r),!0}async function JZ(t){let{pi:e,state:r,data:n}=t;if(!fe(n))return!1;if(n.kind==="boot")return KZ(t);let o;try{o=_k(r,n)}catch{return!1}let i=o?.[0],s=r.targetMaterialStore;return!i||o?.length!==1||!s?!1:await XZ({pi:e,state:r,data:n,candidate:i,store:s})}function YZ(t,e){let r=fe(t.credentials)?t.credentials[e]:void 0;return fe(r)&&Object.hasOwn(r,"passive_install")}async function XZ(t){let{pi:e,state:r,data:n,candidate:o,store:i}=t,{material:s,config:a}=o,c={state:r,configId:s.config_id,generation:n.attachmentGeneration};if(n.kind==="add"){if(!no(c))return!1}else if(r.sessionRemovedConfigIds.has(s.config_id))return!1;let u=YZ(n,s.server_name),d=i.epoch,l=r.attachmentCommandGenerations?.get(s.config_id),f,p=()=>i.epoch===d&&(f===void 0||r.liveEditGenerations?.get(s.config_id)===f)&&r.attachmentCommandGenerations?.get(s.config_id)===l,h=!1;try{i.commit(s,a);let m=n.kind==="add"||r.dynamicallyAddedConfigIds.has(s.config_id);if([...r.servers.values()].find(v=>v.config.id===s.config_id&&v.config.registrySource!==void 0&&(i.hasTargetProvenance(v.config)||Kn(v.config)))){let v=Du({pi:e,state:r,data:{configId:s.config_id},replacement:!0});u&&(f=r.liveEditGenerations?.get(s.config_id)),await v}return!p()||(r.sessionRemovedConfigIds.delete(s.config_id),m?r.dynamicallyAddedConfigIds.add(s.config_id):r.dynamicallyAddedConfigIds.delete(s.config_id),s.operation!=="retire"&&(await Je([a],r,e,p),!p()))?!1:(N(e,r),h=!0,!0)}finally{n.kind==="add"&&(h?hd(c):va(c))}}function na(t,e){let r=t.mcpConnectionEpoch,n=(t.targetMaterialQueue??Promise.resolve()).then(()=>t.mcpConnectionEpoch===r?e():void 0).then(()=>{});return t.targetMaterialQueue=n.catch(()=>{}),n}function QZ(t,e){t.registryGeneration++,gg(t),t.headerSecrets={},t.headerSecretFailures={},t.mcpCatalog=void 0,t.mcpAttachDisabled=!1,t.catalogRefreshInFlight=void 0;let r=[];for(let[n,o]of t.hostLeases){if(o.owner.kind!=="registry")continue;t.configRevisions.set(n,(t.configRevisions.get(n)??0)+1),t.tokens.clearLocalCredential(n);let i=t.oauthCredentialDomains.get(n);i&&t.oauthCredentialRevisions.delete(i),t.oauthCredentialDomains.delete(n),t.credentialRevisions.delete(n),t.stagedOAuthCredentials.delete(n);let s=o.host;if(!s)continue;s.beginDisposal?.();let a=ut({state:t,name:n,owner:o.owner,revision:o.revision,host:s});a&&r.push(s.dispose({strict:!0}).then(()=>{_e({state:t,name:n,retirement:a,result:{status:"retired"}})},c=>{_e({state:t,name:n,retirement:a,result:{status:"failed",error:c}}),t.diagnostics.push({origin:"registry",message:"Previous MCP connection could not be retired safely"}),N(e,t)}))}t.targetMaterialQueue=Promise.all([t.targetMaterialQueue??Promise.resolve(),...r]).then(()=>{}),N(e,t)}function Sk(t,e){e.targetMaterialListenerBound||(e.targetMaterialListenerBound=!0,e.targetMaterialStore??=new Lu,t.events.on("augment:mcp-target-connection",r=>{let n=e.targetMaterialStore;if(n){if(Em(r)){if(!n.setConnection(r))return}else n.revokeConnection(),e.diagnostics.push({origin:"registry",message:"MCP connection metadata is invalid; previous credential authority was revoked"});e.mcpConnectionEpoch=n.epoch,QZ(e,t)}}),t.events.on("augment:mcp-target-material",r=>{let n=e.targetMaterialStore?.epoch;na(e,async()=>{if(e.targetMaterialStore?.epoch!==n)return;!await JZ({pi:t,state:e,data:r})&&e.targetMaterialStore?.epoch===n&&(e.diagnostics.push({origin:"registry",message:"MCP configuration update was rejected; a fresh authorized configuration is required"}),N(t,e))}).catch(()=>{e.targetMaterialStore?.epoch===n&&(e.diagnostics.push({origin:"registry",message:"MCP snapshot application failed"}),N(t,e))})}))}import{logger as f2}from"@hermes/logger";import{execFile as km}from"node:child_process";import{win32 as Tm}from"node:path";import{logger as e2}from"@hermes/logger";var t2=5e3,r2=/^[a-z]:[\\/]/i,n2=/[<>:"|?*]/;function o2(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!r2.test(t)||!Tm.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||n2.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:Tm.join(Tm.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function i2(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function s2(t,e){switch(process.platform){case"darwin":return km("open",[t],e);case"win32":{let r=o2();return r?km(r,["-NoProfile","-NonInteractive","-EncodedCommand",i2(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return km("xdg-open",[t],e)}}function wk(t,e=t2){let r=e2.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let i=!1,s=null,a=setTimeout(()=>{if(!i){i=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{s?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);s=s2(o,c=>{i||(i=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as a2}from"node:http";function ju(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function bk(t){let e=ju(t.title),r=ju(t.heading),n=ju(t.message),o=t.details?ju(t.details):void 0,i=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
|
|
100
|
+
`)}pushCapturedLine(r){this._captured.push(r),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(r),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let r=this._captured.join("");return this._captured=[],r}getLogHistory(){return[...this._logHistory]}};function px(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new im(e,t.suppressStderr)}var nr=class extends Error{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}},sm=new uH;function am(t,e){return sm.run(t,e)}function lH(t){sm.getStore()?.onFailure?.(t)}function hx({getHeaders:t,transport:e,validateUrl:r}){if(t)return async(n,o)=>{r?.(n instanceof Request?n.url:String(n));let i=n instanceof Request?n.headers:void 0,s=new Headers(i);for(let[d,l]of new Headers(o?.headers).entries())s.set(d,l);for(let[d,l]of Object.entries(t()))s.set(d,l);let a=await fetch(n,{...o,headers:s,...r?{redirect:"error"}:{}});if(a.ok||o?.method?.toUpperCase()!=="POST")return a;await a.body?.cancel().catch(()=>{});let c=sm.getStore(),u=new nr({status:a.status,transport:e,operation:c?.operation??"transport"});throw lH(u),u}}function mx(t,e){let r=hx({getHeaders:e.getHeaders,validateUrl:e.validateUrl,transport:"http"});return new Tc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function gx(t,e){let r=hx({getHeaders:e.getHeaders,validateUrl:e.validateUrl,transport:"sse"});return new xc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function yx(){return new _u({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var vx=is,_x=Ae;function pt(t){return t instanceof nr&&t.status===401||(t instanceof rt||t instanceof Kr)&&t.code===401}function cm(t){return t instanceof k&&t.code===A.MethodNotFound}function Cu(t){return t instanceof Error&&(t.name==="ZodError"||t.name==="$ZodError")&&Array.isArray(t.issues)}function Sx(t){return t instanceof k&&t.code===A.RequestTimeout}function um(t){return t instanceof k&&t.code===A.ConnectionClosed}var fH=new Set(["ENOENT","EACCES","ETXTBSY","EAGAIN"]);function wx(t){if(um(t))return!0;let{code:e,syscall:r}=t??{};return typeof e=="string"&&typeof r=="string"&&r.startsWith("spawn")&&fH.has(e)}var pH=new Map([["ECONNREFUSED","connection_refused"],["ECONNRESET","connection_reset"],["EPIPE","connection_reset"],["UND_ERR_SOCKET","connection_reset"],["ENOTFOUND","dns"],["EAI_AGAIN","dns"],["ETIMEDOUT","timeout"],["UND_ERR_CONNECT_TIMEOUT","timeout"],["UND_ERR_HEADERS_TIMEOUT","timeout"],["UND_ERR_BODY_TIMEOUT","timeout"]]),hH=/^(CERT_|ERR_TLS_|ERR_SSL_|UNABLE_TO_|DEPTH_ZERO_SELF_SIGNED_CERT$|SELF_SIGNED_CERT_IN_CHAIN$)/;function mH(t){switch(t){case 401:return"auth";case 403:return"permission";case 404:return"not_found";case 429:return"rate_limited";case 408:case 504:case 524:return"timeout";default:return t>=500&&t<=599?"upstream_5xx":void 0}}function gH(t){if(t instanceof nr)return t.status;if(t instanceof rt||t instanceof Kr)return typeof t.code=="number"?t.code:void 0}function ux(t){if(typeof t=="string")return pH.get(t)??(hH.test(t)?"tls":void 0)}function yH(t){if(typeof t!="object"||t===null)return!1;let{error:e,id:r}=t;return typeof e=="object"&&e!==null&&r!==void 0}function dm(t){let e=!1,r=!1,n=t.onclose,o=t.onmessage;return t.onclose=()=>{e=!0,n?.()},t.onmessage=(i,s)=>{!e&&yH(i)&&(r=!0),o?.(i,s)},()=>({connectionClosed:e&&!r,serverErrorResponse:r})}function vH(t){return t.data?.timeout===tp}function _H(t,e,r){return t.code===A.RequestTimeout?vH(t)&&r?.serverErrorResponse!==!0?"timeout":void 0:t.code===A.ConnectionClosed?r?.connectionClosed!==!0||r.serverErrorResponse?void 0:e==="stdio"?"process_exited":"connection_reset":"protocol_error"}function bx(t,e,r){let n=gH(t);if(n!==void 0)return mH(n);if(t instanceof k)return _H(t,e,r);if(Cu(t))return"protocol_error";let{code:o,syscall:i,cause:s}=t??{};return typeof i=="string"&&i.startsWith("spawn")?o==="ENOENT"||o==="EACCES"?"command_not_found":void 0:ux(s?.code)??ux(o)}var SH=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function Rx(t){if(t instanceof k&&(t.code===A.RequestTimeout||t.code===A.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return SH.some(r=>e.includes(r))}function Cx(t){return t instanceof k&&(t.code===A.MethodNotFound||t.code===A.InvalidRequest)}function lm(t){return t instanceof nr&&t.transport==="http"&&t.status===404||t instanceof rt&&t.code===404}var wH=/^[A-Za-z][A-Za-z0-9_.]{0,63}$/,bH=/^E[A-Z0-9_]{1,62}$/,RH=/^[A-Za-z0-9._:-]{1,64}$/,CH={"https:":443,"http:":80};function Px(t,e){let r={};if(t.type==="stdio")r.networkTransport="pipe";else{r.networkTransport="tcp",r.networkProtocolName="http";try{let n=new URL(t.url);r.serverAddress=n.hostname;let o=n.port?Number(n.port):CH[n.protocol];o!==void 0&&(r.serverPort=o)}catch{}}return e?.protocolVersion&&RH.test(e.protocolVersion)&&(r.mcpProtocolVersion=e.protocolVersion),r}function PH(t){let e;return t instanceof nr?e=t.status:(t instanceof rt||t instanceof Kr)&&(e=t.code),typeof e=="number"&&e>=100&&e<600?e:void 0}function EH(t,e){let r=t.data;return e.timeoutMs!==void 0&&r?.timeout===e.timeoutMs||e.maxTotalTimeoutMs!==void 0&&r?.maxTotalTimeout===e.maxTotalTimeoutMs}function Ex(t,e){if(t instanceof k){if(t.code===A.RequestTimeout&&e&&EH(t,e))return{errorType:"timeout"};if(t.code===A.ConnectionClosed&&e?.connectionClosed)return{errorType:"connection_closed"};let n=String(t.code);return{errorType:n,rpcStatusCode:n}}let r=PH(t);if(r!==void 0)return{errorType:String(r)};if(t instanceof De)return{errorType:"401"};if(t instanceof Error){if(t.name==="AbortError")return{errorType:"cancelled"};let n=t.cause;if(typeof n?.code=="string"&&bH.test(n.code))return{errorType:n.code};if(wH.test(t.name))return{errorType:t.name}}return{errorType:"_OTHER"}}var Q=kH.child({prefix:"pi-mcp"});function AH(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function MH(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&AH(r,o)})}var $H=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),IH=/^Node\.js v\d/,OH=/^[\w$.]*error[\w$]*:/i,xx=400,zH=63e3,kx=3,NH=/[\\/]lib[\\/]cli\.js/,DH="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.",Dx=Symbol("mcpReinitReported");function LH(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,Dx,{value:!0,enumerable:!1,configurable:!0})}function jH(t){return typeof t=="object"&&t!==null&&t[Dx]===!0}function FH(t){let e=t.filter(a=>!IH.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>NH.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return DH;let o=r.findIndex(a=>OH.test(a)),s=(o===-1?r.slice(-kx):r.slice(o,o+kx)).join(" / ");return s.length>xx?`${s.slice(0,xx)}\u2026`:s}function UH(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace($H,"").split(`
|
|
101
|
+
`).map(i=>i.trim()).filter(i=>i.length>0),o=FH(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var qH=6e5,HH=18e5,Tx=2147483647,GH=3e4,Ax=1e4,Lx=[250,1e3,2e3],Vn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},Qs=class extends Error{constructor(){super("MCP authentication refresh is pending in the backend; retry shortly");this.retryable=!0;this.name="BackendRefreshPendingError"}},ZH=250,Mx=3,BH=[200,500];function WH(t){for(let e of Object.values(t))if(Fr(e))return!0;return!1}function fm(t){let e=new Set;for(let r of t.matchAll(zi))e.add(Za(r[0]));return[...e].sort()}function pm(t){return[...new Set(t)].sort()}function $x(t,e){return mv(e.map(r=>t?.[r]??"missing"))}function VH({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n,args:o}){return pm([...e&&t?Ni(t):[],...n&&r?fm(r):[],...o.flatMap(fm)])}var Pu="${augmentToken}";function KH(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 JH(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var jx="(unknown uri)",hm="unknown",Ix=/=+$/,YH=/\s+/g,XH=/[-_]/g,QH=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Kn(t,e){return typeof t=="string"?t:e}function Fx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function eG(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function tG(t){let e=t.replace(YH,"").replace(XH,i=>i==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(Ix,"");if(r.toString("base64").replace(Ix,"")!==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 rG(t){let e=Ux(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Kn(e.uri,jx),n=Kn(e.mimeType,hm);if(typeof e.blob=="string"&&eG(n)){let i=tG(e.blob);if(i!==void 0)return i}let o=Fx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function nG(t){let e=Kn(t.type,"unknown");if(e==="resource")return rG(t);if(e==="audio"){let r=Kn(t.mimeType,hm),n=Fx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Kn(t.uri,jx),n=Kn(t.name,""),o=Kn(t.mimeType,hm);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function oG(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"&&QH.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function iG(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=oG(t);return e||{type:"text",text:Nx(nG(t))}}function sG(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(iG(n))}return e}function aG(t){return sv(t,zH)}function qx(t,e){let r=sG(t);if(r.length===0){let o=aG(e);o!==void 0&&r.push({type:"text",text:Nx(o)})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}function cG(t,e){let r=qx(e?.value(t.content),e?.value(t.structuredContent)),n=r.content.flatMap(o=>o.type==="text"?[{type:"text",text:e?.text(o.text)??""}]:[]);return n.length===0&&n.push({type:"text",text:"MCP stdio tool failed; no usable secret-free diagnostic content"}),{isError:!0,content:n,rawItemCount:r.rawItemCount}}var Hx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),uG=new Set([502,503,504]),Qo=Lx.length+1,dG=2;function lG(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 Ox(t,e){if(pt(t)||lm(t)||t instanceof vt)return;if(e==="stdio"&&wx(t))return{totalAttempts:Qo};let r=t?.cause?.code;if(typeof r=="string")return Hx.has(r)?{totalAttempts:Qo}:void 0;let n=t?.status??t?.code;return typeof n=="number"?n===524?{totalAttempts:dG}:uG.has(n)?{totalAttempts:Qo}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Qo}:void 0}var fG=80,pG=10,hG=/[^a-zA-Z0-9_.()-]/g,mG=new Set(["Error","McpError","McpSecretResolutionError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Eu(t){return t.replace(hG,"_").slice(0,fG)||"unknown"}function gG(t){let e=lG(t);if(e!==void 0&&(/^\d{3}$/.test(e)||Hx.has(e)))return e}function Ve(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=mG.has(e)?e:"Error",n=gG(t);return n===void 0?r:`${r}(${n})`}function yG(t,e,r){return t instanceof vt?new vt(Eu(t.serverName),t.missingKeys.slice(0,pG).map(Eu),void 0,t.reason).message:t instanceof nr?t.message:`MCP ${r} ${e} failed (${Ve(t)})`}function Wn(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Eu(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var mm={heartbeat_timeout:{tool:"The MCP server did not answer its heartbeat in time.",log:"MCP heartbeat timed out"},connection_closed:{tool:"The connection to the MCP server closed before the tool finished.",log:"MCP connection closed during tool execution"},heartbeat_failed:{tool:"The MCP heartbeat failed while the tool was running.",log:"MCP heartbeat failed during tool execution"}},vG="configured MCP server",_G=/^[A-Za-z][A-Za-z0-9 _.-]{0,79}$/,zx=/authorization|bearer|token|secret|password|passwd|api.?key|private.?key|cookie|credential|session/i,SG=/^(?:call_|toolu_)[A-Za-z0-9_-]{1,100}$/;function wG(t){return t!==void 0&&t.transport===void 0}var sn=class extends Error{constructor(e,r){super(mm[e].tool),this.category=e,this.serverDisplayName=r,this.stack=`Error: ${this.message}`}};function bG(t){return Sx(t)?"heartbeat_timeout":um(t)?"connection_closed":"heartbeat_failed"}var xu=class{constructor(e,r){this._lastFailureTransient=!1;this._tools=[];this._refreshPersisting=!1;this._disposing=!1;this._disposed=!1;this._inFlightCalls=new Set;this._wedgeRecoveryOwners=new Set;this._wedgePending=!1;this._wedgeRequired=!1;this._authEpoch=0;this._config=e,this._targetAuth=Y().targetMaterialStore?.auth(e),this._suppressStdioDiagnostics=e.type==="stdio"&&this._targetAuth?.credential!==void 0,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 targetCredentialProvenance(){return this._targetAuth?{credential:this._targetAuth.credential}:void 0}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get lastFailureTransient(){return this._lastFailureTransient}get lastErrorClass(){return this._lastErrorClass}get isDisposed(){return this._disposing||this._disposed}get suppressesProviderDiagnostics(){return this._suppressStdioDiagnostics}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._suppressStdioDiagnostics?[]:this._stdioTransport?.getLogHistory().map(e=>Ga(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=>{Q.warn(`MCP server "${this.name}" connect failed (${Ve(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=this._connectFailureMessage(r,"connect"),o=this._config.type==="stdio"&&!this._suppressStdioDiagnostics&&!pt(r)?Ga(UH(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ve(r))}}async _connectWithRetries(){let e=Qo,r={available:!0};for(let n=1;n<=Qo;n++)try{let o=await this._attemptConnect(r);return n>1&&Q.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let i=Ox(o,this._config.type);if(i===void 0||this._disposed||(e=Math.min(e,i.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let i=(Lx[r-1]??0)+Math.floor(Math.random()*(ZH+1));Q.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ve(e)}; retrying in ${i}ms`),await yn(i)}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){return pt(e)&&this.hasRefreshEligibleOAuthCredential()&&!!this._usableToken()?.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 Vn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let i=dm(n),s=yx();this._client=s;let a;try{if(await am({operation:"connect",onFailure:d=>{a=d}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(vx,()=>{Q.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let c=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=this._safeTools(c.tools??[]),this._status="success",this._lastError=void 0,this._lastFailureTransient=!1,this._lastErrorClass=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let u=Y();return u.tokens.clearAuthRequired(this.name),(u.servers.get(this.name)===void 0||u.servers.get(this.name)===this)&&ut(u,this.name),Q.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(c){let u=a??c;throw this._failedInitOrigin={error:u,origin:i()},await this._closeFailedInitialization(s,n),u}}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){Q.debug(`MCP server "${this.name}" close after failed connect attempt (${Ve(n)})`)}}}_connectFailureMessage(e,r){return this._suppressStdioDiagnostics?"MCP stdio connection failed; provider diagnostics are suppressed to protect credentials":yG(e,r,this._config.type)}_recordConnectFailure(e,r,n=this._connectFailureMessage(e,r)){this._lastFailureTransient=Ox(e,this._config.type)!==void 0;let o=this._failedInitOrigin;if(this._failedInitOrigin=void 0,this._lastErrorClass=bx(e,this._config.type,o!==void 0&&o.error===e?o.origin:void 0),e instanceof vt){this._status="failed";let i=Y();ci(i,this.name,e.reason,ct(i,this.name,this._config.id))}else if(e instanceof Qs||e instanceof Vn)this._status="failed";else if(pt(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(pt(e)){this._status="auth_required";let i=Y(),s=i.servers.get(this.name);(s===void 0||s===this)&&i.tokens.markAuthRequired(this.name)}else{this._status="failed";let i=this._connectFailureMessage(e,r);Ii(Wn(i,Ve(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config,r=Y().targetMaterialStore;if(!this._targetAuth&&(r?.has(e.name)||e.id&&r?.has(e.id)))throw new Error("MCP target provenance is unavailable");switch(this._targetAuth?.headers(),e.type){case"stdio":{let n=dx({...e,command:this._resolvedCommand??e.command,args:this._resolvedArgs??e.args}),o=lx(this._resolvedEnv??e.env);return px({command:n.command,args:n.args,env:o,cwd:e.cwd,...this._suppressStdioDiagnostics?{suppressStderr:!0}:{}})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return gx(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders(),...this._targetAuth?{validateUrl:this._targetAuth.validateUrl}:{}});default:return e}}_createHttpTransport(e,r){let n=mx(e,{headers:r,getHeaders:()=>this._buildAuthHeaders(),...this._targetAuth?{validateUrl:this._targetAuth.validateUrl}:{}});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?WH(r):!1,o=e.type==="stdio"&&Fr(e.command),i=e.type==="stdio"?e.args:[],s=i.some(Fr);if(!(n||o||s))return;let a=Y();if(!this._targetAuth&&!hv(a)){let u=VH({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o,args:i});throw new vt(this.name,u)}let c=this._targetAuth?.getSecret??fv(a);if(n&&r&&await this._resolveMapSecretRefs(r,c,e.type==="stdio"),o&&e.type==="stdio"&&(this._resolvedCommand=await this._resolveCommandSecretRefs(e.command,c,e.useShellInterpolation)),s){let u=[];for(let d of i)u.push(await this._resolveCommandSecretRefs(d,c,!1));this._resolvedArgs=u}}async _resolveMapSecretRefs(e,r,n){let o,i=new Set,s=async c=>{let u=await r(c);return this._suppressStdioDiagnostics&&typeof u=="string"&&i.add(u),u};try{o=await yv({configEnv:e,localEnv:n&&!this._targetAuth?fx():{},getSecret:s})}catch(c){throw Q.error(`MCP server "${this.name}" secret resolution failed (${Ve(c)})`),new vt(this.name,Ni(e),c,"transient")}let a=pm([...o.unresolvedKeys,...o.emptyKeys]);if(a.length>0)throw new vt(this.name,a,void 0,$x(o.failureReasons,a));if(this._targetAuth){if(this._disposed)return;this._targetAuth.headers()}n?(this._suppressStdioDiagnostics&&(this._toolErrorRedactor=ul(i)),this._resolvedEnv=o.resolved):this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r,n){let o;try{o=await vv(e,r,n)}catch(s){throw Q.error(`MCP server "${this.name}" command secret resolution failed (${Ve(s)})`),new vt(this.name,fm(e),s,"transient")}let i=pm([...o.unresolvedKeys,...o.emptyKeys]);if(i.length>0)throw new vt(this.name,i,void 0,$x(o.failureReasons,i));return o.resolved}_expandAugmentToken(){if(this._targetAuth)return;let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(s=>s.includes(Pu)))return;let o;if(KH(e.url)){let s=Y().credentials?.apiKey;s?o=s:this._recordTokenDiagnostic(`${Pu} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Pu} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${JH(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let i={};for(let[s,a]of Object.entries(r))i[s]=a.replaceAll(Pu,o);this._resolvedHeaders=i}_recordTokenDiagnostic(e,r){let n=Y();if(n.diagnostics.some(s=>s.server===this.name&&s.message===e))return;n.diagnostics.push({server:this.name,message:e});let i=`MCP server "${this.name}": ${e}`;r==="error"?Q.error(i):Q.warn(i)}_usableToken(){let e=Y();if(this._targetAuth||e.targetMaterialStore?.has(this.name)||this._config.id&&e.targetMaterialStore?.has(this._config.id))return;let r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!mt(n,this._config)))return r}_buildAuthHeaders(){if(this._targetAuth)return this._targetAuth.headers();let e=this._usableToken();return e?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}hasRefreshEligibleOAuthCredential(){let{config:e}=this;if(e.type!=="http"&&e.type!=="sse"||e.disabled||this._hostedCredentialProvenance!==void 0||!this._usableToken())return!1;if(e.auth==="oauth")return!0;let r=Y();return r.tokens.hasCredentialIdentity?.(this.name,Gt(r,this))===!0}async _maybeProactiveRefresh(){let e=Y(),r=e.tokens,{config:n}=this;(n.type==="http"||n.type==="sse")&&await r.ensureLoaded?.(this.name,Gt(e,this));let i=this._usableToken();i&&this.hasRefreshEligibleOAuthCredential()&&(i.accessToken&&!Id(i)||e.shouldProactivelyRefreshTokens&&(i.refreshToken?await this._refreshTokenDeduped():Ci(i)&&e.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=Y(),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:ct(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]),i=e.refreshes.get(o);if(i)return i.then(a=>a??{kind:"refreshed"});let s=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===s&&e.refreshes.delete(o),this._refreshPromise===s&&(this._refreshPromise=void 0)});return this._refreshPromise=s,e.refreshes.set(o,s),s}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=D(r,this.name)?.retirement?.incumbent.host,i=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&i&&(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 i=e.state.servers.get(this.name),s=e.state.tokens,a=s.get(this.name),c=e.state.credentialRevisions.get(this.name);if(s!==e.tokenStore||!i||!a||!mt(this._config,i.config))return;let u=Gt(e.state,i),d=n===void 0&&u===void 0||Tr(n,u);try{if(a===e.token&&d){s.commit(this.name,r,n),pn({state:e.state,name:this.name,revision:o});return}let l=await s.restoreAfterSupersededRefresh(this.name,r,a,n,o,u);if(!l||e.state.tokens!==s||e.state.servers.get(this.name)!==i||s.get(this.name)!==a||!Tr(Gt(e.state,i),u)||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain||s.reconcileCredentialIdentity?.(this.name,a,u)!==!0)return;pn({state:e.state,name:this.name,revision:l});let f=e.state.currentLoad?.latestPi;f&&N(f,e.state)}catch{Q.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof Z?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof Z)&&zd(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&ci(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),Q.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${Ve(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),ci(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=Gt(e.state,this),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Nd(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let i=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,i),{kind:"transient_failure"};e.tokenStore.commit(this.name,o,r),pn({state:e.state,name:this.name,revision:i}),ut(e.state,this.name);let s=e.state.currentLoad?.latestPi;return s&&N(s,e.state),Q.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:lm(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??{}),r=dm(e);try{await this._client.connect(e)}catch(n){throw this._failedInitOrigin={error:n,origin:r()},this._recordConnectFailure(n,"reinit"),n}Q.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e,r){if(this._config.type!=="http")return e();try{return await e()}catch(n){let o=this._isSessionExpiredError(n),i=this._reinitializingPromise!==void 0;if(!(o||i))throw n;Q.info(o?`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`),r?.("reconnecting");try{await this._reinitializeSession()}catch(s){throw Q.error(`MCP server "${this.name}" session re-initialization failed (${Ve(s)})`),LH(n),n}return r?.("running"),await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Vn}async _withAuthRetry(e,r,n){let o=this._config,i=Y(),s=ct(i,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),am({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||!pt(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new Qs;if(this._hostedCredentialProvenance!==void 0)throw new Vn;if(!this.hasRefreshEligibleOAuthCredential())throw this._markAuthRequired(d,s),d;if(l&&!l.available)throw this._markAuthRequired(d,s),d;Q.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`),n?.onPhase?.("reauthorizing");let f=i.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}this._authEpoch++,n?.onPhase?.("running");try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw pt(h)&&this._markAuthRequired(h,s),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._targetAuth?(this._config.type==="http"||this._config.type==="sse")&&this._config.auth==="oauth"&&this._targetAuth.credential!==void 0:this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=Y();ci(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ve(e)),Q.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed()},e.onerror=()=>{this._probeAfterError()})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},GH),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=Y(),r=ct(e,this.name,this._config.id),n=await this._runProbe();for(let s=2;s<=Mx&&n.outcome==="transient";s++)await yn(BH[s-2]??0),n=await this._runProbe();let o=ct(e,this.name,this._config.id),i=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return i&&n.outcome==="alive"&&ut(e,this.name,r),i&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?Q.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&Q.debug(`MCP server "${this.name}" startup verification ping remained transient after ${Mx} 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:Ax})},"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 (${Ve(r)})`,i=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?Q.debug(i):Q.warn(i),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":cm(e)||Cu(e)?"alive":pt(e)?"authFailure":Rx(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!e||this._disposed)return;let r=new Set(this._inFlightCalls),n=this._authEpoch;try{await e.ping({timeout:Ax})}catch(o){if(this._reinitializingPromise||this._disposed||this._authEpoch!==n||Cu(o)||cm(o)||pt(o))return;this._failInFlightCalls(new sn(bG(o),this._safeDiagnosticName()),!0,r)}}_probeAfterError(){if(this._errorProbe)return;let e=this._sendHeartbeat().finally(()=>{this._errorProbe===e&&(this._errorProbe=void 0)});this._errorProbe=e}_handleTransportClosed(){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(new sn("connection_closed",this._safeDiagnosticName())))}_diagnosticRedactor(){let e=Y().tokens.get(this.name),r=this._config.type==="stdio"?this._config.env:this._config.headers;return ul([...Object.values(r??{}),...Object.values(this._resolvedEnv??{}),...Object.values(this._resolvedHeaders??{}),e?.accessToken??"",e?.refreshToken??""])}_safeDiagnosticName(){let e=this.name;return!_G.test(e)||zx.test(e)||Ga(e)!==e||this._diagnosticRedactor().text(e)!==e||this._toolErrorRedactor&&this._toolErrorRedactor.text(e)!==e?vG:e}_safeCorrelationId(e){if(!(!e||!SG.test(e)||zx.test(e)||this._diagnosticRedactor().text(e)!==e||this._toolErrorRedactor&&this._toolErrorRedactor.text(e)!==e))return e}_wedgeRecoveryOwnership(e){let r=e.failure;return pt(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&&!pt(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,n){let o=[...this._inFlightCalls].filter(u=>!u.livenessRejected&&(!n||n.has(u)));if(o.length===0)return;if(!r){for(let u of o)u.livenessRejected=!0,u.reject(e);Q.warn(`MCP server "${this.name}" failing ${o.length} in-flight tool call(s)`);return}let i=o.map(u=>({call:u,state:this._wedgeRecoveryOwnership(u)})),s=i.some(({state:u})=>u==="recoverable"),a=!1;for(let{call:u,state:d}of i)d==="recoverable"||d==="owned"&&s||(u.livenessRejected=!0,a=!0,u.reject(e instanceof sn?e:u.failure??e));let c=o.filter(u=>u.livenessRejected).length;this._logInFlightFailure({error:e,unsettled:o,failedCount:c}),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=a):a&&this.onWedged?.()}_logInFlightFailure({error:e,unsettled:r,failedCount:n}){if(!(e instanceof sn)){Q.warn(`MCP server "${this.name}" failing ${n} in-flight tool call(s)`);return}if(n===0)return;let o=r.length===1?this._safeCorrelationId(r[0]?.correlationId):void 0;TH(mm[e.category].log,{failure_category:e.category,server_display_name:e.serverDisplayName,...o?{correlation_id:o}:{}})}_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=this._safeTools(e.tools??[]),n=!MH(this._tools,r);if(this._tools=r,n){Q.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){Q.warn(`MCP server "${this.name}" onToolsChanged handler threw (${Ve(o)})`)}}}catch(e){Q.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ve(e)}), keeping cached tools`)}}_safeTools(e){return this._suppressStdioDiagnostics?this._toolErrorRedactor?e.filter(r=>JSON.stringify(this._toolErrorRedactor?.value(r))===JSON.stringify(r)):[]:e}listTools(){return this._tools}async callTool(e,r,n,o,i){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>Tx)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${Tx}.`);let s=this._toolErrorRedactor,c={timeout:this._config.timeoutMs??qH,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??HH,onprogress:m=>{if(!this._suppressStdioDiagnostics){Q.debug(`MCP server "${this.name}" tool "${e}" progress: ${m.progress}${m.total===void 0?"":`/${m.total}`}${m.message?` - ${m.message}`:""}`);try{i?.onProgress?.(m)}catch{}}}},u=this._traceMeta(o?.toolCallId),d=i?.onPhase?m=>{try{i.onPhase?.(m)}catch{}}:void 0,l,f,p=new Promise((m,v)=>{f={reject:v,livenessRejected:!1,sessionRecoveryOwned:!1,correlationId:this._safeCorrelationId(o?.toolCallId)}});p.catch(()=>{}),f&&this._inFlightCalls.add(f);let g=this._withSessionRetry(()=>this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return l=this._client,this._client.callTool({name:e,arguments:r??{},...u},_x,c)},"tool_call",{call:f,onPhase:d}),d).then(m=>(f&&this._settleInFlightCall(f,!0,void 0),m),m=>{throw f&&this._settleInFlightCall(f,!1,m),m});try{let m=await Promise.race([g,p]);if(this._reportCallResult(i,m.isError),this._suppressStdioDiagnostics&&m.isError===!0)return cG({content:m.content,structuredContent:m.structuredContent},s);let v=qx(m.content,m.structuredContent);return{isError:m.isError===!0,content:v.content,rawItemCount:v.rawItemCount}}catch(m){return this._reportCallFailure(i,m,n,{connectionClosed:wG(l),timeoutMs:c.timeout,maxTotalTimeoutMs:c.maxTotalTimeout}),(n?.aborted||m instanceof Error&&m.name==="AbortError")&&this._throwCallCancellation(m),this._reportAndThrowToolError(m,e)}finally{f&&!this._wedgeRecoveryOwners.has(f)&&(f.failure=void 0,this._inFlightCalls.delete(f))}}_traceMeta(e){let r=e===void 0?void 0:xH(e);return r?{_meta:{traceparent:r}}:{}}_reportCallFacts(e,r){try{e?.onFacts?.({...Px(this._config,this._activeTransport),...r})}catch{}}_reportCallResult(e,r){this._reportCallFacts(e,r===!0?{errorType:"tool_error"}:{})}_reportCallFailure(e,r,n,o){let i;n?.aborted?i={errorType:"cancelled"}:r instanceof sn?i={errorType:r.category==="heartbeat_timeout"?"timeout":"connection_closed"}:i=Ex(r,o),this._reportCallFacts(e,i)}_throwCallCancellation(e){throw this._suppressStdioDiagnostics?Wn("MCP stdio tool call cancelled","AbortError"):e}_reportAndThrowToolError(e,r){if(e instanceof sn){let c=Wn(mm[e.category].tool,"Error");throw this._disposed||Ii(c,{server:e.serverDisplayName,op:"tool_call",transport:this._config.type}),c}if(this._suppressStdioDiagnostics){let c=Wn("MCP stdio tool call failed; provider diagnostics are suppressed to protect credentials","Error");throw this._disposed||Ii(c,{server:this.name,op:"tool_call",transport:"stdio"}),c}if(e instanceof Vn||e instanceof Qs)throw e;if(pt(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Eu(r),i=Ve(e),s=Cx(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 (${i}).${s}`;throw jH(e)||Ii(Wn(a,i),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),Wn(a,i)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._toolErrorRedactor=void 0,this._targetAuth&&(this._resolvedHeaders=void 0,this._resolvedEnv=void 0,this._resolvedCommand=void 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(this._suppressStdioDiagnostics){let o=Wn("MCP stdio close failed","Error");if(Q.debug(o.message),e?.strict)throw o;return}if(Q.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var ea=CG.child({prefix:"pi-mcp"}),PG=3,EG=6e4;function xG(t,e){let r=Date.now(),n=r-EG,o=(t.restartHistory.get(e)??[]).filter(i=>i>=n);return o.length>=PG?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}var kG=2e3,TG=6e4,Gx=20,AG=15e3,MG=.2;function gm(t){return t?.status==="failed"&&t.lastFailureTransient&&!t.isDisposed}function Vx(t,e){let r=t.transientReconnects?.get(e);r?.timer&&clearTimeout(r.timer),t.transientReconnects?.delete(e)}function Kx(t){for(let e of[...t.transientReconnects?.keys()??[]])Vx(t,e)}function ku(t,e,r){e.transientReconnects??=new Map;let n=e.servers.get(t);if(!gm(n)){Vx(e,t);return}let o=e.transientReconnects.get(t)??{attempt:0,timer:void 0};if(e.transientReconnects.set(t,o),o.timer&&o.host!==n&&(clearTimeout(o.timer),o.timer=void 0),o.timer||o.attempt>=Gx){o.timer||ea.warn(`MCP server "${t}" transient reconnects exhausted; restart required`);return}let i=Math.min(TG,kG*2**o.attempt),s=1+(Math.random()*2-1)*MG,a=Math.round(i*s);o.attempt+=1;let c=o.attempt;o.host=n;let u=setTimeout(()=>{if(o.timer===u){if(o.timer=void 0,o.host=void 0,e.servers.get(t)!==n){ku(t,e,e.currentLoad?.latestPi??r);return}gm(n)&&(ea.info(`MCP server "${t}" reconnecting after transient failure (attempt ${c}/${Gx})`),ir(t,e,e.currentLoad?.latestPi??r))}},a);o.timer=u,typeof u.unref=="function"&&u.unref()}async function Jx(t,e,r,n){if(n?.aborted)return!1;let o=e.reconnects?.get(t);if(o)return await Zx(o.catch(()=>{}),n),e.servers.get(t)?.status==="success";if(!gm(e.servers.get(t)))return!1;let i=e.transientReconnects?.get(t);i?.timer&&(clearTimeout(i.timer),i.timer=void 0,i.host=void 0),ea.info(`MCP server "${t}" reconnecting on demand for a tool call`);let s=ir(t,e,e.currentLoad?.latestPi??r).catch(()=>{});return await Zx(s,n),e.servers.get(t)?.status==="success"}async function Zx(t,e){let r,n,o=new Promise(i=>{r=setTimeout(i,AG),typeof r.unref=="function"&&r.unref(),n=()=>i(),e?.addEventListener("abort",n,{once:!0})});try{await Promise.race([t,o])}finally{r&&clearTimeout(r),n&&e?.removeEventListener("abort",n)}}function Bx(t){Wt(t),Pa(t)}async function $G(t,e,r){if(!xG(e,t)){ea.warn(`MCP server "${t}" automatic restart rate-limited`);return}ea.warn(`MCP server "${t}" wedged; recycling transport`),await ir(t,e,r)}function Tu(t,e,r){if(Yx(e)){Bx(t),N(t,e);return}Rd(t,r),Nr(e)&&Bx(t),N(t,e)}function Yx(t){return gi()||Pd(t)&&t.toolSearchLatched}function or(t,e,r){return od(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function ym(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,ut(t,e),t.authRefreshNeededReportKeys.delete(e),r}function IG(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),i=e.tokens.get(r.name),s=e.hostedCredentialOwnership?.get(r.name),a=o!==void 0&&s?.revision===o.revision,c=o!==void 0&&s?.domain===o.domain,u=o!==void 0&&s?.ownerDomain===o.ownerDomain,d=o!==void 0&&e.oauthCredentialDomains.get(r.name)===o.domain,l=o!==void 0&&vg(o.domain,r.id,o.ownerDomain);return o!==void 0&&i!==void 0&&s!==void 0&&a&&c&&u&&d&&l?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:s.accessTokenOnly}):s===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function vm(t){let{state:e,config:r,generation:n}=t;return new xu(r,IG({state:e,config:r,hostGeneration:n}))}function Ke(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 _m(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 Sm(t,e,r){return t.configDesiredRevisions.get(e)===r}function Wx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function wm(t,e,r,n){t.onStateChange=(a,c)=>{if(!or(t,e,r))return;let u={server:t.name,state:a,...c===void 0?{}:{errorType:c}};n.events.emit(RG,u),(a==="failed"||a==="auth_required")&&Yx(r)&&Wt(r.currentLoad?.latestPi??n)},t.onWedged=()=>{if(!or(t,e,r))return;let a=r.currentLoad?.latestPi??n;$G(t.name,r,a)};let o=t.hostedCredentialProvenance,i=t.targetCredentialProvenance?.credential,s;i&&(t.config.type==="http"||t.config.type==="sse")&&t.config.auth==="oauth"?s={serverGeneration:e,mcpConfigId:t.config.id,credentialRevision:i.revision,credentialRevisionDomain:i.domain}:o?.kind==="accepted"&&o.hostedAccessTokenOnly&&(s={serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}),t.onAuthRefreshNeeded=()=>{if(!or(t,e,r)||!s)return;let a=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==a&&(r.authRefreshNeededReportKeys.set(t.name,a),N(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!or(t,e,r)||!s)return;let a=r.statusFailureCategories.get(t.name);typeof a=="object"&&a.category==="auth_refresh_needed"&&ut(r,t.name,s)&&N(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{or(t,e,r)&&t.status==="success"&&Tu(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let a=r.currentLoad?.latestPi??n;Cd(a,t,e),a!==n&&Cd(n,t,e)}}async function Xx(t,e,r,n){let o=setTimeout(()=>{or(t,e,r)&&N(n(),r)},ua);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),or(t,e,r)&&(N(n(),r),ku(t.name,r,n()))}}async function Qx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function Au(t,e){if(e.status!=="installed")return!1;let r=D(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function OG(t){let{state:e,config:r,displaced:n,retirement:o}=t;_m(e,n.config),pi(e,r.name),n.beginDisposal?.();try{let i=sd(n.config,r)?Promise.resolve():gt(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;_e({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(i){throw _e({state:e,name:r.name,retirement:o,result:{status:"failed",error:i}}),i}}async function zG(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,i=dt({state:e,name:r.name,owner:n,revision:o,host:r});if(i){r.beginDisposal?.();try{await r.dispose({strict:!0}),_e({state:e,name:r.name,retirement:i,result:{status:"retired"}}),xe({state:e,name:r.name,owner:n,revision:o})}catch(s){throw _e({state:e,name:r.name,retirement:i,result:{status:"failed",error:s}}),s}}}async function NG(t){let{state:e,server:r,config:n,generation:o,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c}=t;return await r.connect(),or(r,o,e)?a?.(n)===!1?(await zG({state:e,server:r,owner:i,leaseRevision:s}),{status:"superseded",config:n}):(r.status==="success"&&Tu(c(),e,r),N(c(),e),ku(r.name,e,c()),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:s}):{status:"superseded",config:n}}function DG(t){let{state:e,config:r,configRevision:n,pi:o,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c}=t,u=D(e,r.name);if(!Sm(e,r.name,n)||u?.revision!==s||a?.(r)===!1)return xe({state:e,name:r.name,owner:i,revision:s}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=ym(e,r.name),l=vm({state:e,config:r,generation:d});return wm(l,d,e,o),fa({state:e,name:r.name,owner:i,revision:s,host:l})?{connection:NG({state:e,server:l,config:r,generation:d,owner:i,leaseRevision:s,sourceOwnership:a,activePi:c})}:(xe({state:e,name:r.name,owner:i,revision:s}),{status:"superseded",config:r})}function LG(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:i,activePi:s}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!Sm(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?te(r,a.name,u):D(r,a.name),l=kr(a,i),f=li({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>DG({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:s}),g=async()=>(f.displacedHost&&f.retirement?await OG({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await nd(f.retirement),h());return f.retirement?g():h()}async function Je(t,e,r,n,o,i){let s=()=>e.currentLoad?.latestPi??r,a=t.map(d=>({config:d,revision:o?.get(d.name)??Ke(e,d.name)})),c=a.map(async d=>{try{let l=await LG({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:i,activePi:s});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(()=>{N(s(),e)},ua);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u);for(let d of a)ku(d.config.name,e,s())}}async function jG({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!Wx(e,t,n))return!1;let i=o.config,s=te(e,t,o);if(!od(e,t,o))return!1;_m(e,i),pi(e,t);let a=dt({state:e,name:t,owner:s.owner,revision:s.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),_e({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw _e({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(D(e,t)?.revision!==s.revision||!Wx(e,t,n))return xe({state:e,name:t,owner:s.owner,revision:s.revision}),!1;let c=ym(e,t),u=vm({state:e,config:i,generation:c});if(wm(u,c,e,r),!fa({state:e,name:t,owner:s.owner,revision:s.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await Xx(u,c,e,d),or(u,c,e)&&u.status==="success"&&Tu(d(),e,u),!0}function ir(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 i=(async()=>{let s=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await jG({name:t,state:e,pi:r,configRevision:a}))return;s=c}while(s<(e.reconnectDesiredGenerations.get(t)??s))})().finally(()=>{e.reconnects.get(t)===i&&e.reconnects.delete(t)});return e.reconnects.set(t,i),i}async function FG(t){let{state:e,name:r,existing:n,config:o,retirement:i}=t;_m(e,n.config),pi(e,r),n.beginDisposal?.();try{let s=o!==void 0&&sd(n.config,o)?Promise.resolve():gt(e,r,n.config.id,n.config),c=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;i&&_e({state:e,name:r,retirement:i,result:{status:"retired"}})}catch(s){throw i&&_e({state:e,name:r,retirement:i,result:{status:"failed",error:s}}),s}}async function ek(t,e,r,n,o){let i=()=>e.currentLoad?.latestPi??r,{servers:s}=no(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=s.find(g=>g.name===t),c=Ke(e,t),u=e.servers.get(t),d=u?te(e,t,u):D(e,t),l={kind:"local",identity:a?.id??t},f=li({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await FG({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await nd(f.retirement),D(e,t)?.revision!==f.lease.revision||!Sm(e,t,c)){xe({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){xe({state:e,name:t,owner:l,revision:f.lease.revision}),N(i(),e);return}let p=ym(e,t),h=vm({state:e,config:a,generation:p});wm(h,p,e,r),fa({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await Xx(h,p,e,i),or(h,p,e)&&h.status==="success"&&Tu(i(),e,h))}async function ta(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>ir(n,e,r)))}finally{e.reconnecting=!1}}var tk=Symbol.for("__pi_mcp_registry_ingress__");function Mu(t){return Object.defineProperty(t,tk,{value:!0}),t}function Jn(t){return Object.getOwnPropertyDescriptor(t,tk)?.value===!0}function an(t){let{state:e,target:r,byConfigId:n=!1}=t;if(!r)return;let o=[...e.servers].filter(([u,d])=>d.config.id===r||!n&&u===r);if(o.length!==1)return;let i=o[0];if(!i)return;let[s,a]=i;if(a.config.id&&[...e.servers].some(([u,d])=>u!==s&&d.config.id===a.config.id))return;let c=D(e,s);if(!(c&&(c.host!==a||c.owner.kind==="registry"&&c.connectionEpoch!==e.mcpConnectionEpoch))&&!(!c&&e.mcpConnectionEpoch!==void 0&&a.config.registrySource!==void 0)&&!((n||s!==r)&&!Jn(a.config)&&!(c?.owner.kind==="registry"&&c.owner.identity===`user:${r}`)))return{name:s,server:a}}import{logger as UG}from"@hermes/logger";var qG=UG.child({prefix:"pi-mcp"}),HG=1e6,GG=1e3,ZG=/^\d+$/;function rk(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function cn(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"||!ZG.test(e)||typeof r!="string"||r.length===0)return;let n=ha(t);if(n.kind!=="invalid")return{revision:e.replace(/^0+(?=\d)/,""),domain:rk(r),...n.kind==="valid"?{ownerDomain:n.ownerDomain}:{}}}function BG(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:Ar(o,n)>0?o:n}function WG(t,e,r){if(t===void 0)return!0;let n=rk(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain||r?.kind==="domain"&&(n.startsWith("private:")||n.startsWith("shared:"))&&e.domain.startsWith("recipient:")&&Mr(n)===r.domain&&Mr(e.domain)===r.domain?!0:r?.kind==="domain"&&!Ie(n)&&Ie(e.domain)&&Mr(n)===r.domain}function VG(t,e,r,n){let o=e.credential_revision??e.credentialRevision,i=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||i!==void 0)&&r===void 0)return qG.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let s=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||s!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";let a=Mr(r.domain);if(s?.kind==="blocked"||s?.kind==="domain"&&r.ownerDomain!==void 0&&r.ownerDomain!==s.domain||s?.kind==="domain"&&r.ownerDomain===void 0&&!Ie(r.domain)&&a!==s.domain)return"reject";let c=n?.acceptedDomains?.get(t);if(!WG(c,r,s))return"reject";let u=BG(n?.acceptedRevisions,r.domain,i);if(u===void 0)return"apply";let d=Ar(r.revision,u);return d>0||d===0&&c===void 0&&s?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===s.domain?"apply":d===0?"equal":"reject"}function KG(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 JG(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(typeof e.access_token!="string"||e.access_token.length===0||["refresh_token","token_type","scope","authorization_endpoint","token_endpoint","issuer","client_id","client_secret","token_endpoint_auth_method"].some(s=>e[s]!==void 0&&typeof e[s]!="string"))return!1;let n=e.access_token_expires_at;if(n===void 0)return!0;if(typeof n!="object"||n===null||Array.isArray(n))return!1;let{seconds:o,nanos:i}=n;return typeof o=="number"&&Number.isSafeInteger(o)&&typeof i=="number"&&Number.isInteger(i)&&i>=0&&i<1e9}function YG(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*GG+Math.floor(t.access_token_expires_at.nanos/HG):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 XG(t,e){return t?t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.expiresAt===e.expiresAt&&t.tokenType===e.tokenType&&t.scope===e.scope&&t.resource===e.resource&&t.serverMetadata?.issuer===e.serverMetadata?.issuer&&t.serverMetadata?.authorization_endpoint===e.serverMetadata?.authorization_endpoint&&t.serverMetadata?.token_endpoint===e.serverMetadata?.token_endpoint&&t.client?.client_id===e.client?.client_id&&t.client?.client_secret===e.client?.client_secret&&t.client?.token_endpoint_auth_method===e.client?.token_endpoint_auth_method:!1}function br(t){let{store:e,serverName:r,proto:n,options:o}=t;if(!JG(n))return{decision:"reject"};let i=cn(n),s=VG(r,n,i,o);if(s==="reject")return{decision:s};let a=YG(n);return s==="equal"&&o?.requireEqualMaterial===!0&&(o.acceptedDomains?.get(r)!==i?.domain||!XG(e.get(r),a))||s==="apply"&&KG(e,r,a,i)?{decision:"reject"}:{decision:s,token:a,revision:i}}function $u(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,i]of Object.entries(e)){let s=br({store:t,serverName:o,proto:i,options:r});if(s.decision!=="apply"){n[s.decision==="equal"?"equal":"rejected"].push(o);continue}let{token:a,revision:c}=s;t.set(o,a),r?.equalRevisionRebindDomains?.delete(o),c!==void 0&&(r?.acceptedRevisions?.set(c.domain,c.revision),r?.acceptedDomains?.set(o,c.domain)),n.applied.push(o)}return n}var bm=QG.child({prefix:"pi-mcp"});function un(t,e){bm.info(`Targeted MCP credential update for config ${t} skipped: ${e}`),nk("MCP targeted credential update skipped",{outcome:e})}function eZ(t,e){let r=an({state:t,target:e,byConfigId:!0});if(!r)return;let o=D(t,r.name)?.owner??kr(r.server.config);return o.kind==="registry"&&o.identity===`user:${e}`?r:void 0}function tZ(t,e,r){let n=Object.entries(t).filter(([o,i])=>{let s=cn(i);if(s===void 0)return!1;let a=hn(s);return s.ownerDomain!==void 0?a===`user:${e}`:o===r&&Ie(s.domain)||a===`user:${e}`});return n.length===1?n[0]?.[1]:void 0}async function ok(t){let{pi:e,state:r,update:n}=t;if(Object.keys(n.credentials).length!==1){bm.warn(`Targeted MCP credential update for config ${n.configId} must contain exactly one entry`),un(n.configId,"invalid_payload");return}let o=eZ(r,n.configId),i=o?tZ(n.credentials,n.configId,o.server.config.name):void 0;if(!o){un(n.configId,"no_live_host");return}if(!i){un(n.configId,"credential_mismatch");return}let s=D(r,o.name),a=r.mcpConnectionEpoch;if(o.server.config.type==="stdio"||o.server.config.auth!=="oauth"){un(n.configId,"unsupported_transport");return}let c=()=>({acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:!0}),u=()=>br({store:r.tokens,serverName:o.name,proto:i,options:c()});if(u().decision==="reject"){un(n.configId,"credential_rejected");return}let d=o.server.getRefreshInFlight?.();if(d&&await Promise.resolve(d).catch(()=>{}),r.mcpConnectionEpoch!==a||r.servers.get(o.name)!==o.server||D(r,o.name)!==s){un(n.configId,"host_changed");return}if(u().decision==="reject"){un(n.configId,"credential_rejected");return}te(r,o.name,o.server),r.shouldProactivelyRefreshTokens=!1;let l=$u(r.tokens,{[o.name]:i},c());if(!l.applied.includes(o.name)&&!l.equal.includes(o.name)){un(n.configId,"not_applied");return}if(l.applied.includes(o.name)){let f=cn(i);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,accessTokenOnly:i.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}await nZ({pi:r.currentLoad?.latestPi??e,state:r,name:o.name,configId:n.configId,reconnect:t.reconnect??ir,report:t.report??N})}function rZ(t,e){return t?"restart_failed":e?"reconnected":"restart_not_connected"}async function nZ(t){let{pi:e,state:r,name:n,configId:o}=t,i=!1;await t.reconnect(n,r,e).catch(a=>{i=!0,bm.warn(`Targeted MCP credential restart failed for config ${o}: ${a instanceof Error?a.name:"non-Error"}`)}),t.report(e,r),Se(r);let s=r.servers.get(n)?.status==="success";nk("MCP targeted credential update applied",{outcome:rZ(i,s)})}import{logger as yZ}from"@hermes/logger";import{randomUUID as oZ}from"node:crypto";import{setToolSource as iZ}from"@augmentcode/auggie-v2";import{logger as sZ}from"@hermes/logger";import{Type as aZ}from"@sinclair/typebox";var sk=sZ.child({prefix:"pi-mcp"}),sr="attach-mcp-server",cZ="augment:mcp-attach-request",uZ=15e3,dZ={type:"object",properties:{config_id:{type:"string",description:"Id (or name) of the MCP server to attach, as listed among the available unattached servers in find-tool's description."}},required:["config_id"]};function lZ(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],i=o.find(l=>l.id===r);if(i)return{kind:"match",entry:i};let s=o.filter(l=>l.name.toLowerCase()===n),a=s.length===1?s[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(s.length===0)return{kind:"none"};let c=new Set(mn(t).map(l=>l.id)),u=s.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:s}}function fZ(t,e){let r=e.name.toLowerCase();return mn(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function Rm(t,e){let r=fZ(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function pZ(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},uZ);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function ik(t){let e=mn(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function hZ(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return Ee(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${Rm(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return Ee(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.${Rm(r,e)}`)}function mZ(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return Ee(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,Ee("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return Ee(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return Ee(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return Ee(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return Ee(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return Ee(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${Rm(n,e)}`);case"NO_ACTIVE_VM":return Ee(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return Ee(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function gZ(t,e,r){if(e.mcpAttachDisabled)return Ee("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${sr} requires a string "config_id" parameter. ${ik(e)}`);let o=lZ(e,n);if(o.kind==="none")return Ee(`No MCP server matching "${n}" is available to attach. ${ik(e)}`);if(o.kind==="ambiguous"){let l=o.candidates.map(f=>`"${f.name}" (id: ${f.id})`).join(", ");return Ee(`Multiple MCP servers match the name "${n}": ${l}. Retry with the exact id of the intended server.`)}let i=o.entry,s=hZ({entry:i,state:e});if(s!==void 0)return s;if(Ed(e,i))return Ee(`MCP server "${i.name}" is already attached to this session. Use find-tool to discover its tools.`);if(i.state!=="available"&&i.state!=="opt_in_required")return Ee(`MCP server "${i.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=oZ();sk.info(`attach-mcp-server: requesting attach of "${i.name}" (config=${i.id} request=${a})`);let c=pZ(e,a);t.events.emit(cZ,{configId:i.id,requestId:a});let u=await c,d=mZ({entry:i,result:u,state:e});return e.mcpAttachDisabled&&(e.mcpCatalog=void 0,t.unregisterTool(sr),io(sr),Nr(e)&&Wt(t)),d}function Iu(t,e){let r={name:sr,label:sr,description:"Attach an available MCP server to this session so its tools become usable. Only servers listed as available-but-not-attached in find-tool's description can be attached. Call this tool immediately when the user's request needs one of those servers; it attaches directly without requiring user approval.",parameters:aZ.Unsafe(dZ),execute:(n,o)=>gZ(t,e,o)};iZ(sr,"mcp"),t.registerTool(r),Or(r),sk.debug("Registered attach-mcp-server tool")}var Ou=yZ.child({prefix:"pi-mcp"}),Cm="augment:mcp-attach-result";function ak(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(Cm,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){Ou.warn(`${Cm} payload missing requestId`);return}let i=e.attachResolvers.get(o);if(!i){Ou.debug(`${Cm}: no pending resolver for request ${o} (already timed out?)`);return}let s={...typeof n?.status=="string"?{status:n.status}:{},...typeof n?.error=="string"?{error:vZ(n.error)}:{}};i(s)}))}function vZ(t){return t==="UNIMPLEMENTED"||t==="DENIED"?t:"TRANSPORT"}function zu(t,e){if(e.mcpAttachCloudSignaled&&Ea(e)){Iu(t,e);return}e.mcpAttachCloudSignaled&&zg(sr)!==void 0&&(t.unregisterTool(sr),io(sr))}function ei(t,e){if(!e.mcpAttachCloudSignaled||!Ea(e)||!e.credentials)return Promise.resolve();if(e.catalogRefreshInFlight)return e.catalogRefreshInFlight;let r=e.credentials,n=e.mcpConnectionEpoch,o=(async()=>{let i=await Wg(r);if(e.mcpConnectionEpoch!==n||e.credentials!==r)return;i.ok?(e.mcpCatalog=i.entries,Ou.debug(`MCP catalog refreshed: ${i.entries.length} entry(s)`)):i.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,Ou.debug("MCP catalog endpoint unavailable (404); disabling attach for this session"));let s=e.currentLoad?.latestPi??t;zu(s,e),Nr(e)&&Wt(s)})().finally(()=>{e.catalogRefreshInFlight===o&&(e.catalogRefreshInFlight=void 0)});return e.catalogRefreshInFlight=o,o}import{logger as $Z}from"@hermes/logger";function _Z(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case yi.OAUTH:return"oauth";case yi.API_KEY:return"header";default:return}let e=String(t).toLowerCase();if(e==="oauth"||e==="mcp_auth_type_oauth")return"oauth";if(e==="header"||e==="api_key"||e==="mcp_auth_type_api_key")return"header"}function SZ(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Dr.CLI:return"cli";case Dr.CLOUD_AGENT:return"cloud_agent";default:return}switch(t){case"MCP_PRODUCT_TYPE_CLI":return"cli";case"MCP_PRODUCT_TYPE_CLOUD_AGENT":return"cloud_agent";default:return}}function Nu(t){if(t==null)return;if(t.length===0)return[];let e=t.map(SZ).filter(r=>r!==void 0);return e.length===0?void 0:e}function Du(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=_Z(r.auth_type),o={name:r.name,type:r.type==="http"||r.type==="sse"||r.type==="stdio"?r.type:void 0,disabled:r.disabled,command:r.command,args:r.args,env:r.env,url:r.url,auth:n==="oauth"?"oauth":void 0,timeoutMs:r.timeout_ms,useShellInterpolation:r.use_shell_interpolation},i=to(o);(i==="http"||i==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...ro(r.name??t.id,o),id:t.id,registrySource:e}}}catch(s){return{ok:!1,reason:s instanceof At?s.message:String(s)}}}function wZ(t){let e=t.config?.auth_type;return e===yi.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function bZ(t){let e=t.name;return t.type==="stdio"?`stdio\0${e}\0${t.command}\0${t.args.join(" ")}`:`${t.type}\0${e}\0${t.url}`}function Pm(t,e,r){let n=new Map;for(let o of t)r(o.id)&&n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()]}function RZ(t,e,r){if(r!==void 0&&t.added_by===r)return Nu(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?Nu(n):[]}function CZ(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:i,currentUserId:s}=t;if(i!=null&&i.length===0){let p=Pm(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(i!=null){let p=new Set(i),h=Pm(e,r,()=>!0),g=new Set(h.map(b=>b.id)),m=h.filter(b=>p.has(b.id)),v=h.filter(b=>!p.has(b.id)).map(b=>b.id),w=i.filter(b=>!g.has(b));return{selected:m,filteredOutIds:v,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=Pm(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let g=!d.has(p.id)&&a.has(p.id)?RZ(p,o,s):Nu(p.enabled_products),m=t.productType??"cloud_agent";g===void 0||g.includes(m)?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function PZ(t,e="cloud_agent"){if(t==null)return e==="cli"?Dr.CLI:Dr.CLOUD_AGENT}function EZ(t){return t.map(e=>({message:`Selected MCP config id "${e}" was not returned by the registry (not opted in to the shared server, deleted, or an unknown id)`}))}function ck(t,e,r,n){try{let o=t.type==="stdio"?Bt(t,n):Zt(t,n);return{ok:!0,server:Mu(o)}}catch(o){let i=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${i}`}}}}function xZ(t){let{payload:e,userIds:r,localServerNames:n,seenNames:o,workspaceRoot:i}=t;if(e.config?.disabled)return e.config.name?{kind:"retained",name:e.config.name}:{kind:"dropped"};let s=r.has(e.id)?"user":"tenant",a=Du(e,s);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${s}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${s}): a local server with the same name takes precedence`}};let d=ck(c,e.id,s,i);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${s}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=ck(c,e.id,s,i);return u.ok?(o.add(c.name),{kind:"connected",server:u.server}):{kind:"retained",name:c.name,diagnostic:u.diagnostic}}function kZ(t){let e=[],r=[],n=[];for(let o of t)wZ(o)?(r.push(o.id),n.push({server:o.config?.name,message:`Skipped MCP server "${o.config?.name??o.id}" (id=${o.id}): OAuth authentication was never completed (no stored credentials), so it cannot connect`})):e.push(o);return{selected:e,droppedIds:r,diagnostics:n}}function TZ(t){let e=[],r=[],n=[],o=new Set;for(let i of t){let s=bZ(i);if(o.has(s)){r.push(i.name),n.push({server:i.name,message:`Skipped duplicate MCP server "${i.name}" (id=${i.id}): byte-identical to another selected server`});continue}o.add(s),e.push(i)}return{servers:e,droppedNames:r,diagnostics:n}}function AZ(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function Lu(t){let e=t.productType??"cloud_agent",r=t.client??new ka(t.creds),{tenant:n,user:o,diagnostics:i}=await iy(r,PZ(t.configIds,e)),s=o.mcp_configs??[],a=new Set(s.map(R=>R.id)),{selected:c,filteredOutIds:u,missingIds:d,retainedNames:l}=CZ({tenantConfigs:n.mcp_configs??[],userConfigs:s,enabledSharedServerIds:o.enabled_shared_server_ids??[],serverProductPreferences:o.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId,productType:e}),f=kZ(c),p=f.selected;u.push(...f.droppedIds),i.push(...f.diagnostics),i.push(...EZ(d));let h=[],g=new Map,m=new Set(t.localServerNames),v=[...p.filter(R=>a.has(R.id)),...p.filter(R=>!a.has(R.id))];for(let R of v){let _=xZ({payload:R,userIds:a,localServerNames:t.localServerNames,seenNames:m,workspaceRoot:t.workspaceRoot});AZ(_,{servers:h,retainedNames:l,diagnostics:i,nameCollisionFallbacks:g})}let w=TZ(h);l.push(...w.droppedNames),i.push(...w.diagnostics);let b=new Map;for(let R of[...n.mcp_configs??[],...s])R.config?.name&&b.set(R.id,R.config.name);return{servers:w.servers,diagnostics:i,filteredOutIds:u,retainedNames:l,namesById:b,nameCollisionFallbacks:g}}import{logger as MZ}from"@hermes/logger";var ti=MZ.child({prefix:"pi-mcp"});function uk(t,e,r){let n=t;if(!n||typeof n!="object"||!n.id){ti.warn("Embedded MCP config is missing an id; ignoring");return}let o=r?.get(n.id);if(o)return o;let i=Du(n,"tenant");if(!i.ok){ti.warn(`Embedded MCP config '${n.id}' is not convertible; ignoring: ${i.reason}`);return}let s=e??process.cwd();try{return Mu(i.server.type==="stdio"?Bt(i.server,s):Zt(i.server,s))}catch(a){ti.warn(`Embedded MCP config '${n.id}' failed expansion; ignoring: ${a instanceof Error?a.message:String(a)}`);return}}function dk(t,e){let r;try{r=JSON.parse(t)}catch(n){ti.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return uk(r,e)}function ri(t,e,r){let n=t;if(typeof n=="string")try{n=JSON.parse(n)}catch(a){ti.warn(`Failed to parse embedded MCP configs: ${a instanceof Error?a.name:"non-Error thrown"}`);return}if(!Array.isArray(n)){ti.warn("Embedded MCP configs payload is not an array; ignoring");return}let o=[],i=new Map,s=!1;for(let a of n){let c=a,u=uk(a,e,r);if(c&&typeof c=="object"&&c.id&&c.config?.name&&i.set(c.id,{name:c.config.name,...u?{config:u}:{}}),c?.config?.disabled){s=!0;continue}u&&o.push(u)}if(!(o.length===0&&!s))return{servers:o,allConfigsById:i}}var xt=$Z.child({prefix:"pi-mcp"});function fk(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function pk(t){let{state:e,name:r,lease:n,host:o,isDeselected:i,selectionIsEmpty:s,replacementOwners:a}=t;if(s)return o?dt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ke(e,r),"retiring"):void 0:(xe({state:e,name:r,owner:n.owner,revision:n.revision}),Ke(e,r),"released");let c=a.get(r),u=li({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return i&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ke(e,r),leaseRevision:u.lease.revision}}function IZ(t){let{state:e,name:r,server:n,selectedIds:o,replacementOwners:i,slotReservations:s,processedNames:a}=t,c=te(e,r,n);if(c.owner.kind!=="registry"||c.host!==n)return;a.add(r);let u={...n.config};e.registryCredentialConfigs.set(r,u),n.config.id&&(e.registryConfigNamesById.set(n.config.id,r),e.registryCredentialConfigsById.set(n.config.id,u));let d=pk({state:e,name:r,lease:c,host:n,isDeselected:fk({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:i});if(d===void 0)return;d!=="released"&&d!=="retiring"&&s.set(r,d);let l=D(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&_e({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&xe({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&_e({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function OZ(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:i,slotReservations:s}=t,a=pk({state:e,name:r,lease:n,isDeselected:fk({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:i});a&&a!=="released"&&a!=="retiring"&&s.set(r,a)}async function zZ(t,e,r){let n=e?new Set(e):void 0,o=new Map,i=[],s=new Set;for(let[a,c]of t.servers){let u=IZ({state:t,name:a,server:c,selectedIds:n,replacementOwners:r,slotReservations:o,processedNames:s});u&&i.push(u)}for(let[a,c]of t.hostLeases)s.has(a)||c.owner.kind!=="registry"||c.host!==void 0||OZ({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(i),o}async function hk(t,e,r,n,o){let i=[],s=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=s.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){s.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&i.push(gt(t,l,f.id,f))}try{await Promise.all(i)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Tt(f)}let d=new Map;for(let[l,f]of s){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),mt(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function NZ(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],i=[],s=[],a=[],c=new Set(r);for(let f of t.servers){if(n&&f.id!==void 0&&!n.has(f.id)){s.push(f.id);continue}if(c.has(f.name)){i.push({server:f.name,message:r.has(f.name)?`Skipped embedded MCP server "${f.name}" (id=${f.id}): a local server with the same name takes precedence`:`Skipped embedded MCP server "${f.name}" (id=${f.id}): another selected registry server with the same name takes precedence`}),a.push(f.name);continue}c.add(f.name),o.push(f)}let u=new Set(o.map(f=>f.name)),d=new Set(a),l=new Map;for(let[f,{name:p}]of t.allConfigsById)n&&!n.has(f)||(l.set(f,p),u.has(p)||d.has(p)||(d.add(p),a.push(p)));return{servers:o,diagnostics:i,filteredOutIds:s,retainedNames:a,namesById:l}}function DZ(t){let{state:e,configIds:r,admittedConfigs:n}=t,o=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,r?.length===0||Array.isArray(o)&&o.length===0)return{servers:[],allConfigsById:new Map};if(o!==void 0)return ri(o,e.workspaceRoot??process.cwd(),n)}async function LZ(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),i=[],s=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(Ge(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);i.push({id:a,name:c}),s.push(gt(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(s);for(let{id:a,name:c}of i)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new Tt(c)}}function jZ(t){let e=new Map,r=t.configIds?new Set(t.configIds):void 0;for(let[n,{name:o}]of t.parsedEmbedded?.allConfigsById??[])(r===void 0||r.has(n))&&e.set(o,{kind:"registry",identity:`user:${n}`});return e}function FZ(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function UZ(t){let e=new Set;for(let[r,n]of t.servers){let o=te(t,r,n);o.owner.kind==="local"&&o.host===n&&e.add(r)}for(let[r,n]of t.hostLeases)n.owner.kind==="local"&&e.add(r);return e}function qZ(t){let{state:e,result:r,previousSelectedIds:n,selection:o}=t,i=new Set([...o??[],...r.servers.flatMap(s=>s.id===void 0?[]:[s.id]),...r.namesById?.keys()??[]]);return hk(e,r.servers,n,i,o!==void 0)}async function mk(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():mi(t,r.id)))}async function lk(t){return await mk(t.state,t.result),t.state.registryGeneration===t.generation&&await qZ(t),t.result}function HZ(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:i,previousSelectedIds:s,selection:a,generation:c,discover:u,productType:d}=t;if(n){xt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let f=NZ(n,r,i);return lk({state:e,result:f,previousSelectedIds:s,selection:a,generation:c})}return o?u({configIds:r,creds:o,currentUserId:o.userId,workspaceRoot:e.workspaceRoot??process.cwd(),localServerNames:i,productType:d}).then(f=>lk({state:e,result:f,previousSelectedIds:s,selection:a,generation:c})):void 0}function GZ(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),xt.warn(o.message);for(let[o,i]of r.namesById??[])e.registryConfigNamesById.set(o,i);r.filteredOutIds.length>0&&xt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function ZZ(t){for(let e of t.servers){let r=`Skipped registry MCP server "${e.name}" (id=${e.id}): credential setup did not complete, likely because another server with the same name claimed it`;t.state.diagnostics.push({server:e.name,message:r,origin:"registry"}),xt.warn(r)}}function BZ(t){let{state:e,result:r}=t,n=r.servers.map(i=>{let s=e.sessionRegistryDisabledOverrides.get(i.name);return s===void 0?i:{...i,disabled:s}}),o=new Set([...n.map(i=>i.name),...r.retainedNames??[]]);for(let i of e.sessionRegistryDisabledOverrides.keys())o.has(i)||e.sessionRegistryDisabledOverrides.delete(i);return n}function gk(t){let{state:e,generation:r}=t;return n=>{if(e.registryGeneration!==r||n.id===void 0)return e.registryGeneration===r;let o=e.missingHostRemovalFences.get(n.id);return!e.sessionRemovedConfigIds.has(n.id)&&o?.registryGeneration!==r}}function Em(t){let{state:e,result:r,selection:n,slotReservations:o}=t,i=new Set([...r.servers.map(s=>s.name),...r.retainedNames??[],...(n??[]).flatMap(s=>{let a=e.registryConfigNamesById.get(s);return a?[a]:[]})]);for(let[s,a]of o){if(i.has(s))continue;let c=D(e,s);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&xe({state:e,name:s,owner:c.owner,revision:a.leaseRevision})}}async function WZ(t){let{state:e,result:r,selection:n,generation:o,connect:i,pi:s,slotReservations:a}=t;if(e.registryGeneration!==o){Em({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),xt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await mk(e,r),e.registryGeneration!==o)return;let c=gk({state:e,generation:o}),u=r.servers.filter(c),d=await Promise.all(u.map(v=>Ir({state:e,config:v,pi:s})));if(e.registryGeneration!==o)return;let l=u.filter((v,w)=>d[w]),f=u.filter((v,w)=>!d[w]);GZ({state:e,result:r,selection:n}),ZZ({state:e,servers:f}),Em({state:e,result:r,selection:n,slotReservations:a});let p=BZ({state:e,result:{...r,servers:l,retainedNames:[...r.retainedNames??[],...f.map(v=>v.name)]}});if(p.length===0)return;let h=p.filter(v=>{let w=e.servers.get(v.name);if((w?te(e,v.name,w):D(e,v.name))?.owner.kind==="local")return xt.info(`Registry install of "${v.name}" skipped: a local server claimed the name during discovery`),!1;let R=a.get(v.name)?.configRevision;if(R===void 0)return!0;let _=e.configDesiredRevisions.get(v.name);return _!==R?(xt.info(`Registry install of "${v.name}" skipped: slot revision advanced from ${R} to ${_} by a concurrent operation`),!1):!0});if(h.length===0)return;xt.info(`Registry discovery: connecting ${h.length} server(s)`);let m=(await i(h,e,e.currentLoad?.latestPi??s,c))?.find(v=>v.status==="failed");if(m)throw m.error instanceof Error?m.error:new Error(String(m.error));await VZ({state:e,pi:s,result:r,generation:o,connect:i})}async function VZ(t){let{state:e,pi:r,result:n,generation:o,connect:i}=t,s=n.nameCollisionFallbacks;if(!(!s||s.size===0))for(let[a,c]of s)for(let u of c){let d=await KZ({state:e,pi:r,generation:o,connect:i,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function KZ(t){let{state:e,pi:r,generation:n,connect:o,name:i,candidate:s}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(i);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===s.id)return"settled";if(!await Ir({state:e,config:s,pi:r})||e.registryGeneration!==n)return"abort";xt.info(`MCP auth fallback: "${i}" (id=${c}) landed ${a.status}; connecting same-named config id=${s.id} in its place`),await o([s],e,e.currentLoad?.latestPi??r,gk({state:e,generation:n}));let d=e.servers.get(i);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===s.id&&d.status==="success"?"settled":"next"}async function JZ(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:i}=t,s=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;xt.warn(s),e.registryGeneration===n&&(await hk(e,[],o,new Set(i??[]),i!==void 0),e.selectedRegistryConfigIds=i,e.diagnostics.push({message:s,origin:"registry"}))}function YZ(t,e){for(let r of e??[]){let n=Ge(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Ye({state:t,domain:n,epoch:o?.epoch})}}async function XZ(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await WZ({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),Em({state:t.resultArgs.state,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:t.resultArgs.state.registryGeneration===t.resultArgs.generation?t.resultArgs.selection:void 0,slotReservations:e}),r instanceof Tt)throw YZ(t.resultArgs.state,t.resultArgs.selection),t.resultArgs.state.diagnostics.some(n=>n.message===r.message)||t.resultArgs.state.diagnostics.push({message:r.message,origin:"registry"}),r;await JZ({...t.resultArgs,error:r})}}function ra(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.discover??Lu,s=o?.connect??Je,a=n;if(!a||typeof a!="object"||Array.isArray(a))return xt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();let c=t.productType??a.productType??"cloud_agent";Array.isArray(a.configIds)&&Rg(r,new Set(a.configIds.map(Ge)));let u=DZ({state:r,configIds:a.configIds,admittedConfigs:t.admittedConfigs}),d=r.credentials;if(!(u||d)){xt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let w of a.configIds??[])Ye({state:r,domain:Ge(w)});return Promise.resolve()}let l=r.selectedRegistryConfigIds??[],f=LZ({state:r,previousSelectedIds:l,configIds:a.configIds}),p=jZ({parsedEmbedded:u,configIds:a.configIds}),h=++r.registryGeneration,g=Promise.all([zZ(r,a.configIds,p),f]).then(([w])=>w);FZ(r);let m=a.configIds?[...a.configIds]:void 0,v=HZ({state:r,configIds:a.configIds,parsedEmbedded:u,credentials:d,localServerNames:UZ(r),previousSelectedIds:l,selection:m,generation:h,discover:i,productType:c});return v?XZ({disposal:g,discovery:v,resultArgs:{state:r,previousSelectedIds:l,selection:m,generation:h,connect:s,pi:e}}):Promise.resolve()}import{logger as QZ}from"@hermes/logger";var dn=QZ.child({prefix:"pi-mcp"});function e2(t,e){Ye({state:t,domain:`user:${e}`}),t.liveEditGenerations??=new Map;let r=(t.liveEditGenerations.get(e)??0)+1;return t.liveEditGenerations.set(e,r),r}function t2(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function Sk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function r2(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function yk(t){let{state:e,configId:r,fence:n,operation:o,retryPreviousFailureOnly:i=!1}=t,s=e.missingHostRemovals.get(r),a=(async()=>{let c=!1;if(s)try{await s.promise}catch{c=!0}i&&!c||await o()})().finally(()=>{e.missingHostRemovals.get(r)?.promise===a&&(r2({state:e,configId:r,fence:n}),e.missingHostRemovals.delete(r))});return e.missingHostRemovals.set(r,{promise:a,liveEditGeneration:n.liveEditGeneration,registryGeneration:n.registryGeneration}),a}function wk(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function vk(t,e){for(let[r,n]of t.servers){if(t.targetMaterialStore?.has(e)&&!t.targetMaterialStore.trusts(n.config)&&!Jn(n.config))continue;let o=te(t,r,n);if(n.config.id===e&&o.owner.kind==="registry"&&o.host===n)return r}}function bk(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function n2(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let i=D(e,r),s=n?kr(n):void 0;if(i===void 0){Ke(e,r);return}let a=i.host===void 0&&i.owner.kind==="registry"&&s?.kind==="registry"&&i.owner.identity===s.identity,c=o?.incumbent.owner.kind==="registry"&&s?.kind==="registry"&&o.incumbent.owner.identity===s.identity;if(!a&&!c)return;(o?.settled&&i.retirement===o?dg({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):xe({state:e,name:r,owner:i.owner,revision:i.revision}))&&D(e,r)===void 0&&(bk(e,r),Ke(e,r))}async function xm(t){let{state:e,configId:r,pi:n,report:o,sourceFence:i}=t,s=e.registryCredentialConfigsById.get(r),a=s?.name;if(!s||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw dn.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=D(e,a),u=kr(s),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ke(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let m=D(e,a)?.retirement===d?d:void 0,v=m?.result;if(d&&v?.status==="failed"&&v.transportDisposed!==!0){let w=v.error instanceof Error?v.error:new Error(String(v.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw dn.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await hi(e,a,r,s)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw dn.warn(b),e.diagnostics.push({server:a,message:b}),w}Sk({state:e,configId:r,fence:i})&&(wk(e,r),n2({state:e,name:a,config:s,retirement:m})),dn.info(`Live MCP remove-server: config id ${r} resolved to no live server (already removed or unknown id)`),o(e.currentLoad?.latestPi??n,e)}function _k(t){let{state:e,name:r,operation:n,result:o}=t;if(o.status!=="rejected")return;let i=`Live MCP remove-server failed to ${n} ${r}: ${o.reason instanceof Error?o.reason.message:String(o.reason)}`;dn.warn(i),e.diagnostics.push({server:r,message:i})}async function o2(t){let{state:e,name:r,configId:n,server:o}=t,[i]=await Promise.allSettled([o.dispose({strict:!0})]);if(_k({state:e,name:r,operation:"dispose",result:i}),i.status==="rejected")return{removed:!1,failure:i.reason,transportDisposed:!1};let[s]=await Promise.allSettled([hi(e,r,n,o.config)]);return _k({state:e,name:r,operation:"detach",result:s}),s.status==="fulfilled"?{removed:!0,failure:void 0,transportDisposed:!0}:{removed:!1,failure:s.reason,transportDisposed:!0}}async function i2(t){let{state:e,configId:r,name:n,pi:o,report:i,sourceFence:s}=t,a=e.servers.get(n),c=a?te(e,n,a):D(e,n);if(!a||!c||c.owner.kind!=="registry"||c.host!==a)return;e.registryConfigNamesById.set(r,n),e.registryCredentialConfigsById.set(r,{...a.config});let u=e.configDesiredRevisions.get(n),d=e.configDesiredSources.get(n),l=Ke(e,n),f=dt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),dn.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:g,transportDisposed:m}=await o2({state:e,name:n,configId:r,server:a});if(h&&Sk({state:e,configId:r,fence:s})?wk(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),_e({state:e,name:n,retirement:f,result:h?{status:"retired"}:{status:"failed",error:g,transportDisposed:m}}),h&&xe({state:e,name:n,owner:c.owner,revision:c.revision})&&bk(e,n),i(p,e),!h)throw g}function ju(t){let{pi:e,state:r,data:n,deps:o}=t,i=n,s=i&&typeof i.configId=="string"?i.configId:"";if(!s)return dn.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!t.replacement&&!oo({state:r,configId:s,generation:i?.attachmentGeneration}))return dn.info(`Ignoring stale live MCP remove-server command for config id ${s}`),Promise.resolve();let a=m=>t.replacement?m:_a({state:r,configId:s,generation:i?.attachmentGeneration,operation:m,wasApplied:()=>!0}),c=o?.report??N,u=vk(r,s),d=r.registryCredentialConfigsById.get(s),l=d?.name?D(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(s),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(s);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let m=r.missingHostRemovalFences.get(s);if(m)return a(yk({state:r,configId:s,fence:m,retryPreviousFailureOnly:!0,operation:()=>xm({state:r,configId:s,pi:e,report:c,sourceFence:m})}))}let h=e2(r,s);if(u===void 0&&d===void 0)return a(xm({state:r,configId:s,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let g=t2({state:r,configId:s,liveEditGeneration:h});return a(yk({state:r,configId:s,fence:g,operation:()=>{let m=vk(r,s);return m===void 0?xm({state:r,configId:s,pi:e,report:c,sourceFence:g}):i2({state:r,configId:s,name:m,pi:e,report:c,sourceFence:g})}}))}import{createHash as s2}from"node:crypto";var a2=/^[1-9][0-9]*$/,c2=/^[a-f0-9]{64}$/,u2=new Set(["version","operation","config_id","server_name","transport","url","command","args","use_shell_interpolation","route_revision","binding_generation","ownership","auth_type","vm_id","connection_version","execution_principal_id","execution_principal_type","access_token","static_secrets"]);function fe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function km(t){return typeof t=="string"&&a2.test(t)&&t.length<=19&&BigInt(t)<=9223372036854775807n}function Am(t){return fe(t)&&typeof t.vmId=="string"&&t.vmId.length>0&&t.vmId.length<=256&&t.vmId.trim()===t.vmId&&km(t.connectionVersion)}function d2(t){if(t.version===2&&t.transport==="stdio")return(t.url===void 0||t.url==="")&&typeof t.command=="string"&&t.command.trim().length>0&&!Fr(t.command)&&Array.isArray(t.args)&&t.args.every(e=>typeof e=="string"&&!Fr(e))&&typeof t.use_shell_interpolation=="boolean"&&t.auth_type!=="oauth";if(t.version!==1||t.transport!=="http"&&t.transport!=="sse"||typeof t.url!="string"||t.command!==void 0||t.args!==void 0||t.use_shell_interpolation!==void 0)return!1;try{let e=new URL(t.url);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password&&!e.hash}catch{return!1}}function Ck(t){if(!(!fe(t)||Object.keys(t).some(e=>!u2.has(e)))&&!(!d2(t)||t.operation!=="install"&&t.operation!=="retire"||t.auth_type!=="oauth"&&t.auth_type!=="static"&&t.auth_type!=="none")){for(let e of["config_id","server_name","vm_id","execution_principal_id"])if(typeof t[e]!="string"||t[e].length===0)return;if(!(typeof t.route_revision!="string"||!c2.test(t.route_revision)||!km(t.connection_version))&&!(t.execution_principal_type!==void 0&&(typeof t.execution_principal_type!="number"||!Number.isInteger(t.execution_principal_type)||t.execution_principal_type<0||t.execution_principal_type>2147483647))&&!(t.ownership==="uncredentialed"?t.auth_type!=="none"||t.binding_generation!=="0":t.ownership!=="recipient"||t.auth_type==="none"||!km(t.binding_generation))){if(t.operation==="retire"||t.auth_type==="none"){if(t.access_token!==void 0||t.static_secrets!==void 0)return}else if(t.auth_type==="oauth"){if(typeof t.access_token!="string"||t.access_token.length===0||t.static_secrets!==void 0)return}else if(t.access_token!==void 0||!fe(t.static_secrets)||Object.keys(t.static_secrets).length===0||Object.values(t.static_secrets).some(e=>typeof e!="string"||e.trim().length===0))return;return{...t,execution_principal_type:t.execution_principal_type??0}}}}function Tm(t,e){return t.execution_principal_id===e.execution_principal_id&&t.execution_principal_type===e.execution_principal_type}function l2(t,e){return t.transport==="stdio"&&e.transport==="stdio"?t.command===e.command&&t.use_shell_interpolation===e.use_shell_interpolation&&t.args.length===e.args.length&&t.args.every((r,n)=>r===e.args[n]):t.transport===e.transport&&t.url===e.url}function f2(t,e){return t.transport==="stdio"&&e.type==="stdio"?e.command===t.command&&e.useShellInterpolation===t.use_shell_interpolation&&e.args.length===t.args.length&&e.args.every((r,n)=>r===t.args[n]):e.type!=="stdio"&&t.transport===e.type&&e.url===t.url&&e.auth==="oauth"==(t.auth_type==="oauth")}function Rk(t,e){return Tm(t,e)&&t.config_id===e.config_id&&t.server_name===e.server_name&&l2(t,e)&&t.route_revision===e.route_revision&&t.ownership===e.ownership&&t.auth_type===e.auth_type}function p2(t,e){let r=Object.keys(t.static_secrets??{});return t.access_token===e.access_token&&r.length===Object.keys(e.static_secrets??{}).length&&r.every(n=>t.static_secrets?.[n]===e.static_secrets?.[n])}function h2(t,e){let r=Ni((e.type==="stdio"?e.env:e.headers)??{}),n=Object.keys(t.static_secrets??{});return t.auth_type==="static"?r.length>0&&r.length===n.length&&n.every(o=>r.includes(o)):r.length===0}var Fu=class{#t=new Map;#o=new WeakSet;#r=new WeakSet;#e;#n;#i=Symbol("mcp-connection");get epoch(){return this.#i}get hasConnection(){return this.#e!==void 0}revokeConnection(){this.#t.clear(),this.#r=new WeakSet,this.#n=void 0,this.#e=void 0,this.#i=Symbol("mcp-connection")}setConnection(e){return Am(e)?this.#e?.vmId===e.vmId&&this.#e.connectionVersion===e.connectionVersion?!1:(this.revokeConnection(),this.#e={...e},!0):(this.revokeConnection(),!0)}has(e){return this.#t.has(e)||[...this.#t.values()].some(r=>r.material.server_name===e)}hasTargetProvenance(e){return this.#o.has(e)}trusts(e){return this.#r.has(e)}retainSelection(e){for(let[r,n]of this.#t)e.has(r)||this.#r.delete(n.config)}config(e){return this.#t.get(e)?.config}validate(e,r,n){let o=this.#t.get(e.config_id);if(!this.#e||e.vm_id!==this.#e.vmId||e.connection_version!==this.#e.connectionVersion||this.#n&&!Tm(e,this.#n))return!1;if(e.operation==="retire")return!n&&!!o&&this.#r.has(r)&&o.config===r&&Tm(e,o.material)&&e.binding_generation===o.material.binding_generation;if(r.disabled||!r.registrySource||r.vfsSource||r.id!==e.config_id||r.name!==e.server_name||!f2(e,r)||!n&&(!o||!this.#r.has(r)||!Rk(e,o.material))||!h2(e,r))return!1;if(!o)return!0;let i=BigInt(e.binding_generation)-BigInt(o.material.binding_generation);return i>=0n&&(i!==0n||o.material.operation==="install"&&Rk(e,o.material)&&p2(e,o.material))}commit(e,r){let n=Object.freeze({...e,...e.transport==="stdio"?{args:Object.freeze([...e.args])}:{},...e.static_secrets?{static_secrets:Object.freeze({...e.static_secrets})}:{}});this.#t.set(e.config_id,{material:n,config:r,epoch:Symbol("target-material")}),this.#r.add(r),this.#o.add(r),this.#n??={...n,access_token:void 0,static_secrets:void 0}}auth(e){if(!this.#r.has(e)||!e.id)return;let r=this.#t.get(e.id)?.epoch,n=()=>{let i=this.#t.get(e.id??"");if(!i||!this.#r.has(e)||i.epoch!==r||i.material.operation!=="install"||i.config!==e||i.material.vm_id!==this.#e?.vmId||i.material.connection_version!==this.#e.connectionVersion)throw new Error("MCP target material is unavailable");return i.material},o=n();return{...o.ownership==="recipient"?{credential:Object.freeze({revision:o.binding_generation,domain:`recipient:${o.config_id}`})}:{},validateUrl:i=>{let s=n();if(s.transport==="stdio")throw new Error("MCP target destination is unavailable");let a=new URL(i),c=new URL(s.url);if(a.username||a.password||a.hash||(s.transport==="sse"?a.origin!==c.origin:a.href!==c.href))throw new Error("MCP target destination is unavailable")},getSecret:async i=>n().static_secrets?.[i],headers:()=>{let i=n();return i.auth_type==="oauth"?{Authorization:`Bearer ${i.access_token}`}:{}}}}};function Pk(t){return s2("sha256").update(t).digest("hex")}function m2(t,e){let r=Array.isArray(t.configIds)?new Set(t.configIds.filter(o=>typeof o=="string")):void 0,n=new Map;for(let o of e.values()){let i=JSON.parse(o);if(!(fe(i)&&fe(i.config))||typeof i.id!="string"||typeof i.config.name!="string"||r&&!r.has(i.id))continue;let s=n.get(i.config.name)??[];s.push(i.id),n.set(i.config.name,s)}return n}function g2(t,e){if(e.length<=1)return!0;let r=ha(t);return r.kind==="valid"&&e.filter(n=>Ge(n)===r.ownerDomain).length===1}function Ek(t){let e=new Map;if(t===void 0)return e;if(typeof t!="string")throw new Error("Invalid MCP config map");let r=JSON.parse(t);if(!Array.isArray(r)||r.some(a=>!fe(a)||!fe(a.config)))throw new Error("Invalid MCP config map");let n=0,o=!1,i=!1,s=-1;for(let a=0;a<t.length;a++){let c=t[a];if(o){i?i=!1:c==="\\"?i=!0:c==='"'&&(o=!1);continue}if(c==='"'&&(o=!0),(c==="{"||c==="[")&&(n===1&&(s=a),n++),(c==="}"||c==="]")&&(n--,n===1&&s>=0)){let u=t.slice(s,a+1),d=JSON.parse(u);if(!fe(d)||typeof d.id!="string"||e.has(d.id))throw new Error("Invalid MCP config map");e.set(d.id,u),s=-1}}return e}function y2(t,e){let r=t.args===void 0?[]:t.args,n=t.use_shell_interpolation===void 0?!1:t.use_shell_interpolation;return(t.url===void 0||t.url==="")&&t.command===e.command&&Array.isArray(r)&&r.length===e.args.length&&r.every((o,i)=>o===e.args[i])&&n===e.use_shell_interpolation}function v2(t){return t.env!==void 0&&(!fe(t.env)||Object.values(t.env).some(e=>typeof e!="string"))?!1:t.timeout_ms===void 0||typeof t.timeout_ms=="number"&&Number.isSafeInteger(t.timeout_ms)&&t.timeout_ms>=0}function _2(t,e,r){if(typeof t!="string"||Pk(t)!==e.route_revision)return;let n=JSON.parse(t);if(!fe(n)||!fe(n.config)||n.id!==e.config_id||n.config.auth_type!=={oauth:2,static:3,none:1}[e.auth_type])return;let i=n.config;if(i.type!==void 0&&i.type!==e.transport||i.name!==e.server_name||i.disabled!==void 0&&i.disabled!==!1||!v2(i))return;let s={id:e.config_id,name:e.server_name,registrySource:"tenant",...i.timeout_ms?{timeoutMs:i.timeout_ms}:{}},a=i.env?Object.freeze({...i.env}):void 0;if(e.transport==="stdio"){if(!y2(i,e))return;let c=[...e.args];return Object.freeze(c),Object.freeze({...s,type:"stdio",command:e.command,args:c,useShellInterpolation:e.use_shell_interpolation,cwd:r??process.cwd(),env:a})}if(i.url===e.url)return Object.freeze({...s,type:e.transport,url:e.url,...e.auth_type==="oauth"?{auth:"oauth"}:{},...a?{headers:a}:{}})}function xk(t,e,r){if(!fe(e)||!fe(e.credentials))return;let n=t.targetMaterialStore;if(!n?.hasConnection)return;let o=Object.entries(e.credentials),i=e.kind==="boot";if(!i&&(e.version!==1||o.length!==1||e.kind!=="add"&&e.kind!=="restart"||e.hasLegacySecrets===!0))return;let s=i?Ek(e.configsJson):new Map;if(i&&(e.headerSecrets!==void 0&&(!fe(e.headerSecrets)||Object.values(e.headerSecrets).some(l=>l!==null&&typeof l!="string"))||e.configIds!==void 0&&(!Array.isArray(e.configIds)||e.configIds.some(l=>typeof l!="string"||!l)||new Set(e.configIds).size!==e.configIds.length)))return;let a=i?m2(e,s):void 0,c=[],u=new Set,d;for(let[l,f]of o){if(i&&!(fe(f)&&Object.hasOwn(f,"target_material"))){let b=a?.get(l)??[];(!fe(f)||b.length===0&&(e.configsJson!==void 0||e.configIds!==void 0)||!g2(f,b)||n.has(l)||br({store:t.tokens,serverName:l,proto:f,options:{requireEqualMaterial:!0}}).decision==="reject")&&r?.add(l);continue}if(!fe(f)||Object.entries(f).some(([b,R])=>b!=="target_material"&&b!=="passive_install"&&R!==""))return;let p=Ck(f.target_material);if(!p||p.server_name!==l||u.has(p.config_id))return;let h=JSON.stringify([p.execution_principal_id,p.execution_principal_type]);if(d!==void 0&&d!==h||(d=h,u.add(p.config_id),!i&&e.target!==(e.kind==="add"?p.config_id:l)))return;let g=i||e.kind==="add";if(g&&p.operation!=="install")return;let m=g?_2(i?s.get(p.config_id):e.config,p,t.workspaceRoot):n.config(p.config_id);if(!m||!n.validate(p,m,g)||i&&Array.isArray(e.configIds)&&!e.configIds.includes(p.config_id))return;let v=t.servers.get(m.name),w=t.hostLeases.get(m.name);if(v&&!n.trusts(v.config)&&!Jn(v.config)&&!n.hasTargetProvenance(v.config)||v&&(v.config.registrySource===void 0||v.config.vfsSource!==void 0||v.config.id!==p.config_id)||v&&(!w||w.host!==v)||w&&(w.owner.kind!=="registry"||w.owner.identity!==`user:${p.config_id}`))return;if(Object.hasOwn(f,"passive_install")){let b=f.passive_install,R=ct(t,m.name,m.id);if(e.kind!=="restart"||p.operation!=="install"||p.auth_type!=="oauth"||p.ownership!=="recipient"||!v||!fe(b)||!Number.isSafeInteger(b.host_generation)||Number(b.host_generation)<=0||R.serverGeneration!==b.host_generation||R.credentialRevisionDomain!==`recipient:${p.config_id}`||typeof b.observed_binding_generation!="string"||!/^[1-9][0-9]*$/.test(b.observed_binding_generation)||R.credentialRevision!==b.observed_binding_generation||BigInt(p.binding_generation)<=BigInt(b.observed_binding_generation))return}c.push({material:p,config:m})}if(!(i&&[...s.keys()].some(l=>n.has(l)&&!u.has(l)&&(!Array.isArray(e.configIds)||e.configIds.includes(l))))){if(i&&c.length>0){let l=ri(e.configsJson,t.workspaceRoot,new Map(c.map(({material:p,config:h})=>[p.config_id,h])));if(!l)return;let f=new Map;for(let{name:p}of l.allConfigsById.values())f.set(p,(f.get(p)??0)+1);for(let{material:p}of c){let h=l.allConfigsById.get(p.config_id);if(!h?.config||f.get(h.name)!==1)return}}return c}}async function S2(t){let{pi:e,state:r,data:n}=t;if(!fe(n)||n.kind!=="boot")return!1;let o=r.targetMaterialStore;if(!o?.hasConnection)return!1;let i,s,a=new Set;try{i=xk(r,n,a);let h=n.configsJson===void 0?void 0:JSON.parse(n.configsJson);if(h!==void 0&&!Array.isArray(h))return!1;s=h}catch{return!1}if(!i)return!1;let c=o.epoch,u=()=>o.epoch===c,d=n.configIds;d===void 0&&s!==void 0&&(d=[...Ek(n.configsJson).keys()]);let l=new Map(i.map(h=>[h.material.config_id,h.config]));o.retainSelection(new Set(l.keys()));for(let{material:h,config:g}of i)o.commit(h,g);r.mcpAttachCloudSignaled||(r.mcpAttachCloudSignaled=!0,Iu(r.currentLoad?.latestPi??e,r)),r.embeddedRegistryConfigs=s;let f=ra({pi:e,state:r,data:{configIds:d},admittedConfigs:l,deps:{connect:(h,g,m,v)=>{if(!u())return Promise.resolve([]);let w=h.map(b=>{let R=b.id?l.get(b.id):void 0;if(!R&&b.id&&o.has(b.id))throw new Error("MCP target material is unavailable");return R??b});return Je(w,g,m,b=>u()&&(v?.(b)??!0))}}});if(a.size>0&&r.diagnostics.push({origin:"registry",message:`Withheld ${a.size} MCP OAuth credential(s) that failed boot admission: ${[...a].join(", ")}`}),u()&&typeof n.onAdmitted=="function"&&n.onAdmitted(u,a),await f,!u())return!1;let p=r.currentLoad?.latestPi??e;return N(p,r),Se(r),ei(p,r),!0}async function w2(t){let{pi:e,state:r,data:n}=t;if(!fe(n))return!1;if(n.kind==="boot")return S2(t);let o;try{o=xk(r,n)}catch{return!1}let i=o?.[0],s=r.targetMaterialStore;return!i||o?.length!==1||!s?!1:await R2({pi:e,state:r,data:n,candidate:i,store:s})}function b2(t,e){let r=fe(t.credentials)?t.credentials[e]:void 0;return fe(r)&&Object.hasOwn(r,"passive_install")}async function R2(t){let{pi:e,state:r,data:n,candidate:o,store:i}=t,{material:s,config:a}=o,c={state:r,configId:s.config_id,generation:n.attachmentGeneration};if(n.kind==="add"){if(!oo(c))return!1}else if(r.sessionRemovedConfigIds.has(s.config_id))return!1;let u=b2(n,s.server_name),d=i.epoch,l=r.attachmentCommandGenerations?.get(s.config_id),f,p=()=>i.epoch===d&&(f===void 0||r.liveEditGenerations?.get(s.config_id)===f)&&r.attachmentCommandGenerations?.get(s.config_id)===l,h=!1;try{i.commit(s,a);let g=n.kind==="add"||r.dynamicallyAddedConfigIds.has(s.config_id);if([...r.servers.values()].find(v=>v.config.id===s.config_id&&v.config.registrySource!==void 0&&(i.hasTargetProvenance(v.config)||Jn(v.config)))){let v=ju({pi:e,state:r,data:{configId:s.config_id},replacement:!0});u&&(f=r.liveEditGenerations?.get(s.config_id)),await v}return!p()||(r.sessionRemovedConfigIds.delete(s.config_id),g?r.dynamicallyAddedConfigIds.add(s.config_id):r.dynamicallyAddedConfigIds.delete(s.config_id),s.operation!=="retire"&&(await Je([a],r,e,p),!p()))?!1:(N(e,r),h=!0,!0)}finally{n.kind==="add"&&(h?gd(c):va(c))}}function na(t,e){let r=t.mcpConnectionEpoch,n=(t.targetMaterialQueue??Promise.resolve()).then(()=>t.mcpConnectionEpoch===r?e():void 0).then(()=>{});return t.targetMaterialQueue=n.catch(()=>{}),n}function C2(t,e){t.registryGeneration++,_g(t),t.headerSecrets={},t.headerSecretFailures={},t.mcpCatalog=void 0,t.mcpAttachDisabled=!1,t.catalogRefreshInFlight=void 0;let r=[];for(let[n,o]of t.hostLeases){if(o.owner.kind!=="registry")continue;t.configRevisions.set(n,(t.configRevisions.get(n)??0)+1),t.tokens.clearLocalCredential(n);let i=t.oauthCredentialDomains.get(n);i&&t.oauthCredentialRevisions.delete(i),t.oauthCredentialDomains.delete(n),t.credentialRevisions.delete(n),t.stagedOAuthCredentials.delete(n);let s=o.host;if(!s)continue;s.beginDisposal?.();let a=dt({state:t,name:n,owner:o.owner,revision:o.revision,host:s});a&&r.push(s.dispose({strict:!0}).then(()=>{_e({state:t,name:n,retirement:a,result:{status:"retired"}})},c=>{_e({state:t,name:n,retirement:a,result:{status:"failed",error:c}}),t.diagnostics.push({origin:"registry",message:"Previous MCP connection could not be retired safely"}),N(e,t)}))}t.targetMaterialQueue=Promise.all([t.targetMaterialQueue??Promise.resolve(),...r]).then(()=>{}),N(e,t)}function kk(t,e){e.targetMaterialListenerBound||(e.targetMaterialListenerBound=!0,e.targetMaterialStore??=new Fu,t.events.on("augment:mcp-target-connection",r=>{let n=e.targetMaterialStore;if(n){if(Am(r)){if(!n.setConnection(r))return}else n.revokeConnection(),e.diagnostics.push({origin:"registry",message:"MCP connection metadata is invalid; previous credential authority was revoked"});e.mcpConnectionEpoch=n.epoch,C2(e,t)}}),t.events.on("augment:mcp-target-material",r=>{let n=e.targetMaterialStore?.epoch;na(e,async()=>{if(e.targetMaterialStore?.epoch!==n)return;!await w2({pi:t,state:e,data:r})&&e.targetMaterialStore?.epoch===n&&(e.diagnostics.push({origin:"registry",message:"MCP configuration update was rejected; a fresh authorized configuration is required"}),N(t,e))}).catch(()=>{e.targetMaterialStore?.epoch===n&&(e.diagnostics.push({origin:"registry",message:"MCP snapshot application failed"}),N(t,e))})}))}import{logger as D2}from"@hermes/logger";import{execFile as Mm}from"node:child_process";import{win32 as $m}from"node:path";import{logger as P2}from"@hermes/logger";var E2=5e3,x2=/^[a-z]:[\\/]/i,k2=/[<>:"|?*]/;function T2(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!x2.test(t)||!$m.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||k2.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:$m.join($m.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function A2(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function M2(t,e){switch(process.platform){case"darwin":return Mm("open",[t],e);case"win32":{let r=T2();return r?Mm(r,["-NoProfile","-NonInteractive","-EncodedCommand",A2(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return Mm("xdg-open",[t],e)}}function Tk(t,e=E2){let r=P2.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let i=!1,s=null,a=setTimeout(()=>{if(!i){i=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{s?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);s=M2(o,c=>{i||(i=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as $2}from"node:http";function Uu(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function Ak(t){let e=Uu(t.title),r=Uu(t.heading),n=Uu(t.message),o=t.details?Uu(t.details):void 0,i=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" />
|
|
@@ -140,13 +140,13 @@ ${C}`,l++;break;case"id":u=C.includes("\0")?void 0:C;break;case"retry":/^\d+$/.t
|
|
|
140
140
|
</main>
|
|
141
141
|
${i}
|
|
142
142
|
</body>
|
|
143
|
-
</html>`}function Rk(t){return bk({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Fu(t,e){return bk({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var c2="127.0.0.1",xk="/callback",Ck=3e3,Pk=3010,u2="Authentication successful. You can close this window.",Uu={"Content-Type":"text/html; charset=utf-8"};function Ek(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function kk(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:new URLSearchParams({code:r,state:e})};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}if(!n.get("code"))throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return o===null&&n.set("state",e),{kind:"success",result:n}}function Am(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function d2(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==xk){e.writeHead(404,Uu),e.end(Fu("Callback route not found."));return}let o=n.searchParams.get("code"),i=n.searchParams.get("state"),s=n.searchParams.get("error");if(s){let a=c=>{e.writeHead(400,Uu),e.end(Fu("Authentication did not complete.",`Error: ${s}`));let u=Am(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!i){e.writeHead(400,Uu),e.end(Fu("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Uu),e.end(Rk(u2)),r.onSuccess(n.searchParams)}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function l2(t){for(let e=Ck;e<=Pk;e++)if(await new Promise(n=>{let o=()=>{t.removeListener("listening",i),n(!1)},i=()=>{t.removeListener("error",o),n(!0)};t.once("error",o),t.once("listening",i),t.listen(e,c2)}))return e;throw new Error(`No free port in ${Ck}-${Pk} for the OAuth callback server`)}async function Tk(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,i=a2((a,c)=>{d2(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),s=await l2(i);return{port:s,redirectUri:`http://localhost:${s}${xk}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>i.close(),setErrorRetryHandler:a=>{o=a}}}var Mm=f2.child({prefix:"pi-mcp"}),p2=300*1e3,$k="MCP authentication was superseded";function Ak(){return Ek()?"You appear to be on a remote machine. Open the URL in a local browser, then paste the final redirect URL or code below.":"Complete sign-in in your browser. If it doesn't open, paste the final redirect URL or code below."}function br(t){if(t.aborted)throw new Error("Authentication cancelled")}function Ik(t,e,r){return t.authenticationGeneration===r.authenticationGeneration&&t.servers.get(e)===r.server&&(t.serverGenerations.get(e)??0)===r.serverGeneration&&(t.configRevisions.get(e)??0)===r.installedConfigRevision&&(t.configDesiredRevisions.get(e)??0)===r.desiredConfigRevision&&t.tokens===r.tokenStore&&t.tokens.get(e)===r.token&&Ok(t.credentialRevisions.get(e),r.credentialRevision)}function Ok(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Mk(t,e,r){if(!Ik(t,e,r))throw new Error($k)}async function h2(t,e,r,n,o,i,s){let a=t.servers.get(e),c=t.tokens,u=c.get(e),d=t.credentialRevisions.get(e);if(c!==r.tokenStore||!a||!u||!ht(r.server.config,a.config))return;let l=a.config,f=Gt(t,a);try{let p=await c.restoreAfterSupersededAuthentication(e,o,u,n,i,f);if(p===void 0||t.tokens!==c||t.servers.get(e)?.config!==l||c.get(e)!==u||!kr(Gt(t,a),f)||!Ok(t.credentialRevisions.get(e),d)||c.reconcileCredentialIdentity?.(e,u,f)!==!0)return;dn({state:t,name:e,revision:p}),N(t.currentLoad?.latestPi??s,t)}catch{Mm.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function m2(t){let e=t.serverMetadata;if(!e.authorization_endpoint||!e.token_endpoint)throw new Error("Authorization server metadata is missing required endpoints");let r=t.client.client_secret,n=t.client.token_endpoint_auth_method;return{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,tokenType:t.tokenType,scope:t.scope,resource:t.resource,serverMetadata:{issuer:e.issuer,authorization_endpoint:e.authorization_endpoint,token_endpoint:e.token_endpoint},client:{client_id:t.client.client_id,...typeof r=="string"?{client_secret:r}:{},...typeof n=="string"?{token_endpoint_auth_method:n}:{}}}}function g2(t,e,r,n){return new Promise((o,i)=>{let s=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=m=>{s||(s=!0,c(),m())},d=()=>u(()=>i(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>i(new Error("Authentication timed out"))),p2)},f=m=>{let g=m instanceof Error?m.message:String(m);u(()=>i(new Error(`Could not read the pasted authorization code (${g}). Restart sign-in and paste the full redirect URL.`)))},p=async(m,g)=>{let v=await n(m,l);if(!s){if(v){h(g);return}u(()=>i(Am(m)))}},h=(m=e.waitForManualCode())=>{m.then(async g=>{if(!(s||!g))try{let v=kk(g,r());if(v.kind==="success"){u(()=>o(v.result));return}let w=e.waitForManualCode();await p(v.params,w)}catch(v){f(v)}}).catch(g=>u(()=>i(g instanceof Error?g:new Error(String(g)))))};if(t.setErrorRetryHandler(m=>n(m,l)),l(),e.signal.aborted){u(()=>i(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(m=>{m&&u(()=>o(m))}).catch(m=>u(()=>i(m instanceof Error?m:new Error(String(m))))),h()})}async function zk(t){let{serverName:e,state:r,pi:n,controller:o}=t,i=r.servers.get(e);if(!i)throw new Error(`Unknown MCP server "${e}"`);let s=i.config;if(s.type!=="http"&&s.type!=="sse")throw new Error(`MCP server "${e}" does not use OAuth authentication`);if(r.authenticating)throw new Error("Another MCP authentication is already in progress");r.authenticating=!0,r.authenticatingServerName=e;let a=++r.authenticationGeneration,c={authenticationGeneration:a,server:i,serverGeneration:r.serverGenerations.get(e)??0,installedConfigRevision:r.configRevisions.get(e)??0,desiredConfigRevision:r.configDesiredRevisions.get(e)??0,tokenStore:r.tokens,token:r.tokens.get(e),credentialRevision:r.credentialRevisions.get(e)},u=Gt(r,i),d;try{br(o.signal),d=await Tk(),br(o.signal);let l=new URL(s.url),f,p;try{f=await el(l),br(o.signal),p=await tl(f),br(o.signal)}catch(be){br(o.signal);let qt=Ti(be);throw qt?Ai(qt):new Error(`OAuth discovery failed for MCP server "${e}". Verify that the endpoint supports OAuth and publishes discovery metadata.`)}let h=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Mk(r,e,c),br(o.signal);let m=await rl({config:s.clientId?{clientId:s.clientId}:{},serverMetadata:p,redirectUris:[d.redirectUri],preferStaticClient:s.registrySource===void 0});br(o.signal);let g=await Fa(l,m,p,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);br(o.signal);let v=g,w=!1,b,R,_=(be,qt)=>{if(w)return R&&b&&Ua(be,b)?R.then(pt=>pt.authUri.toString()):Promise.resolve(null);if(!Ua(be,v))return Promise.resolve(null);w=!0;let un=v;return b=un,qt(),Mm.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),R=nl(un).then(pt=>(v=pt,o.onAuthUrl({url:pt.authUri.toString(),instructions:Ak()}),pt)),R.then(pt=>pt.authUri.toString())};d.setErrorRetryHandler(be=>_(be,()=>{})),o.onAuthUrl({url:g.authUri.toString(),instructions:Ak()}),br(o.signal),await wk(g.authUri.toString());let C=await g2(d,o,()=>v.state,_),I=await ol(C,v);Mk(r,e,c);let ee=m2(I),pe=await c.tokenStore.persistAuthenticated(e,ee,u,h);if(!Ik(r,e,c))throw await h2(r,e,c,u,ee,pe,n),new Error($k);c.tokenStore.commit(e,ee,u),r.preservedCredentialIdentities?.delete(e),dn({state:r,name:e,revision:pe}),r.tokens.clearAuthRequired(e),ct(r,e),await ta([e],r,n),N(r.currentLoad?.latestPi??n,r),Se(r),Mm.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as $2}from"@augmentcode/auggie-v2";import{resolveTargetFiles as y2,SETTINGS_TARGET_ORDER as v2,SettingsManager as _2,scopeToSettingsTarget as S2,settingsTargetToScope as $m}from"@augmentcode/auggie-v2";var w2=v2.map(t=>$m(t)),Nk=(t,e)=>_2.create(t,e);function Dk(t,e){switch(e){case"global":return t.getGlobalSettings().mcpServers;case"project":return t.getProjectSettings().mcpServers;case"local":return t.getLocalSettings().mcpServers;case"managed":return t.getManagedSettings().mcpServers}}function Lk(t,e,r){let n=Nk(e,r);return w2.filter(o=>Dk(n,o)?.[t])}function jk(t){let e=t.map(n=>({target:S2(n),path:n,exists:!0})),r=y2({files:e});return"directTarget"in r?{scopes:t,direct:$m(r.directTarget)}:{scopes:r.files.map(n=>$m(n.target)),direct:null}}function b2(t,e,r){let{servers:n}=ro(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Fk(t,e,r,n,o){try{let i=Nk(n,o);if(!Dk(i,r)?.[t])return{ok:!1,error:`Server "${t}" not found in ${r} settings`};i.update(r,{path:["mcpServers",t,"disabled"],value:e})}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}return{ok:!0,overridden:b2(t,n,o)!==e}}function Im(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function Uk(t,e,r){return Im(t)}function qk(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as R2}from"@hermes/logger";var zm=R2.child({prefix:"pi-mcp"}),Hk="hermes:mcp:register-server-source";function C2(t,e){return t.type==="stdio"?Bt(t,e):Zt(t,e)}function Gk(t,e){return JSON.stringify(t)===JSON.stringify(e)}function P2(t,e){return{...t,disabled:e}}function x2(t){try{return t.getServers()}catch(e){return zm.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function E2(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Zk(t,e){t.diagnostics.push({server:e,message:`plugin MCP server "${e}" is shadowed by an existing MCP server of the same name; skipping`,origin:"plugin"})}function k2(t,e,r,n){let o=new Map;if(!t)return o;for(let i of x2(t)){let s=e.servers.get(i.name),a=C2(i,r),c=e.sessionPluginDisabledOverrides.get(i.name),u=P2(a,c??a.disabled===!0),d=e.pluginServerHosts.get(i.name);s&&d===s&&te(e,i.name,s);let l=D(e,i.name),f=s!==void 0&&l?.owner.kind==="plugin"&&l.host===s,p=s!==void 0&&d===void 0&&n.has(i.name)&&Gk(s.config,u);p&&(te(e,i.name,s),sg({state:e,name:i.name,host:s}));let h=l?.owner.kind==="vfs";if(s&&!(f||p||h)){e.pluginServerNames.delete(i.name),e.pluginServerHosts.delete(i.name),Zk(e,i.name);continue}o.has(i.name)||o.set(i.name,u)}return o}async function T2(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let i=D(r,o);if(i?.owner.kind!=="plugin")continue;let s=i.host;if(!s){Ee({state:r,name:o,owner:i.owner,revision:i.revision});continue}let a=ut({state:r,name:o,owner:i.owner,revision:i.revision,host:s});if(!a)continue;let c=mt(r,o,s.config.id,s.config);s.beginDisposal?.(),n.push(Promise.allSettled([c,s.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw _e({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;_e({state:r,name:o,retirement:a,result:{status:"retired"}}),Ee({state:r,name:o,owner:i.owner,revision:i.revision})}))}await Promise.all(n)}function Bk(t,e){Zk(t,e)}function A2(t){let{state:e,desired:r,previousNames:n,previousHosts:o}=t,i=[],s=new Map;for(let[a,c]of r){let u=e.servers.get(a),d=u?te(e,a,u):D(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){Bk(e,a);continue}u!==void 0&&u===o.get(a)&&n.has(a)&&Gk(u.config,c)||(s.set(a,Ke(e,a,"plugin")),i.push(c))}return{reservedRevisions:s,toConnect:i}}async function M2(t,e,r){let n=r?.connect??Je,o=e.pluginServerSource,i=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&E2(o,e);let s=new Set(e.pluginServerNames);e.pluginServerHosts??=new Map;for(let[h,m]of e.pluginServerHosts){let g=e.servers.get(h);(g===void 0||g===m)&&te(e,h,m)}let a=k2(o,e,i,s);e.configDesiredRevisions??=new Map,e.configRevisions??=new Map;let c=new Map,u=new Set;for(let[h,m]of e.hostLeases)m.owner.kind==="plugin"&&(u.add(h),m.host&&c.set(h,m.host));await T2(a,u,e);let{reservedRevisions:d,toConnect:l}=A2({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;zm.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let g=D(e,h.name),v=g?.owner.kind!=="local"&&g?.owner.kind!=="registry";return v||Bk(e,h.name),v};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),N(f(),e),Se(e)}}function Om(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>M2(t,e,r)).catch(i=>{zm.warn(`Plugin MCP reconciliation failed: ${i instanceof Error?i.message:String(i)}`)});return e.pluginReconcileQueue=o,o}function Wk(t,e){let{name:r,disabled:n,state:o,pi:i}=t,s=o.servers.get(r),a=s?te(o,r,s):D(o,r);return a?.owner.kind!=="plugin"||a.host!==s?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),Om(o.currentLoad?.latestPi??i,o,e))}function Vk(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Om(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Om(e.currentLoad?.latestPi??t,e))})}}function I2(t,e){let n=$2.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function Kk(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(I2(n,o).has(e))return{kind:"blocked",message:`Cannot toggle "${e}": server is managed and cannot be modified`};let i=r.servers.get(e);if(!i)return{kind:"blocked",message:Im(e)};if(pd(r.mcpConfigOverride).has(e))return{kind:"session"};if(xr(i,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let s=Lk(e,n,o);if(s.length===0)return{kind:"blocked",message:Uk(e,n,o)};let{scopes:a,direct:c}=jk(s);return{kind:"local",scopes:a,direct:c}}async function Jk(t){let{server:e,disable:r,state:n,pi:o}=t,i=n.servers.get(e);if(!i)return;let s=n.hostLeases?.get(e)??(n.pluginServerHosts?.get(e)===i?te(n,e,i):void 0);if(s?.owner.kind==="plugin"&&s.host===i){await Wk({name:e,disabled:r,state:n,pi:o});return}pd(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),i.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...i.config,disabled:r};await Je([a],n,o,void 0,void 0,s?.owner.kind),Se(n)}async function Yk(t){let{server:e,disable:r,scope:n,state:o,pi:i,cwd:s,agentDir:a}=t,c=Fk(e,r,n,s,a);if(!c.ok)throw new Error(c.error);return await BE(e,o,i,s,a),Se(o),c.overridden?{notice:qk(e)}:{}}import{DynamicBorder as e4}from"@augmentcode/auggie-v2";import{Key as t4,matchesKey as r4,SearchableWindowedList as n4,SpinnerTimer as o4,truncateToWidth as Vu,wrapTextWithAnsi as i4}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as O2,scopeToSettingsTarget as z2}from"@augmentcode/auggie-v2";import{truncateToWidth as N2,visibleWidth as Jn,wrapTextWithAnsi as D2}from"@earendil-works/pi-tui";var L2=2,j2=2,qu={name:"Name",source:"Source",status:"Status"};function Nm(t){if(t.disabled)return{label:"Disabled",color:"muted"};switch(t.status){case"success":return{label:`${t.tools.length} tools available`,color:"success"};case"failed":return{label:"Failed",color:"error"};case"auth_required":return{label:"Auth required",color:"warning",hint:" Press Enter for options"};case"disabled":return{label:"Disabled",color:"muted"};default:return{label:"Initializing",color:"text"}}}function Dm(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Lm(t,e){let r=e-Jn(t);return r>0?t+" ".repeat(r):t}function Hu(t){return t.reduce((e,r)=>Math.max(e,Jn(r)),0)}function ri(t,e,r,n){let o=`${e}Width`,i=Math.min(Math.max(0,r-t[o]),n);return t[o]+=i,n-i}function Xk(t,e){let r=Math.max(1,Math.floor(e)),n=Math.min(L2,r),o=r-n,i=Math.min(3,o),s=i<2?0:Math.min(j2,Math.floor((o-i)/(i-1))),a=o-s*Math.max(0,i-1),c=["name","source","status"].slice(0,i),u={prefixWidth:n,gapWidth:s,nameWidth:0,sourceWidth:0,statusWidth:0};for(let g of c)a=ri(u,g,1,a);for(let g=1;a>0;g++){let v=!1;for(let w of c)if(!(g>=Jn(qu[w]))&&(a=ri(u,w,g+1,a),v=!0,a===0))break;if(!v)break}let d=t.map(g=>Dm(g)),l=t.map(g=>Nm(g)),f=Math.max(Jn(qu.source),Hu(d)),p=Math.max(Jn(qu.status),Hu(l.map(g=>g.label))),h=Math.max(Jn(qu.name),Hu(t.map(g=>g.name))),m=Math.max(p,Hu(l.map(g=>g.label+(g.hint??""))));return a=ri(u,"source",f,a),a=ri(u,"status",p,a),a=ri(u,"name",h,a),ri(u,"status",m,a),u}function Qk(t,e,r){if(e<=r)return{start:0,end:e};let n=Math.floor(r/2),o=Math.max(0,Math.min(t-n,e-r));return{start:o,end:o+r}}function ni(t,e){let r=Math.max(1,Math.floor(e));return t.flatMap(n=>D2(n,r).map(o=>Jn(o)<=r?o:N2(o,r,"")))}function F2(t,e){return Math.max(0,t-e)}function oi(t,e,r){return Math.max(0,Math.min(t,F2(e,r)))}function eT(t,e,r){let n=oi(t,e,r),o=Math.min(e,n+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Rows ${n+1}-${o} of ${e}`}}function tT(t,e){return String(t+1).padStart(String(e).length," ")}function jm(t){return O2(z2(t))}import{Key as U2,matchesKey as q2}from"@earendil-works/pi-tui";function Gu(t){if(t.source==="plugin"&&t.disabled)return t.canAuthenticate?["authenticate","toggle"]:["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.canAuthenticate&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function rT(){return{step:"serverList",filterQuery:"",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var nT=10,Yn=15;var H2="k",G2="j";function ii(t,e){return(t%e+e)%e}function st(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function Fm(t,e,r=!0){return e.matches(t,"tui.select.up")||r&&t===H2?{kind:"up"}:e.matches(t,"tui.select.down")||r&&t===G2?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:q2(t,U2.backspace)?{kind:"back"}:{kind:"ignore"}}function Z2(t,e,r){if(e.kind==="filterChanged")return{state:{...t,filterQuery:e.query,selectedServer:r[0]?.name??null}};let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=ii(st(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=ii(st(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[st(r,t.selectedServer)];return o?.status==="auth_required"&&o.canAuthenticate?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function B2(t,e,r){let n=r.snapshots[st(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Gu(n);switch(e.kind){case"up":return{state:{...t,actionIndex:ii(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:ii(t.actionIndex+1,o.length)}};case"cancel":case"back":return{state:{...t,step:"serverList"}};case"confirm":{let i=o[t.actionIndex];return i==="viewTools"?{state:{...t,step:"viewTools",toolIndex:0}}:i==="viewLogs"?{state:{...t,step:"viewLogs",logScrollOffset:0}}:i==="authenticate"?{state:t,effect:{kind:"authenticate",server:n.name}}:i==="toggle"?{state:t,effect:{kind:"toggle",server:n.name,disable:!n.disabled}}:{state:t,effect:{kind:"reconnect",server:n.name}}}default:return{state:t}}}function W2(t,e,r){let n=r.snapshots[st(r.snapshots,t.selectedServer)]?.tools.length??0;switch(e.kind){case"up":return{state:{...t,toolIndex:Math.max(0,t.toolIndex-1)}};case"down":return{state:{...t,toolIndex:Math.min(Math.max(0,n-1),t.toolIndex+1)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function V2(t,e,r){let n=r.snapshots[st(r.snapshots,t.selectedServer)]?.logLines()??[],o=ni(n,r.logViewportWidth).length;switch(e.kind){case"up":return{state:{...t,logScrollOffset:oi(t.logScrollOffset-1,o,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:oi(t.logScrollOffset+1,o,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function K2(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Zu(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function J2(t,e){let r=t.targetScopes.length;if(r===0)return{state:Zu(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:ii(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:ii(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Zu(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Zu({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Zu(t,"serverActions")}}default:return{state:t}}}function oT(t,e,r){switch(t.step){case"serverList":return Z2(t,e,r.snapshots);case"serverActions":return B2(t,e,r);case"viewTools":return W2(t,e,r);case"viewLogs":return V2(t,e,r);case"pasteAuthCode":return K2(t,e);case"selectTarget":return J2(t,e);default:return{state:t}}}import{truncateToWidth as Ut,visibleWidth as Y2,wrapTextWithAnsi as cn}from"@earendil-works/pi-tui";var Um="\u2192 ",Bu=" ";function iT(t,e,r){return e?r.bold(r.fg("accent",t)):r.fg("text",t)}function Rr(t,e){return e>0?Ut(t,e,"\u2026"):""}function sT(t,e,r,n,o,i,s){let a=Math.max(1,s),c=Xk(r,a),u=" ".repeat(c.gapWidth),d=(h,m,g,v)=>{let w=[c.nameWidth>0?Lm(m,c.nameWidth):"",c.sourceWidth>0?Lm(g,c.sourceWidth):"",c.statusWidth>0?v:""].filter(b=>b.length>0);return h+w.join(u)},l=Rr(Bu,c.prefixWidth),p=[d(l,i.bold(i.fg("accent",Rr("Name",c.nameWidth))),i.bold(i.fg("accent",Rr("Source",c.sourceWidth))),i.bold(i.fg("accent",Rr("Status",c.statusWidth))))];if(e.length===0)p.push(Ut(i.fg("muted","No MCP servers available"),a,"\u2026"));else if(o.total===0)p.push(Ut(i.fg("muted","No matching MCP servers"),a,"\u2026"));else for(let h of n){let m=h.name===t.selectedServer,g=Nm(h),v=Rr(g.label,c.statusWidth),w=c.statusWidth-Y2(v),b=g.hint?Rr(g.hint,w):"",R=i.fg(g.color,v)+(b?i.fg("muted",b):""),_=Rr(m?Um:Bu,c.prefixWidth);p.push(d(m?i.fg("accent",_):_,iT(Rr(h.name,c.nameWidth),m,i),iT(Rr(Dm(h),c.sourceWidth),m,i),R))}return o.hasOverflow&&p.push(Ut(i.fg("muted",` (${o.current}/${o.total})`),a,"\u2026")),p}var X2={authenticate:{label:"Authenticate",description:"Connect to this server"},viewTools:{label:"View tools",description:"See all tools provided by this server"},viewLogs:{label:"View logs",description:"View logs from this server"},reconnect:{label:"Reconnect",description:"Restart the server connection"},toggle:{label:"Disable",description:"Enable or disable this server"}};function Q2(t,e){if(t==="authenticate")return e.status==="auth_required"?{label:"Authenticate",description:"Connect to this server"}:{label:"Reauthenticate",description:"Refresh authentication"};if(t==="toggle"){let r=e.source!=="local";return e.disabled?r?{label:"Enable for this session",description:"Re-enable this server for the current session only"}:{label:"Enable",description:"Enable this server (saved to settings.json)"}:r?{label:"Disable for this session",description:"Disable this server for the current session only"}:{label:"Disable",description:"Disable this server (saved to settings.json)"}}return X2[t]}function aT(t,e,r,n){let o=Math.max(1,n),i=e[st(e,t.selectedServer)];if(!i)return cn(r.fg("muted","No MCP servers available"),o);let s=i.transport==="stdio"?"Command: ":"URL: ",a=cn(r.fg("muted",s+i.connectionInfo),o);i.source==="plugin"&&a.push(...cn(r.fg("muted","Source: plugin (toggles apply to this session only)"),o)),a.push("");let c=Gu(i);for(let[u,d]of c.entries()){let l=u===t.actionIndex,f=Q2(d,i),p=f.label,h=l?r.bold(r.fg("accent",p)):r.fg("text",p);a.push(Ut((l?Um:Bu)+h+r.fg("muted",` - ${f.description}`),o,"\u2026"))}return a}function cT(t,e,r,n){let o=Math.max(1,n),i=e[st(e,t.selectedServer)];if(!i)return cn(r.fg("muted","No tools available."),o);if(i.disabled)return cn(r.fg("muted","Server is disabled; no tools are currently available."),o);if(i.tools.length===0)return cn(r.fg("muted","No tools available."),o);let s=i.tools.length,{start:a,end:c}=Qk(t.toolIndex,s,Yn),u=[];for(let d=a;d<c;d++){let l=i.tools[d];if(!l)continue;let p=d===t.toolIndex?r.bold(r.fg("accent",l.name)):r.fg("text",l.name);u.push(Ut(r.fg("muted",`${tT(d,s)} `)+p+(l.disabled?r.fg("muted"," (disabled)"):""),o,"\u2026"))}return u}function uT(t,e,r,n){let o=Math.max(1,n),s=e[st(e,t.selectedServer)]?.logLines()??[];if(s.length===0)return cn(r.fg("muted","No logs available yet."),o);let a=ni(s,o),c=a.length,u=eT(t.logScrollOffset,c,Yn),d=[];c>Yn&&d.push(Ut(r.fg("muted",u.rangeLabel),o,"\u2026")),u.aboveCount>0&&d.push(Ut(r.fg("dim",`\u2191 ${u.aboveCount} more rows`),o,"\u2026"));for(let l of a.slice(u.start,u.end))d.push(Ut(r.fg("text",l),o,""));return u.belowCount>0&&d.push(Ut(r.fg("dim",`\u2193 ${u.belowCount} more rows`),o,"\u2026")),d}function dT(t,e,r,n){let o=Math.max(1,n),i=e[st(e,t.selectedServer)]?.name??"",s=[...cn(r.fg("muted",`Save the toggle for "${i}" to which settings file?`),o),""];for(let[a,c]of t.targetScopes.entries()){let u=a===t.targetIndex,d=u?r.bold(r.fg("accent",jm(c))):r.fg("text",jm(c));s.push(Ut((u?Um:Bu)+d,o,"\u2026"))}return s}var Wu=3;function s4(t){return t.type==="stdio"?t.command:t.url}function a4(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
|
|
143
|
+
</html>`}function Mk(t){return Ak({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function qu(t,e){return Ak({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var I2="127.0.0.1",Ok="/callback",$k=3e3,Ik=3010,O2="Authentication successful. You can close this window.",Hu={"Content-Type":"text/html; charset=utf-8"};function zk(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function Nk(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:new URLSearchParams({code:r,state:e})};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}if(!n.get("code"))throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return o===null&&n.set("state",e),{kind:"success",result:n}}function Im(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function z2(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==Ok){e.writeHead(404,Hu),e.end(qu("Callback route not found."));return}let o=n.searchParams.get("code"),i=n.searchParams.get("state"),s=n.searchParams.get("error");if(s){let a=c=>{e.writeHead(400,Hu),e.end(qu("Authentication did not complete.",`Error: ${s}`));let u=Im(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!i){e.writeHead(400,Hu),e.end(qu("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Hu),e.end(Mk(O2)),r.onSuccess(n.searchParams)}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function N2(t){for(let e=$k;e<=Ik;e++)if(await new Promise(n=>{let o=()=>{t.removeListener("listening",i),n(!1)},i=()=>{t.removeListener("error",o),n(!0)};t.once("error",o),t.once("listening",i),t.listen(e,I2)}))return e;throw new Error(`No free port in ${$k}-${Ik} for the OAuth callback server`)}async function Dk(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,i=$2((a,c)=>{z2(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),s=await N2(i);return{port:s,redirectUri:`http://localhost:${s}${Ok}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>i.close(),setErrorRetryHandler:a=>{o=a}}}var Om=D2.child({prefix:"pi-mcp"}),L2=300*1e3,Fk="MCP authentication was superseded";function Lk(){return zk()?"You appear to be on a remote machine. Open the URL in a local browser, then paste the final redirect URL or code below.":"Complete sign-in in your browser. If it doesn't open, paste the final redirect URL or code below."}function Rr(t){if(t.aborted)throw new Error("Authentication cancelled")}function Uk(t,e,r){return t.authenticationGeneration===r.authenticationGeneration&&t.servers.get(e)===r.server&&(t.serverGenerations.get(e)??0)===r.serverGeneration&&(t.configRevisions.get(e)??0)===r.installedConfigRevision&&(t.configDesiredRevisions.get(e)??0)===r.desiredConfigRevision&&t.tokens===r.tokenStore&&t.tokens.get(e)===r.token&&qk(t.credentialRevisions.get(e),r.credentialRevision)}function qk(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function jk(t,e,r){if(!Uk(t,e,r))throw new Error(Fk)}async function j2(t,e,r,n,o,i,s){let a=t.servers.get(e),c=t.tokens,u=c.get(e),d=t.credentialRevisions.get(e);if(c!==r.tokenStore||!a||!u||!mt(r.server.config,a.config))return;let l=a.config,f=Gt(t,a);try{let p=await c.restoreAfterSupersededAuthentication(e,o,u,n,i,f);if(p===void 0||t.tokens!==c||t.servers.get(e)?.config!==l||c.get(e)!==u||!Tr(Gt(t,a),f)||!qk(t.credentialRevisions.get(e),d)||c.reconcileCredentialIdentity?.(e,u,f)!==!0)return;pn({state:t,name:e,revision:p}),N(t.currentLoad?.latestPi??s,t)}catch{Om.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function F2(t){let e=t.serverMetadata;if(!e.authorization_endpoint||!e.token_endpoint)throw new Error("Authorization server metadata is missing required endpoints");let r=t.client.client_secret,n=t.client.token_endpoint_auth_method;return{accessToken:t.accessToken,refreshToken:t.refreshToken,expiresAt:t.expiresAt,tokenType:t.tokenType,scope:t.scope,resource:t.resource,serverMetadata:{issuer:e.issuer,authorization_endpoint:e.authorization_endpoint,token_endpoint:e.token_endpoint},client:{client_id:t.client.client_id,...typeof r=="string"?{client_secret:r}:{},...typeof n=="string"?{token_endpoint_auth_method:n}:{}}}}function U2(t,e,r,n){return new Promise((o,i)=>{let s=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=g=>{s||(s=!0,c(),g())},d=()=>u(()=>i(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>i(new Error("Authentication timed out"))),L2)},f=g=>{let m=g instanceof Error?g.message:String(g);u(()=>i(new Error(`Could not read the pasted authorization code (${m}). Restart sign-in and paste the full redirect URL.`)))},p=async(g,m)=>{let v=await n(g,l);if(!s){if(v){h(m);return}u(()=>i(Im(g)))}},h=(g=e.waitForManualCode())=>{g.then(async m=>{if(!(s||!m))try{let v=Nk(m,r());if(v.kind==="success"){u(()=>o(v.result));return}let w=e.waitForManualCode();await p(v.params,w)}catch(v){f(v)}}).catch(m=>u(()=>i(m instanceof Error?m:new Error(String(m)))))};if(t.setErrorRetryHandler(g=>n(g,l)),l(),e.signal.aborted){u(()=>i(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(g=>{g&&u(()=>o(g))}).catch(g=>u(()=>i(g instanceof Error?g:new Error(String(g))))),h()})}async function Hk(t){let{serverName:e,state:r,pi:n,controller:o}=t,i=r.servers.get(e);if(!i)throw new Error(`Unknown MCP server "${e}"`);let s=i.config;if(s.type!=="http"&&s.type!=="sse")throw new Error(`MCP server "${e}" does not use OAuth authentication`);if(r.authenticating)throw new Error("Another MCP authentication is already in progress");r.authenticating=!0,r.authenticatingServerName=e;let a=++r.authenticationGeneration,c={authenticationGeneration:a,server:i,serverGeneration:r.serverGenerations.get(e)??0,installedConfigRevision:r.configRevisions.get(e)??0,desiredConfigRevision:r.configDesiredRevisions.get(e)??0,tokenStore:r.tokens,token:r.tokens.get(e),credentialRevision:r.credentialRevisions.get(e)},u=Gt(r,i),d;try{Rr(o.signal),d=await Dk(),Rr(o.signal);let l=new URL(s.url),f,p;try{f=await rl(l),Rr(o.signal),p=await nl(f),Rr(o.signal)}catch(be){Rr(o.signal);let qt=Ai(be);throw qt?Mi(qt):new Error(`OAuth discovery failed for MCP server "${e}". Verify that the endpoint supports OAuth and publishes discovery metadata.`)}let h=await c.tokenStore.captureAuthenticatedIdentityVersion(u);jk(r,e,c),Rr(o.signal);let g=await ol({config:s.clientId?{clientId:s.clientId}:{},serverMetadata:p,redirectUris:[d.redirectUri],preferStaticClient:s.registrySource===void 0});Rr(o.signal);let m=await Ua(l,g,p,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);Rr(o.signal);let v=m,w=!1,b,R,_=(be,qt)=>{if(w)return R&&b&&qa(be,b)?R.then(ht=>ht.authUri.toString()):Promise.resolve(null);if(!qa(be,v))return Promise.resolve(null);w=!0;let fn=v;return b=fn,qt(),Om.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),R=il(fn).then(ht=>(v=ht,o.onAuthUrl({url:ht.authUri.toString(),instructions:Lk()}),ht)),R.then(ht=>ht.authUri.toString())};d.setErrorRetryHandler(be=>_(be,()=>{})),o.onAuthUrl({url:m.authUri.toString(),instructions:Lk()}),Rr(o.signal),await Tk(m.authUri.toString());let C=await U2(d,o,()=>v.state,_),I=await sl(C,v);jk(r,e,c);let ee=F2(I),pe=await c.tokenStore.persistAuthenticated(e,ee,u,h);if(!Uk(r,e,c))throw await j2(r,e,c,u,ee,pe,n),new Error(Fk);c.tokenStore.commit(e,ee,u),r.preservedCredentialIdentities?.delete(e),pn({state:r,name:e,revision:pe}),r.tokens.clearAuthRequired(e),ut(r,e),await ta([e],r,n),N(r.currentLoad?.latestPi??n,r),Se(r),Om.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as n4}from"@augmentcode/auggie-v2";import{resolveTargetFiles as q2,SETTINGS_TARGET_ORDER as H2,SettingsManager as G2,scopeToSettingsTarget as Z2,settingsTargetToScope as zm}from"@augmentcode/auggie-v2";var B2=H2.map(t=>zm(t)),Gk=(t,e)=>G2.create(t,e);function Zk(t,e){switch(e){case"global":return t.getGlobalSettings().mcpServers;case"project":return t.getProjectSettings().mcpServers;case"local":return t.getLocalSettings().mcpServers;case"managed":return t.getManagedSettings().mcpServers}}function Bk(t,e,r){let n=Gk(e,r);return B2.filter(o=>Zk(n,o)?.[t])}function Wk(t){let e=t.map(n=>({target:Z2(n),path:n,exists:!0})),r=q2({files:e});return"directTarget"in r?{scopes:t,direct:zm(r.directTarget)}:{scopes:r.files.map(n=>zm(n.target)),direct:null}}function W2(t,e,r){let{servers:n}=no(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Vk(t,e,r,n,o){try{let i=Gk(n,o);if(!Zk(i,r)?.[t])return{ok:!1,error:`Server "${t}" not found in ${r} settings`};i.update(r,{path:["mcpServers",t,"disabled"],value:e})}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}return{ok:!0,overridden:W2(t,n,o)!==e}}function Nm(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function Kk(t,e,r){return Nm(t)}function Jk(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as V2}from"@hermes/logger";var Lm=V2.child({prefix:"pi-mcp"}),Yk="hermes:mcp:register-server-source";function K2(t,e){return t.type==="stdio"?Bt(t,e):Zt(t,e)}function Xk(t,e){return JSON.stringify(t)===JSON.stringify(e)}function J2(t,e){return{...t,disabled:e}}function Y2(t){try{return t.getServers()}catch(e){return Lm.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function X2(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Qk(t,e){t.diagnostics.push({server:e,message:`plugin MCP server "${e}" is shadowed by an existing MCP server of the same name; skipping`,origin:"plugin"})}function Q2(t,e,r,n){let o=new Map;if(!t)return o;for(let i of Y2(t)){let s=e.servers.get(i.name),a=K2(i,r),c=e.sessionPluginDisabledOverrides.get(i.name),u=J2(a,c??a.disabled===!0),d=e.pluginServerHosts.get(i.name);s&&d===s&&te(e,i.name,s);let l=D(e,i.name),f=s!==void 0&&l?.owner.kind==="plugin"&&l.host===s,p=s!==void 0&&d===void 0&&n.has(i.name)&&Xk(s.config,u);p&&(te(e,i.name,s),ug({state:e,name:i.name,host:s}));let h=l?.owner.kind==="vfs";if(s&&!(f||p||h)){e.pluginServerNames.delete(i.name),e.pluginServerHosts.delete(i.name),Qk(e,i.name);continue}o.has(i.name)||o.set(i.name,u)}return o}async function e4(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let i=D(r,o);if(i?.owner.kind!=="plugin")continue;let s=i.host;if(!s){xe({state:r,name:o,owner:i.owner,revision:i.revision});continue}let a=dt({state:r,name:o,owner:i.owner,revision:i.revision,host:s});if(!a)continue;let c=gt(r,o,s.config.id,s.config);s.beginDisposal?.(),n.push(Promise.allSettled([c,s.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw _e({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;_e({state:r,name:o,retirement:a,result:{status:"retired"}}),xe({state:r,name:o,owner:i.owner,revision:i.revision})}))}await Promise.all(n)}function eT(t,e){Qk(t,e)}function t4(t){let{state:e,desired:r,previousNames:n,previousHosts:o}=t,i=[],s=new Map;for(let[a,c]of r){let u=e.servers.get(a),d=u?te(e,a,u):D(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){eT(e,a);continue}u!==void 0&&u===o.get(a)&&n.has(a)&&Xk(u.config,c)||(s.set(a,Ke(e,a,"plugin")),i.push(c))}return{reservedRevisions:s,toConnect:i}}async function r4(t,e,r){let n=r?.connect??Je,o=e.pluginServerSource,i=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&X2(o,e);let s=new Set(e.pluginServerNames);e.pluginServerHosts??=new Map;for(let[h,g]of e.pluginServerHosts){let m=e.servers.get(h);(m===void 0||m===g)&&te(e,h,g)}let a=Q2(o,e,i,s);e.configDesiredRevisions??=new Map,e.configRevisions??=new Map;let c=new Map,u=new Set;for(let[h,g]of e.hostLeases)g.owner.kind==="plugin"&&(u.add(h),g.host&&c.set(h,g.host));await e4(a,u,e);let{reservedRevisions:d,toConnect:l}=t4({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Lm.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let g=d.get(h.name);if(g===void 0||e.configDesiredRevisions.get(h.name)!==g)return!1;let m=D(e,h.name),v=m?.owner.kind!=="local"&&m?.owner.kind!=="registry";return v||eT(e,h.name),v};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),N(f(),e),Se(e)}}function Dm(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>r4(t,e,r)).catch(i=>{Lm.warn(`Plugin MCP reconciliation failed: ${i instanceof Error?i.message:String(i)}`)});return e.pluginReconcileQueue=o,o}function tT(t,e){let{name:r,disabled:n,state:o,pi:i}=t,s=o.servers.get(r),a=s?te(o,r,s):D(o,r);return a?.owner.kind!=="plugin"||a.host!==s?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),Dm(o.currentLoad?.latestPi??i,o,e))}function rT(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Dm(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Dm(e.currentLoad?.latestPi??t,e))})}}function o4(t,e){let n=n4.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function nT(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(o4(n,o).has(e))return{kind:"blocked",message:`Cannot toggle "${e}": server is managed and cannot be modified`};let i=r.servers.get(e);if(!i)return{kind:"blocked",message:Nm(e)};if(md(r.mcpConfigOverride).has(e))return{kind:"session"};if(xr(i,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let s=Bk(e,n,o);if(s.length===0)return{kind:"blocked",message:Kk(e,n,o)};let{scopes:a,direct:c}=Wk(s);return{kind:"local",scopes:a,direct:c}}async function oT(t){let{server:e,disable:r,state:n,pi:o}=t,i=n.servers.get(e);if(!i)return;let s=n.hostLeases?.get(e)??(n.pluginServerHosts?.get(e)===i?te(n,e,i):void 0);if(s?.owner.kind==="plugin"&&s.host===i){await tT({name:e,disabled:r,state:n,pi:o});return}md(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),i.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...i.config,disabled:r};await Je([a],n,o,void 0,void 0,s?.owner.kind),Se(n)}async function iT(t){let{server:e,disable:r,scope:n,state:o,pi:i,cwd:s,agentDir:a}=t,c=Vk(e,r,n,s,a);if(!c.ok)throw new Error(c.error);return await ek(e,o,i,s,a),Se(o),c.overridden?{notice:Jk(e)}:{}}import{DynamicBorder as P4}from"@augmentcode/auggie-v2";import{Key as E4,matchesKey as x4,SearchableWindowedList as k4,SpinnerTimer as T4,truncateToWidth as Ju,wrapTextWithAnsi as A4}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as i4,scopeToSettingsTarget as s4}from"@augmentcode/auggie-v2";import{truncateToWidth as a4,visibleWidth as Yn,wrapTextWithAnsi as c4}from"@earendil-works/pi-tui";var u4=2,d4=2,Gu={name:"Name",source:"Source",status:"Status"};function jm(t){if(t.disabled)return{label:"Disabled",color:"muted"};switch(t.status){case"success":return{label:`${t.tools.length} tools available`,color:"success"};case"failed":return{label:"Failed",color:"error"};case"auth_required":return{label:"Auth required",color:"warning",hint:" Press Enter for options"};case"disabled":return{label:"Disabled",color:"muted"};default:return{label:"Initializing",color:"text"}}}function Fm(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Um(t,e){let r=e-Yn(t);return r>0?t+" ".repeat(r):t}function Zu(t){return t.reduce((e,r)=>Math.max(e,Yn(r)),0)}function ni(t,e,r,n){let o=`${e}Width`,i=Math.min(Math.max(0,r-t[o]),n);return t[o]+=i,n-i}function sT(t,e){let r=Math.max(1,Math.floor(e)),n=Math.min(u4,r),o=r-n,i=Math.min(3,o),s=i<2?0:Math.min(d4,Math.floor((o-i)/(i-1))),a=o-s*Math.max(0,i-1),c=["name","source","status"].slice(0,i),u={prefixWidth:n,gapWidth:s,nameWidth:0,sourceWidth:0,statusWidth:0};for(let m of c)a=ni(u,m,1,a);for(let m=1;a>0;m++){let v=!1;for(let w of c)if(!(m>=Yn(Gu[w]))&&(a=ni(u,w,m+1,a),v=!0,a===0))break;if(!v)break}let d=t.map(m=>Fm(m)),l=t.map(m=>jm(m)),f=Math.max(Yn(Gu.source),Zu(d)),p=Math.max(Yn(Gu.status),Zu(l.map(m=>m.label))),h=Math.max(Yn(Gu.name),Zu(t.map(m=>m.name))),g=Math.max(p,Zu(l.map(m=>m.label+(m.hint??""))));return a=ni(u,"source",f,a),a=ni(u,"status",p,a),a=ni(u,"name",h,a),ni(u,"status",g,a),u}function aT(t,e,r){if(e<=r)return{start:0,end:e};let n=Math.floor(r/2),o=Math.max(0,Math.min(t-n,e-r));return{start:o,end:o+r}}function oi(t,e){let r=Math.max(1,Math.floor(e));return t.flatMap(n=>c4(n,r).map(o=>Yn(o)<=r?o:a4(o,r,"")))}function l4(t,e){return Math.max(0,t-e)}function ii(t,e,r){return Math.max(0,Math.min(t,l4(e,r)))}function cT(t,e,r){let n=ii(t,e,r),o=Math.min(e,n+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Rows ${n+1}-${o} of ${e}`}}function uT(t,e){return String(t+1).padStart(String(e).length," ")}function qm(t){return i4(s4(t))}import{Key as f4,matchesKey as p4}from"@earendil-works/pi-tui";function Bu(t){if(t.source==="plugin"&&t.disabled)return t.canAuthenticate?["authenticate","toggle"]:["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.canAuthenticate&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function dT(){return{step:"serverList",filterQuery:"",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var lT=10,Xn=15;var h4="k",m4="j";function si(t,e){return(t%e+e)%e}function at(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function Hm(t,e,r=!0){return e.matches(t,"tui.select.up")||r&&t===h4?{kind:"up"}:e.matches(t,"tui.select.down")||r&&t===m4?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:p4(t,f4.backspace)?{kind:"back"}:{kind:"ignore"}}function g4(t,e,r){if(e.kind==="filterChanged")return{state:{...t,filterQuery:e.query,selectedServer:r[0]?.name??null}};let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=si(at(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=si(at(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[at(r,t.selectedServer)];return o?.status==="auth_required"&&o.canAuthenticate?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function y4(t,e,r){let n=r.snapshots[at(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Bu(n);switch(e.kind){case"up":return{state:{...t,actionIndex:si(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:si(t.actionIndex+1,o.length)}};case"cancel":case"back":return{state:{...t,step:"serverList"}};case"confirm":{let i=o[t.actionIndex];return i==="viewTools"?{state:{...t,step:"viewTools",toolIndex:0}}:i==="viewLogs"?{state:{...t,step:"viewLogs",logScrollOffset:0}}:i==="authenticate"?{state:t,effect:{kind:"authenticate",server:n.name}}:i==="toggle"?{state:t,effect:{kind:"toggle",server:n.name,disable:!n.disabled}}:{state:t,effect:{kind:"reconnect",server:n.name}}}default:return{state:t}}}function v4(t,e,r){let n=r.snapshots[at(r.snapshots,t.selectedServer)]?.tools.length??0;switch(e.kind){case"up":return{state:{...t,toolIndex:Math.max(0,t.toolIndex-1)}};case"down":return{state:{...t,toolIndex:Math.min(Math.max(0,n-1),t.toolIndex+1)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function _4(t,e,r){let n=r.snapshots[at(r.snapshots,t.selectedServer)]?.logLines()??[],o=oi(n,r.logViewportWidth).length;switch(e.kind){case"up":return{state:{...t,logScrollOffset:ii(t.logScrollOffset-1,o,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:ii(t.logScrollOffset+1,o,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function S4(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Wu(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function w4(t,e){let r=t.targetScopes.length;if(r===0)return{state:Wu(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:si(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:si(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Wu(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Wu({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Wu(t,"serverActions")}}default:return{state:t}}}function fT(t,e,r){switch(t.step){case"serverList":return g4(t,e,r.snapshots);case"serverActions":return y4(t,e,r);case"viewTools":return v4(t,e,r);case"viewLogs":return _4(t,e,r);case"pasteAuthCode":return S4(t,e);case"selectTarget":return w4(t,e);default:return{state:t}}}import{truncateToWidth as Ut,visibleWidth as b4,wrapTextWithAnsi as ln}from"@earendil-works/pi-tui";var Gm="\u2192 ",Vu=" ";function pT(t,e,r){return e?r.bold(r.fg("accent",t)):r.fg("text",t)}function Cr(t,e){return e>0?Ut(t,e,"\u2026"):""}function hT(t,e,r,n,o,i,s){let a=Math.max(1,s),c=sT(r,a),u=" ".repeat(c.gapWidth),d=(h,g,m,v)=>{let w=[c.nameWidth>0?Um(g,c.nameWidth):"",c.sourceWidth>0?Um(m,c.sourceWidth):"",c.statusWidth>0?v:""].filter(b=>b.length>0);return h+w.join(u)},l=Cr(Vu,c.prefixWidth),p=[d(l,i.bold(i.fg("accent",Cr("Name",c.nameWidth))),i.bold(i.fg("accent",Cr("Source",c.sourceWidth))),i.bold(i.fg("accent",Cr("Status",c.statusWidth))))];if(e.length===0)p.push(Ut(i.fg("muted","No MCP servers available"),a,"\u2026"));else if(o.total===0)p.push(Ut(i.fg("muted","No matching MCP servers"),a,"\u2026"));else for(let h of n){let g=h.name===t.selectedServer,m=jm(h),v=Cr(m.label,c.statusWidth),w=c.statusWidth-b4(v),b=m.hint?Cr(m.hint,w):"",R=i.fg(m.color,v)+(b?i.fg("muted",b):""),_=Cr(g?Gm:Vu,c.prefixWidth);p.push(d(g?i.fg("accent",_):_,pT(Cr(h.name,c.nameWidth),g,i),pT(Cr(Fm(h),c.sourceWidth),g,i),R))}return o.hasOverflow&&p.push(Ut(i.fg("muted",` (${o.current}/${o.total})`),a,"\u2026")),p}var R4={authenticate:{label:"Authenticate",description:"Connect to this server"},viewTools:{label:"View tools",description:"See all tools provided by this server"},viewLogs:{label:"View logs",description:"View logs from this server"},reconnect:{label:"Reconnect",description:"Restart the server connection"},toggle:{label:"Disable",description:"Enable or disable this server"}};function C4(t,e){if(t==="authenticate")return e.status==="auth_required"?{label:"Authenticate",description:"Connect to this server"}:{label:"Reauthenticate",description:"Refresh authentication"};if(t==="toggle"){let r=e.source!=="local";return e.disabled?r?{label:"Enable for this session",description:"Re-enable this server for the current session only"}:{label:"Enable",description:"Enable this server (saved to settings.json)"}:r?{label:"Disable for this session",description:"Disable this server for the current session only"}:{label:"Disable",description:"Disable this server (saved to settings.json)"}}return R4[t]}function mT(t,e,r,n){let o=Math.max(1,n),i=e[at(e,t.selectedServer)];if(!i)return ln(r.fg("muted","No MCP servers available"),o);let s=i.transport==="stdio"?"Command: ":"URL: ",a=ln(r.fg("muted",s+i.connectionInfo),o);i.source==="plugin"&&a.push(...ln(r.fg("muted","Source: plugin (toggles apply to this session only)"),o)),a.push("");let c=Bu(i);for(let[u,d]of c.entries()){let l=u===t.actionIndex,f=C4(d,i),p=f.label,h=l?r.bold(r.fg("accent",p)):r.fg("text",p);a.push(Ut((l?Gm:Vu)+h+r.fg("muted",` - ${f.description}`),o,"\u2026"))}return a}function gT(t,e,r,n){let o=Math.max(1,n),i=e[at(e,t.selectedServer)];if(!i)return ln(r.fg("muted","No tools available."),o);if(i.disabled)return ln(r.fg("muted","Server is disabled; no tools are currently available."),o);if(i.tools.length===0)return ln(r.fg("muted","No tools available."),o);let s=i.tools.length,{start:a,end:c}=aT(t.toolIndex,s,Xn),u=[];for(let d=a;d<c;d++){let l=i.tools[d];if(!l)continue;let p=d===t.toolIndex?r.bold(r.fg("accent",l.name)):r.fg("text",l.name);u.push(Ut(r.fg("muted",`${uT(d,s)} `)+p+(l.disabled?r.fg("muted"," (disabled)"):""),o,"\u2026"))}return u}function yT(t,e,r,n){let o=Math.max(1,n),s=e[at(e,t.selectedServer)]?.logLines()??[];if(s.length===0)return ln(r.fg("muted","No logs available yet."),o);let a=oi(s,o),c=a.length,u=cT(t.logScrollOffset,c,Xn),d=[];c>Xn&&d.push(Ut(r.fg("muted",u.rangeLabel),o,"\u2026")),u.aboveCount>0&&d.push(Ut(r.fg("dim",`\u2191 ${u.aboveCount} more rows`),o,"\u2026"));for(let l of a.slice(u.start,u.end))d.push(Ut(r.fg("text",l),o,""));return u.belowCount>0&&d.push(Ut(r.fg("dim",`\u2193 ${u.belowCount} more rows`),o,"\u2026")),d}function vT(t,e,r,n){let o=Math.max(1,n),i=e[at(e,t.selectedServer)]?.name??"",s=[...ln(r.fg("muted",`Save the toggle for "${i}" to which settings file?`),o),""];for(let[a,c]of t.targetScopes.entries()){let u=a===t.targetIndex,d=u?r.bold(r.fg("accent",qm(c))):r.fg("text",qm(c));s.push(Ut((u?Gm:Vu)+d,o,"\u2026"))}return s}var Ku=3;function M4(t){return t.type==="stdio"?t.command:t.url}function $4(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
|
|
144
144
|
`).map(n=>n.trimEnd()).filter(n=>n.length>0):[]}return e.flatMap(r=>r.split(`
|
|
145
|
-
`)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function lT(t){return t.disabled?2:t.status==="auth_required"?0:1}function c4(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:xr(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,canAuthenticate:r.config.type!=="stdio",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:s4(r.config),logLines:()=>a4(r)});return e.sort((r,n)=>lT(r)-lT(n)),e}function u4(t,e){let r=e[st(e,t.selectedServer)]?.name??"";switch(t.step){case"serverActions":return`MCP Servers \u203A ${r}`;case"viewTools":return`MCP Servers \u203A ${r} \u203A Tools`;case"viewLogs":return`MCP Servers \u203A ${r} \u203A Logs`;case"selectTarget":return`MCP Servers \u203A ${r} \u203A Settings file`;default:return"MCP Servers"}}function d4(t){switch(t){case"serverList":return"Type to filter \xB7 \u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function l4(t,e,r,n,o){switch(t.step){case"serverActions":return aT(t,e,n,o);case"viewTools":return cT(t,e,n,o);case"viewLogs":return uT(t,e,n,o);case"selectTarget":return dT(t,e,n,o);default:return sT(t,e,r.getMatchingItems(),r.getVisibleItems(),r.getMetadata(),n,o)}}function f4(t,e,r,n,o){let i=Math.max(1,o),s=Vu(n.bold(n.fg("accent",u4(t,e))),i,"\u2026"),a=t.step==="serverList"&&i>=Wu?[...r.renderInput(i),""]:[],c=l4(t,e,r,n,i);return[s,"",...a,...c,"",Vu(n.fg("muted",d4(t.step)),i,"\u2026")]}function p4(t,e,r,n,o){let i=Math.max(1,o),s=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),a=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[Vu(s,i,"\u2026"),"",Vu(a,i,"\u2026")]}function h4(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function m4(t,e,r){let n=s=>s.flatMap(a=>i4(a,Math.max(1,r))),o=e.bold(e.fg("accent",`MCP Servers \u203A ${t.server} \u203A Authenticate`));if(t.status==="error")return n([o,"",e.fg("error","Authentication failed"),e.fg("muted",t.error??"Unknown error"),"",e.fg("muted","Press any key to dismiss")]);let i=[o,"",e.fg("text","Opening your browser to sign in\u2026")];return t.url&&i.push(e.fg("accent",t.url)),t.instructions&&i.push(e.fg("muted",t.instructions)),i.push("",`${e.fg("text","Paste code or redirect URL: ")}${e.fg("accent",t.input)}`,"",e.fg("muted","Enter Submit \xB7 Esc Cancel")),n(i)}function g4(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function fT(t){return t?"Disabling":"Enabling"}function pT(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var qm=class{constructor(e){this.state=rT();this.busy=null;this.authenticating=null;this.authStatus="pending";this.queuedManualCodes=[];this.authInPaste=!1;this.authPasteBuffer="";this._focused=!1;this.component=this;this.handleInput=e=>{this.dispatch(e)};this.config=e,this.border=new e4(r=>e.theme.fg("border",r)),this.serverList=new n4({items:[],getIdentity:r=>r.name,getSearchText:r=>r.name,maxVisible:nT})}get focused(){return this._focused}set focused(e){this._focused=e,this.syncSearchFocus()}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){let r=Math.max(1,e);this.currentWidth=r,this.syncSearchFocus();let n;if(this.busy)n=p4(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme,r);else if(this.authenticating)n=m4({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,r);else{let o=this.config.snapshots();this.syncServerList(o),this.clampLogScrollOffset(o,r),n=f4(this.state,o,this.serverList,this.config.theme,r)}return[...this.border.render(r),...n,...this.border.render(r)]}invalidate(){}syncServerList(e){this.serverList.setItems(e);let r=this.state.selectedServer;r!==null&&this.serverList.selectIdentity(r)||(this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null})}isSearchAvailable(){return this.currentWidth===void 0||this.currentWidth>=Wu}syncSearchFocus(){let e=this.currentWidth!==void 0&&this.currentWidth>=Wu&&this.state.step==="serverList"&&this.busy===null&&this.authenticating===null;this.serverList.setInputFocused(this._focused&&e)}clampLogScrollOffset(e,r){if(this.state.step!=="viewLogs")return;let n=e[st(e,this.state.selectedServer)],o=ni(n?.logLines()??[],r).length,i=oi(this.state.logScrollOffset,o,Yn);i!==this.state.logScrollOffset&&(this.state={...this.state,logScrollOffset:i})}applyAction(e,r){let n=oT(this.state,e,{snapshots:r,windowSize:Yn,logViewportWidth:this.currentWidth??Wu});this.state=n.state,n.effect&&this.runEffect(n.effect)}dispatchServerList(e,r){this.syncServerList(r);let n=this.isSearchAvailable(),o=Fm(e,this.config.keybindings,!n);if(o.kind==="up"||o.kind==="down"){o.kind==="up"?this.serverList.selectPrevious():this.serverList.selectNext(),this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null};return}if(o.kind==="confirm"||o.kind==="cancel"){this.applyAction(o,[...this.serverList.getMatchingItems()]);return}n&&this.serverList.handleInput(e)&&this.applyAction({kind:"filterChanged",query:this.serverList.getQuery()},[...this.serverList.getMatchingItems()])}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots();this.state.step==="serverList"?this.dispatchServerList(e,r):this.applyAction(Fm(e,this.config.keybindings),r),this.syncSearchFocus(),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,fT(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(pT(e,o))}});return}if(n.direct){this.startToggleWrite(e,r,n.direct);return}this.state={...this.state,step:"selectTarget",targetScopes:n.scopes,targetIndex:0,pendingToggle:{server:e,disable:r}},this.config.tui.requestRender()}startToggleWrite(e,r,n){this.startOp(e,fT(r),async()=>{try{let{notice:o}=await this.config.toggle.applyLocal(e,r,n);o&&this.config.toggle.notify(o)}catch(o){this.config.toggle.notify(pT(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new o4(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=h4(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth("serverActions");return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(r4(e,t4.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&g4(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),i=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),i&&this.handleAuthInput(i)}exitAuth(e="serverList"){let r=this.authenticating,n=e==="serverActions"&&r!==null&&this.config.snapshots().some(o=>o.name===r)?"serverActions":"serverList";this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:n,selectedServer:n==="serverActions"?r:this.state.selectedServer,actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function hT(t,e,r,n,o){await t.ui.custom((i,s,a,c)=>new qm({tui:i,theme:s,keybindings:a,snapshots:()=>c4(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Gm=["list"];function mT(t){let{name:e,status:r}=t,n;switch(r){case"success":{let o=t.tools.length;n=o>0?` \u2705 ${e} (${o} tool${o===1?"":"s"})`:` \u2705 ${e} (ready)`;break}case"failed":n=` \u274C ${e} (failed)`;break;case"auth_required":n=` \u{1F510} ${e} (auth required)`;break;case"disabled":n=` \u26AA ${e} (disabled)`;break;default:n=` \u23F3 ${e} (initializing...)`;break}return r==="failed"&&t.lastError?`${n}
|
|
146
|
-
error: ${t.lastError}`:n}function
|
|
145
|
+
`)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function _T(t){return t.disabled?2:t.status==="auth_required"?0:1}function I4(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:xr(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,canAuthenticate:r.config.type!=="stdio",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:M4(r.config),logLines:()=>$4(r)});return e.sort((r,n)=>_T(r)-_T(n)),e}function O4(t,e){let r=e[at(e,t.selectedServer)]?.name??"";switch(t.step){case"serverActions":return`MCP Servers \u203A ${r}`;case"viewTools":return`MCP Servers \u203A ${r} \u203A Tools`;case"viewLogs":return`MCP Servers \u203A ${r} \u203A Logs`;case"selectTarget":return`MCP Servers \u203A ${r} \u203A Settings file`;default:return"MCP Servers"}}function z4(t){switch(t){case"serverList":return"Type to filter \xB7 \u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function N4(t,e,r,n,o){switch(t.step){case"serverActions":return mT(t,e,n,o);case"viewTools":return gT(t,e,n,o);case"viewLogs":return yT(t,e,n,o);case"selectTarget":return vT(t,e,n,o);default:return hT(t,e,r.getMatchingItems(),r.getVisibleItems(),r.getMetadata(),n,o)}}function D4(t,e,r,n,o){let i=Math.max(1,o),s=Ju(n.bold(n.fg("accent",O4(t,e))),i,"\u2026"),a=t.step==="serverList"&&i>=Ku?[...r.renderInput(i),""]:[],c=N4(t,e,r,n,i);return[s,"",...a,...c,"",Ju(n.fg("muted",z4(t.step)),i,"\u2026")]}function L4(t,e,r,n,o){let i=Math.max(1,o),s=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),a=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[Ju(s,i,"\u2026"),"",Ju(a,i,"\u2026")]}function j4(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function F4(t,e,r){let n=s=>s.flatMap(a=>A4(a,Math.max(1,r))),o=e.bold(e.fg("accent",`MCP Servers \u203A ${t.server} \u203A Authenticate`));if(t.status==="error")return n([o,"",e.fg("error","Authentication failed"),e.fg("muted",t.error??"Unknown error"),"",e.fg("muted","Press any key to dismiss")]);let i=[o,"",e.fg("text","Opening your browser to sign in\u2026")];return t.url&&i.push(e.fg("accent",t.url)),t.instructions&&i.push(e.fg("muted",t.instructions)),i.push("",`${e.fg("text","Paste code or redirect URL: ")}${e.fg("accent",t.input)}`,"",e.fg("muted","Enter Submit \xB7 Esc Cancel")),n(i)}function U4(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function ST(t){return t?"Disabling":"Enabling"}function wT(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Zm=class{constructor(e){this.state=dT();this.busy=null;this.authenticating=null;this.authStatus="pending";this.queuedManualCodes=[];this.authInPaste=!1;this.authPasteBuffer="";this._focused=!1;this.component=this;this.handleInput=e=>{this.dispatch(e)};this.config=e,this.border=new P4(r=>e.theme.fg("border",r)),this.serverList=new k4({items:[],getIdentity:r=>r.name,getSearchText:r=>r.name,maxVisible:lT})}get focused(){return this._focused}set focused(e){this._focused=e,this.syncSearchFocus()}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){let r=Math.max(1,e);this.currentWidth=r,this.syncSearchFocus();let n;if(this.busy)n=L4(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme,r);else if(this.authenticating)n=F4({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,r);else{let o=this.config.snapshots();this.syncServerList(o),this.clampLogScrollOffset(o,r),n=D4(this.state,o,this.serverList,this.config.theme,r)}return[...this.border.render(r),...n,...this.border.render(r)]}invalidate(){}syncServerList(e){this.serverList.setItems(e);let r=this.state.selectedServer;r!==null&&this.serverList.selectIdentity(r)||(this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null})}isSearchAvailable(){return this.currentWidth===void 0||this.currentWidth>=Ku}syncSearchFocus(){let e=this.currentWidth!==void 0&&this.currentWidth>=Ku&&this.state.step==="serverList"&&this.busy===null&&this.authenticating===null;this.serverList.setInputFocused(this._focused&&e)}clampLogScrollOffset(e,r){if(this.state.step!=="viewLogs")return;let n=e[at(e,this.state.selectedServer)],o=oi(n?.logLines()??[],r).length,i=ii(this.state.logScrollOffset,o,Xn);i!==this.state.logScrollOffset&&(this.state={...this.state,logScrollOffset:i})}applyAction(e,r){let n=fT(this.state,e,{snapshots:r,windowSize:Xn,logViewportWidth:this.currentWidth??Ku});this.state=n.state,n.effect&&this.runEffect(n.effect)}dispatchServerList(e,r){this.syncServerList(r);let n=this.isSearchAvailable(),o=Hm(e,this.config.keybindings,!n);if(o.kind==="up"||o.kind==="down"){o.kind==="up"?this.serverList.selectPrevious():this.serverList.selectNext(),this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null};return}if(o.kind==="confirm"||o.kind==="cancel"){this.applyAction(o,[...this.serverList.getMatchingItems()]);return}n&&this.serverList.handleInput(e)&&this.applyAction({kind:"filterChanged",query:this.serverList.getQuery()},[...this.serverList.getMatchingItems()])}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots();this.state.step==="serverList"?this.dispatchServerList(e,r):this.applyAction(Hm(e,this.config.keybindings),r),this.syncSearchFocus(),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,ST(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(wT(e,o))}});return}if(n.direct){this.startToggleWrite(e,r,n.direct);return}this.state={...this.state,step:"selectTarget",targetScopes:n.scopes,targetIndex:0,pendingToggle:{server:e,disable:r}},this.config.tui.requestRender()}startToggleWrite(e,r,n){this.startOp(e,ST(r),async()=>{try{let{notice:o}=await this.config.toggle.applyLocal(e,r,n);o&&this.config.toggle.notify(o)}catch(o){this.config.toggle.notify(wT(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new T4(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=j4(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth("serverActions");return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(x4(e,E4.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&U4(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),i=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),i&&this.handleAuthInput(i)}exitAuth(e="serverList"){let r=this.authenticating,n=e==="serverActions"&&r!==null&&this.config.snapshots().some(o=>o.name===r)?"serverActions":"serverList";this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:n,selectedServer:n==="serverActions"?r:this.state.selectedServer,actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function bT(t,e,r,n,o){await t.ui.custom((i,s,a,c)=>new Zm({tui:i,theme:s,keybindings:a,snapshots:()=>I4(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Wm=["list"];function RT(t){let{name:e,status:r}=t,n;switch(r){case"success":{let o=t.tools.length;n=o>0?` \u2705 ${e} (${o} tool${o===1?"":"s"})`:` \u2705 ${e} (ready)`;break}case"failed":n=` \u274C ${e} (failed)`;break;case"auth_required":n=` \u{1F510} ${e} (auth required)`;break;case"disabled":n=` \u26AA ${e} (disabled)`;break;default:n=` \u23F3 ${e} (initializing...)`;break}return r==="failed"&&t.lastError?`${n}
|
|
146
|
+
error: ${t.lastError}`:n}function q4(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var H4="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function Bm(t,e){return e.length>0?[t,...e]:null}function G4(t){let e=[],r=[];for(let o of t.servers.values())(xr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[Bm("MCP Server Status:",e.map(RT)),Bm("Plugin MCP servers:",r.map(RT)),Bm("Diagnostics:",t.diagnostics.map(q4))];return t.servers.size===0&&n.unshift([H4]),n.filter(o=>o!==null).map(o=>o.join(`
|
|
147
147
|
`)).join(`
|
|
148
148
|
|
|
149
|
-
`)}function S4(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Gm.includes(e))return e}async function w4(t,e,r){if(e.servers.size===0){t.ui.notify("MCP servers are not available","warning");return}if(e.reconnecting){t.ui.notify("MCP servers are already restarting...","warning");return}t.ui.notify("Restarting MCP servers...","info");let n=ta([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function gT(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Gm.filter(o=>o.startsWith(n)).map(o=>({value:o,label:o}))},handler:async(r,n)=>{if(r.trim().length===0&&n.mode==="interactive"&&n.hasUI){await hT(n,e,s=>ta([s],e,t),{classify:s=>Kk({server:s,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(s,a)=>Jk({server:s,disable:a,state:e,pi:t}),applyLocal:(s,a,c)=>Yk({server:s,disable:a,scope:c,state:e,pi:t,cwd:n.cwd,agentDir:n.agentDir}),notify:s=>n.ui.notify(s,"info")},(s,a)=>zk({serverName:s,state:e,pi:t,controller:a}));return}let i=S4(r);if(!i){n.ui.notify(`Unknown /mcp subcommand. Available: ${Gm.join(", ")}.`,"warning");return}if(i==="list"){n.ui.notify(_4(e),"info");return}else return i}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await w4(n,e,t)}})}import{logger as b4}from"@hermes/logger";var yT=b4.child({prefix:"pi-mcp"}),Zm="augment:feature-flags";function R4(t){if(!t||typeof t!="object")return;let e=t;if(!(!e.flags||typeof e.flags!="object")&&!(e.errorStatus!==void 0&&typeof e.errorStatus!="string"))return t}function vT(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Zm,r=>{let n=R4(r);if(n===void 0){yT.warn(`${Zm} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,yT.debug(`Received feature-flag snapshot via ${Zm} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as C4}from"@hermes/logger";var oa=C4.child({prefix:"pi-mcp"}),_T=300*1e3,Bm=600*1e3;function P4(t){if(!t.shouldProactivelyRefreshTokens)return;let e=Date.now();for(let r of t.servers.values()){let{config:n}=r;if(n.type!=="http"&&n.type!=="sse"||n.disabled||!r.hasRefreshEligibleOAuthCredential())continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(Ri(o,e)||o.expiresAt>e+Bm||(oa.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Bm}ms; refreshing`),r.refreshTokenIfPossible().then(i=>{i.kind!=="refreshed"&&oa.warn(`Background refresh for MCP server "${r.name}" did not complete (${i.kind})`)}).catch(()=>{oa.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function ST(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{P4(t)},_T);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,oa.debug(`Started background MCP OAuth refresh loop (interval ${_T}ms, buffer ${Bm}ms)`)}function wT(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,oa.debug("Stopped background MCP OAuth refresh loop"))}import{logger as x4}from"@hermes/logger";var Et=x4.child({prefix:"pi-mcp"});function E4(t,e,r){t.dynamicallyAddedConfigIds.add(e),t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.sessionRemovedConfigIds.delete(e);for(let n of r)n.id!==void 0&&(t.registryConfigNamesById.set(n.id,n.name),t.registryCredentialConfigsById.set(n.id,{...n}))}function sr(t){Ye({state:t.state,domain:He(t.configId),epoch:t.intentEpoch})}function k4(t){let e=new Set;for(let[r,n]of t.servers){let o=te(t,r,n);(o.owner.kind==="local"||o.owner.kind==="registry")&&e.add(r)}for(let[r,n]of t.hostLeases)(n.owner.kind==="local"||n.owner.kind==="registry")&&e.add(r);return e}function bT(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function RT(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),Et.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function ia(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t;sr(t);let s=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Et.warn(s),!o()){if(r.diagnostics.push({message:s,origin:"registry"}),!i()){r.failedAddConfigIds.add(n);return}r.dynamicallyAddedConfigIds.add(n),r.sessionRemovedConfigIds.delete(n)}}function T4(t,e){return e.flatMap(r=>ku(t,r)?[r.config]:[])}function A4(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function M4(t,e){let r=A4(e);if(r){if(ia(t,r.error),r.error instanceof kt)throw r.error;return}let n=T4(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){E4(t.state,t.configId,n);return}!t.superseded()&&e.some(o=>o.status==="collision")&&(t.state.failedAddConfigIds.add(t.configId),t.state.nameCollisionAddConfigIds.add(t.configId))}function CT(t,e){try{M4(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function $4(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t,s=r.servers.get(e.name);if(!s)return!1;let a=te(r,e.name,s);if(a.owner.kind==="plugin"||a.owner.kind==="vfs")return!1;if(i())return Et.info(`Live MCP add-server: embedded config id ${n} resolves to already-connected server "${e.name}"; no-op`),!0;let c=`Live MCP add-server: embedded config id ${n} collides on display name "${e.name}" with an already-connected server; cannot add a second server sharing that name`;return Et.warn(c),o()||(r.registryConfigNamesById.set(n,e.name),r.diagnostics.push({message:c,origin:"registry"}),r.failedAddConfigIds.add(n),r.nameCollisionAddConfigIds.add(n)),!0}async function I4(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await hi(t.state,t.configId),t.superseded()){sr(t);return}if($4(t,e)){sr(t);return}try{if(!await $r({state:t.state,config:e,pi:t.activePi})){sr(t);return}}catch(r){throw ia(t,r),r}Et.info(`Live MCP add-server: connecting embedded config id ${t.configId} (no registry refetch)`);try{let r=await t.connect([e],t.state,t.activePi,t.sourceOwnership);CT(t,r??[])}catch(r){if(ia(t,r),r instanceof kt)throw r}}async function O4(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t;if(o()){sr(t),Et.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){RT(r,e),Et.info(`Live MCP add-server: config id ${n} resolved to no new server (already connected, not opted in, or unknown id)`),i()||r.failedAddConfigIds.add(n),sr(t);return}if(await hi(r,n),o()){sr(t);return}try{if((await Promise.all(e.servers.map(c=>$r({state:r,config:c,pi:t.activePi})))).some(c=>!c)){sr(t);return}}catch(a){throw ia(t,a),a}Et.info(`Live MCP add-server: connecting ${e.servers.length} server(s) for config id ${n}`);let s=await t.connect(e.servers,r,t.activePi,t.sourceOwnership);if(o()){sr(t);return}RT(r,e),CT(t,s??[])}function z4(t,e){if(typeof e=="string")return rk(e,t.workspaceRoot??process.cwd())}function N4(t,e,r){return t.targetMaterialStore?.has(e)===!0||r!==void 0&&t.targetMaterialStore?.has(r.name)===!0}function PT(t){let{pi:e,state:r,data:n,deps:o}=t,i=n,s=i&&typeof i.configId=="string"?i.configId:"";if(!s)return Et.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();let a=z4(r,i?.embeddedConfig);if(N4(r,s,a))return Promise.resolve();if(a!==void 0&&a.id!==s)return Et.warn(`Embedded MCP config id ${a.id??"<missing>"} does not match add target ${s}; rejecting`),Promise.resolve();if(!no({state:r,configId:s,generation:i?.attachmentGeneration}))return Et.info(`Ignoring stale live MCP add-server command for config id ${s}`),Promise.resolve();r.sessionRemovedConfigIds.delete(s);let c=ma({state:r,domain:He(s),forceNew:!0}),u=k4(r),d=r.currentLoad?.latestPi??e,l=r.registryGeneration;r.liveEditGenerations??=new Map;let f=(r.liveEditGenerations.get(s)??0)+1;r.liveEditGenerations.set(s,f);let p=()=>r.registryGeneration!==l||r.liveEditGenerations.get(s)!==f,h={state:r,configId:s,activePi:d,connect:o?.connect??Je,report:o?.report??N,intentEpoch:c.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>bT(r,s)},m;if(a)m=I4(h,a);else{let g=r.credentials;g?m=(o?.discover??Nu)({configIds:[s],creds:g,currentUserId:g.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:u}).then(w=>O4(h,w)).catch(w=>{if(!(w instanceof kt)){ia(h,w);return}throw w}):(Et.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),sr(h),m=Promise.resolve())}return _a({state:r,configId:s,generation:i?.attachmentGeneration,operation:m,wasApplied:()=>bT(r,s)})}import{logger as D4}from"@hermes/logger";var sa=D4.child({prefix:"pi-mcp"}),xT=3,ET=6e4,L4=1e3,j4=8e3;function Wm(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.reconnect??or,s=o?.now??Date.now,a=o?.sleep??hn,c=o?.report??N,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return sa.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();let l=nn({state:r,target:d});if(!l)return sa.warn(`augment:mcp-restart-server: no unique live host for ${d}; re-reporting status`),c(r.currentLoad?.latestPi??e,r),Promise.resolve();if(r.targetMaterialStore?.has(l.name)||r.targetMaterialStore?.has(d))return Promise.resolve();let f=l.name,p=r.mcpConnectionEpoch,h=D(r,f),m=s(),g=r.mcpRestartState.get(f),v=g&&m-g.lastRestart<ET?g.count+1:1,w=r.currentLoad?.latestPi??e;if(v>xT)return sa.warn(`augment:mcp-restart-server: ${f} exceeded ${xT} restarts within ${ET}ms; rejecting`),c(w,r),Promise.resolve();r.mcpRestartState.set(f,{count:v,lastRestart:m});let b=Math.min(L4*2**(v-1),j4);return(v>1?a(b):Promise.resolve()).then(()=>{if(!(r.mcpConnectionEpoch!==p||D(r,f)!==h||nn({state:r,target:d})?.server!==l.server||t.isCurrent&&!t.isCurrent()))return sa.info(`Live MCP restart-server: reconnecting ${f}`),i(f,r,w)}).catch(_=>{let C=`Live MCP restart-server failed for ${f}: ${_ instanceof Error?_.message:String(_)}`;sa.warn(C),r.diagnostics.push({server:f,message:C})}).then(()=>{c(w,r)})}import{logger as F4}from"@hermes/logger";var aa=F4.child({prefix:"pi-mcp"}),U4=/^\d+$/,Vm=1,kT="AUGMENT_ACTIVE_SPACE_ID",q4="augment-mcp-access-token-";function Ku(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function TT(t,e){return e?.["augment:encoding"]!=="base64"?t:/^[A-Za-z0-9+/]*={0,2}$/.test(t)&&t.length%4===0?Buffer.from(t,"base64").toString("utf-8"):t}var Ju=class{constructor(e,r,n){this.cache=new Map;this.inflight=new Map;this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??xd}_headers(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}}lookupBody(e){let r={name:e};return!e.startsWith(q4)&&Object.hasOwn(process.env,kT)&&(r.active_space_id=process.env[kT]??""),r}getSecret(e){let r=Ku(e),n=this.inflight.get(r);if(n)return n;let o=this._resolve(r).finally(()=>{this.inflight.delete(r)});return this.inflight.set(r,o),o}upsertUserSecret(e,r,n){return mn(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=Ku(e),s=(await this._callUpsert({name:o,value:r,scope:Vm,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof s!="string"||!U4.test(s))throw new Error("user secret upsert response contained an invalid persisted version");let a=BigInt(s).toString();return this.cache.set(o,r),aa.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await mn(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=Ku(e);this.cache.delete(r),await this._callDelete({name:r,scope:Vm}),aa.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),i=o.length>cr?`${o.slice(0,cr)}\u2026[truncated]`:o;throw new gt(n.status,n.statusText,i)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),i=o.length>cr?`${o.slice(0,cr)}\u2026[truncated]`:o;throw new gt(n.status,n.statusText,i)}}async getUserSecretWithVersion(e){let r=Ku(e);try{let n=await mn(()=>this._callApi("/mcp-secrets/get",this.lookupBody(r))),o=n.secret?.value,i=n.secret?.version;if(o===void 0||i===void 0)return;let s=n.secret?.scope===Vm||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:TT(o,n.secret?.tags),version:s?i:"0"}}catch(n){if(n instanceof gt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&aa.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await mn(()=>this._callApi(e,r)),i=o.secret?.value;return i===void 0?{errored:!1}:{value:TT(i,o.secret?.tags),errored:!1}}catch(o){if(o instanceof gt&&o.statusCode===404)return aa.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let i=o instanceof Error?o.message:String(o);return aa.debug(`Secret "${n}" lookup via ${e} failed: ${i}`),{errored:!0}}}async _callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:this._headers(),body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>""),s=i.length>cr?`${i.slice(0,cr)}\u2026[truncated]`:i;throw new gt(o.status,o.statusText,s)}return await o.json()}};function Km(t){return{latestPi:t}}import{logger as H4}from"@hermes/logger";var si=H4.child({prefix:"pi-mcp"});async function G4(t){let e=[];for(let[r,n]of t.servers){let o=te(t,r,n);if(o.owner.kind!=="vfs"||o.host!==n)continue;let i=ut({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!i)continue;Ke(t,r);let s=mt(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([s,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw _e({state:t,name:r,retirement:i,result:{status:"failed",error:c.reason}}),c.reason;_e({state:t,name:r,retirement:i,result:{status:"retired"}}),Ee({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function Z4(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),si.warn(r.message))}function B4(t){let{state:e,name:r,stored:n,higherPriorityNames:o,blockedNames:i,workspaceRoot:s}=t;if(o.has(r)){i.add(r);let a=`VFS MCP server "${r}" ignored: a higher-priority server with the same name takes precedence`;e.diagnostics.push({server:r,message:a,origin:"vfs"}),si.warn(a);return}try{let a=to(r,n);return{...a.type==="stdio"?Bt(a,s):Zt(a,s),vfsSource:"vfs"}}catch(a){let c=a instanceof Tt?a.message:`Failed to normalize VFS MCP server "${r}": ${a instanceof Error?a.message:String(a)}`;e.diagnostics.push({server:r,message:c,origin:"vfs"}),si.warn(c);return}}function W4(t,e){let r=new Set;for(let[s,a]of t.servers){let c=te(t,s,a);c.owner.kind!=="vfs"&&c.host===a&&r.add(s)}for(let[s,a]of t.hostLeases)a.owner.kind!=="vfs"&&r.add(s);let n=t.workspaceRoot??process.cwd(),o=[],i=new Set;for(let[s,a]of Object.entries(e.servers??{})){if(a===null)continue;let c=B4({state:t,name:s,stored:a,higherPriorityNames:r,blockedNames:i,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:i}}function V4(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function AT(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.connect??Je,s=n;if(!s||typeof s!="object"||Array.isArray(s))return si.warn("augment:mcp-vfs-servers payload is not an object"),Promise.resolve();let a=typeof s.signature=="string"?s.signature:void 0;if(a!==void 0&&a===r.lastSuccessfulVfsMcpSignature&&V4(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=G4(r);return r.diagnostics=r.diagnostics.filter(l=>l.origin!=="vfs"),r.lastSuccessfulVfsMcpSignature=void 0,r.blockedVfsMcpNames.clear(),d.then(()=>{if(r.vfsGeneration!==c)return!1;Z4(r,s.diagnostics);let{servers:l,blockedNames:f}=W4(r,s);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(si.info(`VFS MCP overlay: connecting ${l.length} server(s)`),i(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(p??[]).some(g=>g.config===m&&ku(r,g)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;si.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var we=K4.child({prefix:"pi-mcp"}),zT="augment:mcp-oauth-credentials",MT="augment:mcp-header-secrets",$T="augment:mcp-header-secret-failures",Jm="augment:mcp-oauth-failures",IT="augment:credentials",J4="augment:mcp-config-ids",OT="augment:mcp-configs",Y4="augment:mcp-vfs-servers",X4="augment:mcp-add-server",Q4="augment:mcp-restart-server",eB="augment:mcp-remove-server",tB="augment:cloud-mode";function rB(t){if(!t.secretsClient||t.tokens instanceof Si)return;let e=t.tokens;t.tokens=new Si(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),we.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function nB(t){if(!t||typeof t!="object"){we.warn(`${zT} payload is not an object`);return}let e=t,r=e.suppressReconnect===!0&&typeof e.credentials=="object"&&e.credentials!==null&&!Array.isArray(e.credentials);return{credentials:r?e.credentials:t,restart:r&&e.restart&&typeof e.restart=="object"?e.restart:void 0,suppressReconnect:r,targetConfigId:r&&typeof e.targetConfigId=="string"?e.targetConfigId:void 0}}function Ym(t,e){let r=e.restart?.serverName;if(typeof r!="string")return!1;let n=e.credentials[r],o=on(n),i=nn({state:t,target:r})?.server;if(i&&i.config.type!=="stdio"&&i.config.auth==="oauth"&&o&&NT({state:t,name:r,revision:o})&&!DT({state:t,revision:o})&&wr({store:t.tokens,serverName:r,proto:n,options:{acceptedRevisions:t.oauthCredentialRevisions,acceptedDomains:t.oauthCredentialDomains,expectedDomains:t.expectedCredentialDomains,equalRevisionRebindDomains:t.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:!0}}).decision!=="reject")return!0;let s="MCP restart credential was rejected; keeping the existing host";return we.warn(s),t.diagnostics.push({server:r,message:s}),!1}function oB(t){let{pi:e,state:r}=t,{payload:n}=t,o=r.mcpConnectionEpoch;if(Object.entries(n.credentials).some(([c,u])=>r.targetMaterialStore?.has(c)||fe(u)&&Object.hasOwn(u,"target_material"))||n.targetConfigId&&r.targetMaterialStore?.has(n.targetConfigId))return;if(n.restart){let c=Object.keys(n.credentials);if(typeof n.restart.serverName!="string"||typeof n.restart.requestId!="string"||c.length!==1){we.warn("MCP restart credentials must contain exactly the target entry");return}let u=nn({state:r,target:n.restart.serverName});if(!u||c[0]!==u.name){we.warn("MCP restart credentials must contain exactly the resolved target entry"),N(r.currentLoad?.latestPi??e,r);return}n={...n,restart:{...n.restart,serverName:u.name}}}if(n.targetConfigId){JE({pi:e,state:r,update:{configId:n.targetConfigId,credentials:n.credentials}});return}if(n.restart&&!Ym(r,n))return;let i=Object.keys(n.credentials).map(c=>({name:c,server:r.servers.get(c),lease:D(r,c)})),s=new Set;for(let c of Object.keys(n.credentials)){let u=r.servers.get(c)?.getRefreshInFlight?.();u&&s.add(u)}let a=()=>{if(r.mcpConnectionEpoch!==o||i.some(({name:d,server:l,lease:f})=>r.servers.get(d)!==l||D(r,d)!==f)||n.restart&&!Ym(r,n))return;let c=uB({pi:e,state:r,credentials:n.credentials,suppressReconnect:n.suppressReconnect,requireEqualMaterial:n.restart!==void 0}),{restart:u}=n;if(!(typeof u?.serverName!="string"||typeof u.requestId!="string")){if(c.rejected.length===0&&c.applied.length+c.equal.length===1&&(c.applied.includes(u.serverName)||c.equal.includes(u.serverName))){Wm({pi:e,state:r,isCurrent:()=>r.mcpConnectionEpoch===o&&i.every(({name:d,server:l,lease:f})=>r.servers.get(d)===l&&D(r,d)===f)&&Ym(r,n),data:{serverName:u.serverName,requestId:u.requestId}});return}if(Object.hasOwn(n.credentials,u.serverName)&&!c.equal.includes(u.serverName)){let d="MCP restart credential was rejected; keeping the existing host";we.warn(d),r.diagnostics.push({server:u.serverName,message:d})}}};if(s.size===0){a();return}Promise.allSettled(s).then(a)}function iB(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(zT,r=>{let n=nB(r);n&&oB({pi:t,state:e,payload:n})}))}function NT(t){let{state:e,name:r,revision:n}=t,o=ln(n);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let i=e.expectedCredentialDomains.get(r),s=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id,u=a?.config.registrySource!==void 0&&c!==void 0&&He(c)===o;return n.ownerDomain!==void 0?i?.kind==="domain"?i.domain===o:u:i===void 0&&s===void 0?u:i?.kind==="domain"&&(i.domain===o||Ie(n.domain))||s===n.domain}function DT(t){let{state:e,revision:r}=t,n=ln(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function sB(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[i,s]of Object.entries(r)){let a=on(s);if(wr({store:e.tokens,serverName:i,proto:s,options:{requireRevision:!0}}).decision!=="reject"&&a!==void 0){if(DT({state:e,revision:a})){wg({state:e,revision:a,credential:s,suppressReconnect:n});continue}if(NT({state:e,name:i,revision:a})){o[i]=s;continue}_g({state:e,serverName:i,revision:a,credential:s,suppressReconnect:n})}}return o}function aB(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let i=r[o],s=on(i);s===void 0?(e.credentialRevisions.delete(o),e.hostedCredentialOwnership.delete(o)):(e.credentialRevisions.set(o,s),e.hostedCredentialOwnership.set(o,{...s,accessTokenOnly:i?.refresh_token===void 0})),e.statusFailureCategories.delete(o),e.authRefreshNeededReportKeys.delete(o),e.tokens.clearAuthRequired(o)}}function cB(t){let{pi:e,state:r,seeded:n,suppressReconnect:o}=t;if(o)return;let i=r.currentLoad?.latestPi??e;for(let s of n){let a=r.servers.get(s),c=r.expectedCredentialDomains.get(s),u=D(r,s),d=c?.kind!=="domain"||u?.owner.kind==="registry"&&u.owner.identity===c.domain;a&&d&&a.config.type!=="stdio"&&a.config.auth==="oauth"&&or(s,r,i).catch(()=>{}).finally(()=>{N(i,r),Se(r)})}}function uB(t){let{pi:e,state:r,credentials:n,suppressReconnect:o}=t;r.oauthCredentialRevisions??=new Map,r.oauthCredentialDomains??=new Map,r.credentialRevisions??=new Map,r.expectedCredentialDomains??=new Map;let i=sB({state:r,credentials:n,suppressReconnect:o}),s={acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:t.requireEqualMaterial};Object.entries(i).some(([u,d])=>{let{decision:l}=wr({store:r.tokens,serverName:u,proto:d,options:s});return l==="apply"||l==="equal"&&t.requireEqualMaterial===!0})&&(r.shouldProactivelyRefreshTokens=!1);let c=Au(r.tokens,i,s);return aB({state:r,applicable:i,seeded:c.applied}),c.applied.length===0||(we.info(`Seeded MCP OAuth token(s) for ${c.applied.length} server(s)`),cB({pi:e,state:r,seeded:c.applied,suppressReconnect:o})),c}function dB(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(MT,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${MT} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);av(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on($T,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${$T} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);uv(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(Jm,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${Jm} payload is not an object`);return}let n=r;if(typeof n.entries!="object"||n.entries===null||Array.isArray(n.entries)){we.warn(`${Jm} entries is not an object`);return}rg(e,n.entries)}))}function lB(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(IT,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){we.warn(`${IT} payload missing apiKey or apiUrl`);return}e.credentials={apiKey:n.apiKey,apiUrl:n.apiUrl,...typeof n.userAgent=="string"?{userAgent:n.userAgent}:{},...typeof n.userId=="string"?{userId:n.userId}:{}},e.secretsClient=new Ju(e.credentials),rB(e)}),t.events.on(J4,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0),Iu(e.currentLoad?.latestPi??t,e),ra({pi:t,state:e,data:r}).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(n=>{we.warn(`Registry config apply did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Se(e),Qo(n,e)})}))}function LT(t,e){e.isCloudMode!==!1||e.mcpAttachCloudSignaled||!e.credentials||ra({pi:t,state:e,data:{configIds:void 0,productType:"cli"},productType:"cli"}).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(r=>{we.warn(`CLI registry discovery failed: ${r instanceof Error?r.message:String(r)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{Se(e)})}function fB(t,e){e.cloudModeListenerBound||(e.cloudModeListenerBound=!0,t.events.on(tB,r=>{let n=r;if(typeof n?.enabled!="boolean")return;let o=e.isCloudMode;e.isCloudMode=n.enabled,o!==!1&&!n.enabled&&(o&&(e.mcpAttachCloudSignaled=!1),e.connectStarted&&e.initialConnectPromise===null&<(e.currentLoad?.latestPi??t,e))}))}function pB(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(OT,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){we.warn(`${OT} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let i=ti(o,e.workspaceRoot??process.cwd());for(let{config:s}of i?.allConfigsById.values()??[])s&&$r({state:e,config:s,pi:t}).catch(a=>{we.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}we.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function hB(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(Y4,r=>{AT({pi:t,state:e,data:r}).then(()=>{N(e.currentLoad?.latestPi??t,e),Se(e)})}))}function jT(t,e){zr(e)?(Wt(t),Ca(t)):Lg(t,e),Se(e)}function mB(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(X4,r=>{let n=()=>PT({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(o=>{we.warn(`Live MCP add-server did not retire credentials durably: ${o instanceof Error?o.message:String(o)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{let o=e.currentLoad?.latestPi??t;Se(e),Qo(o,e)})}))}function gB(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(Q4,r=>{let n=()=>Wm({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).then(()=>{Se(e)})}))}function yB(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(eB,r=>{let n=()=>Du({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).catch(o=>{we.warn(`Live MCP remove-server did not retire durably: ${o instanceof Error?o.message:String(o)}`)}).finally(()=>{let o=e.currentLoad?.latestPi??t;Se(e),Qo(o,e)})}))}function Ute(t){return sv(t)}function vB(t,e,r){e.connectStarted=!0,mi()&&Wt(r);let{servers:n,diagnostics:o}=ro(t.cwd,t.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let s of o)e.diagnostics.push(s),we.warn(s.message);let i=Je(n,e,r).then(()=>ZE(e)).catch(s=>{we.info("MCP driver-level connection pass rejected",{error:s instanceof Error?s.message:String(s)})}).finally(()=>{N(e.currentLoad?.latestPi??r,e),Se(e),LT(e.currentLoad?.latestPi??r,e),e.initialConnectPromise=null});e.initialConnectPromise=i}async function _B(t,e){if(!t.initialConnectPromise)return;let r,n=new Promise(o=>{r=setTimeout(o,1e4)});try{await Promise.race([t.initialConnectPromise,n])}catch(o){we.info("Initial MCP connection failed or rejected during ACP readiness wait",{error:o instanceof Error?o.message:String(o)})}finally{r&&clearTimeout(r)}jT(e,t)}var FT=t=>{let e=Y();e.currentLoad=Km(t),e.recoverTransientServer=(n,o)=>qE(n,e,t,o),e.themeChangeUnsubscribe?.(),e.themeChangeUnsubscribe=t.events.on("theme_changed",()=>{Se(e)});let r=!1;gT(t,e),Sk(t,e),iB(t,e),dB(t,e),lB(t,e),pB(t,e),hB(t,e),mB(t,e),gB(t,e),yB(t,e),fB(t,e),vT(t,e),QE(t,e),Iu(t,e),t.on("session_start",async(n,o)=>{e.currentLoad=Km(t),e.workspaceRoot=o.cwd;let i=o.mcpConfigOverride;e.mcpConfigOverride=Array.isArray(i)&&i.length>0?i:void 0,e.ui=o.ui,ST(e),e.connectStarted?jT(t,e):vB(o,e,t),o.mode==="acp"&&await _B(e,t),r||(r=!0,t.events.emit(Hk,Vk(t,e)))}),t.on("session_shutdown",()=>{wT(e),UE(e)})};Ig(FT);var qte=FT;export{qte as default,Ute as setMcpErrorReporter};
|
|
149
|
+
`)}function Z4(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Wm.includes(e))return e}async function B4(t,e,r){if(e.servers.size===0){t.ui.notify("MCP servers are not available","warning");return}if(e.reconnecting){t.ui.notify("MCP servers are already restarting...","warning");return}t.ui.notify("Restarting MCP servers...","info");let n=ta([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function CT(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Wm.filter(o=>o.startsWith(n)).map(o=>({value:o,label:o}))},handler:async(r,n)=>{if(r.trim().length===0&&n.mode==="interactive"&&n.hasUI){await bT(n,e,s=>ta([s],e,t),{classify:s=>nT({server:s,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(s,a)=>oT({server:s,disable:a,state:e,pi:t}),applyLocal:(s,a,c)=>iT({server:s,disable:a,scope:c,state:e,pi:t,cwd:n.cwd,agentDir:n.agentDir}),notify:s=>n.ui.notify(s,"info")},(s,a)=>Hk({serverName:s,state:e,pi:t,controller:a}));return}let i=Z4(r);if(!i){n.ui.notify(`Unknown /mcp subcommand. Available: ${Wm.join(", ")}.`,"warning");return}if(i==="list"){n.ui.notify(G4(e),"info");return}else return i}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await B4(n,e,t)}})}import{logger as W4}from"@hermes/logger";var PT=W4.child({prefix:"pi-mcp"}),Vm="augment:feature-flags";function V4(t){if(!t||typeof t!="object")return;let e=t;if(!(!e.flags||typeof e.flags!="object")&&!(e.errorStatus!==void 0&&typeof e.errorStatus!="string"))return t}function ET(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Vm,r=>{let n=V4(r);if(n===void 0){PT.warn(`${Vm} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,PT.debug(`Received feature-flag snapshot via ${Vm} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as K4}from"@hermes/logger";var oa=K4.child({prefix:"pi-mcp"}),xT=300*1e3,Km=600*1e3;function J4(t){if(!t.shouldProactivelyRefreshTokens)return;let e=Date.now();for(let r of t.servers.values()){let{config:n}=r;if(n.type!=="http"&&n.type!=="sse"||n.disabled||!r.hasRefreshEligibleOAuthCredential())continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(Ci(o,e)||o.expiresAt>e+Km||(oa.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Km}ms; refreshing`),r.refreshTokenIfPossible().then(i=>{i.kind!=="refreshed"&&oa.warn(`Background refresh for MCP server "${r.name}" did not complete (${i.kind})`)}).catch(()=>{oa.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function kT(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{J4(t)},xT);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,oa.debug(`Started background MCP OAuth refresh loop (interval ${xT}ms, buffer ${Km}ms)`)}function TT(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,oa.debug("Stopped background MCP OAuth refresh loop"))}import{logger as Y4}from"@hermes/logger";var kt=Y4.child({prefix:"pi-mcp"});function X4(t,e,r){t.dynamicallyAddedConfigIds.add(e),t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.sessionRemovedConfigIds.delete(e);for(let n of r)n.id!==void 0&&(t.registryConfigNamesById.set(n.id,n.name),t.registryCredentialConfigsById.set(n.id,{...n}))}function ar(t){Ye({state:t.state,domain:Ge(t.configId),epoch:t.intentEpoch})}function Q4(t){let e=new Set;for(let[r,n]of t.servers){let o=te(t,r,n);(o.owner.kind==="local"||o.owner.kind==="registry")&&e.add(r)}for(let[r,n]of t.hostLeases)(n.owner.kind==="local"||n.owner.kind==="registry")&&e.add(r);return e}function AT(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function MT(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),kt.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function ia(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t;ar(t);let s=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(kt.warn(s),!o()){if(r.diagnostics.push({message:s,origin:"registry"}),!i()){r.failedAddConfigIds.add(n);return}r.dynamicallyAddedConfigIds.add(n),r.sessionRemovedConfigIds.delete(n)}}function eB(t,e){return e.flatMap(r=>Au(t,r)?[r.config]:[])}function tB(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function rB(t,e){let r=tB(e);if(r){if(ia(t,r.error),r.error instanceof Tt)throw r.error;return}let n=eB(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){X4(t.state,t.configId,n);return}!t.superseded()&&e.some(o=>o.status==="collision")&&(t.state.failedAddConfigIds.add(t.configId),t.state.nameCollisionAddConfigIds.add(t.configId))}function $T(t,e){try{rB(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function nB(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t,s=r.servers.get(e.name);if(!s)return!1;let a=te(r,e.name,s);if(a.owner.kind==="plugin"||a.owner.kind==="vfs")return!1;if(i())return kt.info(`Live MCP add-server: embedded config id ${n} resolves to already-connected server "${e.name}"; no-op`),!0;let c=`Live MCP add-server: embedded config id ${n} collides on display name "${e.name}" with an already-connected server; cannot add a second server sharing that name`;return kt.warn(c),o()||(r.registryConfigNamesById.set(n,e.name),r.diagnostics.push({message:c,origin:"registry"}),r.failedAddConfigIds.add(n),r.nameCollisionAddConfigIds.add(n)),!0}async function oB(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await mi(t.state,t.configId),t.superseded()){ar(t);return}if(nB(t,e)){ar(t);return}try{if(!await Ir({state:t.state,config:e,pi:t.activePi})){ar(t);return}}catch(r){throw ia(t,r),r}kt.info(`Live MCP add-server: connecting embedded config id ${t.configId} (no registry refetch)`);try{let r=await t.connect([e],t.state,t.activePi,t.sourceOwnership);$T(t,r??[])}catch(r){if(ia(t,r),r instanceof Tt)throw r}}async function iB(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:i}=t;if(o()){ar(t),kt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){MT(r,e),kt.info(`Live MCP add-server: config id ${n} resolved to no new server (already connected, not opted in, or unknown id)`),i()||r.failedAddConfigIds.add(n),ar(t);return}if(await mi(r,n),o()){ar(t);return}try{if((await Promise.all(e.servers.map(c=>Ir({state:r,config:c,pi:t.activePi})))).some(c=>!c)){ar(t);return}}catch(a){throw ia(t,a),a}kt.info(`Live MCP add-server: connecting ${e.servers.length} server(s) for config id ${n}`);let s=await t.connect(e.servers,r,t.activePi,t.sourceOwnership);if(o()){ar(t);return}MT(r,e),$T(t,s??[])}function sB(t,e){if(typeof e=="string")return dk(e,t.workspaceRoot??process.cwd())}function aB(t,e,r){return t.targetMaterialStore?.has(e)===!0||r!==void 0&&t.targetMaterialStore?.has(r.name)===!0}function IT(t){let{pi:e,state:r,data:n,deps:o}=t,i=n,s=i&&typeof i.configId=="string"?i.configId:"";if(!s)return kt.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();let a=sB(r,i?.embeddedConfig);if(aB(r,s,a))return Promise.resolve();if(a!==void 0&&a.id!==s)return kt.warn(`Embedded MCP config id ${a.id??"<missing>"} does not match add target ${s}; rejecting`),Promise.resolve();if(!oo({state:r,configId:s,generation:i?.attachmentGeneration}))return kt.info(`Ignoring stale live MCP add-server command for config id ${s}`),Promise.resolve();r.sessionRemovedConfigIds.delete(s);let c=ma({state:r,domain:Ge(s),forceNew:!0}),u=Q4(r),d=r.currentLoad?.latestPi??e,l=r.registryGeneration;r.liveEditGenerations??=new Map;let f=(r.liveEditGenerations.get(s)??0)+1;r.liveEditGenerations.set(s,f);let p=()=>r.registryGeneration!==l||r.liveEditGenerations.get(s)!==f,h={state:r,configId:s,activePi:d,connect:o?.connect??Je,report:o?.report??N,intentEpoch:c.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>AT(r,s)},g;if(a)g=oB(h,a);else{let m=r.credentials;m?g=(o?.discover??Lu)({configIds:[s],creds:m,currentUserId:m.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:u}).then(w=>iB(h,w)).catch(w=>{if(!(w instanceof Tt)){ia(h,w);return}throw w}):(kt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),ar(h),g=Promise.resolve())}return _a({state:r,configId:s,generation:i?.attachmentGeneration,operation:g,wasApplied:()=>AT(r,s)})}import{logger as cB}from"@hermes/logger";var sa=cB.child({prefix:"pi-mcp"}),OT=3,zT=6e4,uB=1e3,dB=8e3;function Jm(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.reconnect??ir,s=o?.now??Date.now,a=o?.sleep??yn,c=o?.report??N,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return sa.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();let l=an({state:r,target:d});if(!l)return sa.warn(`augment:mcp-restart-server: no unique live host for ${d}; re-reporting status`),c(r.currentLoad?.latestPi??e,r),Promise.resolve();if(r.targetMaterialStore?.has(l.name)||r.targetMaterialStore?.has(d))return Promise.resolve();let f=l.name,p=r.mcpConnectionEpoch,h=D(r,f),g=s(),m=r.mcpRestartState.get(f),v=m&&g-m.lastRestart<zT?m.count+1:1,w=r.currentLoad?.latestPi??e;if(v>OT)return sa.warn(`augment:mcp-restart-server: ${f} exceeded ${OT} restarts within ${zT}ms; rejecting`),c(w,r),Promise.resolve();r.mcpRestartState.set(f,{count:v,lastRestart:g});let b=Math.min(uB*2**(v-1),dB);return(v>1?a(b):Promise.resolve()).then(()=>{if(!(r.mcpConnectionEpoch!==p||D(r,f)!==h||an({state:r,target:d})?.server!==l.server||t.isCurrent&&!t.isCurrent()))return sa.info(`Live MCP restart-server: reconnecting ${f}`),i(f,r,w)}).catch(_=>{let C=`Live MCP restart-server failed for ${f}: ${_ instanceof Error?_.message:String(_)}`;sa.warn(C),r.diagnostics.push({server:f,message:C})}).then(()=>{c(w,r)})}import{logger as lB}from"@hermes/logger";var aa=lB.child({prefix:"pi-mcp"}),fB=/^\d+$/,Ym=1,NT="AUGMENT_ACTIVE_SPACE_ID",pB="augment-mcp-access-token-";function Yu(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function DT(t,e){return e?.["augment:encoding"]!=="base64"?t:/^[A-Za-z0-9+/]*={0,2}$/.test(t)&&t.length%4===0?Buffer.from(t,"base64").toString("utf-8"):t}var Xu=class{constructor(e,r,n){this.cache=new Map;this.inflight=new Map;this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??kd}_headers(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}}lookupBody(e){let r={name:e};return!e.startsWith(pB)&&Object.hasOwn(process.env,NT)&&(r.active_space_id=process.env[NT]??""),r}getSecret(e){let r=Yu(e),n=this.inflight.get(r);if(n)return n;let o=this._resolve(r).finally(()=>{this.inflight.delete(r)});return this.inflight.set(r,o),o}upsertUserSecret(e,r,n){return vn(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=Yu(e),s=(await this._callUpsert({name:o,value:r,scope:Ym,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof s!="string"||!fB.test(s))throw new Error("user secret upsert response contained an invalid persisted version");let a=BigInt(s).toString();return this.cache.set(o,r),aa.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await vn(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=Yu(e);this.cache.delete(r),await this._callDelete({name:r,scope:Ym}),aa.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),i=o.length>ur?`${o.slice(0,ur)}\u2026[truncated]`:o;throw new yt(n.status,n.statusText,i)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),i=o.length>ur?`${o.slice(0,ur)}\u2026[truncated]`:o;throw new yt(n.status,n.statusText,i)}}async getUserSecretWithVersion(e){let r=Yu(e);try{let n=await vn(()=>this._callApi("/mcp-secrets/get",this.lookupBody(r))),o=n.secret?.value,i=n.secret?.version;if(o===void 0||i===void 0)return;let s=n.secret?.scope===Ym||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:DT(o,n.secret?.tags),version:s?i:"0"}}catch(n){if(n instanceof yt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&aa.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await vn(()=>this._callApi(e,r)),i=o.secret?.value;return i===void 0?{errored:!1}:{value:DT(i,o.secret?.tags),errored:!1}}catch(o){if(o instanceof yt&&o.statusCode===404)return aa.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let i=o instanceof Error?o.message:String(o);return aa.debug(`Secret "${n}" lookup via ${e} failed: ${i}`),{errored:!0}}}async _callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:this._headers(),body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let i=await o.text().catch(()=>""),s=i.length>ur?`${i.slice(0,ur)}\u2026[truncated]`:i;throw new yt(o.status,o.statusText,s)}return await o.json()}};function Xm(t){return{latestPi:t}}import{logger as hB}from"@hermes/logger";var ai=hB.child({prefix:"pi-mcp"});async function mB(t){let e=[];for(let[r,n]of t.servers){let o=te(t,r,n);if(o.owner.kind!=="vfs"||o.host!==n)continue;let i=dt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!i)continue;Ke(t,r);let s=gt(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([s,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw _e({state:t,name:r,retirement:i,result:{status:"failed",error:c.reason}}),c.reason;_e({state:t,name:r,retirement:i,result:{status:"retired"}}),xe({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function gB(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),ai.warn(r.message))}function yB(t){let{state:e,name:r,stored:n,higherPriorityNames:o,blockedNames:i,workspaceRoot:s}=t;if(o.has(r)){i.add(r);let a=`VFS MCP server "${r}" ignored: a higher-priority server with the same name takes precedence`;e.diagnostics.push({server:r,message:a,origin:"vfs"}),ai.warn(a);return}try{let a=ro(r,n);return{...a.type==="stdio"?Bt(a,s):Zt(a,s),vfsSource:"vfs"}}catch(a){let c=a instanceof At?a.message:`Failed to normalize VFS MCP server "${r}": ${a instanceof Error?a.message:String(a)}`;e.diagnostics.push({server:r,message:c,origin:"vfs"}),ai.warn(c);return}}function vB(t,e){let r=new Set;for(let[s,a]of t.servers){let c=te(t,s,a);c.owner.kind!=="vfs"&&c.host===a&&r.add(s)}for(let[s,a]of t.hostLeases)a.owner.kind!=="vfs"&&r.add(s);let n=t.workspaceRoot??process.cwd(),o=[],i=new Set;for(let[s,a]of Object.entries(e.servers??{})){if(a===null)continue;let c=yB({state:t,name:s,stored:a,higherPriorityNames:r,blockedNames:i,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:i}}function _B(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function LT(t){let{pi:e,state:r,data:n,deps:o}=t,i=o?.connect??Je,s=n;if(!s||typeof s!="object"||Array.isArray(s))return ai.warn("augment:mcp-vfs-servers payload is not an object"),Promise.resolve();let a=typeof s.signature=="string"?s.signature:void 0;if(a!==void 0&&a===r.lastSuccessfulVfsMcpSignature&&_B(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=mB(r);return r.diagnostics=r.diagnostics.filter(l=>l.origin!=="vfs"),r.lastSuccessfulVfsMcpSignature=void 0,r.blockedVfsMcpNames.clear(),d.then(()=>{if(r.vfsGeneration!==c)return!1;gB(r,s.diagnostics);let{servers:l,blockedNames:f}=vB(r,s);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(ai.info(`VFS MCP overlay: connecting ${l.length} server(s)`),i(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(g=>g.status==="failed"||g.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(g=>(p??[]).some(m=>m.config===g&&Au(r,m)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;ai.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var we=SB.child({prefix:"pi-mcp"}),HT="augment:mcp-oauth-credentials",jT="augment:mcp-header-secrets",FT="augment:mcp-header-secret-failures",Qm="augment:mcp-oauth-failures",UT="augment:credentials",wB="augment:mcp-config-ids",qT="augment:mcp-configs",bB="augment:mcp-vfs-servers",RB="augment:mcp-add-server",CB="augment:mcp-restart-server",PB="augment:mcp-remove-server",EB="augment:cloud-mode";function xB(t){if(!t.secretsClient||t.tokens instanceof wi)return;let e=t.tokens;t.tokens=new wi(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),we.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function kB(t){if(!t||typeof t!="object"){we.warn(`${HT} payload is not an object`);return}let e=t,r=e.suppressReconnect===!0&&typeof e.credentials=="object"&&e.credentials!==null&&!Array.isArray(e.credentials);return{credentials:r?e.credentials:t,restart:r&&e.restart&&typeof e.restart=="object"?e.restart:void 0,suppressReconnect:r,targetConfigId:r&&typeof e.targetConfigId=="string"?e.targetConfigId:void 0}}function eg(t,e){let r=e.restart?.serverName;if(typeof r!="string")return!1;let n=e.credentials[r],o=cn(n),i=an({state:t,target:r})?.server;if(i&&i.config.type!=="stdio"&&i.config.auth==="oauth"&&o&>({state:t,name:r,revision:o})&&!ZT({state:t,revision:o})&&br({store:t.tokens,serverName:r,proto:n,options:{acceptedRevisions:t.oauthCredentialRevisions,acceptedDomains:t.oauthCredentialDomains,expectedDomains:t.expectedCredentialDomains,equalRevisionRebindDomains:t.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:!0}}).decision!=="reject")return!0;let s="MCP restart credential was rejected; keeping the existing host";return we.warn(s),t.diagnostics.push({server:r,message:s}),!1}function TB(t){let{pi:e,state:r}=t,{payload:n}=t,o=r.mcpConnectionEpoch;if(Object.entries(n.credentials).some(([c,u])=>r.targetMaterialStore?.has(c)||fe(u)&&Object.hasOwn(u,"target_material"))||n.targetConfigId&&r.targetMaterialStore?.has(n.targetConfigId))return;if(n.restart){let c=Object.keys(n.credentials);if(typeof n.restart.serverName!="string"||typeof n.restart.requestId!="string"||c.length!==1){we.warn("MCP restart credentials must contain exactly the target entry");return}let u=an({state:r,target:n.restart.serverName});if(!u||c[0]!==u.name){we.warn("MCP restart credentials must contain exactly the resolved target entry"),N(r.currentLoad?.latestPi??e,r);return}n={...n,restart:{...n.restart,serverName:u.name}}}if(n.targetConfigId){ok({pi:e,state:r,update:{configId:n.targetConfigId,credentials:n.credentials}});return}if(n.restart&&!eg(r,n))return;let i=Object.keys(n.credentials).map(c=>({name:c,server:r.servers.get(c),lease:D(r,c)})),s=new Set;for(let c of Object.keys(n.credentials)){let u=r.servers.get(c)?.getRefreshInFlight?.();u&&s.add(u)}let a=()=>{if(r.mcpConnectionEpoch!==o||i.some(({name:d,server:l,lease:f})=>r.servers.get(d)!==l||D(r,d)!==f)||n.restart&&!eg(r,n))return;let c=OB({pi:e,state:r,credentials:n.credentials,suppressReconnect:n.suppressReconnect,requireEqualMaterial:n.restart!==void 0}),{restart:u}=n;if(!(typeof u?.serverName!="string"||typeof u.requestId!="string")){if(c.rejected.length===0&&c.applied.length+c.equal.length===1&&(c.applied.includes(u.serverName)||c.equal.includes(u.serverName))){Jm({pi:e,state:r,isCurrent:()=>r.mcpConnectionEpoch===o&&i.every(({name:d,server:l,lease:f})=>r.servers.get(d)===l&&D(r,d)===f)&&eg(r,n),data:{serverName:u.serverName,requestId:u.requestId}});return}if(Object.hasOwn(n.credentials,u.serverName)&&!c.equal.includes(u.serverName)){let d="MCP restart credential was rejected; keeping the existing host";we.warn(d),r.diagnostics.push({server:u.serverName,message:d})}}};if(s.size===0){a();return}Promise.allSettled(s).then(a)}function AB(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(HT,r=>{let n=kB(r);n&&TB({pi:t,state:e,payload:n})}))}function GT(t){let{state:e,name:r,revision:n}=t,o=hn(n);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let i=e.expectedCredentialDomains.get(r),s=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id,u=a?.config.registrySource!==void 0&&c!==void 0&&Ge(c)===o;return n.ownerDomain!==void 0?i?.kind==="domain"?i.domain===o:u:i===void 0&&s===void 0?u:i?.kind==="domain"&&(i.domain===o||Ie(n.domain))||s===n.domain}function ZT(t){let{state:e,revision:r}=t,n=hn(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function MB(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[i,s]of Object.entries(r)){let a=cn(s);if(br({store:e.tokens,serverName:i,proto:s,options:{requireRevision:!0}}).decision!=="reject"&&a!==void 0){if(ZT({state:e,revision:a})){Cg({state:e,revision:a,credential:s,suppressReconnect:n});continue}if(GT({state:e,name:i,revision:a})){o[i]=s;continue}bg({state:e,serverName:i,revision:a,credential:s,suppressReconnect:n})}}return o}function $B(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let i=r[o],s=cn(i);s===void 0?(e.credentialRevisions.delete(o),e.hostedCredentialOwnership.delete(o)):(e.credentialRevisions.set(o,s),e.hostedCredentialOwnership.set(o,{...s,accessTokenOnly:i?.refresh_token===void 0})),e.statusFailureCategories.delete(o),e.authRefreshNeededReportKeys.delete(o),e.tokens.clearAuthRequired(o)}}function IB(t){let{pi:e,state:r,seeded:n,suppressReconnect:o}=t;if(o)return;let i=r.currentLoad?.latestPi??e;for(let s of n){let a=r.servers.get(s),c=r.expectedCredentialDomains.get(s),u=D(r,s),d=c?.kind!=="domain"||u?.owner.kind==="registry"&&u.owner.identity===c.domain;a&&d&&a.config.type!=="stdio"&&a.config.auth==="oauth"&&ir(s,r,i).catch(()=>{}).finally(()=>{N(i,r),Se(r)})}}function OB(t){let{pi:e,state:r,credentials:n,suppressReconnect:o}=t;r.oauthCredentialRevisions??=new Map,r.oauthCredentialDomains??=new Map,r.credentialRevisions??=new Map,r.expectedCredentialDomains??=new Map;let i=MB({state:r,credentials:n,suppressReconnect:o}),s={acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0,requireEqualMaterial:t.requireEqualMaterial};Object.entries(i).some(([u,d])=>{let{decision:l}=br({store:r.tokens,serverName:u,proto:d,options:s});return l==="apply"||l==="equal"&&t.requireEqualMaterial===!0})&&(r.shouldProactivelyRefreshTokens=!1);let c=$u(r.tokens,i,s);return $B({state:r,applicable:i,seeded:c.applied}),c.applied.length===0||(we.info(`Seeded MCP OAuth token(s) for ${c.applied.length} server(s)`),IB({pi:e,state:r,seeded:c.applied,suppressReconnect:o})),c}function zB(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(jT,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${jT} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);lv(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(FT,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${FT} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);pv(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(Qm,r=>{if(!r||typeof r!="object"||Array.isArray(r)){we.warn(`${Qm} payload is not an object`);return}let n=r;if(typeof n.entries!="object"||n.entries===null||Array.isArray(n.entries)){we.warn(`${Qm} entries is not an object`);return}ig(e,n.entries)}))}function NB(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(UT,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){we.warn(`${UT} payload missing apiKey or apiUrl`);return}e.credentials={apiKey:n.apiKey,apiUrl:n.apiUrl,...typeof n.userAgent=="string"?{userAgent:n.userAgent}:{},...typeof n.userId=="string"?{userId:n.userId}:{}},e.secretsClient=new Xu(e.credentials),xB(e)}),t.events.on(wB,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0),zu(e.currentLoad?.latestPi??t,e),ra({pi:t,state:e,data:r}).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(n=>{we.warn(`Registry config apply did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Se(e),ei(n,e)})}))}function BT(t,e){e.isCloudMode!==!1||e.mcpAttachCloudSignaled||!e.credentials||ra({pi:t,state:e,data:{configIds:void 0,productType:"cli"},productType:"cli"}).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(r=>{we.warn(`CLI registry discovery failed: ${r instanceof Error?r.message:String(r)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{Se(e)})}function DB(t,e){e.cloudModeListenerBound||(e.cloudModeListenerBound=!0,t.events.on(EB,r=>{let n=r;if(typeof n?.enabled!="boolean")return;let o=e.isCloudMode;e.isCloudMode=n.enabled,o!==!1&&!n.enabled&&(o&&(e.mcpAttachCloudSignaled=!1),e.connectStarted&&e.initialConnectPromise===null&&BT(e.currentLoad?.latestPi??t,e))}))}function LB(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(qT,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){we.warn(`${qT} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let i=ri(o,e.workspaceRoot??process.cwd());for(let{config:s}of i?.allConfigsById.values()??[])s&&Ir({state:e,config:s,pi:t}).catch(a=>{we.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}we.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function jB(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(bB,r=>{LT({pi:t,state:e,data:r}).then(()=>{N(e.currentLoad?.latestPi??t,e),Se(e)})}))}function WT(t,e){Nr(e)?(Wt(t),Pa(t)):qg(t,e),Se(e)}function FB(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(RB,r=>{let n=()=>IT({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).then(()=>{N(e.currentLoad?.latestPi??t,e)}).catch(o=>{we.warn(`Live MCP add-server did not retire credentials durably: ${o instanceof Error?o.message:String(o)}`),N(e.currentLoad?.latestPi??t,e)}).finally(()=>{let o=e.currentLoad?.latestPi??t;Se(e),ei(o,e)})}))}function UB(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(CB,r=>{let n=()=>Jm({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).then(()=>{Se(e)})}))}function qB(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(PB,r=>{let n=()=>ju({pi:t,state:e,data:r});(e.targetMaterialQueue?na(e,n):n()).catch(o=>{we.warn(`Live MCP remove-server did not retire durably: ${o instanceof Error?o.message:String(o)}`)}).finally(()=>{let o=e.currentLoad?.latestPi??t;Se(e),ei(o,e)})}))}function wre(t){return dv(t)}function HB(t,e,r){e.connectStarted=!0,gi()&&Wt(r);let{servers:n,diagnostics:o}=no(t.cwd,t.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let s of o)e.diagnostics.push(s),we.warn(s.message);let i=Je(n,e,r).then(()=>Qx(e)).catch(s=>{we.info("MCP driver-level connection pass rejected",{error:s instanceof Error?s.message:String(s)})}).finally(()=>{N(e.currentLoad?.latestPi??r,e),Se(e),BT(e.currentLoad?.latestPi??r,e),e.initialConnectPromise=null});e.initialConnectPromise=i}async function GB(t,e){if(!t.initialConnectPromise)return;let r,n=new Promise(o=>{r=setTimeout(o,1e4)});try{await Promise.race([t.initialConnectPromise,n])}catch(o){we.info("Initial MCP connection failed or rejected during ACP readiness wait",{error:o instanceof Error?o.message:String(o)})}finally{r&&clearTimeout(r)}WT(e,t)}var VT=t=>{let e=Y();e.currentLoad=Xm(t),e.recoverTransientServer=(n,o)=>Jx(n,e,t,o),e.themeChangeUnsubscribe?.(),e.themeChangeUnsubscribe=t.events.on("theme_changed",()=>{Se(e)});let r=!1;CT(t,e),kk(t,e),AB(t,e),zB(t,e),NB(t,e),LB(t,e),jB(t,e),FB(t,e),UB(t,e),qB(t,e),DB(t,e),ET(t,e),ak(t,e),zu(t,e),t.on("session_start",async(n,o)=>{e.currentLoad=Xm(t),e.workspaceRoot=o.cwd;let i=o.mcpConfigOverride;e.mcpConfigOverride=Array.isArray(i)&&i.length>0?i:void 0,e.ui=o.ui,kT(e),e.connectStarted?WT(t,e):HB(o,e,t),o.mode==="acp"&&await GB(e,t),r||(r=!0,t.events.emit(Yk,rT(t,e)))}),t.on("session_shutdown",()=>{TT(e),Kx(e)})};Ng(VT);var bre=VT;export{bre as default,wre as setMcpErrorReporter};
|
|
150
150
|
/*! Bundled license information:
|
|
151
151
|
|
|
152
152
|
content-type/index.js:
|