@augmentcode/onison 1.2.0-prerelease.202608191509 → 1.2.0-prerelease.202608191548

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.
@@ -1,29 +1,29 @@
1
- var rE=Object.create;var su=Object.defineProperty;var nE=Object.getOwnPropertyDescriptor;var oE=Object.getOwnPropertyNames;var sE=Object.getPrototypeOf,iE=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 R=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},iu=(t,e)=>{for(var r in e)su(t,r,{get:e[r],enumerable:!0})},aE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oE(e))!iE.call(t,o)&&o!==r&&su(t,o,{get:()=>e[o],enumerable:!(n=nE(e,o))||n.enumerable});return t};var ki=(t,e,r)=>(r=t!=null?rE(sE(t)):{},aE(e||!t||!t.__esModule?su(r,"default",{value:t,enumerable:!0}):r,t));var xs=R(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.regexpCode=K.getEsmExportName=K.getProperty=K.safeStringify=K.stringify=K.strConcat=K.addCodeArg=K.str=K._=K.nil=K._Code=K.Name=K.IDENTIFIER=K._CodeOrName=void 0;var Ps=class{};K._CodeOrName=Ps;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var on=class extends Ps{constructor(e){if(super(),!K.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}}};K.Name=on;var gt=class extends Ps{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 on&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=gt;K.nil=new gt("");function Tw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Nl(r,e[n]),r.push(t[++n]);return new gt(r)}K._=Tw;var zl=new gt("+");function Aw(t,...e){let r=[Cs(t[0])],n=0;for(;n<e.length;)r.push(zl),Nl(r,e[n]),r.push(zl,Cs(t[++n]));return TO(r),new gt(r)}K.str=Aw;function Nl(t,e){e instanceof gt?t.push(...e._items):e instanceof on?t.push(e):t.push(MO(e))}K.addCodeArg=Nl;function TO(t){let e=1;for(;e<t.length-1;){if(t[e]===zl){let r=AO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function AO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof on||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 on))return`"${t}${e.slice(1)}`}function $O(t,e){return e.emptyStr()?t:t.emptyStr()?e:Aw`${t}${e}`}K.strConcat=$O;function MO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Cs(Array.isArray(t)?t.join(","):t)}function IO(t){return new gt(Cs(t))}K.stringify=IO;function Cs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Cs;function OO(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new gt(`.${t}`):Tw`[${t}]`}K.getProperty=OO;function zO(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new gt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=zO;function NO(t){return new gt(t.toString())}K.regexpCode=NO});var jl=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Xe=xs(),Dl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ja;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ja||(Qe.UsedValueState=ja={}));Qe.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var Fa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Xe.Name?e:this.name(e)}name(e){return new Xe.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}}};Qe.Scope=Fa;var Ua=class extends Xe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};Qe.ValueScopeName=Ua;var DO=(0,Xe._)`\n`,Ll=class extends Fa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?DO:Xe.nil}}get(){return this._scope}name(e){return new Ua(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:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,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,Xe._)`${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 s=Xe.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ja.Started);let d=r(u);if(d){let l=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Xe._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Xe._)`${s}${d}${this.opts._n}`;else throw new Dl(u);c.set(u,ja.Completed)})}return s}};Qe.ValueScope=Ll});var D=R(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.or=L.and=L.not=L.CodeGen=L.operators=L.varKinds=L.ValueScopeName=L.ValueScope=L.Scope=L.Name=L.regexpCode=L.stringify=L.getProperty=L.nil=L.strConcat=L.str=L._=void 0;var q=xs(),kt=jl(),Er=xs();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Er.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Er.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Er.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Er.Name}});var Za=jl();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Za.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Za.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Za.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Za.varKinds}});L.operators={GT:new q._Code(">"),GTE:new q._Code(">="),LT:new q._Code("<"),LTE:new q._Code("<="),EQ:new q._Code("==="),NEQ:new q._Code("!=="),NOT:new q._Code("!"),OR:new q._Code("||"),AND:new q._Code("&&"),ADD:new q._Code("+")};var or=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Fl=class extends or{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?kt.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 q._CodeOrName?this.rhs.names:{}}},qa=class extends or{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 q.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=eo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return Ga(e,this.rhs)}},Ul=class extends qa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ql=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Hl=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Gl=class extends or{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Zl=class extends or{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 q._CodeOrName?this.code.names:{}}},ks=class extends or{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 s=n[o];s.optimizeNames(e,r)||(LO(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>cn(e,r.names),{})}},sr=class extends ks{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Bl=class extends ks{},Qn=class extends sr{};Qn.kind="else";var sn=class t extends sr{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 Qn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t($w(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 Ga(e,this.condition),this.else&&cn(e,this.else.names),e}};sn.kind="if";var an=class extends sr{};an.kind="for";var Vl=class extends an{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 cn(super.names,this.iteration.names)}},Wl=class extends an{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ga(super.names,this.from);return Ga(e,this.to)}},Ha=class extends an{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 cn(super.names,this.iterable.names)}},Es=class extends sr{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)}};Es.kind="func";var Ts=class extends ks{render(e){return"return "+super.render(e)}};Ts.kind="return";var Kl=class extends sr{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&&cn(e,this.catch.names),this.finally&&cn(e,this.finally.names),e}},As=class extends sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};As.kind="catch";var $s=class extends sr{render(e){return"finally"+super.render(e)}};$s.kind="finally";var Jl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new Bl]}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 s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Fl(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new qa(e,r,n))}add(e,r){return this._leafNode(new Ul(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new Zl(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,q.addCodeArg)(r,o));return r.push("}"),new q._Code(r)}if(e,r,n){if(this._blockNode(new sn(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 sn(e))}else(){return this._elseNode(new Qn)}endIf(){return this._endBlockNode(sn,Qn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Vl(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new Wl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${i}.length`,a=>{this.var(s,(0,q._)`${i}[${a}]`),n(s)})}return this._for(new Ha("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,q._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ha("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(an)}label(e){return this._leafNode(new ql(e))}break(e){return this._leafNode(new Hl(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 Kl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new As(s),r(s)}return n&&(this._currNode=o.finally=new $s,this.code(n)),this._endBlockNode(As,$s)}throw(e){return this._leafNode(new Gl(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=q.nil,n,o){return this._blockNode(new Es(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Es)}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 sn))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}};L.CodeGen=Jl;function cn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ga(t,e){return e instanceof q._CodeOrName?cn(t,e.names):t}function eo(t,e,r){if(t instanceof q.Name)return n(t);if(!o(t))return t;return new q._Code(t._items.reduce((s,i)=>(i instanceof q.Name&&(i=n(i)),i instanceof q._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof q._Code&&s._items.some(i=>i instanceof q.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function LO(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function $w(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${Yl(t)}`}L.not=$w;var jO=Mw(L.operators.AND);function FO(...t){return t.reduce(jO)}L.and=FO;var UO=Mw(L.operators.OR);function qO(...t){return t.reduce(UO)}L.or=qO;function Mw(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${Yl(e)} ${t} ${Yl(r)}`}function Yl(t){return t instanceof q.Name?t:(0,q._)`(${t})`}});var H=R(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var se=D(),HO=xs();function GO(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=GO;function ZO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(zw(t,e),!Nw(e,t.self.RULES.all))}j.alwaysValidSchema=ZO;function zw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||jw(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=zw;function Nw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=Nw;function BO(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}j.schemaHasRulesButRef=BO;function VO({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)}`}j.schemaRefOrVal=VO;function WO(t){return Dw(decodeURIComponent(t))}j.unescapeFragment=WO;function KO(t){return encodeURIComponent(Ql(t))}j.escapeFragment=KO;function Ql(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Ql;function Dw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Dw;function JO(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=JO;function Iw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?t(o,s,i):e(o,s,i),i):s instanceof se.Name?(e(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}j.mergeEvaluated={props:Iw({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} || {}`),ep(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Lw}),items:Iw({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 Lw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&ep(t,r,e),r}j.evaluatedPropsToName=Lw;function ep(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}j.setEvaluated=ep;var Ow={};function YO(t,e){return t.scopeValue("func",{ref:e,code:Ow[e.code]||(Ow[e.code]=new HO._Code(e.code))})}j.useFunc=YO;var Xl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Xl||(j.Type=Xl={}));function XO(t,e,r){if(t instanceof se.Name){let n=e===Xl.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():"/"+Ql(t)}j.getErrorPath=XO;function jw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}j.checkStrictMode=jw});var ir=R(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var Ne=D(),QO={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};tp.default=QO});var Ms=R(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var G=D(),Ba=H(),Fe=ir();De.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,G.str)`"${t}" keyword must be ${e} ($data)`:(0,G.str)`"${t}" keyword is invalid ($data)`};function ez(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=qw(t,e,r);n??(i||a)?Fw(s,c):Uw(o,(0,G._)`[${c}]`)}De.reportError=ez;function tz(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=qw(t,e,r);Fw(o,a),s||i||Uw(n,Fe.default.vErrors)}De.reportExtraError=tz;function rz(t,e){t.assign(Fe.default.errors,e),t.if((0,G._)`${Fe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,G._)`${Fe.default.vErrors}.length`,e),()=>t.assign(Fe.default.vErrors,null)))}De.resetErrorsCount=rz;function nz({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Fe.default.errors,a=>{t.const(i,(0,G._)`${Fe.default.vErrors}[${a}]`),t.if((0,G._)`${i}.instancePath === undefined`,()=>t.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Fe.default.instancePath,s.errorPath))),t.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,G._)`${i}.schema`,r),t.assign((0,G._)`${i}.data`,n))})}De.extendErrors=nz;function Fw(t,e){let r=t.const("err",e);t.if((0,G._)`${Fe.default.vErrors} === null`,()=>t.assign(Fe.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Fe.default.vErrors}.push(${r})`),t.code((0,G._)`${Fe.default.errors}++`)}function Uw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,G._)`new ${t.ValidationError}(${e})`):(r.assign((0,G._)`${n}.errors`,e),r.return(!1))}var un={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function qw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:oz(t,e,r)}function oz(t,e,r={}){let{gen:n,it:o}=t,s=[sz(o,r),iz(t,r)];return az(t,e,s),n.object(...s)}function sz({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:t;return[Fe.default.instancePath,(0,G.strConcat)(Fe.default.instancePath,r)]}function iz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,G.str)`${e}/${t}`;return r&&(o=(0,G.str)`${o}${(0,Ba.getErrorPath)(r,Ba.Type.Str)}`),[un.schemaPath,o]}function az(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([un.keyword,o],[un.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([un.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([un.schema,i],[un.parentSchema,(0,G._)`${d}${l}`],[Fe.default.data,s]),u&&n.push([un.propertyName,u])}});var Gw=R(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;var cz=Ms(),uz=D(),dz=ir(),lz={message:"boolean schema is false"};function pz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Hw(t,!1):typeof r=="object"&&r.$async===!0?e.return(dz.default.data):(e.assign((0,uz._)`${n}.errors`,null),e.return(!0))}to.topBoolOrEmptySchema=pz;function fz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Hw(t)):r.var(e,!0)}to.boolOrEmptySchema=fz;function Hw(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,cz.reportError)(o,lz,void 0,e)}});var rp=R(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.getRules=ro.isJSONType=void 0;var hz=["string","number","integer","boolean","null","object","array"],mz=new Set(hz);function gz(t){return typeof t=="string"&&mz.has(t)}ro.isJSONType=gz;function yz(){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:{}}}ro.getRules=yz});var np=R(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.shouldUseRule=Tr.shouldUseGroup=Tr.schemaHasRulesForType=void 0;function vz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Zw(t,n)}Tr.schemaHasRulesForType=vz;function Zw(t,e){return e.rules.some(r=>Bw(t,r))}Tr.shouldUseGroup=Zw;function Bw(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))}Tr.shouldUseRule=Bw});var Is=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var _z=rp(),Sz=np(),wz=Ms(),N=D(),Vw=H(),no;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(no||(Le.DataType=no={}));function bz(t){let e=Ww(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}Le.getSchemaTypes=bz;function Ww(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(_z.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Ww;function Rz(t,e){let{gen:r,data:n,opts:o}=t,s=Pz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Sz.schemaHasRulesForType)(t,e[0]));if(i){let a=sp(e,n,o.strictNumbers,no.Wrong);r.if(a,()=>{s.length?Cz(t,e,s):ip(t)})}return i}Le.coerceAndCheckDataType=Rz;var Kw=new Set(["string","number","integer","boolean","null"]);function Pz(t,e){return e?t.filter(r=>Kw.has(r)||e==="array"&&r==="array"):[]}function Cz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);s.coerceTypes==="array"&&n.if((0,N._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(i,(0,N._)`typeof ${o}`).if(sp(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(Kw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ip(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),xz(t,a)});function c(u){switch(u){case"string":n.elseIf((0,N._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${i} == "boolean" || ${o} === null
1
+ var iE=Object.create;var au=Object.defineProperty;var aE=Object.getOwnPropertyDescriptor;var cE=Object.getOwnPropertyNames;var uE=Object.getPrototypeOf,dE=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 R=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},cu=(t,e)=>{for(var r in e)au(t,r,{get:e[r],enumerable:!0})},lE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of cE(e))!dE.call(t,o)&&o!==r&&au(t,o,{get:()=>e[o],enumerable:!(n=aE(e,o))||n.enumerable});return t};var Ti=(t,e,r)=>(r=t!=null?iE(uE(t)):{},lE(e||!t||!t.__esModule?au(r,"default",{value:t,enumerable:!0}):r,t));var Es=R(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.regexpCode=K.getEsmExportName=K.getProperty=K.safeStringify=K.stringify=K.strConcat=K.addCodeArg=K.str=K._=K.nil=K._Code=K.Name=K.IDENTIFIER=K._CodeOrName=void 0;var xs=class{};K._CodeOrName=xs;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var sn=class extends xs{constructor(e){if(super(),!K.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}}};K.Name=sn;var gt=class extends xs{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 sn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=gt;K.nil=new gt("");function Iw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)jl(r,e[n]),r.push(t[++n]);return new gt(r)}K._=Iw;var Ll=new gt("+");function Ow(t,...e){let r=[ks(t[0])],n=0;for(;n<e.length;)r.push(Ll),jl(r,e[n]),r.push(Ll,ks(t[++n]));return IO(r),new gt(r)}K.str=Ow;function jl(t,e){e instanceof gt?t.push(...e._items):e instanceof sn?t.push(e):t.push(NO(e))}K.addCodeArg=jl;function IO(t){let e=1;for(;e<t.length-1;){if(t[e]===Ll){let r=OO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function OO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof sn||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 sn))return`"${t}${e.slice(1)}`}function zO(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ow`${t}${e}`}K.strConcat=zO;function NO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ks(Array.isArray(t)?t.join(","):t)}function DO(t){return new gt(ks(t))}K.stringify=DO;function ks(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=ks;function LO(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new gt(`.${t}`):Iw`[${t}]`}K.getProperty=LO;function jO(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new gt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=jO;function FO(t){return new gt(t.toString())}K.regexpCode=FO});var ql=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Es(),Fl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ua;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ua||(Xe.UsedValueState=Ua={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var qa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Xe.Scope=qa;var Ha=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Ha;var UO=(0,Ye._)`\n`,Ul=class extends qa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?UO:Ye.nil}}get(){return this._scope}name(e){return new Ha(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:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,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,Ye._)`${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 s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Ua.Started);let d=r(u);if(d){let l=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ye._)`${s}${d}${this.opts._n}`;else throw new Fl(u);c.set(u,Ua.Completed)})}return s}};Xe.ValueScope=Ul});var D=R(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.or=L.and=L.not=L.CodeGen=L.operators=L.varKinds=L.ValueScopeName=L.ValueScope=L.Scope=L.Name=L.regexpCode=L.stringify=L.getProperty=L.nil=L.strConcat=L.str=L._=void 0;var q=Es(),kt=ql(),Tr=Es();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Tr._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Tr.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Tr.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Tr.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Tr.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Tr.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Tr.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Tr.Name}});var Va=ql();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Va.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Va.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Va.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Va.varKinds}});L.operators={GT:new q._Code(">"),GTE:new q._Code(">="),LT:new q._Code("<"),LTE:new q._Code("<="),EQ:new q._Code("==="),NEQ:new q._Code("!=="),NOT:new q._Code("!"),OR:new q._Code("||"),AND:new q._Code("&&"),ADD:new q._Code("+")};var or=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Hl=class extends or{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?kt.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=ro(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},Ga=class extends or{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 q.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ro(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return Ba(e,this.rhs)}},Gl=class extends Ga{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Zl=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Bl=class extends or{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vl=class extends or{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wl=class extends or{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=ro(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Ts=class extends or{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 s=n[o];s.optimizeNames(e,r)||(qO(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>un(e,r.names),{})}},sr=class extends Ts{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Kl=class extends Ts{},to=class extends sr{};to.kind="else";var an=class t extends sr{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 to(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(zw(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=ro(this.condition,e,r),this}get names(){let e=super.names;return Ba(e,this.condition),this.else&&un(e,this.else.names),e}};an.kind="if";var cn=class extends sr{};cn.kind="for";var Jl=class extends cn{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=ro(this.iteration,e,r),this}get names(){return un(super.names,this.iteration.names)}},Yl=class extends cn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ba(super.names,this.from);return Ba(e,this.to)}},Za=class extends cn{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=ro(this.iterable,e,r),this}get names(){return un(super.names,this.iterable.names)}},As=class extends sr{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)}};As.kind="func";var $s=class extends Ts{render(e){return"return "+super.render(e)}};$s.kind="return";var Xl=class extends sr{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&&un(e,this.catch.names),this.finally&&un(e,this.finally.names),e}},Ms=class extends sr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ms.kind="catch";var Is=class extends sr{render(e){return"finally"+super.render(e)}};Is.kind="finally";var Ql=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new Kl]}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 s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Hl(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ga(e,r,n))}add(e,r){return this._leafNode(new Gl(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new Wl(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,q.addCodeArg)(r,o));return r.push("}"),new q._Code(r)}if(e,r,n){if(this._blockNode(new an(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 an(e))}else(){return this._elseNode(new to)}endIf(){return this._endBlockNode(an,to)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Jl(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new Yl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${i}.length`,a=>{this.var(s,(0,q._)`${i}[${a}]`),n(s)})}return this._for(new Za("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,q._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Za("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(cn)}label(e){return this._leafNode(new Zl(e))}break(e){return this._leafNode(new Bl(e))}return(e){let r=new $s;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($s)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Xl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ms(s),r(s)}return n&&(this._currNode=o.finally=new Is,this.code(n)),this._endBlockNode(Ms,Is)}throw(e){return this._leafNode(new Vl(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=q.nil,n,o){return this._blockNode(new As(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(As)}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 an))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}};L.CodeGen=Ql;function un(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ba(t,e){return e instanceof q._CodeOrName?un(t,e.names):t}function ro(t,e,r){if(t instanceof q.Name)return n(t);if(!o(t))return t;return new q._Code(t._items.reduce((s,i)=>(i instanceof q.Name&&(i=n(i)),i instanceof q._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof q._Code&&s._items.some(i=>i instanceof q.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function qO(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function zw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${ep(t)}`}L.not=zw;var HO=Nw(L.operators.AND);function GO(...t){return t.reduce(HO)}L.and=GO;var ZO=Nw(L.operators.OR);function BO(...t){return t.reduce(ZO)}L.or=BO;function Nw(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${ep(e)} ${t} ${ep(r)}`}function ep(t){return t instanceof q.Name?t:(0,q._)`(${t})`}});var H=R(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var se=D(),VO=Es();function WO(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=WO;function KO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(jw(t,e),!Fw(e,t.self.RULES.all))}j.alwaysValidSchema=KO;function jw(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Hw(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=jw;function Fw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=Fw;function JO(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}j.schemaHasRulesButRef=JO;function YO({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)}`}j.schemaRefOrVal=YO;function XO(t){return Uw(decodeURIComponent(t))}j.unescapeFragment=XO;function QO(t){return encodeURIComponent(rp(t))}j.escapeFragment=QO;function rp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=rp;function Uw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Uw;function ez(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=ez;function Dw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?t(o,s,i):e(o,s,i),i):s instanceof se.Name?(e(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}j.mergeEvaluated={props:Dw({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} || {}`),np(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:qw}),items:Dw({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 qw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&np(t,r,e),r}j.evaluatedPropsToName=qw;function np(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}j.setEvaluated=np;var Lw={};function tz(t,e){return t.scopeValue("func",{ref:e,code:Lw[e.code]||(Lw[e.code]=new VO._Code(e.code))})}j.useFunc=tz;var tp;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(tp||(j.Type=tp={}));function rz(t,e,r){if(t instanceof se.Name){let n=e===tp.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():"/"+rp(t)}j.getErrorPath=rz;function Hw(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}j.checkStrictMode=Hw});var ir=R(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var Ne=D(),nz={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};op.default=nz});var Os=R(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var G=D(),Wa=H(),Fe=ir();De.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,G.str)`"${t}" keyword must be ${e} ($data)`:(0,G.str)`"${t}" keyword is invalid ($data)`};function oz(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Bw(t,e,r);n??(i||a)?Gw(s,c):Zw(o,(0,G._)`[${c}]`)}De.reportError=oz;function sz(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Bw(t,e,r);Gw(o,a),s||i||Zw(n,Fe.default.vErrors)}De.reportExtraError=sz;function iz(t,e){t.assign(Fe.default.errors,e),t.if((0,G._)`${Fe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,G._)`${Fe.default.vErrors}.length`,e),()=>t.assign(Fe.default.vErrors,null)))}De.resetErrorsCount=iz;function az({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Fe.default.errors,a=>{t.const(i,(0,G._)`${Fe.default.vErrors}[${a}]`),t.if((0,G._)`${i}.instancePath === undefined`,()=>t.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Fe.default.instancePath,s.errorPath))),t.assign((0,G._)`${i}.schemaPath`,(0,G.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,G._)`${i}.schema`,r),t.assign((0,G._)`${i}.data`,n))})}De.extendErrors=az;function Gw(t,e){let r=t.const("err",e);t.if((0,G._)`${Fe.default.vErrors} === null`,()=>t.assign(Fe.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Fe.default.vErrors}.push(${r})`),t.code((0,G._)`${Fe.default.errors}++`)}function Zw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,G._)`new ${t.ValidationError}(${e})`):(r.assign((0,G._)`${n}.errors`,e),r.return(!1))}var dn={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function Bw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:cz(t,e,r)}function cz(t,e,r={}){let{gen:n,it:o}=t,s=[uz(o,r),dz(t,r)];return lz(t,e,s),n.object(...s)}function uz({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,Wa.getErrorPath)(e,Wa.Type.Str)}`:t;return[Fe.default.instancePath,(0,G.strConcat)(Fe.default.instancePath,r)]}function dz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,G.str)`${e}/${t}`;return r&&(o=(0,G.str)`${o}${(0,Wa.getErrorPath)(r,Wa.Type.Str)}`),[dn.schemaPath,o]}function lz(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([dn.keyword,o],[dn.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([dn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([dn.schema,i],[dn.parentSchema,(0,G._)`${d}${l}`],[Fe.default.data,s]),u&&n.push([dn.propertyName,u])}});var Ww=R(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.boolOrEmptySchema=no.topBoolOrEmptySchema=void 0;var pz=Os(),fz=D(),hz=ir(),mz={message:"boolean schema is false"};function gz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Vw(t,!1):typeof r=="object"&&r.$async===!0?e.return(hz.default.data):(e.assign((0,fz._)`${n}.errors`,null),e.return(!0))}no.topBoolOrEmptySchema=gz;function yz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Vw(t)):r.var(e,!0)}no.boolOrEmptySchema=yz;function Vw(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,pz.reportError)(o,mz,void 0,e)}});var sp=R(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.getRules=oo.isJSONType=void 0;var vz=["string","number","integer","boolean","null","object","array"],_z=new Set(vz);function Sz(t){return typeof t=="string"&&_z.has(t)}oo.isJSONType=Sz;function wz(){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:{}}}oo.getRules=wz});var ip=R(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.shouldUseRule=Ar.shouldUseGroup=Ar.schemaHasRulesForType=void 0;function bz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Kw(t,n)}Ar.schemaHasRulesForType=bz;function Kw(t,e){return e.rules.some(r=>Jw(t,r))}Ar.shouldUseGroup=Kw;function Jw(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))}Ar.shouldUseRule=Jw});var zs=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var Rz=sp(),Pz=ip(),Cz=Os(),N=D(),Yw=H(),so;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(so||(Le.DataType=so={}));function xz(t){let e=Xw(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}Le.getSchemaTypes=xz;function Xw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Rz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Xw;function kz(t,e){let{gen:r,data:n,opts:o}=t,s=Ez(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Pz.schemaHasRulesForType)(t,e[0]));if(i){let a=cp(e,n,o.strictNumbers,so.Wrong);r.if(a,()=>{s.length?Tz(t,e,s):up(t)})}return i}Le.coerceAndCheckDataType=kz;var Qw=new Set(["string","number","integer","boolean","null"]);function Ez(t,e){return e?t.filter(r=>Qw.has(r)||e==="array"&&r==="array"):[]}function Tz(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);s.coerceTypes==="array"&&n.if((0,N._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(i,(0,N._)`typeof ${o}`).if(cp(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(Qw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),up(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),Az(t,a)});function c(u){switch(u){case"string":n.elseIf((0,N._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${i} == "boolean" || ${o} === null
3
3
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":n.elseIf((0,N._)`${i} === "boolean" || ${o} === null
4
4
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":n.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,N._)`${i} === "string" || ${i} === "number"
5
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function xz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function op(t,e,r,n=no.Correct){let o=n===no.Correct?N.operators.EQ:N.operators.NEQ,s;switch(t){case"null":return(0,N._)`${e} ${o} null`;case"array":s=(0,N._)`Array.isArray(${e})`;break;case"object":s=(0,N._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,N._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,N._)`typeof ${e} ${o} ${t}`}return n===no.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}Le.checkDataType=op;function sp(t,e,r,n){if(t.length===1)return op(t[0],e,r,n);let o,s=(0,Vw.toHash)(t);if(s.array&&s.object){let i=(0,N._)`typeof ${e} != "object"`;o=s.null?i:(0,N._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=N.nil;s.number&&delete s.integer;for(let i in s)o=(0,N.and)(o,op(i,e,r,n));return o}Le.checkDataTypes=sp;var kz={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function ip(t){let e=Ez(t);(0,wz.reportError)(e,kz)}Le.reportTypeError=ip;function Ez(t){let{gen:e,data:r,schema:n}=t,o=(0,Vw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Yw=R(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.assignDefaults=void 0;var oo=D(),Tz=H();function Az(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Jw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Jw(t,s,o.default))}Va.assignDefaults=Az;function Jw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,oo._)`${s}${(0,oo.getProperty)(e)}`;if(o){(0,Tz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,oo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,oo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,oo._)`${a} = ${(0,oo.stringify)(r)}`)}});var yt=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ue=D(),ap=H(),Ar=ir(),$z=H();function Mz(t,e){let{gen:r,data:n,it:o}=t;r.if(up(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ue._)`${e}`},!0),t.error()})}te.checkReportMissingProp=Mz;function Iz({gen:t,data:e,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(up(t,e,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}te.checkMissingProp=Iz;function Oz(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=Oz;function Xw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Xw;function cp(t,e,r){return(0,ue._)`${Xw(t)}.call(${e}, ${r})`}te.isOwnProperty=cp;function zz(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${cp(t,e,r)}`:o}te.propertyInData=zz;function up(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(cp(t,e,r))):o}te.noPropertyInData=up;function Qw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=Qw;function Nz(t,e){return Qw(e).filter(r=>!(0,ap.alwaysValidSchema)(t,e[r]))}te.schemaProperties=Nz;function Dz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,ue._)`${t}, ${e}, ${n}${o}`:e,l=[[Ar.default.instancePath,(0,ue.strConcat)(Ar.default.instancePath,s)],[Ar.default.parentData,i.parentData],[Ar.default.parentDataProperty,i.parentDataProperty],[Ar.default.rootData,Ar.default.rootData]];i.opts.dynamicRef&&l.push([Ar.default.dynamicAnchors,Ar.default.dynamicAnchors]);let p=(0,ue._)`${d}, ${r.object(...l)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${p})`:(0,ue._)`${a}(${p})`}te.callValidateCode=Dz;var Lz=(0,ue._)`new RegExp`;function jz({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ue._)`${o.code==="new RegExp"?Lz:(0,$z.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=jz;function Fz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ue._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ap.Type.Num},s),e.if((0,ue.not)(s),a)})}}te.validateArray=Fz;function Uz(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,ap.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=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(i,(0,ue._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=Uz});var rb=R(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.validateKeywordUsage=qt.validSchemaType=qt.funcKeywordCode=qt.macroKeywordCode=void 0;var Ue=D(),dn=ir(),qz=yt(),Hz=Ms();function Gz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=tb(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ue.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qt.macroKeywordCode=Gz;function Zz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Vz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=tb(n,o,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)m(),e.modifying&&eb(t),y(()=>t.error());else{let S=e.async?f():h();e.modifying&&eb(t),y(()=>Bz(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Ue._)`await `),w=>n.assign(l,!1).if((0,Ue._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Ue._)`${w}.errors`),()=>n.throw(w))),S}function h(){let S=(0,Ue._)`${d}.errors`;return n.assign(S,null),m(Ue.nil),S}function m(S=e.async?(0,Ue._)`await `:Ue.nil){let w=c.opts.passContext?dn.default.this:dn.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Ue._)`${S}${(0,qz.callValidateCode)(t,d,w,b)}`,e.modifying)}function y(S){var w;n.if((0,Ue.not)((w=e.valid)!==null&&w!==void 0?w:l),S)}}qt.funcKeywordCode=Zz;function eb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ue._)`${n.parentData}[${n.parentDataProperty}]`))}function Bz(t,e){let{gen:r}=t;r.if((0,Ue._)`Array.isArray(${e})`,()=>{r.assign(dn.default.vErrors,(0,Ue._)`${dn.default.vErrors} === null ? ${e} : ${dn.default.vErrors}.concat(${e})`).assign(dn.default.errors,(0,Ue._)`${dn.default.vErrors}.length`),(0,Hz.extendErrors)(t)},()=>t.error())}function Vz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function tb(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,Ue.stringify)(r)})}function Wz(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")}qt.validSchemaType=Wz;function Kz({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}qt.validateKeywordUsage=Kz});var ob=R($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.extendSubschemaMode=$r.extendSubschemaData=$r.getSubschema=void 0;var Ht=D(),nb=H();function Jz(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){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,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,nb.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}$r.getSubschema=Jz;function Yz(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){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,p=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Ht.str)`${u}${(0,nb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);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]}}$r.extendSubschemaData=Yz;function Xz(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}$r.extendSubschemaMode=Xz});var dp=R((U6,sb)=>{"use strict";sb.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,s;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(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var ab=R((q6,ib)=>{"use strict";var Mr=ib.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(){};Wa(e,n,o,t,"",t)};Mr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Mr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Mr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Mr.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 Wa(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Mr.arrayKeywords)for(var p=0;p<l.length;p++)Wa(t,e,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in Mr.propsKeywords){if(l&&typeof l=="object")for(var f in l)Wa(t,e,r,l[f],o+"/"+d+"/"+Qz(f),s,o,d,n,f)}else(d in Mr.keywords||t.allKeys&&!(d in Mr.skipKeywords))&&Wa(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function Qz(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Os=R(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var eN=H(),tN=dp(),rN=ab(),nN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function oN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!lp(t):e?cb(t)<=e:!1}et.inlineRef=oN;var sN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function lp(t){for(let e in t){if(sN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(lp)||typeof r=="object"&&lp(r))return!0}return!1}function cb(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!nN.has(r)&&(typeof t[r]=="object"&&(0,eN.eachItem)(t[r],n=>e+=cb(n)),e===1/0))return 1/0}return e}function ub(t,e="",r){r!==!1&&(e=so(e));let n=t.parse(e);return db(t,n)}et.getFullPath=ub;function db(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=db;var iN=/#\/?$/;function so(t){return t?t.replace(iN,""):""}et.normalizeId=so;function aN(t,e,r){return r=so(r),t.resolve(e,r)}et.resolveUrl=aN;var cN=/^[a-z_][-a-z0-9._]*$/i;function uN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=so(t[r]||e),s={"":o},i=ub(n,o,!1),a={},c=new Set;return rN(t,{allKeys:!0},(l,p,f,h)=>{if(h===void 0)return;let m=i+p,y=s[h];typeof l[r]=="string"&&(y=S.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=y;function S(b){let k=this.opts.uriResolver.resolve;if(b=so(y?k(y,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!==so(m)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!cN.test(b))throw new Error(`invalid anchor "${b}"`);S.call(this,`#${b}`)}}}),a;function u(l,p,f){if(p!==void 0&&!tN(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}et.getSchemaRefs=uN});var Ds=R(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.getData=Ir.KeywordCxt=Ir.validateFunctionCode=void 0;var mb=Gw(),lb=Is(),fp=np(),Ka=Is(),dN=Yw(),Ns=rb(),pp=ob(),T=D(),z=ir(),lN=Os(),ar=H(),zs=Ms();function pN(t){if(vb(t)&&(_b(t),yb(t))){mN(t);return}gb(t,()=>(0,mb.topBoolOrEmptySchema)(t))}Ir.validateFunctionCode=pN;function gb({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${pb(r,o)}`),hN(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${fN(o)}`,n.$async,()=>t.code(pb(r,o)).code(s))}function fN(t){return(0,T._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,T._)`, ${z.default.dynamicAnchors}={}`:T.nil}}={}`}function hN(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,T._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,T._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,T._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,T._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,T._)`""`),t.var(z.default.parentData,(0,T._)`undefined`),t.var(z.default.parentDataProperty,(0,T._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`{}`)})}function mN(t){let{schema:e,opts:r,gen:n}=t;gb(t,()=>{r.$comment&&e.$comment&&wb(t),SN(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&gN(t),Sb(t),RN(t)})}function gN(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function pb(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function yN(t,e){if(vb(t)&&(_b(t),yb(t))){vN(t,e);return}(0,mb.boolOrEmptySchema)(t,e)}function yb({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 vb(t){return typeof t.schema!="boolean"}function vN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&wb(t),wN(t),bN(t);let s=n.const("_errs",z.default.errors);Sb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function _b(t){(0,ar.checkUnknownRules)(t),_N(t)}function Sb(t,e){if(t.opts.jtd)return fb(t,[],!1,e);let r=(0,lb.getSchemaTypes)(t.schema),n=(0,lb.coerceAndCheckDataType)(t,r);fb(t,r,!n,e)}function _N(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ar.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function SN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ar.checkStrictMode)(t,"default is ignored in the schema root")}function wN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,lN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function bN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function wb({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function RN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,T._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,z.default.vErrors),s.unevaluated&&PN(t),e.return((0,T._)`${z.default.errors} === 0`))}function PN({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function fb(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ar.schemaHasRulesButRef)(s,d))){o.block(()=>Rb(t,"$ref",d.all.$ref.definition));return}c.jtd||CN(t,e),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,fp.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ka.checkDataType)(p.type,i,c.strictNumbers)),hb(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ka.reportTypeError)(t)),o.endIf()):hb(t,p),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function hb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,dN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,fp.shouldUseRule)(n,s)&&Rb(t,s.keyword,s.definition,e.type)})}function CN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(xN(t,e),t.opts.allowUnionTypes||kN(t,e),EN(t,t.dataTypes))}function xN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{bb(t.dataTypes,r)||hp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),AN(t,e)}}function kN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hp(t,"use allowUnionTypes to allow union type keyword")}function EN(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:s}=o.definition;s.length&&!s.some(i=>TN(e,i))&&hp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function TN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function bb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function AN(t,e){let r=[];for(let n of t.dataTypes)bb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function hp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ar.checkStrictMode)(t,e,t.opts.strictTypes)}var Ja=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,ar.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",Pb(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,T.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,T.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,T._)`${r} !== undefined && (${(0,T.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=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Ka.checkDataTypes)(c,r,s.opts.strictNumbers,Ka.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,pp.getSubschema)(this.it,e);(0,pp.extendSubschemaData)(n,this.it,e),(0,pp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return yN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ar.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ar.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,T.Name)),!0}};Ir.KeywordCxt=Ja;function Rb(t,e,r,n){let o=new Ja(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 $N=/^\/(?:[^~]|~0|~1)*$/,MN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Pb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!$N.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=MN.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(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,ar.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Ir.getData=Pb});var Ya=R(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var mp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};gp.default=mp});var Ls=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var yp=Os(),vp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,yp.resolveUrl)(e,r,n),this.missingSchema=(0,yp.normalizeId)((0,yp.getFullPath)(e,this.missingRef))}};_p.default=vp});var Qa=R(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.resolveSchema=vt.getCompilingSchema=vt.resolveRef=vt.compileSchema=vt.SchemaEnv=void 0;var Et=D(),IN=Ya(),ln=ir(),Tt=Os(),Cb=H(),ON=Ds(),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,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};vt.SchemaEnv=io;function wp(t){let e=xb.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:IN.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ln.default.data,parentData:ln.default.parentData,parentDataProperty:ln.default.parentDataProperty,dataNames:[ln.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,ON.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(ln.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${ln.default.self}`,`${ln.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;f.evaluated={props:h instanceof Et.Name?void 0:h,items:m instanceof Et.Name?void 0:m,dynamicProps:h instanceof Et.Name,dynamicItems:m instanceof Et.Name},f.source&&(f.source.evaluated=(0,Et.stringify)(f.evaluated))}return t.validate=f,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)}}vt.compileSchema=wp;function zN(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=LN.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new io({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=NN.call(this,s)}vt.resolveRef=zN;function NN(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:wp.call(this,t)}function xb(t){for(let e of this._compilations)if(DN(e,t))return e}vt.getCompilingSchema=xb;function DN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function LN(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xa.call(this,t,e)}function Xa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Sp.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Xa.call(this,t,i);return typeof a?.schema!="object"?void 0:Sp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||wp.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new io({schema:a,schemaId:c,root:t,baseId:o})}return Sp.call(this,r,i)}}vt.resolveSchema=Xa;var jN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Sp(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,Cb.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!jN.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Cb.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Xa.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new io({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var kb=R((W6,FN)=>{FN.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 Pp=R((K6,Ib)=>{"use strict";var UN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tb=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),bp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ab=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),qN=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Rp(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 HN=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Eb(t){return t.length=0,!0}function GN(t,e,r){if(t.length){let n=Rp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function ZN(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=GN;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Eb}else{o.push(u);continue}}return o.length&&(a===Eb?r.zone=o.join(""):i?n.push(o.join("")):n.push(Rp(o))),r.address=n.join(""),r}function $b(t){if(BN(t,":")<2)return{host:t,isIPV6:!1};let e=ZN(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 BN(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function VN(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 WN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},KN=/[@/?#:]/g,JN=/[@/?#]/g;function Mb(t,e){let r=e?JN:KN;return r.lastIndex=0,t.replace(r,n=>WN[n])}function YN(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(bp(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Ab(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function XN(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(bp(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Ab(s)?e+=s:e+="%"+o,r+=2;continue}}qN(t[r])?e+=t[r]:e+=escape(t[r])}return e}function QN(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(bp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function eD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Tb(r)){let n=$b(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Mb(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}Ib.exports={nonSimpleDomain:HN,recomposeAuthority:eD,reescapeHostDelimiters:Mb,normalizePercentEncoding:YN,normalizePathEncoding:XN,escapePreservingEscapes:QN,removeDotSegments:VN,isIPv4:Tb,isUUID:UN,normalizeIPv6:$b,stringArrayToHexStripped:Rp}});var Lb=R((J6,Db)=>{"use strict";var{isUUID:tD}=Pp(),rD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,nD=["http","https","ws","wss","urn","urn:uuid"];function oD(t){return nD.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 Ob(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function zb(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 sD(t){return t.secure=Cp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function iD(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 aD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(rD);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}`,s=xp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function cD(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}`,s=xp(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function uD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!tD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function dD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Nb={scheme:"http",domainHost:!0,parse:Ob,serialize:zb},lD={scheme:"https",domainHost:Nb.domainHost,parse:Ob,serialize:zb},ec={scheme:"ws",domainHost:!0,parse:sD,serialize:iD},pD={scheme:"wss",domainHost:ec.domainHost,parse:ec.parse,serialize:ec.serialize},fD={scheme:"urn",parse:aD,serialize:cD,skipNormalize:!0},hD={scheme:"urn:uuid",parse:uD,serialize:dD,skipNormalize:!0},tc={http:Nb,https:lD,ws:ec,wss:pD,urn:fD,"urn:uuid":hD};Object.setPrototypeOf(tc,null);function xp(t){return t&&(tc[t]||tc[t.toLowerCase()])||void 0}Db.exports={wsIsSecure:Cp,SCHEMES:tc,isValidSchemeName:oD,getSchemeHandler:xp}});var Hb=R((Y6,oc)=>{"use strict";var{normalizeIPv6:mD,removeDotSegments:js,recomposeAuthority:gD,normalizePercentEncoding:yD,normalizePathEncoding:vD,escapePreservingEscapes:_D,reescapeHostDelimiters:SD,isIPv4:wD,nonSimpleDomain:bD}=Pp(),{SCHEMES:RD,getSchemeHandler:Fb}=Lb();function PD(t,e){return typeof t=="string"?t=$D(t,e):typeof t=="object"&&(t=nc(pn(t,e),e)),t}function CD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=rc(t,n),{parsed:i,malformedAuthorityOrPort:a}=rc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Ub(o,i,n,!0);return n.skipEscape=!0,pn(c,n)}function Ub(t,e,r,n){let o={};return n||(t=nc(pn(t,r),r),e=nc(pn(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 xD(t,e,r){let n=jb(t,r),o=jb(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function pn(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=[],s=Fb(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=yD(r.path):(r.path=_D(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=gD(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=js(a)),i===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 kD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ED=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,TD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function AD(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 rc(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,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(ED);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(TD);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(kD);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=AD(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(wD(n.host)===!1){let p=mD(n.host);n.host=p.host.toLowerCase(),s=p.isIPV6}else s=!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=Fb(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&bD(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=SD(unescape(n.host),s))),n.path&&(n.path=vD(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 nc(t,e){return rc(t,e).parsed}function $D(t,e){return qb(t,e).normalized}function qb(t,e){let{parsed:r,malformedAuthorityOrPort:n}=rc(t,e);return{normalized:n?t:pn(r,e),malformedAuthorityOrPort:n}}function jb(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=qb(t,e);return n?void 0:r}if(typeof t=="object")return pn(t,e)}var kp={SCHEMES:RD,normalize:PD,resolve:CD,resolveComponent:Ub,equal:xD,serialize:pn,parse:nc};oc.exports=kp;oc.exports.default=kp;oc.exports.fastUri=kp});var Zb=R(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var Gb=Hb();Gb.code='require("ajv/dist/runtime/uri").default';Ep.default=Gb});var Qb=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var MD=Ds();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return MD.KeywordCxt}});var ao=D();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return ao._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return ao.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return ao.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return ao.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return ao.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return ao.CodeGen}});var ID=Ya(),Jb=Ls(),OD=rp(),Fs=Qa(),zD=D(),Us=Os(),sc=Is(),Ap=H(),Bb=kb(),ND=Zb(),Yb=(t,e)=>new RegExp(t,e);Yb.code="new RegExp";var DD=["removeAdditional","useDefaults","coerceTypes"],LD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),jD={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."},FD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vb=200;function UD(t){var e,r,n,o,s,i,a,c,u,d,l,p,f,h,m,y,S,w,b,k,_,P,O,ge,ye;let Ze=t.strict,Ao=(e=t.code)===null||e===void 0?void 0:e.optimize,Ci=Ao===!0||Ao===void 0?1:Ao||0,xi=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Yb,lr=(o=t.uriResolver)!==null&&o!==void 0?o:ND.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:Ze)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:Ze)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Ci,regExp:xi}:{optimize:Ci,regExp:xi},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Vb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Vb,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(ge=t.unicodeRegExp)!==null&&ge!==void 0?ge:!0,int32range:(ye=t.int32range)!==null&&ye!==void 0?ye:!0,uriResolver:lr}}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,...UD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new zD.ValueScope({scope:{},prefixes:LD,es5:r,lines:n}),this.logger=VD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,OD.getRules)(),Wb.call(this,jD,e,"NOT SUPPORTED"),Wb.call(this,FD,e,"DEPRECATED","warn"),this._metaOpts=ZD.call(this),e.formats&&HD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&GD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),qD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Bb;n==="id"&&(o={...Bb},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 s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Jb.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.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 s.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 i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Us.normalizeId)(r||s),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 s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Kb.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=Kb.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(KD.call(this,n,r),!r)return(0,Ap.eachItem)(n,s=>Tp.call(this,s)),this;YD.call(this,r);let o={...r,type:(0,sc.getJSONTypes)(r.type),schemaType:(0,sc.getJSONTypes)(r.schemaType)};return(0,Ap.eachItem)(n,o.type.length===0?s=>Tp.call(this,s,o):s=>o.type.forEach(i=>Tp.call(this,s,o,i))),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(s=>s.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,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=Xb(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,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=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)(i||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),s&&!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=ID.default;qs.MissingRefError=Jb.default;Me.default=qs;function Wb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Kb(t){return t=(0,Us.normalizeId)(t),this.schemas[t]||this.refs[t]}function qD(){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 HD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function GD(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 ZD(){let t={...this.opts};for(let e of DD)delete t[e];return t}var BD={log(){},warn(){},error(){}};function VD(t){if(t===!1)return BD;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 WD=/^[a-z_$][a-z0-9_$:-]*$/i;function KD(t,e){let{RULES:r}=this;if((0,Ap.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!WD.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 Tp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,sc.getJSONTypes)(e.type),schemaType:(0,sc.getJSONTypes)(e.schemaType)}};e.before?JD.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function JD(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 YD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Xb(e)),t.validateSchema=this.compile(e,!0))}var XD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xb(t){return{anyOf:[t,XD]}}});var eR=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var QD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};$p.default=QD});var oR=R(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.callRef=fn.getValidate=void 0;var eL=Ls(),tR=yt(),tt=D(),co=ir(),rR=Qa(),ic=H(),tL={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=rR.resolveRef.call(c,u,o,r);if(d===void 0)throw new eL.default(n.opts.uriResolver,o,r);if(d instanceof rR.SchemaEnv)return p(d);return f(d);function l(){if(s===u)return ac(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return ac(t,(0,tt._)`${h}.validate`,u,u.$async)}function p(h){let m=nR(t,h);ac(t,m,h,h.$async)}function f(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,tt.stringify)(h)}:{ref:h}),y=e.name("valid"),S=t.subschema({schema:h,dataTypes:[],schemaPath:tt.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function nR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,tt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}fn.getValidate=nR;function ac(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?co.default.this:tt.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,tt._)`await ${(0,tR.callValidateCode)(t,e,u)}`),f(e),i||o.assign(h,!0)},m=>{o.if((0,tt._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,tR.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let m=(0,tt._)`${h}.errors`;o.assign(co.default.vErrors,(0,tt._)`${co.default.vErrors} === null ? ${m} : ${co.default.vErrors}.concat(${m})`),o.assign(co.default.errors,(0,tt._)`${co.default.vErrors}.length`)}function f(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ic.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,tt._)`${h}.evaluated.props`);s.props=ic.mergeEvaluated.props(o,S,s.props,tt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ic.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,tt._)`${h}.evaluated.items`);s.items=ic.mergeEvaluated.items(o,S,s.items,tt.Name)}}}fn.callRef=ac;fn.default=tL});var sR=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var rL=eR(),nL=oR(),oL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rL.default,nL.default];Mp.default=oL});var iR=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var cc=D(),Or=cc.operators,uc={maximum:{okStr:"<=",ok:Or.LTE,fail:Or.GT},minimum:{okStr:">=",ok:Or.GTE,fail:Or.LT},exclusiveMaximum:{okStr:"<",ok:Or.LT,fail:Or.GTE},exclusiveMinimum:{okStr:">",ok:Or.GT,fail:Or.LTE}},sL={message:({keyword:t,schemaCode:e})=>(0,cc.str)`must be ${uc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cc._)`{comparison: ${uc[t].okStr}, limit: ${e}}`},iL={keyword:Object.keys(uc),type:"number",schemaType:"number",$data:!0,error:sL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,cc._)`${r} ${uc[e].fail} ${n} || isNaN(${r})`)}};Ip.default=iL});var aR=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var Hs=D(),aL={message:({schemaCode:t})=>(0,Hs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Hs._)`{multipleOf: ${t}}`},cL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Hs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Hs._)`${i} !== parseInt(${i})`;t.fail$data((0,Hs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Op.default=cL});var uR=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});function cR(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}zp.default=cR;cR.code='require("ajv/dist/runtime/ucs2length").default'});var dR=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var hn=D(),uL=H(),dL=uR(),lL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,hn._)`{limit: ${t}}`},pL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:lL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?hn.operators.GT:hn.operators.LT,i=o.opts.unicode===!1?(0,hn._)`${r}.length`:(0,hn._)`${(0,uL.useFunc)(t.gen,dL.default)}(${r})`;t.fail$data((0,hn._)`${i} ${s} ${n}`)}};Np.default=pL});var lR=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var fL=yt(),hL=H(),uo=D(),mL={message:({schemaCode:t})=>(0,uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,uo._)`{pattern: ${t}}`},gL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,uo._)`new RegExp`:(0,hL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,uo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,uo._)`!${d}`)}else{let c=(0,fL.usePattern)(t,o);t.fail$data((0,uo._)`!${c}.test(${r})`)}}};Dp.default=gL});var pR=R(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var Gs=D(),yL={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}}`},vL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:yL,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}`)}};Lp.default=vL});var fR=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Zs=yt(),Bs=D(),_L=H(),SL={message:({params:{missingProperty:t}})=>(0,Bs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Bs._)`{missingProperty: ${t}}`},wL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(f?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,_L.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Bs.nil,l);else for(let f of r)(0,Zs.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Zs.checkMissingProp)(t,r,f)),(0,Zs.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Zs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,Zs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Bs.not)(h),()=>{t.error(),e.break()})},Bs.nil)}}};jp.default=wL});var hR=R(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var Vs=D(),bL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Vs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Vs._)`{limit: ${t}}`},RL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:bL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Vs.operators.GT:Vs.operators.LT;t.fail$data((0,Vs._)`${r}.length ${o} ${n}`)}};Fp.default=RL});var dc=R(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});var mR=dp();mR.code='require("ajv/dist/runtime/equal").default';Up.default=mR});var gR=R(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var qp=Is(),Ie=D(),PL=H(),CL=dc(),xL={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},kL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:xL,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,qp.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Ie._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Ie._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Ie._)`${h} > 1`,()=>(l()?p:f)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,m){let y=e.name("item"),S=(0,qp.checkDataTypes)(u,y,a.opts.strictNumbers,qp.DataType.Wrong),w=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${h}--;`,()=>{e.let(y,(0,Ie._)`${r}[${h}]`),e.if(S,(0,Ie._)`continue`),u.length>1&&e.if((0,Ie._)`typeof ${y} == "string"`,(0,Ie._)`${y} += "_"`),e.if((0,Ie._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Ie._)`${w}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ie._)`${w}[${y}] = ${h}`)})}function f(h,m){let y=(0,PL.useFunc)(e,CL.default),S=e.name("outer");e.label(S).for((0,Ie._)`;${h}--;`,()=>e.for((0,Ie._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Ie._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};Hp.default=kL});var yR=R(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});var Gp=D(),EL=H(),TL=dc(),AL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Gp._)`{allowedValue: ${t}}`},$L={keyword:"const",$data:!0,error:AL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Gp._)`!${(0,EL.useFunc)(e,TL.default)}(${r}, ${o})`):t.fail((0,Gp._)`${s} !== ${r}`)}};Zp.default=$L});var vR=R(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var Ws=D(),ML=H(),IL=dc(),OL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ws._)`{allowedValues: ${t}}`},zL={keyword:"enum",schemaType:"array",$data:!0,error:OL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,ML.useFunc)(e,IL.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 f=e.const("vSchema",s);d=(0,Ws.or)(...o.map((h,m)=>p(f,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,Ws._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,h){let m=o[h];return typeof m=="object"&&m!==null?(0,Ws._)`${u()}(${r}, ${f}[${h}])`:(0,Ws._)`${r} === ${m}`}}};Bp.default=zL});var _R=R(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});var NL=iR(),DL=aR(),LL=dR(),jL=lR(),FL=pR(),UL=fR(),qL=hR(),HL=gR(),GL=yR(),ZL=vR(),BL=[NL.default,DL.default,LL.default,jL.default,FL.default,UL.default,qL.default,HL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},GL.default,ZL.default];Vp.default=BL});var Kp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.validateAdditionalItems=void 0;var mn=D(),Wp=H(),VL={message:({params:{len:t}})=>(0,mn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mn._)`{limit: ${t}}`},WL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:VL,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}SR(t,n)}};function SR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,mn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,mn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Wp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,mn._)`${a} <= ${e.length}`);r.if((0,mn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:Wp.Type.Num},u),i.allErrors||r.if((0,mn.not)(u),()=>r.break())})}}Ks.validateAdditionalItems=SR;Ks.default=WL});var Jp=R(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.validateTuple=void 0;var wR=D(),lc=H(),KL=yt(),JL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return bR(t,"additionalItems",e);r.items=!0,!(0,lc.alwaysValidSchema)(r,e)&&t.ok((0,KL.validateArray)(t))}};function bR(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=lc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,wR._)`${s}.length`);r.forEach((l,p)=>{(0,lc.alwaysValidSchema)(a,l)||(n.if((0,wR._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(p.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,lc.checkStrictMode)(a,y,p.strictTuples)}}}Js.validateTuple=bR;Js.default=JL});var RR=R(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var YL=Jp(),XL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,YL.validateTuple)(t,"items")};Yp.default=XL});var CR=R(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var PR=D(),QL=H(),ej=yt(),tj=Kp(),rj={message:({params:{len:t}})=>(0,PR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,PR._)`{limit: ${t}}`},nj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,QL.alwaysValidSchema)(n,e)&&(o?(0,tj.validateAdditionalItems)(t,o):t.ok((0,ej.validateArray)(t)))}};Xp.default=nj});var xR=R(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var _t=D(),pc=H(),oj={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},sj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:oj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pc.alwaysValidSchema)(s,r)){let m=(0,_t._)`${d} >= ${i}`;a!==void 0&&(m=(0,_t._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>t.reset());function p(){let m=e.name("_valid"),y=e.let("count",0);f(m,()=>e.if(m,()=>h(y)))}function f(m,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:pc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,_t._)`${m}++`),a===void 0?e.if((0,_t._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,_t._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,_t._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};Qp.default=sj});var TR=R(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateSchemaDeps=Gt.validatePropertyDeps=Gt.error=void 0;var ef=D(),ij=H(),Ys=yt();Gt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ef.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ef._)`{property: ${t},
5
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function Az({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function ap(t,e,r,n=so.Correct){let o=n===so.Correct?N.operators.EQ:N.operators.NEQ,s;switch(t){case"null":return(0,N._)`${e} ${o} null`;case"array":s=(0,N._)`Array.isArray(${e})`;break;case"object":s=(0,N._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,N._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,N._)`typeof ${e} ${o} ${t}`}return n===so.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}Le.checkDataType=ap;function cp(t,e,r,n){if(t.length===1)return ap(t[0],e,r,n);let o,s=(0,Yw.toHash)(t);if(s.array&&s.object){let i=(0,N._)`typeof ${e} != "object"`;o=s.null?i:(0,N._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=N.nil;s.number&&delete s.integer;for(let i in s)o=(0,N.and)(o,ap(i,e,r,n));return o}Le.checkDataTypes=cp;var $z={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function up(t){let e=Mz(t);(0,Cz.reportError)(e,$z)}Le.reportTypeError=up;function Mz(t){let{gen:e,data:r,schema:n}=t,o=(0,Yw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var tb=R(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.assignDefaults=void 0;var io=D(),Iz=H();function Oz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)eb(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>eb(t,s,o.default))}Ka.assignDefaults=Oz;function eb(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,io._)`${s}${(0,io.getProperty)(e)}`;if(o){(0,Iz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,io._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,io._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,io._)`${a} = ${(0,io.stringify)(r)}`)}});var yt=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ue=D(),dp=H(),$r=ir(),zz=H();function Nz(t,e){let{gen:r,data:n,it:o}=t;r.if(pp(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ue._)`${e}`},!0),t.error()})}te.checkReportMissingProp=Nz;function Dz({gen:t,data:e,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(pp(t,e,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}te.checkMissingProp=Dz;function Lz(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=Lz;function rb(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=rb;function lp(t,e,r){return(0,ue._)`${rb(t)}.call(${e}, ${r})`}te.isOwnProperty=lp;function jz(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${lp(t,e,r)}`:o}te.propertyInData=jz;function pp(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(lp(t,e,r))):o}te.noPropertyInData=pp;function nb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=nb;function Fz(t,e){return nb(e).filter(r=>!(0,dp.alwaysValidSchema)(t,e[r]))}te.schemaProperties=Fz;function Uz({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,ue._)`${t}, ${e}, ${n}${o}`:e,l=[[$r.default.instancePath,(0,ue.strConcat)($r.default.instancePath,s)],[$r.default.parentData,i.parentData],[$r.default.parentDataProperty,i.parentDataProperty],[$r.default.rootData,$r.default.rootData]];i.opts.dynamicRef&&l.push([$r.default.dynamicAnchors,$r.default.dynamicAnchors]);let p=(0,ue._)`${d}, ${r.object(...l)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${p})`:(0,ue._)`${a}(${p})`}te.callValidateCode=Uz;var qz=(0,ue._)`new RegExp`;function Hz({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ue._)`${o.code==="new RegExp"?qz:(0,zz.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=Hz;function Gz(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ue._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:dp.Type.Num},s),e.if((0,ue.not)(s),a)})}}te.validateArray=Gz;function Zz(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,dp.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=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(i,(0,ue._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=Zz});var ib=R(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.validateKeywordUsage=qt.validSchemaType=qt.funcKeywordCode=qt.macroKeywordCode=void 0;var Ue=D(),ln=ir(),Bz=yt(),Vz=Os();function Wz(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=sb(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ue.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qt.macroKeywordCode=Wz;function Kz(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Yz(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=sb(n,o,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)m(),e.modifying&&ob(t),y(()=>t.error());else{let S=e.async?f():h();e.modifying&&ob(t),y(()=>Jz(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Ue._)`await `),w=>n.assign(l,!1).if((0,Ue._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Ue._)`${w}.errors`),()=>n.throw(w))),S}function h(){let S=(0,Ue._)`${d}.errors`;return n.assign(S,null),m(Ue.nil),S}function m(S=e.async?(0,Ue._)`await `:Ue.nil){let w=c.opts.passContext?ln.default.this:ln.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Ue._)`${S}${(0,Bz.callValidateCode)(t,d,w,b)}`,e.modifying)}function y(S){var w;n.if((0,Ue.not)((w=e.valid)!==null&&w!==void 0?w:l),S)}}qt.funcKeywordCode=Kz;function ob(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ue._)`${n.parentData}[${n.parentDataProperty}]`))}function Jz(t,e){let{gen:r}=t;r.if((0,Ue._)`Array.isArray(${e})`,()=>{r.assign(ln.default.vErrors,(0,Ue._)`${ln.default.vErrors} === null ? ${e} : ${ln.default.vErrors}.concat(${e})`).assign(ln.default.errors,(0,Ue._)`${ln.default.vErrors}.length`),(0,Vz.extendErrors)(t)},()=>t.error())}function Yz({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function sb(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,Ue.stringify)(r)})}function Xz(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")}qt.validSchemaType=Xz;function Qz({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}qt.validateKeywordUsage=Qz});var cb=R(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.extendSubschemaMode=Mr.extendSubschemaData=Mr.getSubschema=void 0;var Ht=D(),ab=H();function eN(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){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,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ab.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Mr.getSubschema=eN;function tN(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){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,p=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Ht.str)`${u}${(0,ab.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);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]}}Mr.extendSubschemaData=tN;function rN(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Mr.extendSubschemaMode=rN});var fp=R((B6,ub)=>{"use strict";ub.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,s;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(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var lb=R((V6,db)=>{"use strict";var Ir=db.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(){};Ja(e,n,o,t,"",t)};Ir.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ir.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ir.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ir.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 Ja(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Ir.arrayKeywords)for(var p=0;p<l.length;p++)Ja(t,e,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in Ir.propsKeywords){if(l&&typeof l=="object")for(var f in l)Ja(t,e,r,l[f],o+"/"+d+"/"+nN(f),s,o,d,n,f)}else(d in Ir.keywords||t.allKeys&&!(d in Ir.skipKeywords))&&Ja(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function nN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ns=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.getSchemaRefs=Qe.resolveUrl=Qe.normalizeId=Qe._getFullPath=Qe.getFullPath=Qe.inlineRef=void 0;var oN=H(),sN=fp(),iN=lb(),aN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function cN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!hp(t):e?pb(t)<=e:!1}Qe.inlineRef=cN;var uN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function hp(t){for(let e in t){if(uN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(hp)||typeof r=="object"&&hp(r))return!0}return!1}function pb(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!aN.has(r)&&(typeof t[r]=="object"&&(0,oN.eachItem)(t[r],n=>e+=pb(n)),e===1/0))return 1/0}return e}function fb(t,e="",r){r!==!1&&(e=ao(e));let n=t.parse(e);return hb(t,n)}Qe.getFullPath=fb;function hb(t,e){return t.serialize(e).split("#")[0]+"#"}Qe._getFullPath=hb;var dN=/#\/?$/;function ao(t){return t?t.replace(dN,""):""}Qe.normalizeId=ao;function lN(t,e,r){return r=ao(r),t.resolve(e,r)}Qe.resolveUrl=lN;var pN=/^[a-z_][-a-z0-9._]*$/i;function fN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ao(t[r]||e),s={"":o},i=fb(n,o,!1),a={},c=new Set;return iN(t,{allKeys:!0},(l,p,f,h)=>{if(h===void 0)return;let m=i+p,y=s[h];typeof l[r]=="string"&&(y=S.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=y;function S(b){let k=this.opts.uriResolver.resolve;if(b=ao(y?k(y,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!==ao(m)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!pN.test(b))throw new Error(`invalid anchor "${b}"`);S.call(this,`#${b}`)}}}),a;function u(l,p,f){if(p!==void 0&&!sN(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Qe.getSchemaRefs=fN});var js=R(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.getData=Or.KeywordCxt=Or.validateFunctionCode=void 0;var _b=Ww(),mb=zs(),gp=ip(),Ya=zs(),hN=tb(),Ls=ib(),mp=cb(),T=D(),z=ir(),mN=Ns(),ar=H(),Ds=Os();function gN(t){if(bb(t)&&(Rb(t),wb(t))){_N(t);return}Sb(t,()=>(0,_b.topBoolOrEmptySchema)(t))}Or.validateFunctionCode=gN;function Sb({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${gb(r,o)}`),vN(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${yN(o)}`,n.$async,()=>t.code(gb(r,o)).code(s))}function yN(t){return(0,T._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,T._)`, ${z.default.dynamicAnchors}={}`:T.nil}}={}`}function vN(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,T._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,T._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,T._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,T._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,T._)`""`),t.var(z.default.parentData,(0,T._)`undefined`),t.var(z.default.parentDataProperty,(0,T._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`{}`)})}function _N(t){let{schema:e,opts:r,gen:n}=t;Sb(t,()=>{r.$comment&&e.$comment&&Cb(t),PN(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&SN(t),Pb(t),kN(t)})}function SN(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function gb(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function wN(t,e){if(bb(t)&&(Rb(t),wb(t))){bN(t,e);return}(0,_b.boolOrEmptySchema)(t,e)}function wb({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 bb(t){return typeof t.schema!="boolean"}function bN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Cb(t),CN(t),xN(t);let s=n.const("_errs",z.default.errors);Pb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function Rb(t){(0,ar.checkUnknownRules)(t),RN(t)}function Pb(t,e){if(t.opts.jtd)return yb(t,[],!1,e);let r=(0,mb.getSchemaTypes)(t.schema),n=(0,mb.coerceAndCheckDataType)(t,r);yb(t,r,!n,e)}function RN(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ar.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function PN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ar.checkStrictMode)(t,"default is ignored in the schema root")}function CN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,mN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function xN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cb({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function kN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,T._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,z.default.vErrors),s.unevaluated&&EN(t),e.return((0,T._)`${z.default.errors} === 0`))}function EN({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function yb(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:d}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ar.schemaHasRulesButRef)(s,d))){o.block(()=>kb(t,"$ref",d.all.$ref.definition));return}c.jtd||TN(t,e),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,gp.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ya.checkDataType)(p.type,i,c.strictNumbers)),vb(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ya.reportTypeError)(t)),o.endIf()):vb(t,p),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function vb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,hN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,gp.shouldUseRule)(n,s)&&kb(t,s.keyword,s.definition,e.type)})}function TN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(AN(t,e),t.opts.allowUnionTypes||$N(t,e),MN(t,t.dataTypes))}function AN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{xb(t.dataTypes,r)||yp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),ON(t,e)}}function $N(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yp(t,"use allowUnionTypes to allow union type keyword")}function MN(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,gp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>IN(e,i))&&yp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function IN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function xb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function ON(t,e){let r=[];for(let n of t.dataTypes)xb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function yp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ar.checkStrictMode)(t,e,t.opts.strictTypes)}var Xa=class{constructor(e,r,n){if((0,Ls.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,ar.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",Eb(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ls.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,T.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,T.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,T._)`${r} !== undefined && (${(0,T.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?Ds.reportExtraError:Ds.reportError)(this,this.def.error,r)}$dataError(){(0,Ds.reportError)(this,this.def.$dataError||Ds.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ds.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=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Ya.checkDataTypes)(c,r,s.opts.strictNumbers,Ya.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,mp.getSubschema)(this.it,e);(0,mp.extendSubschemaData)(n,this.it,e),(0,mp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return wN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ar.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ar.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,T.Name)),!0}};Or.KeywordCxt=Xa;function kb(t,e,r,n){let o=new Xa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ls.funcKeywordCode)(o,r):"macro"in r?(0,Ls.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ls.funcKeywordCode)(o,r)}var zN=/^\/(?:[^~]|~0|~1)*$/,NN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Eb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!zN.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=NN.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(s=r[e-d],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,T._)`${s}${(0,T.getProperty)((0,ar.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Or.getData=Eb});var Qa=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var vp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_p.default=vp});var Fs=R(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var Sp=Ns(),wp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Sp.resolveUrl)(e,r,n),this.missingSchema=(0,Sp.normalizeId)((0,Sp.getFullPath)(e,this.missingRef))}};bp.default=wp});var tc=R(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.resolveSchema=vt.getCompilingSchema=vt.resolveRef=vt.compileSchema=vt.SchemaEnv=void 0;var Et=D(),DN=Qa(),pn=ir(),Tt=Ns(),Tb=H(),LN=js(),co=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,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};vt.SchemaEnv=co;function Pp(t){let e=Ab.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:DN.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:pn.default.data,parentData:pn.default.parentData,parentDataProperty:pn.default.parentDataProperty,dataNames:[pn.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,LN.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(pn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${pn.default.self}`,`${pn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;f.evaluated={props:h instanceof Et.Name?void 0:h,items:m instanceof Et.Name?void 0:m,dynamicProps:h instanceof Et.Name,dynamicItems:m instanceof Et.Name},f.source&&(f.source.evaluated=(0,Et.stringify)(f.evaluated))}return t.validate=f,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)}}vt.compileSchema=Pp;function jN(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=qN.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new co({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=FN.call(this,s)}vt.resolveRef=jN;function FN(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Pp.call(this,t)}function Ab(t){for(let e of this._compilations)if(UN(e,t))return e}vt.getCompilingSchema=Ab;function UN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function qN(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ec.call(this,t,e)}function ec(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Rp.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ec.call(this,t,i);return typeof a?.schema!="object"?void 0:Rp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Pp.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new co({schema:a,schemaId:c,root:t,baseId:o})}return Rp.call(this,r,i)}}vt.resolveSchema=ec;var HN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Rp(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,Tb.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!HN.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Tb.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ec.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new co({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var $b=R((Q6,GN)=>{GN.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 kp=R((eJ,Db)=>{"use strict";var ZN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ib=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),Cp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ob=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),BN=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function xp(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 VN=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Mb(t){return t.length=0,!0}function WN(t,e,r){if(t.length){let n=xp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function KN(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=WN;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Mb}else{o.push(u);continue}}return o.length&&(a===Mb?r.zone=o.join(""):i?n.push(o.join("")):n.push(xp(o))),r.address=n.join(""),r}function zb(t){if(JN(t,":")<2)return{host:t,isIPV6:!1};let e=KN(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 JN(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function YN(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 XN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},QN=/[@/?#:]/g,eD=/[@/?#]/g;function Nb(t,e){let r=e?eD:QN;return r.lastIndex=0,t.replace(r,n=>XN[n])}function tD(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(Cp(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Ob(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function rD(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(Cp(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Ob(s)?e+=s:e+="%"+o,r+=2;continue}}BN(t[r])?e+=t[r]:e+=escape(t[r])}return e}function nD(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(Cp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function oD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ib(r)){let n=zb(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Nb(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}Db.exports={nonSimpleDomain:VN,recomposeAuthority:oD,reescapeHostDelimiters:Nb,normalizePercentEncoding:tD,normalizePathEncoding:rD,escapePreservingEscapes:nD,removeDotSegments:YN,isIPv4:Ib,isUUID:ZN,normalizeIPv6:zb,stringArrayToHexStripped:xp}});var qb=R((tJ,Ub)=>{"use strict";var{isUUID:sD}=kp(),iD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,aD=["http","https","ws","wss","urn","urn:uuid"];function cD(t){return aD.indexOf(t)!==-1}function Ep(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 Lb(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function jb(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 uD(t){return t.secure=Ep(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function dD(t){if((t.port===(Ep(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 lD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(iD);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}`,s=Tp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function pD(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}`,s=Tp(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function fD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!sD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function hD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Fb={scheme:"http",domainHost:!0,parse:Lb,serialize:jb},mD={scheme:"https",domainHost:Fb.domainHost,parse:Lb,serialize:jb},rc={scheme:"ws",domainHost:!0,parse:uD,serialize:dD},gD={scheme:"wss",domainHost:rc.domainHost,parse:rc.parse,serialize:rc.serialize},yD={scheme:"urn",parse:lD,serialize:pD,skipNormalize:!0},vD={scheme:"urn:uuid",parse:fD,serialize:hD,skipNormalize:!0},nc={http:Fb,https:mD,ws:rc,wss:gD,urn:yD,"urn:uuid":vD};Object.setPrototypeOf(nc,null);function Tp(t){return t&&(nc[t]||nc[t.toLowerCase()])||void 0}Ub.exports={wsIsSecure:Ep,SCHEMES:nc,isValidSchemeName:cD,getSchemeHandler:Tp}});var Vb=R((rJ,ic)=>{"use strict";var{normalizeIPv6:_D,removeDotSegments:Us,recomposeAuthority:SD,normalizePercentEncoding:wD,normalizePathEncoding:bD,escapePreservingEscapes:RD,reescapeHostDelimiters:PD,isIPv4:CD,nonSimpleDomain:xD}=kp(),{SCHEMES:kD,getSchemeHandler:Gb}=qb();function ED(t,e){return typeof t=="string"?t=zD(t,e):typeof t=="object"&&(t=sc(fn(t,e),e)),t}function TD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=oc(t,n),{parsed:i,malformedAuthorityOrPort:a}=oc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Zb(o,i,n,!0);return n.skipEscape=!0,fn(c,n)}function Zb(t,e,r,n){let o={};return n||(t=sc(fn(t,r),r),e=sc(fn(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=Us(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=Us(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Us(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=Us(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 AD(t,e,r){let n=Hb(t,r),o=Hb(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function fn(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=[],s=Gb(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=wD(r.path):(r.path=RD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=SD(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Us(a)),i===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 $D=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,MD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ID=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function OD(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 oc(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,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(MD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(ID);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($D);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=OD(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(CD(n.host)===!1){let p=_D(n.host);n.host=p.host.toLowerCase(),s=p.isIPV6}else s=!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=Gb(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&xD(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=PD(unescape(n.host),s))),n.path&&(n.path=bD(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 sc(t,e){return oc(t,e).parsed}function zD(t,e){return Bb(t,e).normalized}function Bb(t,e){let{parsed:r,malformedAuthorityOrPort:n}=oc(t,e);return{normalized:n?t:fn(r,e),malformedAuthorityOrPort:n}}function Hb(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Bb(t,e);return n?void 0:r}if(typeof t=="object")return fn(t,e)}var Ap={SCHEMES:kD,normalize:ED,resolve:TD,resolveComponent:Zb,equal:AD,serialize:fn,parse:sc};ic.exports=Ap;ic.exports.default=Ap;ic.exports.fastUri=Ap});var Kb=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var Wb=Vb();Wb.code='require("ajv/dist/runtime/uri").default';$p.default=Wb});var nR=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var ND=js();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return ND.KeywordCxt}});var uo=D();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return uo._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return uo.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return uo.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return uo.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return uo.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return uo.CodeGen}});var DD=Qa(),eR=Fs(),LD=sp(),qs=tc(),jD=D(),Hs=Ns(),ac=zs(),Ip=H(),Jb=$b(),FD=Kb(),tR=(t,e)=>new RegExp(t,e);tR.code="new RegExp";var UD=["removeAdditional","useDefaults","coerceTypes"],qD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),HD={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."},GD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Yb=200;function ZD(t){var e,r,n,o,s,i,a,c,u,d,l,p,f,h,m,y,S,w,b,k,_,P,O,ge,ye;let Ze=t.strict,Mo=(e=t.code)===null||e===void 0?void 0:e.optimize,ki=Mo===!0||Mo===void 0?1:Mo||0,Ei=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:tR,lr=(o=t.uriResolver)!==null&&o!==void 0?o:FD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:Ze)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:Ze)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:ki,regExp:Ei}:{optimize:ki,regExp:Ei},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Yb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Yb,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(ge=t.unicodeRegExp)!==null&&ge!==void 0?ge:!0,int32range:(ye=t.int32range)!==null&&ye!==void 0?ye:!0,uriResolver:lr}}var Gs=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,...ZD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new jD.ValueScope({scope:{},prefixes:qD,es5:r,lines:n}),this.logger=YD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,LD.getRules)(),Xb.call(this,HD,e,"NOT SUPPORTED"),Xb.call(this,GD,e,"DEPRECATED","warn"),this._metaOpts=KD.call(this),e.formats&&VD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&WD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),BD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Jb;n==="id"&&(o={...Jb},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 s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof eR.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.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 s.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 i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Hs.normalizeId)(r||s),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 s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Qb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new qs.SchemaEnv({schema:{},schemaId:n});if(r=qs.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=Qb.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,Hs.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(QD.call(this,n,r),!r)return(0,Ip.eachItem)(n,s=>Mp.call(this,s)),this;tL.call(this,r);let o={...r,type:(0,ac.getJSONTypes)(r.type),schemaType:(0,ac.getJSONTypes)(r.schemaType)};return(0,Ip.eachItem)(n,o.type.length===0?s=>Mp.call(this,s,o):s=>o.type.forEach(i=>Mp.call(this,s,o,i))),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(s=>s.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,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,d=i[a];u&&d&&(i[a]=rR(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,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=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,Hs.normalizeId)(i||n);let u=Hs.getSchemaRefs.call(this,e,n);return c=new qs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!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):qs.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{qs.compileSchema.call(this,e)}finally{this.opts=r}}};Gs.ValidationError=DD.default;Gs.MissingRefError=eR.default;Me.default=Gs;function Xb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Qb(t){return t=(0,Hs.normalizeId)(t),this.schemas[t]||this.refs[t]}function BD(){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 VD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function WD(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 KD(){let t={...this.opts};for(let e of UD)delete t[e];return t}var JD={log(){},warn(){},error(){}};function YD(t){if(t===!1)return JD;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 XD=/^[a-z_$][a-z0-9_$:-]*$/i;function QD(t,e){let{RULES:r}=this;if((0,Ip.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XD.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 Mp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ac.getJSONTypes)(e.type),schemaType:(0,ac.getJSONTypes)(e.schemaType)}};e.before?eL.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function eL(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 tL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rR(e)),t.validateSchema=this.compile(e,!0))}var rL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rR(t){return{anyOf:[t,rL]}}});var oR=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var nL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Op.default=nL});var cR=R(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.callRef=hn.getValidate=void 0;var oL=Fs(),sR=yt(),et=D(),lo=ir(),iR=tc(),cc=H(),sL={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return l();let d=iR.resolveRef.call(c,u,o,r);if(d===void 0)throw new oL.default(n.opts.uriResolver,o,r);if(d instanceof iR.SchemaEnv)return p(d);return f(d);function l(){if(s===u)return uc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return uc(t,(0,et._)`${h}.validate`,u,u.$async)}function p(h){let m=aR(t,h);uc(t,m,h,h.$async)}function f(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,et.stringify)(h)}:{ref:h}),y=e.name("valid"),S=t.subschema({schema:h,dataTypes:[],schemaPath:et.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function aR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}hn.getValidate=aR;function uc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?lo.default.this:et.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,et._)`await ${(0,sR.callValidateCode)(t,e,u)}`),f(e),i||o.assign(h,!0)},m=>{o.if((0,et._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,sR.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let m=(0,et._)`${h}.errors`;o.assign(lo.default.vErrors,(0,et._)`${lo.default.vErrors} === null ? ${m} : ${lo.default.vErrors}.concat(${m})`),o.assign(lo.default.errors,(0,et._)`${lo.default.vErrors}.length`)}function f(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=cc.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,et._)`${h}.evaluated.props`);s.props=cc.mergeEvaluated.props(o,S,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=cc.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,et._)`${h}.evaluated.items`);s.items=cc.mergeEvaluated.items(o,S,s.items,et.Name)}}}hn.callRef=uc;hn.default=sL});var uR=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var iL=oR(),aL=cR(),cL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iL.default,aL.default];zp.default=cL});var dR=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var dc=D(),zr=dc.operators,lc={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},uL={message:({keyword:t,schemaCode:e})=>(0,dc.str)`must be ${lc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,dc._)`{comparison: ${lc[t].okStr}, limit: ${e}}`},dL={keyword:Object.keys(lc),type:"number",schemaType:"number",$data:!0,error:uL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,dc._)`${r} ${lc[e].fail} ${n} || isNaN(${r})`)}};Np.default=dL});var lR=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var Zs=D(),lL={message:({schemaCode:t})=>(0,Zs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Zs._)`{multipleOf: ${t}}`},pL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Zs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Zs._)`${i} !== parseInt(${i})`;t.fail$data((0,Zs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Dp.default=pL});var fR=R(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});function pR(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}Lp.default=pR;pR.code='require("ajv/dist/runtime/ucs2length").default'});var hR=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var mn=D(),fL=H(),hL=fR(),mL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,mn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,mn._)`{limit: ${t}}`},gL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?mn.operators.GT:mn.operators.LT,i=o.opts.unicode===!1?(0,mn._)`${r}.length`:(0,mn._)`${(0,fL.useFunc)(t.gen,hL.default)}(${r})`;t.fail$data((0,mn._)`${i} ${s} ${n}`)}};jp.default=gL});var mR=R(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var yL=yt(),vL=H(),po=D(),_L={message:({schemaCode:t})=>(0,po.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,po._)`{pattern: ${t}}`},SL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_L,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,po._)`new RegExp`:(0,vL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,po._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,po._)`!${d}`)}else{let c=(0,yL.usePattern)(t,o);t.fail$data((0,po._)`!${c}.test(${r})`)}}};Fp.default=SL});var gR=R(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});var Bs=D(),wL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Bs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Bs._)`{limit: ${t}}`},bL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Bs.operators.GT:Bs.operators.LT;t.fail$data((0,Bs._)`Object.keys(${r}).length ${o} ${n}`)}};Up.default=bL});var yR=R(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Vs=yt(),Ws=D(),RL=H(),PL={message:({params:{missingProperty:t}})=>(0,Ws.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ws._)`{missingProperty: ${t}}`},CL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:PL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(f?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,RL.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ws.nil,l);else for(let f of r)(0,Vs.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Vs.checkMissingProp)(t,r,f)),(0,Vs.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Vs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,Vs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ws.not)(h),()=>{t.error(),e.break()})},Ws.nil)}}};qp.default=CL});var vR=R(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var Ks=D(),xL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ks.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ks._)`{limit: ${t}}`},kL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ks.operators.GT:Ks.operators.LT;t.fail$data((0,Ks._)`${r}.length ${o} ${n}`)}};Hp.default=kL});var pc=R(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var _R=fp();_R.code='require("ajv/dist/runtime/equal").default';Gp.default=_R});var SR=R(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var Zp=zs(),Ie=D(),EL=H(),TL=pc(),AL={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},$L={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:AL,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Zp.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Ie._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Ie._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Ie._)`${h} > 1`,()=>(l()?p:f)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,m){let y=e.name("item"),S=(0,Zp.checkDataTypes)(u,y,a.opts.strictNumbers,Zp.DataType.Wrong),w=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${h}--;`,()=>{e.let(y,(0,Ie._)`${r}[${h}]`),e.if(S,(0,Ie._)`continue`),u.length>1&&e.if((0,Ie._)`typeof ${y} == "string"`,(0,Ie._)`${y} += "_"`),e.if((0,Ie._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Ie._)`${w}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ie._)`${w}[${y}] = ${h}`)})}function f(h,m){let y=(0,EL.useFunc)(e,TL.default),S=e.name("outer");e.label(S).for((0,Ie._)`;${h}--;`,()=>e.for((0,Ie._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Ie._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};Bp.default=$L});var wR=R(Wp=>{"use strict";Object.defineProperty(Wp,"__esModule",{value:!0});var Vp=D(),ML=H(),IL=pc(),OL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vp._)`{allowedValue: ${t}}`},zL={keyword:"const",$data:!0,error:OL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Vp._)`!${(0,ML.useFunc)(e,IL.default)}(${r}, ${o})`):t.fail((0,Vp._)`${s} !== ${r}`)}};Wp.default=zL});var bR=R(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var Js=D(),NL=H(),DL=pc(),LL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Js._)`{allowedValues: ${t}}`},jL={keyword:"enum",schemaType:"array",$data:!0,error:LL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,NL.useFunc)(e,DL.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 f=e.const("vSchema",s);d=(0,Js.or)(...o.map((h,m)=>p(f,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,Js._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,h){let m=o[h];return typeof m=="object"&&m!==null?(0,Js._)`${u()}(${r}, ${f}[${h}])`:(0,Js._)`${r} === ${m}`}}};Kp.default=jL});var RR=R(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var FL=dR(),UL=lR(),qL=hR(),HL=mR(),GL=gR(),ZL=yR(),BL=vR(),VL=SR(),WL=wR(),KL=bR(),JL=[FL.default,UL.default,qL.default,HL.default,GL.default,ZL.default,BL.default,VL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WL.default,KL.default];Jp.default=JL});var Xp=R(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.validateAdditionalItems=void 0;var gn=D(),Yp=H(),YL={message:({params:{len:t}})=>(0,gn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,gn._)`{limit: ${t}}`},XL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:YL,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Yp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}PR(t,n)}};function PR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,gn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,gn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Yp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,gn._)`${a} <= ${e.length}`);r.if((0,gn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:Yp.Type.Num},u),i.allErrors||r.if((0,gn.not)(u),()=>r.break())})}}Ys.validateAdditionalItems=PR;Ys.default=XL});var Qp=R(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.validateTuple=void 0;var CR=D(),fc=H(),QL=yt(),ej={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return xR(t,"additionalItems",e);r.items=!0,!(0,fc.alwaysValidSchema)(r,e)&&t.ok((0,QL.validateArray)(t))}};function xR(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=fc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,CR._)`${s}.length`);r.forEach((l,p)=>{(0,fc.alwaysValidSchema)(a,l)||(n.if((0,CR._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(p.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,fc.checkStrictMode)(a,y,p.strictTuples)}}}Xs.validateTuple=xR;Xs.default=ej});var kR=R(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var tj=Qp(),rj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,tj.validateTuple)(t,"items")};ef.default=rj});var TR=R(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var ER=D(),nj=H(),oj=yt(),sj=Xp(),ij={message:({params:{len:t}})=>(0,ER.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ER._)`{limit: ${t}}`},aj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:ij,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,nj.alwaysValidSchema)(n,e)&&(o?(0,sj.validateAdditionalItems)(t,o):t.ok((0,oj.validateArray)(t)))}};tf.default=aj});var AR=R(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var _t=D(),hc=H(),cj={message:({params:{min:t,max:e}})=>e===void 0?(0,_t.str)`must contain at least ${t} valid item(s)`:(0,_t.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,_t._)`{minContains: ${t}}`:(0,_t._)`{minContains: ${t}, maxContains: ${e}}`},uj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,_t._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,hc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,hc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,hc.alwaysValidSchema)(s,r)){let m=(0,_t._)`${d} >= ${i}`;a!==void 0&&(m=(0,_t._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,_t._)`${o}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>t.reset());function p(){let m=e.name("_valid"),y=e.let("count",0);f(m,()=>e.if(m,()=>h(y)))}function f(m,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:hc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,_t._)`${m}++`),a===void 0?e.if((0,_t._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,_t._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,_t._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};rf.default=uj});var IR=R(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateSchemaDeps=Gt.validatePropertyDeps=Gt.error=void 0;var nf=D(),dj=H(),Qs=yt();Gt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,nf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,nf._)`{property: ${t},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${e},
8
- deps: ${r}}`};var aj={keyword:"dependencies",type:"object",schemaType:"object",error:Gt.error,code(t){let[e,r]=cj(t);kR(t,e),ER(t,r)}};function cj({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 kR(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ys.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ys.checkReportMissingProp)(t,u)}):(r.if((0,ef._)`${c} && (${(0,Ys.checkMissingProp)(t,a,s)})`),(0,Ys.reportMissingProp)(t,s),r.else())}}Gt.validatePropertyDeps=kR;function ER(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,ij.alwaysValidSchema)(s,e[a])||(r.if((0,Ys.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Gt.validateSchemaDeps=ER;Gt.default=aj});var $R=R(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var AR=D(),uj=H(),dj={message:"property name must be valid",params:({params:t})=>(0,AR._)`{propertyName: ${t.propertyName}}`},lj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,uj.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,AR.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tf.default=lj});var nf=R(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var fc=yt(),At=D(),pj=ir(),hc=H(),fj={message:"must NOT have additional properties",params:({params:t})=>(0,At._)`{additionalProperty: ${t.additionalProperty}}`},hj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:fj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,hc.alwaysValidSchema)(i,r))return;let u=(0,fc.allSchemaProperties)(n.properties),d=(0,fc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,At._)`${s} === ${pj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let w=(0,hc.schemaRefOrVal)(i,n.properties,"properties");S=(0,fc.isOwnProperty)(e,w,y)}else u.length?S=(0,At.or)(...u.map(w=>(0,At._)`${y} === ${w}`)):S=At.nil;return d.length&&(S=(0,At.or)(S,...d.map(w=>(0,At._)`${(0,fc.usePattern)(t,w)}.test(${y})`))),(0,At.not)(S)}function f(y){e.code((0,At._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,hc.alwaysValidSchema)(i,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,At.not)(S),()=>{t.reset(),f(y)})):(m(y,S),a||e.if((0,At.not)(S),()=>e.break()))}}function m(y,S,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:hc.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,S)}}};rf.default=hj});var OR=R(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var mj=Ds(),MR=yt(),of=H(),IR=nf(),gj={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&IR.default.code(new mj.KeywordCxt(s,IR.default,"additionalProperties"));let i=(0,MR.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=of.mergeEvaluated.props(e,(0,of.toHash)(i),s.props));let a=i.filter(l=>!(0,of.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,MR.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};sf.default=gj});var LR=R(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var zR=yt(),mc=D(),NR=H(),DR=H(),yj={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,zR.allSchemaProperties)(r),c=a.filter(m=>(0,NR.alwaysValidSchema)(s,r[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof mc.Name)&&(s.props=(0,DR.evaluatedPropsToName)(e,s.props));let{props:l}=s;p();function p(){for(let m of a)u&&f(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function f(m){for(let y in u)new RegExp(m).test(y)&&(0,NR.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,mc._)`${(0,zR.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:DR.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,mc._)`${l}[${y}]`,!0):!S&&!s.allErrors&&e.if((0,mc.not)(d),()=>e.break())})})}}};af.default=yj});var jR=R(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var vj=H(),_j={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,vj.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"}};cf.default=_j});var FR=R(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var Sj=yt(),wj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sj.validateUnion,error:{message:"must match a schema in anyOf"}};uf.default=wj});var UR=R(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var gc=D(),bj=H(),Rj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gc._)`{passingSchemas: ${t.passing}}`},Pj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Rj,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 s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let p;(0,bj.alwaysValidSchema)(o,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,gc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,gc.Name)})})}}};df.default=Pj});var qR=R(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var Cj=H(),xj={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((s,i)=>{if((0,Cj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};lf.default=xj});var ZR=R(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var yc=D(),GR=H(),kj={message:({params:t})=>(0,yc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yc._)`{failingKeyword: ${t.ifClause}}`},Ej={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:kj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,GR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=HR(n,"then"),s=HR(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){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,yc.not)(a),u("else"));t.pass(i,()=>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 p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,yc._)`${d}`):t.setParams({ifClause:d})}}}};function HR(t,e){let r=t.schema[e];return r!==void 0&&!(0,GR.alwaysValidSchema)(t,r)}pf.default=Ej});var BR=R(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var Tj=H(),Aj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Tj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ff.default=Aj});var VR=R(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var $j=Kp(),Mj=RR(),Ij=Jp(),Oj=CR(),zj=xR(),Nj=TR(),Dj=$R(),Lj=nf(),jj=OR(),Fj=LR(),Uj=jR(),qj=FR(),Hj=UR(),Gj=qR(),Zj=ZR(),Bj=BR();function Vj(t=!1){let e=[Uj.default,qj.default,Hj.default,Gj.default,Zj.default,Bj.default,Dj.default,Lj.default,Nj.default,jj.default,Fj.default];return t?e.push(Mj.default,Oj.default):e.push($j.default,Ij.default),e.push(zj.default),e}hf.default=Vj});var WR=R(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var _e=D(),Wj={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},Kj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Wj,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(S,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(S,m)),t.fail$data((0,_e.or)(w(),b()));function w(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${S}`}function b(){let k=d.$async?(0,_e._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,_e._)`${S}(${n})`,_=(0,_e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,_e._)`${S} && ${S} !== true && ${y} === ${e} && !${_}`}}function f(){let h=l.formats[s];if(!h){w();return}if(h===!0)return;let[m,y,S]=b(h);m===e&&t.pass(k());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(_){let P=_ instanceof RegExp?(0,_e.regexpCode)(_):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:_,code:P});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,_e._)`${O}.validate`]:["string",_,O]}function k(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${S}(${n})`}return typeof y=="function"?(0,_e._)`${S}(${n})`:(0,_e._)`${S}.test(${n})`}}}};mf.default=Kj});var KR=R(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Jj=WR(),Yj=[Jj.default];gf.default=Yj});var JR=R(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.contentVocabulary=lo.metadataVocabulary=void 0;lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var XR=R(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var Xj=sR(),Qj=_R(),e1=VR(),t1=KR(),YR=JR(),r1=[Xj.default,Qj.default,(0,e1.default)(),t1.default,YR.metadataVocabulary,YR.contentVocabulary];yf.default=r1});var eP=R(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.DiscrError=void 0;var QR;(function(t){t.Tag="tag",t.Mapping="mapping"})(QR||(vc.DiscrError=QR={}))});var rP=R(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var po=D(),vf=eP(),tP=Qa(),n1=Ls(),o1=H(),s1={message:({params:{discrError:t,tagName:e}})=>t===vf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,po._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},i1={keyword:"discriminator",type:"object",schemaType:"object",error:s1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.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(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,po._)`${r}${(0,po.getProperty)(a)}`);e.if((0,po._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:vf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,po._)`${u} === ${h}`),e.assign(c,l(f[h]));e.else(),t.error(!1,{discrError:vf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(m,po.Name),h}function p(){var f;let h={},m=S(o),y=!0;for(let k=0;k<i.length;k++){let _=i[k];if(_?.$ref&&!(0,o1.schemaHasRulesButRef)(_,s.self.RULES)){let O=_.$ref;if(_=tP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),_ instanceof tP.SchemaEnv&&(_=_.schema),_===void 0)throw new n1.default(s.opts.uriResolver,s.baseId,O)}let P=(f=_?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||S(_)),w(P,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:k}){return Array.isArray(k)&&k.includes(a)}function w(k,_){if(k.const)b(k.const,_);else if(k.enum)for(let P of k.enum)b(P,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(k,_){if(typeof k!="string"||k in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[k]=_}}}};_f.default=i1});var nP=R((jJ,a1)=>{a1.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 wf=R((de,Sf)=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.MissingRefError=de.ValidationError=de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=de.Ajv=void 0;var c1=Qb(),u1=XR(),d1=rP(),oP=nP(),l1=["/properties"],_c="http://json-schema.org/draft-07/schema",fo=class extends c1.default{_addVocabularies(){super._addVocabularies(),u1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(d1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(oP,l1):oP;this.addMetaSchema(e,_c,!1),this.refs["http://json-schema.org/schema"]=_c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_c)?_c:void 0)}};de.Ajv=fo;Sf.exports=de=fo;Sf.exports.Ajv=fo;Object.defineProperty(de,"__esModule",{value:!0});de.default=fo;var p1=Ds();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return p1.KeywordCxt}});var ho=D();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return ho._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return ho.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return ho.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return ho.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return ho.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return ho.CodeGen}});var f1=Ya();Object.defineProperty(de,"ValidationError",{enumerable:!0,get:function(){return f1.default}});var h1=Ls();Object.defineProperty(de,"MissingRefError",{enumerable:!0,get:function(){return h1.default}})});var pP=R(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.formatNames=Bt.fastFormats=Bt.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Bt.fullFormats={date:Zt(cP,Cf),time:Zt(Rf(!0),xf),"date-time":Zt(sP(!0),dP),"iso-time":Zt(Rf(),uP),"iso-date-time":Zt(sP(),lP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:S1,"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:k1,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:w1,int32:{type:"number",validate:P1},int64:{type:"number",validate:C1},float:{type:"number",validate:aP},double:{type:"number",validate:aP},password:!0,binary:!0};Bt.fastFormats={...Bt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Cf),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xf),"date-time":Zt(/^\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,dP),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,uP),"iso-date-time":Zt(/^\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,lP),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};Bt.formatNames=Object.keys(Bt.fullFormats);function m1(t){return t%4===0&&(t%100!==0||t%400===0)}var g1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function cP(t){let e=g1.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&&m1(r)?29:y1[n])}function Cf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var bf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Rf(t){return function(r){let n=bf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+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&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function xf(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 uP(t,e){if(!(t&&e))return;let r=bf.exec(t),n=bf.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 Pf=/t|\s/i;function sP(t){let e=Rf(t);return function(n){let o=n.split(Pf);return o.length===2&&cP(o[0])&&e(o[1])}}function dP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function lP(t,e){if(!(t&&e))return;let[r,n]=t.split(Pf),[o,s]=e.split(Pf),i=Cf(r,o);if(i!==void 0)return i||xf(n,s)}var v1=/\/|:/,_1=/^(?:[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 S1(t){return v1.test(t)&&_1.test(t)}var iP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function w1(t){return iP.lastIndex=0,iP.test(t)}var b1=-(2**31),R1=2**31-1;function P1(t){return Number.isInteger(t)&&t<=R1&&t>=b1}function C1(t){return Number.isInteger(t)}function aP(){return!0}var x1=/[^\\]\\Z/;function k1(t){if(x1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var fP=R(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.formatLimitDefinition=void 0;var E1=wf(),$t=D(),zr=$t.operators,Sc={formatMaximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},formatMinimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},formatExclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},formatExclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},T1={message:({keyword:t,schemaCode:e})=>(0,$t.str)`should be ${Sc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$t._)`{comparison: ${Sc[t].okStr}, limit: ${e}}`};mo.formatLimitDefinition={keyword:Object.keys(Sc),type:"string",schemaType:"string",$data:!0,error:T1,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new E1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,$t._)`${p}[${c.schemaCode}]`);t.fail$data((0,$t.or)((0,$t._)`typeof ${f} != "object"`,(0,$t._)`${f} instanceof RegExp`,(0,$t._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(p)}`:void 0});t.fail$data(l(h))}function l(p){return(0,$t._)`${p}.compare(${r}, ${n}) ${Sc[o].fail} 0`}},dependencies:["format"]};var A1=t=>(t.addKeyword(mo.formatLimitDefinition),t);mo.default=A1});var yP=R((Xs,gP)=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});var go=pP(),$1=fP(),kf=D(),hP=new kf.Name("fullFormats"),M1=new kf.Name("fastFormats"),Ef=(t,e={keywords:!0})=>{if(Array.isArray(e))return mP(t,e,go.fullFormats,hP),t;let[r,n]=e.mode==="fast"?[go.fastFormats,M1]:[go.fullFormats,hP],o=e.formats||go.formatNames;return mP(t,o,r,n),e.keywords&&(0,$1.default)(t),t};Ef.get=(t,e="full")=>{let n=(e==="fast"?go.fastFormats:go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function mP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,kf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}gP.exports=Xs=Ef;Object.defineProperty(Xs,"__esModule",{value:!0});Xs.default=Ef});var BP=R((w5,ZP)=>{ZP.exports=GP;GP.sync=dF;var qP=pr("fs");function uF(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 HP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:uF(e,r)}function GP(t,e,r){qP.stat(t,function(n,o){r(n,n?!1:HP(o,t,e))})}function dF(t,e){return HP(qP.statSync(t),t,e)}});var YP=R((b5,JP)=>{JP.exports=WP;WP.sync=lF;var VP=pr("fs");function WP(t,e,r){VP.stat(t,function(n,o){r(n,n?!1:KP(o,e))})}function lF(t,e){return KP(VP.statSync(t),e)}function KP(t,e){return t.isFile()&&pF(t,e)}function pF(t,e){var r=t.mode,n=t.uid,o=t.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),i=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===i||r&a&&n===s||r&d&&s===0;return l}});var QP=R((P5,XP)=>{var R5=pr("fs"),$c;process.platform==="win32"||global.TESTING_WINDOWS?$c=BP():$c=YP();XP.exports=Vf;Vf.sync=fF;function Vf(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){Vf(t,e||{},function(s,i){s?o(s):n(i)})})}$c(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function fF(t,e){try{return $c.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var iC=R((C5,sC)=>{var Po=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",eC=pr("path"),hF=Po?";":":",tC=QP(),rC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),nC=(t,e)=>{let r=e.colon||hF,n=t.match(/\//)||Po&&t.match(/\\/)?[""]:[...Po?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Po?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Po?o.split(r):[""];return Po&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},oC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=nC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(rC(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=eC.join(f,t),m=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((p,f)=>{if(l===o.length)return p(a(d+1));let h=o[l];tC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return p(u+h);return p(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},mF=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=nC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=eC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let p=d+n[l];try{if(tC.sync(p,{pathExt:o}))if(e.all)s.push(p);else return p}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw rC(t)};sC.exports=oC;oC.sync=mF});var cC=R((x5,Wf)=>{"use strict";var aC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Wf.exports=aC;Wf.exports.default=aC});var pC=R((k5,lC)=>{"use strict";var uC=pr("path"),gF=iC(),yF=cC();function dC(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,s=o&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=gF.sync(t.command,{path:r[yF({env:r})],pathExt:e?uC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=uC.resolve(o?t.options.cwd:"",i)),i}function vF(t){return dC(t)||dC(t,!0)}lC.exports=vF});var fC=R((E5,Jf)=>{"use strict";var Kf=/([()\][%!^"`<>&|;, *?])/g;function _F(t){return t=t.replace(Kf,"^$1"),t}function SF(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Kf,"^$1"),e&&(t=t.replace(Kf,"^$1")),t}Jf.exports.command=_F;Jf.exports.argument=SF});var mC=R((T5,hC)=>{"use strict";hC.exports=/^#!(.*)/});var yC=R((A5,gC)=>{"use strict";var wF=mC();gC.exports=(t="")=>{let e=t.match(wF);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var _C=R(($5,vC)=>{"use strict";var Yf=pr("fs"),bF=yC();function RF(t){let r=Buffer.alloc(150),n;try{n=Yf.openSync(t,"r"),Yf.readSync(n,r,0,150,0),Yf.closeSync(n)}catch{}return bF(r.toString())}vC.exports=RF});var RC=R((M5,bC)=>{"use strict";var PF=pr("path"),SC=pC(),wC=fC(),CF=_C(),xF=process.platform==="win32",kF=/\.(?:com|exe)$/i,EF=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function TF(t){t.file=SC(t);let e=t.file&&CF(t.file);return e?(t.args.unshift(t.file),t.command=e,SC(t)):t.file}function AF(t){if(!xF)return t;let e=TF(t),r=!kF.test(e);if(t.options.forceShell||r){let n=EF.test(e);t.command=PF.normalize(t.command),t.command=wC.command(t.command),t.args=t.args.map(s=>wC.argument(s,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 $F(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:AF(n)}bC.exports=$F});var xC=R((I5,CC)=>{"use strict";var Xf=process.platform==="win32";function Qf(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 MF(t,e){if(!Xf)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=PC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function PC(t,e){return Xf&&t===1&&!e.file?Qf(e.original,"spawn"):null}function IF(t,e){return Xf&&t===1&&!e.file?Qf(e.original,"spawnSync"):null}CC.exports={hookChildProcess:MF,verifyENOENT:PC,verifyENOENTSync:IF,notFoundError:Qf}});var TC=R((O5,Co)=>{"use strict";var kC=pr("child_process"),eh=RC(),th=xC();function EC(t,e,r){let n=eh(t,e,r),o=kC.spawn(n.command,n.args,n.options);return th.hookChildProcess(o,n),o}function OF(t,e,r){let n=eh(t,e,r),o=kC.spawnSync(n.command,n.args,n.options);return o.error=o.error||th.verifyENOENTSync(o.status,n),o}Co.exports=EC;Co.exports.spawn=EC;Co.exports.sync=OF;Co.exports._parse=eh;Co.exports._enoent=th});var zC=R(nh=>{"use strict";var MC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,jF=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,IC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,FF=/\\([\u000b\u0020-\u00ff])/g,UF=/([\\"])/g,OC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;nh.format=qF;nh.parse=HF;function qF(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!OC.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!IC.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+ZF(e[o])}return n}function HF(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?GF(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(!OC.test(n))throw new TypeError("invalid media type");var o=new BF(n.toLowerCase());if(r!==-1){var s,i,a;for(MC.lastIndex=r;i=MC.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(FF,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function GF(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 ZF(t){var e=String(t);if(IC.test(e))return e;if(e.length>0&&!jF.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(UF,"\\$1")+'"'}function BF(t){this.parameters=Object.create(null),this.type=t}});import{logger as rZ}from"@hermes/logger";import{logger as lq}from"@hermes/logger";var cE="mcp-auth";function ze(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(cE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as UU}from"@augmentcode/auggie-v2";import{logger as qU}from"@hermes/logger";import{logger as AE}from"@hermes/logger";import{logger as dE}from"@hermes/logger";function uE(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 fr(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":uE(t,e,r)?"plugin":"local"}function lE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var qh=dE.child({prefix:"pi-mcp"}),pE="augment:mcp-status-report";function Jt(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 s=t.credentialRevisions?.get(e);return{serverGeneration:t.serverGenerations?.get(e)??0,mcpConfigId:r??n?.config.id,credentialRevision:s?.revision,credentialRevisionDomain:s?.domain}}function $o(t,e,r,n){let o=Jt(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 st(t,e,r){if(r){let o=Jt(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 fE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=Jt(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 Ei=3e4;function hE(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>=Ei?"failed":void 0}default:return}}var Hh="authentication required",mE="Authentication refresh is pending in the backend; retry shortly.",gE="timed out connecting after 30s",yE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",vE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",_E="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).";function SE(t,e){let r=new Set;for(let i of t.servers.values())i.config.id!==void 0&&r.add(i.config.id);let n=new Set(e.map(i=>i.mcpConfigId).filter(i=>i!==void 0)),o=new Set(e.map(i=>i.name)),s=i=>t.registryConfigNamesById.get(i)??i;for(let i of t.failedAddConfigIds){if(r.has(i)||n.has(i))continue;let a=s(i);n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(i)?vE:yE,mcpConfigId:i,dynamicallyAdded:!0})}for(let i of t.selectedRegistryConfigIds??[]){if(r.has(i)||n.has(i)||t.sessionRemovedConfigIds.has(i))continue;let a=s(i);o.has(a)||(n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:_E,mcpConfigId:i}))}}function wE(t,e){return e!==void 0?e.isAuthError?Hh:e.error:t.status==="initializing"?gE:t.lastError??(t.status==="auth_required"?Hh:void 0)}function bE(t,e){let r=hE(t);if(r===void 0)return;let n=fE(e,t.name),o=r==="connected"?lE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:fr(t,e.pluginServerHosts,e.hostLeases),status:r,transport:t.config.type,tools:t.tools.map(u=>u.name)},i=t.config.id;i!==void 0&&(s.mcpConfigId=i,e.dynamicallyAddedConfigIds.has(i)&&(s.dynamicallyAdded=!0));let a=e.statusFailureCategories?.get(t.name),c=typeof a=="object"?{revision:a.credentialRevision,domain:a.credentialRevisionDomain}:e.credentialRevisions?.get(t.name);return c?.revision!==void 0&&c.domain!==void 0&&(s.credentialRevision=c.revision,s.credentialRevisionDomain=c.domain),r==="failed"&&(s.errorMessage=n==="auth_refresh_needed"?mE:wE(t,o),s.failureCategory=n??(t.status==="auth_required"||o?.isAuthError===!0?"auth_terminal":"transport_transient"),typeof a=="object"&&(s.serverGeneration=a.serverGeneration)),s}function RE(t){let e=[];for(let r of t.servers.values()){let n=bE(r,t);n!==void 0&&e.push(n)}return SE(t,e),e}function J(t,e){try{let r=RE(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(pE,o),qh.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){qh.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Ti={local:4,registry:3,plugin:2,vfs:1};function zt(t){return t.hostLeases??=new Map,t.hostLeases}function PE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Mo(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Io(t,e){return t.kind===e.kind&&t.identity===e.identity}function Gh(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 au(t,e){let r=PE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Ai(t,e,r){if(r.kind==="registry"){Mo(t).set(e,{kind:"domain",domain:r.identity});return}Mo(t).set(e,{kind:"blocked"})}function cu(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 En(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 Q(t,e,r){let n=zt(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?En(i,s):{kind:s??"local",identity:e},c={owner:a,revision:au(t,e),host:r};return n.set(e,c),Ai(t,e,a),c}function Zh(t){let{state:e,name:r,host:n}=t,o=zt(e),s=o.get(r);if(!s||s.host!==n||s.owner.kind!=="local"||e.servers.get(r)!==n)return;let i={owner:{kind:"plugin",identity:n.config.id??r},revision:au(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),Ai(e,r,i.owner),i}function Oo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=zt(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Ti[n.kind]>Ti[a.owner.kind],p=Ti[n.kind]===Ti[a.owner.kind],f=o===a.revision&&(s===void 0||s===a.host);if(!(l||p&&f))return}let c=a?.host,u=a?Gh(a):void 0;cu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:au(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),Ai(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function uu(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 we(t){let{state:e,name:r,retirement:n,result:o}=t;if(n.settled)return!1;n.settled=!0,n.result=o;let i=zt(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Mo(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function $i(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e).get(r);return!i||i.revision!==o||!Io(i.owner,n)||i.host!==void 0||i.retirement!==void 0?!1:(i.host=s,e.servers.set(r,s),n.kind==="plugin"?(e.pluginServerNames.add(r),e.pluginServerHosts.set(r,s)):(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),!0)}function bt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e).get(r);if(!i||i.revision!==o||!Io(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=Gh(i);if(a)return cu(e,r,s),i.host=void 0,i.retirement=a,a}function Bh(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=zt(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Io(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Io(i.owner,n)||i.revision!==o.incumbent.revision?(Ai(e,r,i.owner),!0):(s.delete(r),Mo(e).set(r,{kind:"blocked"}),!0))}function be(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e),a=i.get(r);return!a||a.revision!==o||!Io(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(cu(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),Mo(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return zt(t).get(e)}function Vh(t,e,r){return zt(t).get(e)?.host===r}function zo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function hr(t){if(!(t.type!=="http"&&t.type!=="sse"||t.auth!=="oauth"))return{id:t.id,name:t.name,type:t.type,url:t.url,auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Be(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:t.url===e.url&&t.auth===e.auth}function du(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function CE(t){let{state:e,name:r,expectedRegistryConfigId:n,expectedConfig:o,currentConfig:s}=t;if(o)return o;let i=n?e.registryCredentialConfigsById?.get(n):void 0;if(i?.name===r)return i;let a=e.registryCredentialConfigs?.get(r);if(a?.id===n)return a;if(s?.id===n)return s}function xE(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!Be(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function Wh(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!du(e,r):n!==void 0&&e!==n}function Kh(t,e,r){return r&&e!==void 0&&t!==void 0&&du(t,e)}function kE(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!du(s,n))}function Jh(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(xE({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||Wh({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&Wh({identity:i.domain,...l})?!0:kE({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function EE(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return hr(r);if(n!==void 0)return{id:n,name:e}}function TE(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!hr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function Yh(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=CE({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,p=Jh({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),f=Kh(s,u,d),h=Kh(i,u,d),m=!p,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,w=p&&!(m||f||h||y);if(o==="durable"){let P=EE({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:w})}let b=Jh({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),k=m&&!b,_=!1;return t.equalRevisionRebindDomains?.delete(e),(k||f)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),_=!0),(k||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),_=!0),k&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),TE({state:t,name:e,mode:o,stillOwnsNameScopedRevision:k,retiredConfig:c}),_&&(zo(t,e),st(t,e),t.authRefreshNeededReportKeys?.delete(e)),k}function ct(t,e,r,n){return Yh(t,e,r,n,"durable")}function No(t,e,r,n){return Yh(t,e,r,n,"session")}function mr(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 Xh="augment:mcp-oauth-credentials",Qh=300*1e3,$E=256,em=AE.child({prefix:"pi-mcp"}),Rt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function We(t){return`user:${t}`}function Fr(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)/,"")},s=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(s?.revision!==o.revision||s?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let i=e.oauthCredentialRevisions.get(o.domain);(i===void 0||mr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function ut(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!=="user"&&r!=="tenant"?t:We(t.slice(e+1))}function ME(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function IE(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 OE(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function zE(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&ME(t.credentialRevisions.get(e),r.credentialRevision)&&OE(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function NE(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 DE(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??"")||!Be(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Ur(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 jr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function tm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=Qh&&jr(t,n)}function LE(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&jr(t,e)}function rm(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Ur(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();tm(e,a);let c=ut(n.domain),u=i.get(c),d=u?.credential.credential_revision??u?.credential.credentialRevision;if(typeof d=="string"&&mr(n.revision,d)<=0)return;!u&&i.size>=$E&&LE(e),jr(e,c);let l={credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(c,l),l.expiryTimer=setTimeout(()=>{i.get(c)===l&&jr(e,c)},Qh),l.expiryTimer.unref?.(),em.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function jE(t,e){Ur(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function Ve(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:s=!1}=t;Ur(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||jr(e,r)}}function Mi(t){let{state:e,domain:r,forceNew:n=!1}=t;Ur(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let s=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Ve({state:e,domain:r,epoch:o.epoch});let i={epoch:jE(e,r),configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0};return e.registryCredentialIntents.set(r,i),s!==void 0&&s.configFingerprint===void 0&&e.stagedOAuthCredentials.set(r,{...s,intentEpoch:i.epoch}),e.pendingRegistryCredentialDomains.add(r),{domain:r,...i}}function nm(t,e){Ur(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Ve({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()??[])e.has(r)||jr(t,r);for(let r of e){let n=t.registryCredentialIntents.get(r);Mi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function FE(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;Ur(e);let n=We(r.id),o=NE(r),s=DE({state:e,config:r,domain:n});s||e.equalRevisionRebindDomains.delete(r.name);let i=e.registryCredentialIntents.get(n);if(i&&i.configFingerprint===void 0){i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s;let a=e.stagedOAuthCredentials.get(n);a?.intentEpoch===i.epoch&&(a.configFingerprint=o)}else i&&i.configFingerprint!==o?(Ve({state:e,domain:n,epoch:i.epoch}),i=void 0):i&&(i.allowEqualRevisionRebind=s);if(!i){let a=Mi({state:e,domain:n});if(i=e.registryCredentialIntents.get(n),!i||i.epoch!==a.epoch)return;i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s}return e.pendingRegistryCredentialDomains.add(n),UE({state:e,config:r,domain:n}),{domain:n,...i}}function om(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Ur(e);let s=ut(r.domain),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:mr(r.revision,a),p=l===0;l!==void 0&&l<0||p&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&mr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:p})}function UE(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n}),(o===void 0||ut(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),st(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function qE(t){let{state:e,config:r,pi:n,intent:o}=t,s=e.stagedOAuthCredentials.get(o.domain);if(!s||s.intentEpoch!==o.epoch||s.configFingerprint!==o.configFingerprint||s.requiresEqualRevisionRebind&&!o.allowEqualRevisionRebind)return;e.stagedOAuthCredentials.delete(o.domain),s.requiresEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let i={[r.name]:s.credential};n.events.emit(Xh,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function HE(t){let{state:e,domain:r}=t,n=Date.now();tm(e,n);let o=e.bootOAuthCredentialBuffer?.get(r);return jr(e,r),o}function GE(t){let{config:e,pi:r,buffered:n}=t;em.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`);let o={[e.name]:n.credential};r.events.emit(Xh,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function ZE(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(Be(n,r)){if(n.name===r.name)return;await No(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 ct(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function BE(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=zE(e,r.name,o);Ve({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}: ${s instanceof Error?s.message:String(s)}`;return e.diagnostics.push({server:r.name,message:a,origin:"registry"}),new Rt(a)}async function VE(t){let{state:e,config:r,pi:n,intent:o,previousConfig:s,rollbackSnapshot:i}=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 ZE({state:e,config:r,previousConfig:s})}catch(h){throw BE({state:e,config:r,intent:o,rollbackSnapshot:i,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 Ve({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let p={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,p),e.registryCredentialConfigsById.set(l,p),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),qE({state:e,config:r,pi:n,intent:o});let f=HE({state:e,domain:o.domain});return Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),f&&GE({config:r,pi:n,buffered:f}),!0}function qr(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),s=FE({state:e,config:r});if(!s)return Promise.resolve(!1);let i=e.registryCredentialIntents.get(s.domain);if(!i||i.epoch!==s.epoch)return Promise.resolve(!1);if(i.finalization)return i.finalization;let a=IE(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 VE({state:e,config:r,pi:n,intent:s,previousConfig:d,rollbackSnapshot:a})});return e.registryCredentialFinalizationsByName.set(r.name,u),i.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 cT}from"@augmentcode/auggie-v2";import{homedir as sm}from"node:os";import{sep as WE}from"node:path";var lu=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},KE=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,JE=/\\\$\{/g,YE=new Set(["workspaceFolder","augmentToken"]),im="${workspaceFolder}";function am(t,e){return t.includes(im)?t.split(im).join(e):t}function cm(t,e){return t.includes("${")?t.replace(KE,(n,o,s)=>{if(YE.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new lu(o)}).replace(JE,"${"):t}function XE(t){return t.startsWith("~")?t==="~"?sm():t.startsWith("~/")||t.startsWith(`~${WE}`)?sm()+t.slice(1):t:t}function pu(t,e,r){return XE(cm(am(t,e),r))}function Ii(t,e,r){return cm(am(t,e),r)}function um(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Ii(s,e,r);return n}var QE="$augment-";function eT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(QE)?s:Ii(s,e,r);return n}function Nt(t,e){let r=process.env;return{...t,url:Ii(t.url,e,r),headers:eT(t.headers,e,r)}}function Dt(t,e){let r=process.env;return{...t,command:pu(t.command,e,r),args:t.args,env:t.env?um(t.env,e,r):void 0,cwd:t.cwd?pu(t.cwd,e,r):e}}import{readFileSync as oT}from"node:fs";import{logger as tT}from"@hermes/logger";var rT=tT.child({prefix:"pi-mcp"}),Pt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function Tn(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 nT(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 An(t,e){let r=Tn(e);if(!r)throw new Pt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Pt(`MCP server "${t}" has type "${r}" but no 'url' property`);return{type:r,name:e.name??t,disabled:e.disabled,url:e.url,headers:e.headers,auth:e.auth==="oauth"?"oauth":void 0,timeoutMs:e.timeoutMs}}let n=e.command;if(!n)throw new Pt(`MCP server "${t}" has type "stdio" but no 'command' property`);let o=(e.args??[]).map(a=>String(a)),s=o.length>0?`${n} ${o.join(" ")}`:n,i=e.name??t;return e.useShellInterpolation===!1&&rT.warn(`MCP server "${i}": useShellInterpolation:false is ignored; settings.json stdio servers always shell-wrap in Wave 1 (V1 json.ts parity)`),{type:"stdio",name:i,disabled:e.disabled,command:s,args:[],env:nT(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var pm=t=>oT(t,"utf8");function Oi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function dm(t){return Oi(t)&&("command"in t||"url"in t)}function hu(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function lm(t,e){return hu(t.name)??e}function fu(t,e){let r=Tn(t);if(r==="http"||r==="sse")return hu(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return hu(t.name,t.title,n)??e}function sT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[fu(n,String(r)),n]});if(Oi(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[fu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(Oi(n))return Object.entries(n).map(([o,s])=>{let i=s;return[lm(i,o),i]})}if(dm(t)){let r=t;return[[fu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(dm))return Object.entries(t).map(([r,n])=>{if(!Oi(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[lm(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 mu(t){return t instanceof Error?t.message:String(t)}function iT(t,e,r,n,o){if(r)return e;try{return n(t)}catch(s){o.push({message:`Failed to read --mcp-config file "${t}": ${mu(s)}`});return}}function aT(t,e,r){let n=t.trim();if(n.length===0)return[];let o=n.startsWith("[")||n.startsWith("{"),s=o?"inline JSON":`file "${t}"`,i=iT(t,n,o,e,r);if(i===void 0)return[];let a;try{a=JSON.parse(i)}catch(c){return r.push({message:`Failed to parse --mcp-config ${s}: ${mu(c)}`}),[]}try{return sT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${mu(c)}`}),[]}}function gu(t,e=pm){let r={},n=[];for(let o of t)for(let[s,i]of aT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function yu(t,e=pm){return!t||t.length===0?new Set:new Set(Object.keys(gu(t,e).servers))}var uT=["global","project","local","managed"];function dT(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 lT(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 pT(t,e,r){let n=gu(t);r.push(...n.diagnostics);let o=n.servers;if(!e||e.size===0)return o;for(let[s,i]of Object.entries(o)){let a=e.get(s);a!==void 0&&(o[s]={...i,disabled:a})}return o}function fT(t,e,r){let n=cT.create(t,e);for(let{scope:o,error:s}of n.drainErrors()){let i=s.message.includes("parse settings JSON")?"parse":"read";r.push({message:`Failed to ${i} ${o} settings.json: ${s.message}`})}return lT(uT.map(o=>dT(n,o)))}function $n(t,e,r,n){let o=[],s=r&&r.length>0?pT(r,n,o):fT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=An(a,c);i.push(u.type==="stdio"?Dt(u,t):Nt(u,t))}catch(u){let d=u instanceof Pt?u.message:`Failed to normalize MCP server "${a}": ${u instanceof Error?u.message:String(u)}`;o.push({server:a,message:d})}return{servers:i,diagnostics:o}}import{setToolSource as _m}from"@augmentcode/auggie-v2";import{logger as CT}from"@hermes/logger";import{Type as xT}from"@sinclair/typebox";var Mn=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;get(e){return this._tokens.get(e)}commit(e,r){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e)}set(e,r,n){this.commit(e,r)}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,s){return this.persist(e,n,o)}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,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)}}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)}delete(e,r){this._tokens.delete(e)}clearLocalCredential(e){this._tokens.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)}};var zi=Symbol.for("__pi_mcp_state__");function hT(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 mT(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function gT(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&hT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&mT(a,e)}),s=t.expectedCredentialDomains.get(r.name);if(!(!o||t.sessionRemovedConfigIds.has(e)||t.oauthCredentialDomains.has(r.name)||s?.kind!=="domain"||s.domain!==`user:${e}`)){t.equalRevisionRebindDomains.set(r.name,s.domain);for(let i of n)t.tokens.clearLocalCredential(i),t.oauthCredentialDomains.delete(i),t.credentialRevisions.delete(i),t.hostedCredentialOwnership?.delete(i),t.preservedCredentialIdentities?.delete(i),t.statusFailureCategories?.delete(i),t.authRefreshNeededReportKeys?.delete(i),t.expectedCredentialDomains.set(i,{kind:"blocked"})}}}function yT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=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 s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&gT(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&&Q(t,r,n);t.pluginReconcileQueue??=Promise.resolve(),t.mcpAttachDisabled??=!1,t.mcpAttachCloudSignaled??=!1,t.attachResolvers??=new Map,t.attachResultListenerBound??=!1,t.attachmentCommandGenerations??=new Map,t.attachmentCommandInFlightGenerations??=new Map,t.attachmentCommandAppliedGenerations??=new Map}async function Do(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 Ni(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 vT(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 fm(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Di(t){let{state:e,configId:r,generation:n,operation:o,wasApplied:s}=t;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o:o.then(i=>(s()?vT({state:e,configId:r,generation:n}):fm({state:e,configId:r,generation:n}),i),i=>{throw fm({state:e,configId:r,generation:n}),i})}function re(){let t=globalThis;if(t[zi])return yT(t[zi]),t[zi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Mn,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations: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,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,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};return t[zi]=e,e}var hm=Symbol.for("__hermes_mcp_tool_registry__"),_T=Symbol.for("__hermes_mcp_extension_factory__");function mm(){let t=globalThis;return t[hm]??=new Map,t[hm]}function gr(t){mm().set(t.name,t)}function gm(t,e){let r=mm();(e===void 0||r.get(t)===e)&&r.delete(t)}function ym(t){Reflect.set(t,_T,!0)}function Li(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 ST(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function wT(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 bT(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
- `).trim()}function vu(t,e,r){if(t.isError){let o=bT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=wT(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}}async function vm(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Li(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=ST(t.params),o=await e.callTool(r,n,t.signal);return vu(o,t.serverName,r)}var RT=/[^a-zA-Z0-9_-]/g;function _u(t){return t.replace(RT,"_")}function PT(t,e){let r=_u(e),n=_u(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var yr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=PT(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=`_${_u(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Su=CT.child({prefix:"pi-mcp"});function ji(){return re().toolRegistrationsByPi}function Sm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=xT.Unsafe(n.inputSchema??{})}catch(c){Su.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>re().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,p)=>vm({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(f=>f.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function wu(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n),s=r.definitionsByName?.get(n);e.ownerByToolName.delete(n),t.unregisterTool(n),gm(n,s),r.definitionsByName?.delete(n),kT(t,e,n,r,o)}function kT(t,e,r,n,o){let s=re();for(let[i,a]of e.byServer){if(a===n||!a.registeredNames.has(r))continue;let c=s.servers.get(i);if(c===void 0||c!==a.host||c.status!=="success"||s.serverGenerations?.get(i)!==a.generation)continue;let u=new yr(i);for(let d of c.listTools()){let{namespaced:l,collision:p}=u.put(d.name);if(p||l!==r)continue;let f=Sm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!f)return;_m(r,"mcp"),t.registerTool(f),gr(f),a.definitionsByName??=new Map,a.definitionsByName.set(r,f),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function ET(t,e){let r=ji(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=re().serverGenerations?.get(e.name),s=n.byServer.get(e.name);if(s?.host===e&&s.generation===o)return{registration:s,replaced:!1};if(s)for(let a of s.registeredNames)wu(t,n,s,a);let i={generation:o,host:e,map:new yr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function bu(t,e){let{registration:r,replaced:n}=ET(t,e),o=new Set(r.registeredNames),s=new yr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:p}=s.put(d.name);if(p){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=re();y.diagnostics.some(w=>w.server===i&&w.message.includes(`both map to "${l}"`))||(Su.warn(m),y.diagnostics.push({server:i,message:m}));continue}let f=Sm({pi:t,serverName:i,tool:d,map:s,namespaced:l});f&&(_m(l,"mcp"),t.registerTool(f),gr(f),r.definitionsByName??=new Map,r.definitionsByName.set(l,f),ji().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=ji().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&wu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Su.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Ru(t,e,r){let n=ji().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 s of o.registeredNames)wu(t,n,o,s);return n.byServer.delete(e.name),!0}function wm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&bu(t,r)}import{getToolSource as jT}from"@augmentcode/auggie-v2";import{Type as TT}from"@sinclair/typebox";var AT="cliMcpToolSearchAutoEnable",$T="cliMcpToolSearchTokenThreshold",MT=!1,bm=2e4;function IT(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function OT(t){let e=0;for(let r of t.servers.values())e+=zT(r);return e}function zT(t){if(t.status!=="success")return 0;let e=new yr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||NT(n.inputSchema)&&(r+=IT(n))}return r}function NT(t){try{return TT.Unsafe(t??{}),!0}catch{return!1}}function DT(t){let r=t.featureFlags?.flags?.[AT];return typeof r=="boolean"?r:MT}function LT(t){let r=t.featureFlags?.flags?.[$T];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:bm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:bm}function Rm(t){return DT(t)?OT(t)>=LT(t):!1}var FT="AUGGIE_ENABLE_TOOL_SEARCH",UT=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Lo(){return process.env[FT]==="1"}function In(t){return Lo()||t.toolSearchLatched?!0:Rm(t)?(t.toolSearchLatched=!0,!0):!1}function Fi(t){let e=t.getActiveTools(),r=e.filter(n=>!qT(n)||UT.has(n));r.length!==e.length&&t.setActiveTools(r)}function qT(t){return jT(t)==="mcp"}import{setToolSource as $m}from"@augmentcode/auggie-v2";import{logger as cA}from"@hermes/logger";import{Type as Mm}from"@sinclair/typebox";import{logger as HT}from"@hermes/logger";var jo={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Hr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Pm=HT.child({prefix:"pi-mcp"}),GT=5e3,ZT=1,BT=2,VT=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),WT=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function KT(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 JT(t){return t===ZT||typeof t=="string"&&VT.has(t)?"available":t===BT||typeof t=="string"&&WT.has(t)?"opt_in_required":"unknown"}function YT(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:KT(t.auth_type),state:JT(t.state)}}function Pu(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 Fo(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Pu(t,r))}async function Cm(t,e,r){let n=t.apiUrl.replace(/\/+$/,""),o=e??fetch;try{let s=await o(`${n}/settings/get-mcp-catalog-metadata`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({product_type:Hr.UNSPECIFIED}),signal:AbortSignal.timeout(r??GT)});if(!s.ok)return Pm.debug(`MCP catalog fetch failed with ${s.status}; treating catalog as empty`),{ok:!1,disable:s.status===404};let i=await s.json(),a=[];for(let c of i.entries??[]){let u=YT(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Pm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var XT="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",QT=`You are a tool search assistant. Given a user's query and a list of available tools, identify the single best matching tool.
8
+ deps: ${r}}`};var lj={keyword:"dependencies",type:"object",schemaType:"object",error:Gt.error,code(t){let[e,r]=pj(t);$R(t,e),MR(t,r)}};function pj({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 $R(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Qs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Qs.checkReportMissingProp)(t,u)}):(r.if((0,nf._)`${c} && (${(0,Qs.checkMissingProp)(t,a,s)})`),(0,Qs.reportMissingProp)(t,s),r.else())}}Gt.validatePropertyDeps=$R;function MR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,dj.alwaysValidSchema)(s,e[a])||(r.if((0,Qs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Gt.validateSchemaDeps=MR;Gt.default=lj});var zR=R(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var OR=D(),fj=H(),hj={message:"property name must be valid",params:({params:t})=>(0,OR._)`{propertyName: ${t.propertyName}}`},mj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:hj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,fj.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,OR.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};of.default=mj});var af=R(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var mc=yt(),At=D(),gj=ir(),gc=H(),yj={message:"must NOT have additional properties",params:({params:t})=>(0,At._)`{additionalProperty: ${t.additionalProperty}}`},vj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,gc.alwaysValidSchema)(i,r))return;let u=(0,mc.allSchemaProperties)(n.properties),d=(0,mc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,At._)`${s} === ${gj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let w=(0,gc.schemaRefOrVal)(i,n.properties,"properties");S=(0,mc.isOwnProperty)(e,w,y)}else u.length?S=(0,At.or)(...u.map(w=>(0,At._)`${y} === ${w}`)):S=At.nil;return d.length&&(S=(0,At.or)(S,...d.map(w=>(0,At._)`${(0,mc.usePattern)(t,w)}.test(${y})`))),(0,At.not)(S)}function f(y){e.code((0,At._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,gc.alwaysValidSchema)(i,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,At.not)(S),()=>{t.reset(),f(y)})):(m(y,S),a||e.if((0,At.not)(S),()=>e.break()))}}function m(y,S,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:gc.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,S)}}};sf.default=vj});var LR=R(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var _j=js(),NR=yt(),cf=H(),DR=af(),Sj={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&DR.default.code(new _j.KeywordCxt(s,DR.default,"additionalProperties"));let i=(0,NR.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=cf.mergeEvaluated.props(e,(0,cf.toHash)(i),s.props));let a=i.filter(l=>!(0,cf.alwaysValidSchema)(s,r[l]));if(a.length===0)return;let c=e.name("valid");for(let l of a)u(l)?d(l):(e.if((0,NR.propertyInData)(e,o,l,s.opts.ownProperties)),d(l),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(l),t.ok(c);function u(l){return s.opts.useDefaults&&!s.compositeRule&&r[l].default!==void 0}function d(l){t.subschema({keyword:"properties",schemaProp:l,dataProp:l},c)}}};uf.default=Sj});var qR=R(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var jR=yt(),yc=D(),FR=H(),UR=H(),wj={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,jR.allSchemaProperties)(r),c=a.filter(m=>(0,FR.alwaysValidSchema)(s,r[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof yc.Name)&&(s.props=(0,UR.evaluatedPropsToName)(e,s.props));let{props:l}=s;p();function p(){for(let m of a)u&&f(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function f(m){for(let y in u)new RegExp(m).test(y)&&(0,FR.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,yc._)`${(0,jR.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:UR.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,yc._)`${l}[${y}]`,!0):!S&&!s.allErrors&&e.if((0,yc.not)(d),()=>e.break())})})}}};df.default=wj});var HR=R(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var bj=H(),Rj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,bj.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"}};lf.default=Rj});var GR=R(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var Pj=yt(),Cj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Pj.validateUnion,error:{message:"must match a schema in anyOf"}};pf.default=Cj});var ZR=R(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var vc=D(),xj=H(),kj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,vc._)`{passingSchemas: ${t.passing}}`},Ej={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kj,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 s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let p;(0,xj.alwaysValidSchema)(o,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,vc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,vc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,vc.Name)})})}}};ff.default=Ej});var BR=R(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Tj=H(),Aj={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((s,i)=>{if((0,Tj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};hf.default=Aj});var KR=R(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var _c=D(),WR=H(),$j={message:({params:t})=>(0,_c.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,_c._)`{failingKeyword: ${t.ifClause}}`},Mj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:$j,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,WR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=VR(n,"then"),s=VR(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){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,_c.not)(a),u("else"));t.pass(i,()=>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 p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,_c._)`${d}`):t.setParams({ifClause:d})}}}};function VR(t,e){let r=t.schema[e];return r!==void 0&&!(0,WR.alwaysValidSchema)(t,r)}mf.default=Mj});var JR=R(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Ij=H(),Oj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Ij.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};gf.default=Oj});var YR=R(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var zj=Xp(),Nj=kR(),Dj=Qp(),Lj=TR(),jj=AR(),Fj=IR(),Uj=zR(),qj=af(),Hj=LR(),Gj=qR(),Zj=HR(),Bj=GR(),Vj=ZR(),Wj=BR(),Kj=KR(),Jj=JR();function Yj(t=!1){let e=[Zj.default,Bj.default,Vj.default,Wj.default,Kj.default,Jj.default,Uj.default,qj.default,Fj.default,Hj.default,Gj.default];return t?e.push(Nj.default,Lj.default):e.push(zj.default,Dj.default),e.push(jj.default),e}yf.default=Yj});var XR=R(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var _e=D(),Xj={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},Qj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Xj,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(S,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(S,m)),t.fail$data((0,_e.or)(w(),b()));function w(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${S}`}function b(){let k=d.$async?(0,_e._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,_e._)`${S}(${n})`,_=(0,_e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,_e._)`${S} && ${S} !== true && ${y} === ${e} && !${_}`}}function f(){let h=l.formats[s];if(!h){w();return}if(h===!0)return;let[m,y,S]=b(h);m===e&&t.pass(k());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(_){let P=_ instanceof RegExp?(0,_e.regexpCode)(_):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,O=r.scopeValue("formats",{key:s,ref:_,code:P});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,_e._)`${O}.validate`]:["string",_,O]}function k(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${S}(${n})`}return typeof y=="function"?(0,_e._)`${S}(${n})`:(0,_e._)`${S}.test(${n})`}}}};vf.default=Qj});var QR=R(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var e1=XR(),t1=[e1.default];_f.default=t1});var eP=R(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.contentVocabulary=fo.metadataVocabulary=void 0;fo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];fo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rP=R(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var r1=uR(),n1=RR(),o1=YR(),s1=QR(),tP=eP(),i1=[r1.default,n1.default,(0,o1.default)(),s1.default,tP.metadataVocabulary,tP.contentVocabulary];Sf.default=i1});var oP=R(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});Sc.DiscrError=void 0;var nP;(function(t){t.Tag="tag",t.Mapping="mapping"})(nP||(Sc.DiscrError=nP={}))});var iP=R(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var ho=D(),wf=oP(),sP=tc(),a1=Fs(),c1=H(),u1={message:({params:{discrError:t,tagName:e}})=>t===wf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ho._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},d1={keyword:"discriminator",type:"object",schemaType:"object",error:u1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.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(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,ho._)`${r}${(0,ho.getProperty)(a)}`);e.if((0,ho._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:wf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,ho._)`${u} === ${h}`),e.assign(c,l(f[h]));e.else(),t.error(!1,{discrError:wf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(m,ho.Name),h}function p(){var f;let h={},m=S(o),y=!0;for(let k=0;k<i.length;k++){let _=i[k];if(_?.$ref&&!(0,c1.schemaHasRulesButRef)(_,s.self.RULES)){let O=_.$ref;if(_=sP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,O),_ instanceof sP.SchemaEnv&&(_=_.schema),_===void 0)throw new a1.default(s.opts.uriResolver,s.baseId,O)}let P=(f=_?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||S(_)),w(P,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:k}){return Array.isArray(k)&&k.includes(a)}function w(k,_){if(k.const)b(k.const,_);else if(k.enum)for(let P of k.enum)b(P,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(k,_){if(typeof k!="string"||k in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[k]=_}}}};bf.default=d1});var aP=R((GJ,l1)=>{l1.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 Pf=R((de,Rf)=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.MissingRefError=de.ValidationError=de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=de.Ajv=void 0;var p1=nR(),f1=rP(),h1=iP(),cP=aP(),m1=["/properties"],wc="http://json-schema.org/draft-07/schema",mo=class extends p1.default{_addVocabularies(){super._addVocabularies(),f1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(h1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(cP,m1):cP;this.addMetaSchema(e,wc,!1),this.refs["http://json-schema.org/schema"]=wc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(wc)?wc:void 0)}};de.Ajv=mo;Rf.exports=de=mo;Rf.exports.Ajv=mo;Object.defineProperty(de,"__esModule",{value:!0});de.default=mo;var g1=js();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return g1.KeywordCxt}});var go=D();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return go._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return go.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return go.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return go.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return go.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return go.CodeGen}});var y1=Qa();Object.defineProperty(de,"ValidationError",{enumerable:!0,get:function(){return y1.default}});var v1=Fs();Object.defineProperty(de,"MissingRefError",{enumerable:!0,get:function(){return v1.default}})});var gP=R(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.formatNames=Bt.fastFormats=Bt.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Bt.fullFormats={date:Zt(pP,Ef),time:Zt(xf(!0),Tf),"date-time":Zt(uP(!0),hP),"iso-time":Zt(xf(),fP),"iso-date-time":Zt(uP(),mP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:P1,"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:$1,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:C1,int32:{type:"number",validate:E1},int64:{type:"number",validate:T1},float:{type:"number",validate:lP},double:{type:"number",validate:lP},password:!0,binary:!0};Bt.fastFormats={...Bt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ef),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Tf),"date-time":Zt(/^\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,hP),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,fP),"iso-date-time":Zt(/^\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,mP),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};Bt.formatNames=Object.keys(Bt.fullFormats);function _1(t){return t%4===0&&(t%100!==0||t%400===0)}var S1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,w1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function pP(t){let e=S1.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&&_1(r)?29:w1[n])}function Ef(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Cf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xf(t){return function(r){let n=Cf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+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&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Tf(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 fP(t,e){if(!(t&&e))return;let r=Cf.exec(t),n=Cf.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 kf=/t|\s/i;function uP(t){let e=xf(t);return function(n){let o=n.split(kf);return o.length===2&&pP(o[0])&&e(o[1])}}function hP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function mP(t,e){if(!(t&&e))return;let[r,n]=t.split(kf),[o,s]=e.split(kf),i=Ef(r,o);if(i!==void 0)return i||Tf(n,s)}var b1=/\/|:/,R1=/^(?:[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 P1(t){return b1.test(t)&&R1.test(t)}var dP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function C1(t){return dP.lastIndex=0,dP.test(t)}var x1=-(2**31),k1=2**31-1;function E1(t){return Number.isInteger(t)&&t<=k1&&t>=x1}function T1(t){return Number.isInteger(t)}function lP(){return!0}var A1=/[^\\]\\Z/;function $1(t){if(A1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var yP=R(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.formatLimitDefinition=void 0;var M1=Pf(),$t=D(),Nr=$t.operators,bc={formatMaximum:{okStr:"<=",ok:Nr.LTE,fail:Nr.GT},formatMinimum:{okStr:">=",ok:Nr.GTE,fail:Nr.LT},formatExclusiveMaximum:{okStr:"<",ok:Nr.LT,fail:Nr.GTE},formatExclusiveMinimum:{okStr:">",ok:Nr.GT,fail:Nr.LTE}},I1={message:({keyword:t,schemaCode:e})=>(0,$t.str)`should be ${bc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$t._)`{comparison: ${bc[t].okStr}, limit: ${e}}`};yo.formatLimitDefinition={keyword:Object.keys(bc),type:"string",schemaType:"string",$data:!0,error:I1,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new M1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,$t._)`${p}[${c.schemaCode}]`);t.fail$data((0,$t.or)((0,$t._)`typeof ${f} != "object"`,(0,$t._)`${f} instanceof RegExp`,(0,$t._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(p)}`:void 0});t.fail$data(l(h))}function l(p){return(0,$t._)`${p}.compare(${r}, ${n}) ${bc[o].fail} 0`}},dependencies:["format"]};var O1=t=>(t.addKeyword(yo.formatLimitDefinition),t);yo.default=O1});var wP=R((ei,SP)=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});var vo=gP(),z1=yP(),Af=D(),vP=new Af.Name("fullFormats"),N1=new Af.Name("fastFormats"),$f=(t,e={keywords:!0})=>{if(Array.isArray(e))return _P(t,e,vo.fullFormats,vP),t;let[r,n]=e.mode==="fast"?[vo.fastFormats,N1]:[vo.fullFormats,vP],o=e.formats||vo.formatNames;return _P(t,o,r,n),e.keywords&&(0,z1.default)(t),t};$f.get=(t,e="full")=>{let n=(e==="fast"?vo.fastFormats:vo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function _P(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Af._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}SP.exports=ei=$f;Object.defineProperty(ei,"__esModule",{value:!0});ei.default=$f});var JP=R((x5,KP)=>{KP.exports=WP;WP.sync=hF;var BP=pr("fs");function fF(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 VP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:fF(e,r)}function WP(t,e,r){BP.stat(t,function(n,o){r(n,n?!1:VP(o,t,e))})}function hF(t,e){return VP(BP.statSync(t),t,e)}});var tC=R((k5,eC)=>{eC.exports=XP;XP.sync=mF;var YP=pr("fs");function XP(t,e,r){YP.stat(t,function(n,o){r(n,n?!1:QP(o,e))})}function mF(t,e){return QP(YP.statSync(t),e)}function QP(t,e){return t.isFile()&&gF(t,e)}function gF(t,e){var r=t.mode,n=t.uid,o=t.gid,s=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),i=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===i||r&a&&n===s||r&d&&s===0;return l}});var nC=R((T5,rC)=>{var E5=pr("fs"),Ic;process.platform==="win32"||global.TESTING_WINDOWS?Ic=JP():Ic=tC();rC.exports=Jf;Jf.sync=yF;function Jf(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){Jf(t,e||{},function(s,i){s?o(s):n(i)})})}Ic(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function yF(t,e){try{return Ic.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var dC=R((A5,uC)=>{var xo=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",oC=pr("path"),vF=xo?";":":",sC=nC(),iC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),aC=(t,e)=>{let r=e.colon||vF,n=t.match(/\//)||xo&&t.match(/\\/)?[""]:[...xo?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=xo?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=xo?o.split(r):[""];return xo&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},cC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=aC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(iC(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=oC.join(f,t),m=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((p,f)=>{if(l===o.length)return p(a(d+1));let h=o[l];sC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return p(u+h);return p(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},_F=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=aC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=oC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let p=d+n[l];try{if(sC.sync(p,{pathExt:o}))if(e.all)s.push(p);else return p}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw iC(t)};uC.exports=cC;cC.sync=_F});var pC=R(($5,Yf)=>{"use strict";var lC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Yf.exports=lC;Yf.exports.default=lC});var gC=R((M5,mC)=>{"use strict";var fC=pr("path"),SF=dC(),wF=pC();function hC(t,e){let r=t.options.env||process.env,n=process.cwd(),o=t.options.cwd!=null,s=o&&process.chdir!==void 0&&!process.chdir.disabled;if(s)try{process.chdir(t.options.cwd)}catch{}let i;try{i=SF.sync(t.command,{path:r[wF({env:r})],pathExt:e?fC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=fC.resolve(o?t.options.cwd:"",i)),i}function bF(t){return hC(t)||hC(t,!0)}mC.exports=bF});var yC=R((I5,Qf)=>{"use strict";var Xf=/([()\][%!^"`<>&|;, *?])/g;function RF(t){return t=t.replace(Xf,"^$1"),t}function PF(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Xf,"^$1"),e&&(t=t.replace(Xf,"^$1")),t}Qf.exports.command=RF;Qf.exports.argument=PF});var _C=R((O5,vC)=>{"use strict";vC.exports=/^#!(.*)/});var wC=R((z5,SC)=>{"use strict";var CF=_C();SC.exports=(t="")=>{let e=t.match(CF);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var RC=R((N5,bC)=>{"use strict";var eh=pr("fs"),xF=wC();function kF(t){let r=Buffer.alloc(150),n;try{n=eh.openSync(t,"r"),eh.readSync(n,r,0,150,0),eh.closeSync(n)}catch{}return xF(r.toString())}bC.exports=kF});var kC=R((D5,xC)=>{"use strict";var EF=pr("path"),PC=gC(),CC=yC(),TF=RC(),AF=process.platform==="win32",$F=/\.(?:com|exe)$/i,MF=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function IF(t){t.file=PC(t);let e=t.file&&TF(t.file);return e?(t.args.unshift(t.file),t.command=e,PC(t)):t.file}function OF(t){if(!AF)return t;let e=IF(t),r=!$F.test(e);if(t.options.forceShell||r){let n=MF.test(e);t.command=EF.normalize(t.command),t.command=CC.command(t.command),t.args=t.args.map(s=>CC.argument(s,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 zF(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:OF(n)}xC.exports=zF});var AC=R((L5,TC)=>{"use strict";var th=process.platform==="win32";function rh(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 NF(t,e){if(!th)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=EC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function EC(t,e){return th&&t===1&&!e.file?rh(e.original,"spawn"):null}function DF(t,e){return th&&t===1&&!e.file?rh(e.original,"spawnSync"):null}TC.exports={hookChildProcess:NF,verifyENOENT:EC,verifyENOENTSync:DF,notFoundError:rh}});var IC=R((j5,ko)=>{"use strict";var $C=pr("child_process"),nh=kC(),oh=AC();function MC(t,e,r){let n=nh(t,e,r),o=$C.spawn(n.command,n.args,n.options);return oh.hookChildProcess(o,n),o}function LF(t,e,r){let n=nh(t,e,r),o=$C.spawnSync(n.command,n.args,n.options);return o.error=o.error||oh.verifyENOENTSync(o.status,n),o}ko.exports=MC;ko.exports.spawn=MC;ko.exports.sync=LF;ko.exports._parse=nh;ko.exports._enoent=oh});var jC=R(ih=>{"use strict";var NC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,HF=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,DC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,GF=/\\([\u000b\u0020-\u00ff])/g,ZF=/([\\"])/g,LC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;ih.format=BF;ih.parse=VF;function BF(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!LC.test(r))throw new TypeError("invalid type");var n=r;if(e&&typeof e=="object")for(var o,s=Object.keys(e).sort(),i=0;i<s.length;i++){if(o=s[i],!DC.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+KF(e[o])}return n}function VF(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?WF(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(!LC.test(n))throw new TypeError("invalid media type");var o=new JF(n.toLowerCase());if(r!==-1){var s,i,a;for(NC.lastIndex=r;i=NC.exec(e);){if(i.index!==r)throw new TypeError("invalid parameter format");r+=i[0].length,s=i[1].toLowerCase(),a=i[2],a.charCodeAt(0)===34&&(a=a.slice(1,-1),a.indexOf("\\")!==-1&&(a=a.replace(GF,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function WF(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 KF(t){var e=String(t);if(DC.test(e))return e;if(e.length>0&&!HF.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(ZF,"\\$1")+'"'}function JF(t){this.parameters=Object.create(null),this.type=t}});import{logger as aZ}from"@hermes/logger";import{logger as gq}from"@hermes/logger";var pE="mcp-auth";function ze(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(pE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as ZU}from"@augmentcode/auggie-v2";import{logger as BU}from"@hermes/logger";import{logger as OE}from"@hermes/logger";import{logger as hE}from"@hermes/logger";function fE(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 fr(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":fE(t,e,r)?"plugin":"local"}function mE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var Zh=hE.child({prefix:"pi-mcp"}),gE="augment:mcp-status-report";function Jt(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 s=t.credentialRevisions?.get(e);return{serverGeneration:t.serverGenerations?.get(e)??0,mcpConfigId:r??n?.config.id,credentialRevision:s?.revision,credentialRevisionDomain:s?.domain}}function Io(t,e,r,n){let o=Jt(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 ot(t,e,r){if(r){let o=Jt(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 yE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=Jt(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 Ai=3e4;function vE(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>=Ai?"failed":void 0}default:return}}var Bh="authentication required",_E="Authentication refresh is pending in the backend; retry shortly.",SE="timed out connecting after 30s",wE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",bE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",RE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).";function PE(t,e){let r=new Set;for(let i of t.servers.values())i.config.id!==void 0&&r.add(i.config.id);let n=new Set(e.map(i=>i.mcpConfigId).filter(i=>i!==void 0)),o=new Set(e.map(i=>i.name)),s=i=>t.registryConfigNamesById.get(i)??i;for(let i of t.failedAddConfigIds){if(r.has(i)||n.has(i))continue;let a=s(i);n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(i)?bE:wE,mcpConfigId:i,dynamicallyAdded:!0})}for(let i of t.selectedRegistryConfigIds??[]){if(r.has(i)||n.has(i)||t.sessionRemovedConfigIds.has(i))continue;let a=s(i);o.has(a)||(n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:RE,mcpConfigId:i}))}}function CE(t,e){return e!==void 0?e.isAuthError?Bh:e.error:t.status==="initializing"?SE:t.lastError??(t.status==="auth_required"?Bh:void 0)}function xE(t,e){let r=vE(t);if(r===void 0)return;let n=yE(e,t.name),o=r==="connected"?mE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:fr(t,e.pluginServerHosts,e.hostLeases),status:r,transport:t.config.type,tools:t.tools.map(u=>u.name)},i=t.config.id;i!==void 0&&(s.mcpConfigId=i,e.dynamicallyAddedConfigIds.has(i)&&(s.dynamicallyAdded=!0));let a=e.statusFailureCategories?.get(t.name),c=typeof a=="object"?{revision:a.credentialRevision,domain:a.credentialRevisionDomain}:e.credentialRevisions?.get(t.name);return c?.revision!==void 0&&c.domain!==void 0&&(s.credentialRevision=c.revision,s.credentialRevisionDomain=c.domain),r==="failed"&&(s.errorMessage=n==="auth_refresh_needed"?_E:CE(t,o),s.failureCategory=n??(t.status==="auth_required"||o?.isAuthError===!0?"auth_terminal":"transport_transient"),typeof a=="object"&&(s.serverGeneration=a.serverGeneration)),s}function kE(t){let e=[];for(let r of t.servers.values()){let n=xE(r,t);n!==void 0&&e.push(n)}return PE(t,e),e}function J(t,e){try{let r=kE(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(gE,o),Zh.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){Zh.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var $i={local:4,registry:3,plugin:2,vfs:1};function zt(t){return t.hostLeases??=new Map,t.hostLeases}function EE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Oo(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function zo(t,e){return t.kind===e.kind&&t.identity===e.identity}function Vh(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 uu(t,e){let r=EE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Mi(t,e,r){if(r.kind==="registry"){Oo(t).set(e,{kind:"domain",domain:r.identity});return}Oo(t).set(e,{kind:"blocked"})}function du(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 Tn(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 Q(t,e,r){let n=zt(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?Tn(i,s):{kind:s??"local",identity:e},c={owner:a,revision:uu(t,e),host:r};return n.set(e,c),Mi(t,e,a),c}function Wh(t){let{state:e,name:r,host:n}=t,o=zt(e),s=o.get(r);if(!s||s.host!==n||s.owner.kind!=="local"||e.servers.get(r)!==n)return;let i={owner:{kind:"plugin",identity:n.config.id??r},revision:uu(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),Mi(e,r,i.owner),i}function No(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=zt(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=$i[n.kind]>$i[a.owner.kind],p=$i[n.kind]===$i[a.owner.kind],f=o===a.revision&&(s===void 0||s===a.host);if(!(l||p&&f))return}let c=a?.host,u=a?Vh(a):void 0;du(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:uu(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),Mi(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function lu(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 we(t){let{state:e,name:r,retirement:n,result:o}=t;if(n.settled)return!1;n.settled=!0,n.result=o;let i=zt(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Oo(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function Ii(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e).get(r);return!i||i.revision!==o||!zo(i.owner,n)||i.host!==void 0||i.retirement!==void 0?!1:(i.host=s,e.servers.set(r,s),n.kind==="plugin"?(e.pluginServerNames.add(r),e.pluginServerHosts.set(r,s)):(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),!0)}function bt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e).get(r);if(!i||i.revision!==o||!zo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=Vh(i);if(a)return du(e,r,s),i.host=void 0,i.retirement=a,a}function Kh(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=zt(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!zo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!zo(i.owner,n)||i.revision!==o.incumbent.revision?(Mi(e,r,i.owner),!0):(s.delete(r),Oo(e).set(r,{kind:"blocked"}),!0))}function be(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=zt(e),a=i.get(r);return!a||a.revision!==o||!zo(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(du(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),Oo(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return zt(t).get(e)}function Jh(t,e,r){return zt(t).get(e)?.host===r}function Do(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function hr(t){if(!(t.type!=="http"&&t.type!=="sse"||t.auth!=="oauth"))return{id:t.id,name:t.name,type:t.type,url:t.url,auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Be(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:t.url===e.url&&t.auth===e.auth}function pu(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function TE(t){let{state:e,name:r,expectedRegistryConfigId:n,expectedConfig:o,currentConfig:s}=t;if(o)return o;let i=n?e.registryCredentialConfigsById?.get(n):void 0;if(i?.name===r)return i;let a=e.registryCredentialConfigs?.get(r);if(a?.id===n)return a;if(s?.id===n)return s}function AE(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!Be(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function Yh(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!pu(e,r):n!==void 0&&e!==n}function Xh(t,e,r){return r&&e!==void 0&&t!==void 0&&pu(t,e)}function $E(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!pu(s,n))}function Qh(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(AE({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||Yh({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&Yh({identity:i.domain,...l})?!0:$E({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function ME(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return hr(r);if(n!==void 0)return{id:n,name:e}}function IE(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!hr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function em(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=TE({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,p=Qh({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),f=Xh(s,u,d),h=Xh(i,u,d),m=!p,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,w=p&&!(m||f||h||y);if(o==="durable"){let P=ME({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:w})}let b=Qh({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),k=m&&!b,_=!1;return t.equalRevisionRebindDomains?.delete(e),(k||f)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),_=!0),(k||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),_=!0),k&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),IE({state:t,name:e,mode:o,stillOwnsNameScopedRevision:k,retiredConfig:c}),_&&(Do(t,e),ot(t,e),t.authRefreshNeededReportKeys?.delete(e)),k}function ut(t,e,r,n){return em(t,e,r,n,"durable")}function Lo(t,e,r,n){return em(t,e,r,n,"session")}function tm(t){let e=t.credential_owner_domain??t.credentialOwnerDomain;return typeof e=="string"&&/^user:.+/.test(e)?e:void 0}function mr(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 rm="augment:mcp-oauth-credentials",nm=300*1e3,zE=256,fu=OE.child({prefix:"pi-mcp"}),Rt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function st(t){return`user:${t}`}function Fr(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)/,"")},s=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(s?.revision!==o.revision||s?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let i=e.oauthCredentialRevisions.get(o.domain);(i===void 0||mr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function An(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!=="user"&&r!=="tenant"?t:st(t.slice(e+1))}function it(t){return/^secret:(private|shared):.+/.test(t)}function Ur(t){return t.ownerDomain??An(t.domain)}function om(t,e,r){let n=st(e);return r!==void 0?r===n:it(t)||An(t)===n}function NE(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function DE(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 LE(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function jE(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&NE(t.credentialRevisions.get(e),r.credentialRevision)&&LE(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function FE(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 UE(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??"")||!Be(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function qr(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 gr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function sm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=nm&&gr(t,n)}function qE(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&gr(t,e)}function im(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;qr(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();sm(e,a);let c=Ur(n),u=it(c)?`${c}\0${r}`:c,d=i.get(u),l=d?.credential.credential_revision??d?.credential.credentialRevision;if(typeof l=="string"&&mr(n.revision,l)<=0)return;!d&&i.size>=zE&&qE(e),gr(e,u);let p={serverName:r,credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(u,p),p.expiryTimer=setTimeout(()=>{i.get(u)===p&&gr(e,u)},nm),p.expiryTimer.unref?.(),fu.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function HE(t,e){qr(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function Ve(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:s=!1}=t;qr(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||gr(e,r)}}function Oi(t){let{state:e,domain:r,forceNew:n=!1}=t;qr(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let s=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Ve({state:e,domain:r,epoch:o.epoch});let i={epoch:HE(e,r),configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0};return e.registryCredentialIntents.set(r,i),s!==void 0&&s.configFingerprint===void 0&&e.stagedOAuthCredentials.set(r,{...s,intentEpoch:i.epoch}),e.pendingRegistryCredentialDomains.add(r),{domain:r,...i}}function am(t,e){qr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Ve({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)&&!it(n)&&gr(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);Oi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function GE(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;qr(e);let n=st(r.id),o=FE(r),s=UE({state:e,config:r,domain:n});s||e.equalRevisionRebindDomains.delete(r.name);let i=e.registryCredentialIntents.get(n);if(i&&i.configFingerprint===void 0){i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s;let a=e.stagedOAuthCredentials.get(n);a?.intentEpoch===i.epoch&&(a.configFingerprint=o)}else i&&i.configFingerprint!==o?(Ve({state:e,domain:n,epoch:i.epoch}),i=void 0):i&&(i.allowEqualRevisionRebind=s);if(!i){let a=Oi({state:e,domain:n});if(i=e.registryCredentialIntents.get(n),!i||i.epoch!==a.epoch)return;i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s}return e.pendingRegistryCredentialDomains.add(n),ZE({state:e,config:r,domain:n}),{domain:n,...i}}function cm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;qr(e);let s=Ur(r),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:mr(r.revision,a),p=l===0;l!==void 0&&l<0||p&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&mr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:p})}function ZE(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 s=e.credentialRevisions.get(r.name);(o===void 0||s?.ownerDomain!==void 0&&s.ownerDomain!==n||s?.ownerDomain===void 0&&!it(o)&&An(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),ot(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function BE(t){let{state:e,config:r,pi:n,intent:o}=t,s=e.stagedOAuthCredentials.get(o.domain);if(!s||s.intentEpoch!==o.epoch||s.configFingerprint!==o.configFingerprint||s.requiresEqualRevisionRebind&&!o.allowEqualRevisionRebind)return;e.stagedOAuthCredentials.delete(o.domain),s.requiresEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let i={[r.name]:s.credential};n.events.emit(rm,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function VE(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();sm(e,o);let s=e.bootOAuthCredentialBuffer?.get(r);if(s)return gr(e,r),s;for(let[i,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&it(i.split("\0",1)[0]))return gr(e,i),a}function WE(t){let{config:e,pi:r,buffered:n}=t;fu.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),fu.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(rm,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function KE(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(Be(n,r)){if(n.name===r.name)return;await Lo(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 ut(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function JE(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=jE(e,r.name,o);Ve({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}: ${s instanceof Error?s.message:String(s)}`;return e.diagnostics.push({server:r.name,message:a,origin:"registry"}),new Rt(a)}async function YE(t){let{state:e,config:r,pi:n,intent:o,previousConfig:s,rollbackSnapshot:i}=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 KE({state:e,config:r,previousConfig:s})}catch(h){throw JE({state:e,config:r,intent:o,rollbackSnapshot:i,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 Ve({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let p={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,p),e.registryCredentialConfigsById.set(l,p),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),BE({state:e,config:r,pi:n,intent:o});let f=VE({state:e,domain:o.domain,serverName:r.name});return Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),f&&WE({config:r,pi:n,buffered:f}),!0}function Hr(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),s=GE({state:e,config:r});if(!s)return Promise.resolve(!1);let i=e.registryCredentialIntents.get(s.domain);if(!i||i.epoch!==s.epoch)return Promise.resolve(!1);if(i.finalization)return i.finalization;let a=DE(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 YE({state:e,config:r,pi:n,intent:s,previousConfig:d,rollbackSnapshot:a})});return e.registryCredentialFinalizationsByName.set(r.name,u),i.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 pT}from"@augmentcode/auggie-v2";import{homedir as um}from"node:os";import{sep as XE}from"node:path";var hu=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},QE=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,eT=/\\\$\{/g,tT=new Set(["workspaceFolder","augmentToken"]),dm="${workspaceFolder}";function lm(t,e){return t.includes(dm)?t.split(dm).join(e):t}function pm(t,e){return t.includes("${")?t.replace(QE,(n,o,s)=>{if(tT.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new hu(o)}).replace(eT,"${"):t}function rT(t){return t.startsWith("~")?t==="~"?um():t.startsWith("~/")||t.startsWith(`~${XE}`)?um()+t.slice(1):t:t}function mu(t,e,r){return rT(pm(lm(t,e),r))}function zi(t,e,r){return pm(lm(t,e),r)}function fm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=zi(s,e,r);return n}var nT="$augment-";function oT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(nT)?s:zi(s,e,r);return n}function Nt(t,e){let r=process.env;return{...t,url:zi(t.url,e,r),headers:oT(t.headers,e,r)}}function Dt(t,e){let r=process.env;return{...t,command:mu(t.command,e,r),args:t.args,env:t.env?fm(t.env,e,r):void 0,cwd:t.cwd?mu(t.cwd,e,r):e}}import{readFileSync as cT}from"node:fs";import{logger as sT}from"@hermes/logger";var iT=sT.child({prefix:"pi-mcp"}),Pt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function $n(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 aT(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 Mn(t,e){let r=$n(e);if(!r)throw new Pt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Pt(`MCP server "${t}" has type "${r}" but no 'url' property`);return{type:r,name:e.name??t,disabled:e.disabled,url:e.url,headers:e.headers,auth:e.auth==="oauth"?"oauth":void 0,timeoutMs:e.timeoutMs}}let n=e.command;if(!n)throw new Pt(`MCP server "${t}" has type "stdio" but no 'command' property`);let o=(e.args??[]).map(a=>String(a)),s=o.length>0?`${n} ${o.join(" ")}`:n,i=e.name??t;return e.useShellInterpolation===!1&&iT.warn(`MCP server "${i}": useShellInterpolation:false is ignored; settings.json stdio servers always shell-wrap in Wave 1 (V1 json.ts parity)`),{type:"stdio",name:i,disabled:e.disabled,command:s,args:[],env:aT(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var gm=t=>cT(t,"utf8");function Ni(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function hm(t){return Ni(t)&&("command"in t||"url"in t)}function yu(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function mm(t,e){return yu(t.name)??e}function gu(t,e){let r=$n(t);if(r==="http"||r==="sse")return yu(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return yu(t.name,t.title,n)??e}function uT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[gu(n,String(r)),n]});if(Ni(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[gu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(Ni(n))return Object.entries(n).map(([o,s])=>{let i=s;return[mm(i,o),i]})}if(hm(t)){let r=t;return[[gu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(hm))return Object.entries(t).map(([r,n])=>{if(!Ni(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[mm(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 vu(t){return t instanceof Error?t.message:String(t)}function dT(t,e,r,n,o){if(r)return e;try{return n(t)}catch(s){o.push({message:`Failed to read --mcp-config file "${t}": ${vu(s)}`});return}}function lT(t,e,r){let n=t.trim();if(n.length===0)return[];let o=n.startsWith("[")||n.startsWith("{"),s=o?"inline JSON":`file "${t}"`,i=dT(t,n,o,e,r);if(i===void 0)return[];let a;try{a=JSON.parse(i)}catch(c){return r.push({message:`Failed to parse --mcp-config ${s}: ${vu(c)}`}),[]}try{return uT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${vu(c)}`}),[]}}function _u(t,e=gm){let r={},n=[];for(let o of t)for(let[s,i]of lT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function Su(t,e=gm){return!t||t.length===0?new Set:new Set(Object.keys(_u(t,e).servers))}var fT=["global","project","local","managed"];function hT(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 mT(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 gT(t,e,r){let n=_u(t);r.push(...n.diagnostics);let o=n.servers;if(!e||e.size===0)return o;for(let[s,i]of Object.entries(o)){let a=e.get(s);a!==void 0&&(o[s]={...i,disabled:a})}return o}function yT(t,e,r){let n=pT.create(t,e);for(let{scope:o,error:s}of n.drainErrors()){let i=s.message.includes("parse settings JSON")?"parse":"read";r.push({message:`Failed to ${i} ${o} settings.json: ${s.message}`})}return mT(fT.map(o=>hT(n,o)))}function In(t,e,r,n){let o=[],s=r&&r.length>0?gT(r,n,o):yT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Mn(a,c);i.push(u.type==="stdio"?Dt(u,t):Nt(u,t))}catch(u){let d=u instanceof Pt?u.message:`Failed to normalize MCP server "${a}": ${u instanceof Error?u.message:String(u)}`;o.push({server:a,message:d})}return{servers:i,diagnostics:o}}import{setToolSource as Rm}from"@augmentcode/auggie-v2";import{logger as TT}from"@hermes/logger";import{Type as AT}from"@sinclair/typebox";var On=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;get(e){return this._tokens.get(e)}commit(e,r){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e)}set(e,r,n){this.commit(e,r)}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,s){return this.persist(e,n,o)}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,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)}}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)}delete(e,r){this._tokens.delete(e)}clearLocalCredential(e){this._tokens.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)}};var Di=Symbol.for("__pi_mcp_state__");function vT(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 _T(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function ST(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&vT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&_T(a,e)}),s=t.expectedCredentialDomains.get(r.name);if(!(!o||t.sessionRemovedConfigIds.has(e)||t.oauthCredentialDomains.has(r.name)||s?.kind!=="domain"||s.domain!==`user:${e}`)){t.equalRevisionRebindDomains.set(r.name,s.domain);for(let i of n)t.tokens.clearLocalCredential(i),t.oauthCredentialDomains.delete(i),t.credentialRevisions.delete(i),t.hostedCredentialOwnership?.delete(i),t.preservedCredentialIdentities?.delete(i),t.statusFailureCategories?.delete(i),t.authRefreshNeededReportKeys?.delete(i),t.expectedCredentialDomains.set(i,{kind:"blocked"})}}}function wT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=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 s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&ST(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&&Q(t,r,n);t.pluginReconcileQueue??=Promise.resolve(),t.mcpAttachDisabled??=!1,t.mcpAttachCloudSignaled??=!1,t.attachResolvers??=new Map,t.attachResultListenerBound??=!1,t.attachmentCommandGenerations??=new Map,t.attachmentCommandInFlightGenerations??=new Map,t.attachmentCommandAppliedGenerations??=new Map}async function jo(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 Li(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 bT(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 ym(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function ji(t){let{state:e,configId:r,generation:n,operation:o,wasApplied:s}=t;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o:o.then(i=>(s()?bT({state:e,configId:r,generation:n}):ym({state:e,configId:r,generation:n}),i),i=>{throw ym({state:e,configId:r,generation:n}),i})}function re(){let t=globalThis;if(t[Di])return wT(t[Di]),t[Di];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new On,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations: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,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,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};return t[Di]=e,e}var vm=Symbol.for("__hermes_mcp_tool_registry__"),RT=Symbol.for("__hermes_mcp_extension_factory__");function _m(){let t=globalThis;return t[vm]??=new Map,t[vm]}function yr(t){_m().set(t.name,t)}function Sm(t,e){let r=_m();(e===void 0||r.get(t)===e)&&r.delete(t)}function wm(t){Reflect.set(t,RT,!0)}function Fi(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 PT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function CT(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 xT(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
+ `).trim()}function wu(t,e,r){if(t.isError){let o=xT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=CT(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}}async function bm(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Fi(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=PT(t.params),o=await e.callTool(r,n,t.signal);return wu(o,t.serverName,r)}var kT=/[^a-zA-Z0-9_-]/g;function bu(t){return t.replace(kT,"_")}function ET(t,e){let r=bu(e),n=bu(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var vr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=ET(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=`_${bu(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Ru=TT.child({prefix:"pi-mcp"});function Ui(){return re().toolRegistrationsByPi}function Pm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=AT.Unsafe(n.inputSchema??{})}catch(c){Ru.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>re().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,p)=>bm({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(f=>f.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function Pu(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n),s=r.definitionsByName?.get(n);e.ownerByToolName.delete(n),t.unregisterTool(n),Sm(n,s),r.definitionsByName?.delete(n),$T(t,e,n,r,o)}function $T(t,e,r,n,o){let s=re();for(let[i,a]of e.byServer){if(a===n||!a.registeredNames.has(r))continue;let c=s.servers.get(i);if(c===void 0||c!==a.host||c.status!=="success"||s.serverGenerations?.get(i)!==a.generation)continue;let u=new vr(i);for(let d of c.listTools()){let{namespaced:l,collision:p}=u.put(d.name);if(p||l!==r)continue;let f=Pm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!f)return;Rm(r,"mcp"),t.registerTool(f),yr(f),a.definitionsByName??=new Map,a.definitionsByName.set(r,f),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function MT(t,e){let r=Ui(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=re().serverGenerations?.get(e.name),s=n.byServer.get(e.name);if(s?.host===e&&s.generation===o)return{registration:s,replaced:!1};if(s)for(let a of s.registeredNames)Pu(t,n,s,a);let i={generation:o,host:e,map:new vr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function Cu(t,e){let{registration:r,replaced:n}=MT(t,e),o=new Set(r.registeredNames),s=new vr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:p}=s.put(d.name);if(p){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=re();y.diagnostics.some(w=>w.server===i&&w.message.includes(`both map to "${l}"`))||(Ru.warn(m),y.diagnostics.push({server:i,message:m}));continue}let f=Pm({pi:t,serverName:i,tool:d,map:s,namespaced:l});f&&(Rm(l,"mcp"),t.registerTool(f),yr(f),r.definitionsByName??=new Map,r.definitionsByName.set(l,f),Ui().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Ui().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&Pu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Ru.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function xu(t,e,r){let n=Ui().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 s of o.registeredNames)Pu(t,n,o,s);return n.byServer.delete(e.name),!0}function Cm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&Cu(t,r)}import{getToolSource as HT}from"@augmentcode/auggie-v2";import{Type as IT}from"@sinclair/typebox";var OT="cliMcpToolSearchAutoEnable",zT="cliMcpToolSearchTokenThreshold",NT=!1,xm=2e4;function DT(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function LT(t){let e=0;for(let r of t.servers.values())e+=jT(r);return e}function jT(t){if(t.status!=="success")return 0;let e=new vr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||FT(n.inputSchema)&&(r+=DT(n))}return r}function FT(t){try{return IT.Unsafe(t??{}),!0}catch{return!1}}function UT(t){let r=t.featureFlags?.flags?.[OT];return typeof r=="boolean"?r:NT}function qT(t){let r=t.featureFlags?.flags?.[zT];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:xm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:xm}function km(t){return UT(t)?LT(t)>=qT(t):!1}var GT="AUGGIE_ENABLE_TOOL_SEARCH",ZT=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Fo(){return process.env[GT]==="1"}function zn(t){return Fo()||t.toolSearchLatched?!0:km(t)?(t.toolSearchLatched=!0,!0):!1}function qi(t){let e=t.getActiveTools(),r=e.filter(n=>!BT(n)||ZT.has(n));r.length!==e.length&&t.setActiveTools(r)}function BT(t){return HT(t)==="mcp"}import{setToolSource as zm}from"@augmentcode/auggie-v2";import{logger as pA}from"@hermes/logger";import{Type as Nm}from"@sinclair/typebox";import{logger as VT}from"@hermes/logger";var Uo={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Gr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Em=VT.child({prefix:"pi-mcp"}),WT=5e3,KT=1,JT=2,YT=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),XT=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function QT(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 eA(t){return t===KT||typeof t=="string"&&YT.has(t)?"available":t===JT||typeof t=="string"&&XT.has(t)?"opt_in_required":"unknown"}function tA(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:QT(t.auth_type),state:eA(t.state)}}function ku(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 qo(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!ku(t,r))}async function Tm(t,e,r){let n=t.apiUrl.replace(/\/+$/,""),o=e??fetch;try{let s=await o(`${n}/settings/get-mcp-catalog-metadata`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({product_type:Gr.UNSPECIFIED}),signal:AbortSignal.timeout(r??WT)});if(!s.ok)return Em.debug(`MCP catalog fetch failed with ${s.status}; treating catalog as empty`),{ok:!1,disable:s.status===404};let i=await s.json(),a=[];for(let c of i.entries??[]){let u=tA(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Em.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var rA="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",nA=`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).`,eA=/[\n\r]/g,tA=/</g,rA=/>/g;function Gr(t){return t.replace(eA," ").replace(tA,"\u2039").replace(rA,"\u203A").trim()}function nA(){let t=process.env[XT];return t?.trim()?t:QT}var oA=/\{\{(query|server_name|tool_list)\}\}/g;function xm(t,e,r){let n={"{{query}}":Gr(t),"{{server_name}}":Gr(e),"{{tool_list}}":r};return nA().replace(oA,o=>n[o]??o)}function Re(t){return{content:[{type:"text",text:t}],details:void 0}}function km(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Cu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Ui(t,e,r){let n={mcp_server:t,tools:km(e).map(Cu),note:r};return Re(JSON.stringify(n,null,2))}function Em(t){return km(t).map(e=>{let r=Gr(e.name),n=Gr(e.description??"");return`- ${r}: ${n}`}).join(`
17
- `)}function Tm(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 sA}from"@earendil-works/pi-ai";var iA="augment:tool-search-usage";function aA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Am(t,e,r){let n=e.model;if(!n)return;let o=await e.modelRegistry.getApiKeyAndHeaders(n);if(!(o.ok&&o.apiKey))return;let s={role:"user",content:[{type:"text",text:r}],timestamp:Date.now()},i=await sA(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(iA,a),aA(i)}var Om=cA.child({prefix:"pi-mcp"}),Uo="find-tool",Zr="execute-tool",uA=10,Im=15,dA=20,lA={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"]},pA={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 zm(t,e){let r=re(),n=r.servers.get(e);if(!n||n.status!=="success"){let o=t.getAllTools().map(c=>c.name),s=t.getActiveTools(),i=e.trim().toLowerCase(),a=Fo(r).find(c=>c.id===e.trim()||c.name.toLowerCase()===i);throw a&&!o.includes(e)?new Error(`MCP server "${a.name}" is available but not attached. Call attach-mcp-server now with config_id "${a.id}"; it attaches directly without requiring user approval.`):new Error(Li(e,n?.status,o,s))}return n}function fA(t){if(t==null)throw new Error(`${Zr} 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(`${Zr} "arguments" must be an object, not ${e}.`)}return t}async function hA(t,e,r,n,o){let s=xm(r,n,Em(o)),i=await Am(t,e,s);if(!i)return;let a=Tm(i);return o.find(c=>c.name===a)}async function mA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Uo} requires string "query" and "mcp_server" parameters.`);let s=zm(t,o).listTools();if(s.length===0)throw new Error(`No tools available on MCP server "${o}".`);if(s.length<=uA)return Ui(o,s,"All tools on this server.");try{let i=await hA(t,e,n,o,s);return i?Re(JSON.stringify(Cu(i),null,2)):Ui(o,s,"No single best match; all tools listed.")}catch(i){return Om.warn(`${Uo} LLM match failed: ${i instanceof Error?i.message:String(i)}`),Ui(o,s,"Search failed; all tools listed.")}}async function gA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Zr} requires string "mcp_server" and "tool_name" parameters.`);let i=fA(s),c=await zm(t,n).callTool(o,i,r);return vu(c,n,o)}function yA(){let t=re(),e=[...t.servers.values()].filter(s=>s.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 ${Zr}.`,n=[];if(e.length===0)n.push(`${r} No MCP servers are currently connected.`);else{let s=e.map(i=>{let a=i.listTools().map(d=>d.name),c=a.slice(0,Im).join(", "),u=a.length>Im?", \u2026":"";return`- ${i.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
16
+ Respond with ONLY the tool name (no markdown, no explanation).`,oA=/[\n\r]/g,sA=/</g,iA=/>/g;function Zr(t){return t.replace(oA," ").replace(sA,"\u2039").replace(iA,"\u203A").trim()}function aA(){let t=process.env[rA];return t?.trim()?t:nA}var cA=/\{\{(query|server_name|tool_list)\}\}/g;function Am(t,e,r){let n={"{{query}}":Zr(t),"{{server_name}}":Zr(e),"{{tool_list}}":r};return aA().replace(cA,o=>n[o]??o)}function Re(t){return{content:[{type:"text",text:t}],details:void 0}}function $m(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Eu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Hi(t,e,r){let n={mcp_server:t,tools:$m(e).map(Eu),note:r};return Re(JSON.stringify(n,null,2))}function Mm(t){return $m(t).map(e=>{let r=Zr(e.name),n=Zr(e.description??"");return`- ${r}: ${n}`}).join(`
17
+ `)}function Im(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 uA}from"@earendil-works/pi-ai";var dA="augment:tool-search-usage";function lA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Om(t,e,r){let n=e.model;if(!n)return;let o=await e.modelRegistry.getApiKeyAndHeaders(n);if(!(o.ok&&o.apiKey))return;let s={role:"user",content:[{type:"text",text:r}],timestamp:Date.now()},i=await uA(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(dA,a),lA(i)}var Lm=pA.child({prefix:"pi-mcp"}),Ho="find-tool",Br="execute-tool",fA=10,Dm=15,hA=20,mA={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"]},gA={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 jm(t,e){let r=re(),n=r.servers.get(e);if(!n||n.status!=="success"){let o=t.getAllTools().map(c=>c.name),s=t.getActiveTools(),i=e.trim().toLowerCase(),a=qo(r).find(c=>c.id===e.trim()||c.name.toLowerCase()===i);throw a&&!o.includes(e)?new Error(`MCP server "${a.name}" is available but not attached. Call attach-mcp-server now with config_id "${a.id}"; it attaches directly without requiring user approval.`):new Error(Fi(e,n?.status,o,s))}return n}function yA(t){if(t==null)throw new Error(`${Br} 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(`${Br} "arguments" must be an object, not ${e}.`)}return t}async function vA(t,e,r,n,o){let s=Am(r,n,Mm(o)),i=await Om(t,e,s);if(!i)return;let a=Im(i);return o.find(c=>c.name===a)}async function _A(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Ho} requires string "query" and "mcp_server" parameters.`);let s=jm(t,o).listTools();if(s.length===0)throw new Error(`No tools available on MCP server "${o}".`);if(s.length<=fA)return Hi(o,s,"All tools on this server.");try{let i=await vA(t,e,n,o,s);return i?Re(JSON.stringify(Eu(i),null,2)):Hi(o,s,"No single best match; all tools listed.")}catch(i){return Lm.warn(`${Ho} LLM match failed: ${i instanceof Error?i.message:String(i)}`),Hi(o,s,"Search failed; all tools listed.")}}async function SA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Br} requires string "mcp_server" and "tool_name" parameters.`);let i=yA(s),c=await jm(t,n).callTool(o,i,r);return wu(c,n,o)}function wA(){let t=re(),e=[...t.servers.values()].filter(s=>s.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 ${Br}.`,n=[];if(e.length===0)n.push(`${r} No MCP servers are currently connected.`);else{let s=e.map(i=>{let a=i.listTools().map(d=>d.name),c=a.slice(0,Dm).join(", "),u=a.length>Dm?", \u2026":"";return`- ${i.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
18
18
  ${s.join(`
19
- `)}`)}let o=Fo(t).slice(0,dA);if(o.length>0){let s=o.map(i=>{let a=Gr(i.description),c=i.requiresAuth?" [requires auth]":"";return`- ${i.name}${a?` \u2014 ${a}`:""}${c}`});n.push(`Available but not attached (use attach-mcp-server to enable):
19
+ `)}`)}let o=qo(t).slice(0,hA);if(o.length>0){let s=o.map(i=>{let a=Zr(i.description),c=i.requiresAuth?" [requires auth]":"";return`- ${i.name}${a?` \u2014 ${a}`:""}${c}`});n.push(`Available but not attached (use attach-mcp-server to enable):
20
20
  ${s.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 Br(t){let e={name:Uo,label:Uo,description:yA(),parameters:Mm.Unsafe(lA),execute:(n,o,s,i,a)=>mA(t,a,o)},r={name:Zr,label:Zr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:Mm.Unsafe(pA),execute:(n,o,s)=>gA(t,o,s)};$m(Uo,"mcp"),$m(Zr,"mcp"),t.registerTool(e),t.registerTool(r),gr(e),gr(r),Om.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as XF}from"@hermes/logger";import{logger as wA}from"@hermes/logger";import{logger as vA}from"@hermes/logger";function Vr(t){return new Promise(e=>setTimeout(e,t))}var Nm=vA.child({prefix:"pi-mcp"}),qo={maxTries:3,initialMs:500,mult:2,maxMs:2e3},xu=3e4,Yt=200,dt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function ku(t){return t instanceof dt?t.statusCode>=500:!0}async function Wr(t){let e;for(let r=0;r<qo.maxTries;r++)try{return await t()}catch(n){if(e=n,!ku(n))throw n;if(r<qo.maxTries-1){let o=Math.min(qo.initialMs*qo.mult**r,qo.maxMs);await Vr(o)}}throw e}var qi=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??xu}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 s=await o.text().catch(()=>""),i=s.length>Yt?`${s.slice(0,Yt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return Wr(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return Wr(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function Dm(t,e){let r=[],[n,o]=await Promise.allSettled([t.getMcpTenantConfigs(e),t.getMcpUserConfigs(e)]),s={},i={};if(n.status==="fulfilled")s=n.value;else{let a=`Failed to fetch tenant MCP configs: ${String(n.reason)}`;Nm.warn(a),r.push({message:a})}if(o.status==="fulfilled")i=o.value;else{let a=`Failed to fetch user MCP configs: ${String(o.reason)}`;Nm.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function _A(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var Lm=32;function SA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>Lm&&(e=e.slice(0,Lm)),e=e.replace(/_+$/,""),e}function jm(t,e){let r=e?SA(e):"",n=_A(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function Fm(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)}function Um(t){let e=JSON.parse(t);if(typeof e.accessToken!="string")throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:e.accessToken,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,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 Lt=wA.child({prefix:"pi-mcp"}),B=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},zn=class extends Error{},Hm=[100,500],bA=Hm.length+1,RA=t=>new Promise(e=>{setTimeout(e,t)});function qm(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Tu="augment.mcp-access-token.",PA=JSON.stringify({retired:!0}),Hi=3;function jt(t){return`${Tu}${t}`}function Gi(t){return`legacy:${t}`}function Xt(t){return t?.id?jm(t.id,t.name):void 0}function Zi(t){if(t?.id)return{type:t.type??null,id:t.id,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function vr(t){let e=Zi(t);return e?JSON.stringify(e):void 0}function CA(t){if(t)return JSON.stringify({type:t.type??null,id:t.id??null,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null})}function Au(t){if(typeof t=="string")try{return Au(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 typeof e.id!="string"||e.id.length===0?JSON.stringify(t):JSON.stringify({type:e.type??null,id:e.id,name:e.name??null,url:e.url??null,auth:e.auth??null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function xA(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function On(t){try{let e=JSON.parse(t);return{credentialIdentity:Au(e.credentialIdentity),state:xA(e)}}catch{return{}}}function Ho(t,e){let r={...t,type:"oauth",credentialIdentity:Zi(e)};return JSON.stringify(r)}function Kr(t,e){let r=Fm({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:Zi(e),credentialState:"active"})}function kA(t){return JSON.stringify({credentialIdentity:Zi(t),credentialState:"retired",retired:!0})}function EA(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=CA(e),s=Au(n.credentialIdentity);if(!(o&&s!==void 0&&s!==o)&&!(typeof n.accessToken!="string"||n.accessToken.length===0||typeof n.serverMetadata!="object"||n.serverMetadata===null||typeof n.client!="object"||n.client===null))return n}function Eu(t){try{let e=Um(t),r=e.serverMetadata,n=e.client;if(!r||!n||typeof e.accessToken!="string"||e.accessToken.length===0||typeof r.authorization_endpoint!="string"||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:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var Go=class{_memory=new Mn;_getClient;_shouldPersist;_dirtyGenerations=new Map;_durableQueues=new Map;_registryMemoryWriteGenerations=new Map;_registryMemoryAuthorities=new Map;_registryMemoryCommittedAuthorities=new Map;_delay;_nextGeneration=0;constructor(e,r,n,o=RA){this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"&&this._memory.seed(n)}get(e){return this._memory.get(e)}commit(e,r){this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}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,o)}).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r,n),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,o)});return}await this._persist(e,r,n,!1),this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}_beginRegistryMemoryWrite(e,r){let n=vr(r);if(!n)throw new B;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){this._registryMemoryWriteGenerations.get(e)!==n.generation||this._registryMemoryAuthorities.get(e)!==n.identity||this._memory.credentialRetirementGeneration(e)!==n.retirementGeneration||(this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.set(e,n.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=Xt(e),n=vr(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 B}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<Hi;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new B}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=On(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new B;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=Eu(i.value);if(!c)throw new B;try{await r.upsertUserSecret(n,Kr(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Xt(e),n=vr(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new B;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new B;let i=On(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Eu(s.value))throw new B;return s.version})}catch{throw new B}}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 s=this._getClient(),i=Xt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,Kr(r,n),o)):void 0,c=this._shouldPersist()&&s?()=>this._writeLegacyKey(e,r,!1,n):void 0;if(a)return this._drainRegistryWrites(e,a,c,void 0,n);if(n?.id||this._shouldPersist()&&!s)throw new B;if(c)return{revision:await this._asPersistenceResult(c()),domain:Gi(e)}}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,s)}async restoreAfterSupersededAuthentication(e,r,n,o,s){let i=this._getClient(),a=Xt(o),c;if(a&&o){if(!i||s?.domain!==`private:${o.id}`)throw new B;if(c=await this._enqueueWrite(a,()=>this._restoreRegistryCredential({client:i,key:a,persistedToken:r,currentToken:n,registry:o,persistedRevision:s})),!c)return}if(!this._shouldPersist())return c;if(!i)throw new B;if(a&&o){try{await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredential({client:i,key:jt(e),persistedToken:r,currentToken:n,registry:o}))}catch{Lt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return c}if(s?.domain!==Gi(e))throw new B;try{return await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredentialExact({client:i,key:jt(e),serverName:e,persistedToken:r,currentToken:n,registry:o,persistedRevision:s}))}catch{throw new B}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:s,currentToken:i,registry:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==Ho(s,a)))try{return{revision:await r.upsertUserSecret(n,Ho(i,a),c.revision),domain:Gi(o)}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i,persistedRevision:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.version!==a.revision||c.value!==Kr(o,i)))try{return{revision:await r.upsertUserSecret(n,Kr(s,i),a.revision),domain:`private:${i.id}`}}catch(u){if(this._isVersionConflict(u))return;throw u}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i}=e,a=await r.getUserSecretWithVersion(n);if(!(!a||a.value!==Ho(o,i)))try{await r.upsertUserSecret(n,Ho(s,i),a.version)}catch(c){if(!this._isVersionConflict(c))throw c}}async _drainRegistryWrites(e,r,n,o,s){let i;try{i=await r}catch{throw new B}if(o?.(),s?.id&&!i)throw new B;try{await n?.()}catch{Lt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return s?.id&&i?{revision:i,domain:`private:${s.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let s=vr(o);if(!s)throw new B;for(let i=0;i<Hi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?On(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new B;try{return await this._upsertUserSecretOnce(e,r,Kr(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new B}async _retireRegistryCredential(e,r,n){let o=vr(n);if(!o)throw new B;for(let s=0;s<Hi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?On(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new B;try{await this._upsertUserSecretOnce(e,r,kA(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new B}_isVersionConflict(e){return e instanceof dt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=Xt(n),c=a&&n&&i?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()&&i?()=>this._writeLegacyKey(e,r,o,n):void 0;if(c)return this._drainRegistryWrites(e,c,u,s,n);if(n?.id||this._shouldPersist()&&!i)throw new B;if(u)return{revision:await this._asPersistenceResult(u()),domain:Gi(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new B}}_enqueueWrite(e,r,n){let o=qm(e),s=++this._nextGeneration;n?.onGeneration?.(s);let i=this._durableQueues.get(o),a=i??{latestGeneration:s,latestMutationGeneration:n?s:0,tail:Promise.resolve()};a.latestGeneration=s,n&&(a.latestMutationGeneration=s),i||this._durableQueues.set(o,a);let c=()=>this._runPersistence(a,s,r,n),u=i?a.tail.catch(()=>{}).then(c):c();return a.tail=u,u.finally(()=>{a.latestGeneration===s&&this._durableQueues.get(o)?.tail===u&&this._durableQueues.delete(o)}).catch(()=>{}),u}async _runPersistence(e,r,n,o){let s=o?bA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new zn;try{return await n()}catch(a){this._throwIfPersistenceCanceled(e,r,o);let c=this._persistenceRetryDelay(a,i,o);if(c===void 0)throw a;await this._delay(c)}}throw new B}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new zn}_persistenceRetryDelay(e,r,n){let o=n?Hm[r]:void 0,s=!(e instanceof B)&&ku(e);if(o===void 0||!s){n&&Lt.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 s=0,i=this._enqueueWrite(jt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,jt(e),Ho(r,o));return this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e),c},{credentialShape:"legacy",operation:"write",onGeneration:a=>{s=a,this._dirtyGenerations.set(e,a)}});return i.catch(a=>{(a instanceof zn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=vr(r),s=this._registryMemoryCommittedAuthorities.get(e),i=n?.preserveNameState===!0&&(s===void 0||s!==o),a=(this._registryMemoryWriteGenerations.get(e)??0)+1;this._registryMemoryWriteGenerations.set(e,a),this._registryMemoryAuthorities.delete(e);let c=this._getClient(),u=Xt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let f=this._getClient();if(!f)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(f,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new B));let l=this._shouldPersist()&&!i,p;return l&&(c?p=this._enqueueWrite(jt(e),async()=>{let f=await c.upsertUserSecret(jt(e),PA)}):p=Promise.reject(new B)),this._awaitRetirements(e,d,p).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Lt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Lt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(s.status==="rejected")throw s.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=jt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let i=this._getClient();if(!i)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(i,n)},{credentialShape:"legacy",operation:"delete",onGeneration:i=>{o=i,this._dirtyGenerations.set(e,i)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(i=>{i instanceof zn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Xt(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(()=>{Lt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(qm(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=Xt(r),o=vr(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<Hi;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:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return{identityRejected:!1,authorityVersion:"0"};let a=On(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=Eu(i.value);if(!c)return{identityRejected:!0};if(a.credentialIdentity===o&&a.state==="active")return{identityRejected:!1,token:c};try{return await r.upsertUserSecret(n,Kr(c,s),i.version),{identityRejected:!1,token:c}}catch(u){return this._isVersionConflict(u)?void 0:{identityRejected:!0}}}async _importLegacyToken(e,r,n,o){let s=Xt(n),i=vr(n);if(!s||!i||!n||o===void 0)return;let a=await this._loadLegacyToken(e,r,n);if(a)try{return await this._enqueueWrite(s,async()=>{let c=await e.getUserSecretWithVersion(s);if((c?.version??"0")===o){if(c){let u=On(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,Kr(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(jt(r));return o?EA(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 s=this._memory.credentialRetirementGeneration(e),i=await this._loadRegistryToken(o,r);if(i.identityRejected)return;let a=i.token;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,i.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Lt.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)!==s||(this._memory.set(e,a),Lt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var Gm="Augment Code",Zm="https://augmentcode.com",Bm="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var AA=1e3,$A=500;function Mu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Zo(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var $u=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function Vm(t){return new URLSearchParams({k:t}).toString().slice(2)}function MA(t,e){let r=`${Vm(t)}:${Vm(e)}`;return`Basic ${btoa(r)}`}function Ym(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function IA(t){return t.client.token_endpoint_auth_method==="none"||!Ym(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function OA(t){return t==="basic"?"body":t==="body"?"basic":void 0}function zA(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var NA=401,Xm=500;function Iu(t,...e){return t.status<Xm&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function Wm(t){return Iu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===NA}async function Km(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 s=Ym(t);e==="basic"&&s?n.Authorization=MA(t.client.client_id,s):(o.set("client_id",t.client.client_id),e==="body"&&s&&o.set("client_secret",s));let i=await fetch(t.serverMetadata.token_endpoint,{method:"POST",headers:n,body:o.toString(),signal:AbortSignal.timeout(1e4)});if(!i.ok){let c=await i.text().catch(()=>""),u=zA(c),d=c.slice(0,$A);throw new Jr(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new $u;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*AA:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function Jm(t,e){try{return await Km(t,e,t.resource)}catch(r){if(r instanceof Jr&&t.resource&&Iu(r,"invalid_target"))return await Km(t,e,void 0);throw r}}var Jr=class t extends Error{status;statusText;body;oauthErrorCode;clientAuthPlacementsExhausted;constructor(e,r,n,o,s=!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=s}withClientAuthPlacementsExhausted(){return new t(this.status,this.statusText,this.body,this.oauthErrorCode,!0)}};function Ou(t){return!(t instanceof Jr)||t.status>=Xm?!1:Iu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function zu(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=IA(t);try{return await Jm(e,r)}catch(n){let o=OA(r);if(!(n instanceof Jr)||!o||!Wm(n))throw n;try{return await Jm(e,o)}catch(s){throw s instanceof Jr&&Wm(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as A0}from"@hermes/logger";var Lu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Lu="oauth4webapi/v3.8.6");function jn(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 Ft="ERR_INVALID_ARG_VALUE",Ke="ERR_INVALID_ARG_TYPE";function le(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var Hu=Symbol(),DA=Symbol(),LA=Symbol(),Xr=Symbol();var Qm=Symbol();var jA=new TextEncoder,FA=new TextDecoder;function ju(t){return typeof t=="string"?jA.encode(t):FA.decode(t)}var Fu;Uint8Array.prototype.toBase64?Fu=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Fu=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 Uu;Uint8Array.fromBase64?Uu=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw le("The input to be decoded is not correctly encoded.",Ft,e)}}:Uu=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 le("The input to be decoded is not correctly encoded.",Ft,e)}};function Vi(t){return typeof t=="string"?Uu(t):Fu(t)}var Dn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=v0,Error.captureStackTrace?.(this,this.constructor)}},Bo=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 I(t,e,r){return new Bo(t,{code:e,cause:r})}function Wi(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Gu(t){jn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Lu&&!e.has("user-agent")&&e.set("user-agent",Lu),e.has("authorization"))throw le('"options.headers" must not include the "authorization" header name',Ft);return e}function Zu(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw le('"options.signal" must return or be an instance of AbortSignal',Ke);return e}}function UA(t){return t.includes("//")?t.replace("//","/"):t}function qA(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=UA(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function HA(t,e,r,n){if(!(t instanceof URL))throw le(`"${e}" must be an instance of URL`,Ke);dg(t,n?.[Hu]!==!0);let o=r(new URL(t.href)),s=Gu(n?.headers);return s.set("accept","application/json"),(n?.[Xr]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:Zu(o,n?.signal)})}function Nn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw le(`${r} must be a number`,Ke,o);if(t>0)return;if(e){if(t!==0)throw le(`${r} must be a non-negative number`,Ft,o);return}throw le(`${r} must be a positive number`,Ft,o)}catch(s){throw n?I(s.message,n,o):s}}function Ee(t,e,r,n){try{if(typeof t!="string")throw le(`${e} must be a string`,Ke,n);if(t.length===0)throw le(`${e} must not be empty`,Ft,n)}catch(o){throw r?I(o.message,r,n):o}}async function rg(t,e){let r=t;if(!(r instanceof URL)&&r!==Yi)throw le('"expectedIssuerIdentifier" must be an instance of URL',Ke);if(!jn(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Qu,e);Ko(e);let n=await ta(e);if(Ee(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==Yi&&new URL(n.issuer).href!==r.href)throw I('"response" body "issuer" property does not match the expected value',Qi,{expected:r.href,body:n,attribute:"issuer"});return n}function ng(t){ZA(t,"application/json")}function GA(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 I(r,S0,t)}function ZA(t,e){if(n0(t)!==e)throw GA(t,e)}function Bu(){return Vi(crypto.getRandomValues(new Uint8Array(32)))}function og(){return Bu()}function sg(){return Bu()}function ig(){return Bu()}async function ag(t){return Ee(t,"codeVerifier"),Vi(await crypto.subtle.digest("SHA-256",ju(t)))}function Vu(t){let e=t?.[DA];return typeof e=="number"&&Number.isFinite(e)?e:0}function Wu(t){let e=t?.[LA];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Ku(){return Math.floor(Date.now()/1e3)}function Xi(t){if(typeof t!="object"||t===null)throw le('"as" must be an object',Ke);Ee(t.issuer,'"as.issuer"')}function Ju(t){if(typeof t!="object"||t===null)throw le('"client" must be an object',Ke);Ee(t.client_id,'"client.client_id"')}function eg(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 Yu(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function cg(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{let s=eg(r.client_id),i=eg(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function ug(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var BA=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function dg(t,e){if(e&&t.protocol!=="https:")throw I("only requests to HTTPS are allowed",w0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw I("only HTTP and HTTPS requests are allowed",b0,t)}function tg(t,e,r,n){let o;if(typeof t!="string"||!(o=BA(t)))throw I(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?R0:P0,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return dg(o,n),o}function lg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?tg(t.mtls_endpoint_aliases[e],e,r,n):tg(t[e],e,r,n)}var Ln=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=y0,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)}},Vo=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=_0,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)}},Wo=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=g0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ki="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",VA="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",WA='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',KA="("+Ki+")\\s*=\\s*"+WA,JA="("+Ki+")\\s*=\\s*("+Ki+")",YA=new RegExp("^[,\\s]*("+Ki+")"),XA=new RegExp("^[,\\s]*"+KA+"[,\\s]*(.*)"),QA=new RegExp("^[,\\s]*"+JA+"[,\\s]*(.*)"),e0=new RegExp("^("+VA+")(?:$|[,\\s])(.*)");function t0(t){if(!jn(t,Response))throw le('"response" must be an instance of Response',Ke);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(YA),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let p,f;if(o=n.match(XA)){if([,p,f,n]=o,f.includes("\\"))try{f=JSON.parse(`"${f}"`)}catch{}u[p.toLowerCase()]=f;continue}if(o=n.match(QA)){[,p,f,n]=o,u[p.toLowerCase()]=f;continue}if(o=n.match(e0)){if(Object.keys(u).length)break;[,d,n]=o;break}return}else n=i||void 0;let l={scheme:s,parameters:u};d&&(l.token68=d),r.push(l)}if(r.length)return r}async function r0(t){if(t.status>399&&t.status<500){Ko(t),ng(t);try{let e=await t.clone().json();if(Wi(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function pg(t,e,r){if(t.status!==e){a0(t);let n;throw(n=await r0(t))?(await t.body?.cancel(),new Ln("server responded with an error in the response body",{cause:n,response:t})):I(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Qu,t)}}function fg(t){if(!Xu.has(t))throw le('"options.DPoP" is not a valid DPoPHandle',Ft)}function n0(t){return t.headers.get("content-type")?.split(";")[0]}async function o0(t,e,r,n,o,s,i){return await r(t,e,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(i?.[Xr]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Zu(n,i?.signal)})}async function s0(t,e,r,n,o,s){let i=lg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[Hu]!==!0);o.set("grant_type",n);let a=Gu(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(fg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await o0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var hg=new WeakMap,i0=new WeakMap;function mg(t){if(!t.id_token)return;let e=hg.get(t);if(!e)throw le('"ref" was already garbage collected or did not resolve from the proper sources',Ft);return e}async function gg(t,e,r,n,o,s){if(Xi(t),Ju(e),!jn(r,Response))throw le('"response" must be an instance of Response',Ke);await pg(r,200,"Token Endpoint"),Ko(r);let i=await ta(r);if(Ee(i.access_token,'"response" body "access_token" property',V,{body:i}),Ee(i.token_type,'"response" body "token_type" property',V,{body:i}),i.token_type=i.token_type.toLowerCase(),i.expires_in!==void 0){let a=typeof i.expires_in!="number"?parseFloat(i.expires_in):i.expires_in;Nn(a,!0,'"response" body "expires_in" property',V,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ee(i.refresh_token,'"response" body "refresh_token" property',V,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw I('"response" body "scope" property must be a string',V,{body:i});if(i.id_token!==void 0){Ee(i.id_token,'"response" body "id_token" property',V,{body:i});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Nn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await C0(i.id_token,x0.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Vu(e),Wu(e),o).then(f0.bind(void 0,a)).then(u0.bind(void 0,t)).then(c0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw I('ID Token "aud" (audience) claim includes additional untrusted audiences',_r,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw I('unexpected ID Token "azp" (authorized party) claim value',_r,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Nn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),i0.set(r,u),hg.set(i,c)}if(s?.[i.token_type]!==void 0)s[i.token_type](r,i);else if(i.token_type!=="dpop"&&i.token_type!=="bearer")throw new Dn("unsupported `token_type` value",{cause:{body:i}});return i}function a0(t){let e;if(e=t0(t))throw new Wo("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function c0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw I('unexpected JWT "aud" (audience) claim value',_r,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw I('unexpected JWT "aud" (audience) claim value',_r,{expected:t,claims:e.claims,claim:"aud"});return e}function u0(t,e){let r=t[T0]?.(e)??t.issuer;if(e.claims.iss!==r)throw I('unexpected JWT "iss" (issuer) claim value',_r,{expected:r,claims:e.claims,claim:"iss"});return e}var Xu=new WeakSet;function d0(t){return Xu.add(t),t}var l0=Symbol();async function yg(t,e,r,n,o,s,i){if(Xi(t),Ju(e),!Xu.has(n))throw le('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ft);Ee(o,'"redirectUri"');let a=Yr(n,"code");if(!a)throw I('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==l0&&(Ee(s,'"codeVerifier"'),c.set("code_verifier",s)),s0(t,e,r,"authorization_code",c,i)}var p0={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 f0(t,e){for(let r of t)if(e.claims[r]===void 0)throw I(`JWT "${r}" (${p0[r]}) claim missing`,V,{claims:e.claims});return e}var Nu=Symbol(),Du=Symbol();async function vg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?h0(t,e,r,n.expectedNonce,n.maxAge,n[Qm],n.recognizedTokenTypes):m0(t,e,r,n?.[Qm],n?.recognizedTokenTypes)}async function h0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=Nu;break;case Nu:break;default:Ee(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Du;break;case Du:break;default:Nn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await gg(t,e,r,a,s,i);Ee(c.id_token,'"response" body "id_token" property',V,{body:c});let u=mg(c);if(o!==Du){let d=Ku()+Vu(e),l=Wu(e);if(u.auth_time+o<d-l)throw I("too much time has elapsed since the last End-User authentication",Ji,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===Nu){if(u.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',_r,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw I('unexpected ID Token "nonce" claim value',_r,{expected:n,claims:u,claim:"nonce"});return c}async function m0(t,e,r,n,o){let s=await gg(t,e,r,void 0,n,o),i=mg(s);if(i){if(e.default_max_age!==void 0){Nn(e.default_max_age,!0,'"client.default_max_age"');let a=Ku()+Vu(e),c=Wu(e);if(i.auth_time+e.default_max_age<a-c)throw I("too much time has elapsed since the last End-User authentication",Ji,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',_r,{expected:void 0,claims:i,claim:"nonce"})}return s}var g0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",y0="OAUTH_RESPONSE_BODY_ERROR",v0="OAUTH_UNSUPPORTED_OPERATION",_0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var qu="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var S0="OAUTH_RESPONSE_IS_NOT_JSON",Qu="OAUTH_RESPONSE_IS_NOT_CONFORM",w0="OAUTH_HTTP_REQUEST_FORBIDDEN",b0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Ji="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",_r="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Qi="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var R0="OAUTH_MISSING_SERVER_METADATA",P0="OAUTH_INVALID_SERVER_METADATA";function Ko(t){if(t.bodyUsed)throw le('"response" body has been used already',Ft)}async function C0(t,e,r,n,o){let{0:s,1:i,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:s,1:i,length:a}=t.split(".");else throw new Dn("JWE decryption is not configured",{cause:t});if(a!==3)throw I("Invalid JWT",V,t);let c;try{c=JSON.parse(ju(Vi(s)))}catch(l){throw I("failed to parse JWT Header body as base64url encoded JSON",qu,l)}if(!Wi(c))throw I("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new Dn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(ju(Vi(i)))}catch(l){throw I("failed to parse JWT Payload body as base64url encoded JSON",qu,l)}if(!Wi(u))throw I("JWT Payload must be a top level object",V,t);let d=Ku()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw I('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw I('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Ji,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw I('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw I('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw I('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw I('unexpected JWT "nbf" (not before) claim value',Ji,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw I('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function x0(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw I('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw I('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 I('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw I('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Yr(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw I(`"${e}" parameter must be provided only once`,V);return r}var k0=Symbol(),E0=Symbol();function _g(t,e,r,n){if(Xi(t),Ju(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw le('"parameters" must be an instance of URLSearchParams, or URL',Ke);if(Yr(r,"response"))throw I('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=Yr(r,"iss"),s=Yr(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw I('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw I('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case E0:if(s!==void 0)throw I('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case k0:break;default:if(Ee(n,'"expectedState" argument'),s!==n)throw I(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(Yr(r,"error"))throw new Vo("authorization response from the server is an error",{cause:r});let a=Yr(r,"id_token"),c=Yr(r,"token");if(a!==void 0||c!==void 0)throw new Dn("implicit and hybrid flows are not supported");return d0(new URLSearchParams(r))}async function Sg(t,e,r){Xi(t);let n=lg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[Hu]!==!0),o=Gu(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(fg(r.DPoP),await r.DPoP.addProof(n,o,s,r.initialAccessToken)),r?.initialAccessToken&&o.set("authorization",`${o.has("dpop")?"DPoP":"Bearer"} ${r.initialAccessToken}`);let i=await(r?.[Xr]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:Zu(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function wg(t){if(!jn(t,Response))throw le('"response" must be an instance of Response',Ke);await pg(t,201,"Dynamic Client Registration Endpoint"),Ko(t);let e=await ta(t);return Ee(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&Ee(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&Nn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function bg(t,e){return HA(t,"resourceIdentifier",r=>(qA(r,".well-known/oauth-protected-resource",!0),r),e)}async function ea(t,e){let r=t;if(!(r instanceof URL)&&r!==Yi)throw le('"expectedResourceIdentifier" must be an instance of URL',Ke);if(!jn(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',Qu,e);Ko(e);let n=await ta(e);if(Ee(n.resource,'"response" body "resource" property',V,{body:n}),r!==Yi&&new URL(n.resource).href!==r.href)throw I('"response" body "resource" property does not match the expected value',Qi,{expected:r.href,body:n,attribute:"resource"});return n}async function ta(t,e=ng){let r;try{r=await t.json()}catch(n){throw e(t),I('failed to parse "response" body as JSON',qu,n)}if(!Wi(r))throw I('"response" body must be a top level object',V,{body:r});return r}var Yi=Symbol(),T0=Symbol();var Cg=A0.child({prefix:"pi-mcp"}),Jo=1e4,$0=1e3,M0=401,Rg=200,I0=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,O0=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,xg;function Fn(){return xg??globalThis.fetch}function kg(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Eg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function td(t){let e=Eg(t);try{let r=await z0(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await F0(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ra(r)}throw new Error("Failed to discover metadata URL")}async function z0(t){try{let e=await bg(t,{signal:AbortSignal.timeout(Jo),[Xr]:xg??void 0});return e.ok?await ea(t,e):(e.body?.cancel().catch(()=>{}),await Tg(t,e.headers.get("www-authenticate"))??await Pg(t))}catch{return await Pg(t)}}async function Pg(t){for(let e of["HEAD","GET"])try{let r=await Fn()(t,{method:e,signal:AbortSignal.timeout(Jo)});r.body?.cancel().catch(()=>{});let n=await Tg(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Tg(t,e){let r=j0(e);if(r)try{let n=await Fn()(r,{signal:AbortSignal.timeout(Jo)});return await N0(t,n)}catch{return}}async function N0(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await ea(t,new Response(r,n))}catch(o){if(!(o instanceof Bo)||o.code!==Qi)throw o;let s=D0(r);if(!s||!L0(s,t))throw o;return await ea(s,new Response(r,n))}}function D0(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function L0(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 j0(t){if(!t)return;let e=t.match(I0),r=t.match(O0),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function F0(t){for(let e of U0(t))try{let r=new URL(e,t),n=await Fn()(r,{signal:AbortSignal.timeout(Jo)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function U0(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 rd(t){try{let e=await Fn()(t,{signal:AbortSignal.timeout(Jo)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await q0(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await rg(o,new Response(r,n))}catch(e){throw ra(e)}}async function q0(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 ed=class extends Error{issuer;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 H0(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 nd({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return H0({...t,clientId:n});if(!e.registration_endpoint)throw new ed(e.issuer);return await G0(e,r)}async function G0(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Sg(t,{client_name:Gm,client_uri:Zm,logo_uri:Bm,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[Xr]:Z0});return n.ok||Cg.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await wg(n)}catch(r){throw ra(r)}}async function Z0(t,e){let r=await Fn()(t,kg(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Cg.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${V0(n)}`),r.status===200&&(o.status=201,o.statusText="Created"),o.status===201)try{let s=JSON.parse(n);s.client_secret_expires_at||(s.client_secret_expires_at=0),"client_secret"in s&&!s.client_secret&&(s.client_secret=void 0),n=JSON.stringify(s)}catch{}return new Response(n,o)}function B0(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}),Fn()(t,kg(o))}function V0(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>Rg?`${t.slice(0,Rg)}\u2026`:t}}async function od(t,e,r,n,o,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let i=og(),a=await ag(i),c=sg(),u,d=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean).join(" ")||void 0,l=Eg(s??t).toString(),p=new URL(r.authorization_endpoint);return p.searchParams.set("response_type","code"),p.searchParams.set("client_id",e.client_id),p.searchParams.set("code_challenge",a),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("redirect_uri",n),p.searchParams.set("resource",l),p.searchParams.set("state",c),d&&p.searchParams.set("scope",d),r.code_challenge_methods_supported?.includes("S256")||(u=ig(),p.searchParams.set("nonce",u)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:i,nonce:u,scope:d,state:c,resource:l,authUri:p}}async function W0(t,e,r){let n=await yg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[Xr]:B0,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return vg(t.serverMetadata,t.client,await K0(n))}async function sd(t,e){try{let r=_g(e.serverMetadata,e.client,t,e.state),n=await Y0(e.client,o=>W0(e,r,o));return e$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ra(r)}}async function K0(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 Ag(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function J0(t){let e=Ag(t);return e===void 0?ug():t.token_endpoint_auth_method==="client_secret_basic"?cg(e):Yu(e)}async function Y0(t,e){try{return await e(J0(t))}catch(r){let n=X0(t);if(n&&Q0(r))return await e(n);throw r}}function X0(t){let e=Ag(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return Yu(e)}function Q0(t){return t instanceof Ln?t.error==="invalid_client"||t.error==="unauthorized":t instanceof Wo?t.status===M0||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function e$(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*$0:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ra(t){if(t instanceof Ln||t instanceof Vo){let e=t.error_description?` (${t.error_description})`:"";return new Error(`${t.message}${e}`,{cause:t})}return t instanceof Error?t:new Error(String(t))}var t$=/(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,$g=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,Mg=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,Ig=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Yo="[redacted]";function r$(t){return $g.test(t)||Mg.test(t)||Ig.test(t)}var n$=new RegExp($g.source,"g"),o$=new RegExp(Mg.source,"gi"),s$=new RegExp(Ig.source,"g");function Og(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function ad(t){return t&&Og(t,8192).replace(n$,Yo).replace(o$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Yo}`).replace(s$,Yo)}function id(t,e,r){if(e)return Yo;if(typeof t=="string")return r$(t)?Yo:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>id(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=id(s,t$.test(o),r+1);return n}function zg(t,e=500){if(t==null)return;let r=id(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return Og(n,e)}var Dg={reportError:()=>{}},Ng=Symbol.for("__pi_mcp_error_reporter_slot__");function Lg(){let t=globalThis,e=t[Ng];return e||(e={reporter:null},t[Ng]=e),e}function jg(t){let e=Lg(),r=e.reporter??Dg;return e.reporter=t,r}function i$(){return Lg().reporter??Dg}function cd(t,e){try{i$().reportError(t,e)}catch{}}import{logger as a$}from"@hermes/logger";var ud=a$.child({prefix:"pi-mcp"});function Fg(t,e,r){let n=0,o=0,s=r?.authoritative?{}:{...t.headerSecrets};for(let[i,a]of Object.entries(e))typeof a=="string"&&a!==""?(s[i]=a,n++):a===null||a===""?i in s&&(delete s[i],o++):ud.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];ud.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function Ug(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Tu)){let o=t.headerSecrets[e];if(o!==void 0)return o;let s=t.headerSecretFailures[e];if(s==="missing"||s==="permission_denied")return{reason:s}}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 qg(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[s,i]of Object.entries(e))(i==="missing"||i==="permission_denied"||i==="transient")&&(n[s]=i,delete o[s]);t.headerSecrets=o,t.headerSecretFailures=n,ud.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function Hg(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as c$}from"@hermes/logger";var Xo=c$.child({prefix:"pi-mcp"}),u$="$augment-",Qo=/\$augment-[a-zA-Z0-9_.-]+/g,d$=new RegExp(Qo.source);function na(t){return d$.test(t)}function oa(t){return t.slice(u$.length)}function dd(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(Qo))e.add(oa(n[0]));return[...e].sort()}var l$=["permission_denied","missing","transient"];function Gg(t){let e=new Set(t);return l$.find(r=>e.has(r))??"missing"}var lt=class extends Error{serverName;missingKeys;reason;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 Zg(t,e,r,n,o,s,i){let a=[...t.matchAll(Qo)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,p=oa(d);try{let f=await r(p);if(f===void 0||typeof f=="object"){n.add(p),s.set(p,f===void 0?"missing":f.reason),Xo.warn(`Secret "${p}" unavailable for "${e}"; leaving reference as-is`);continue}let h=f;h.trim()===""&&(o.add(p),Xo.warn(`Secret "${p}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),Xo.debug(`Resolved secret reference for "${e}"`)}catch(f){n.add(p),s.set(p,"transient"),Xo.error(`Failed to resolve secret "${p}" for "${e}" (${f instanceof Error?f.name:"non-Error"}); leaving reference as-is`)}}return c}async function Bg({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set,i=new Map;for(let[a,c]of Object.entries(t)){if(!na(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){Xo.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await Zg(c,a,r,o,s,i)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var p$=/["$`\\]/g;function f$(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 h$(t,e){let r=f$(e);if(r==="double")return t.replace(p$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function Vg(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await Zg(t,"command",e,r,n,o,h$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as WF}from"node:async_hooks";var Wg,ld=Object.freeze({status:"aborted"});function v(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let p=d[l];p in a||(a[p]=u[p].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Un=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Wg=globalThis).__zod_globalConfig??(Wg.__zod_globalConfig={});var qn=globalThis.__zod_globalConfig;function Je(t){return t&&Object.assign(qn,t),qn}var U={};iu(U,{BIGINT_FORMAT_RANGES:()=>Xg,Class:()=>fd,NUMBER_FORMAT_RANGES:()=>_d,aborted:()=>br,allowsEval:()=>gd,assert:()=>_$,assertEqual:()=>m$,assertIs:()=>y$,assertNever:()=>v$,assertNotEqual:()=>g$,assignProp:()=>Sr,base64ToUint8Array:()=>ey,base64urlToUint8Array:()=>N$,cached:()=>Gn,captureStackTrace:()=>aa,cleanEnum:()=>z$,cleanRegex:()=>ns,clone:()=>pt,cloneDef:()=>w$,createTransparentProxy:()=>k$,defineLazy:()=>Y,esc:()=>ia,escapeRegex:()=>er,explicitlyAborted:()=>Sd,extend:()=>A$,finalizeIssue:()=>ft,floatSafeRemainder:()=>hd,getElementAtPath:()=>b$,getEnumValues:()=>ts,getLengthableOrigin:()=>os,getParsedType:()=>x$,getSizableOrigin:()=>Qg,hexToUint8Array:()=>L$,isObject:()=>Qr,isPlainObject:()=>wr,issue:()=>Zn,joinValues:()=>sa,jsonStringifyReplacer:()=>Hn,merge:()=>M$,mergeDefs:()=>Qt,normalizeParams:()=>A,nullish:()=>rs,numKeys:()=>C$,objectClone:()=>S$,omit:()=>T$,optionalKeys:()=>vd,parsedType:()=>wd,partial:()=>I$,pick:()=>E$,prefixIssues:()=>tr,primitiveTypes:()=>Yg,promiseAllObject:()=>R$,propertyKeyTypes:()=>yd,randomString:()=>P$,required:()=>O$,safeExtend:()=>$$,shallowClone:()=>Jg,slugify:()=>md,stringifyPrimitive:()=>ca,uint8ArrayToBase64:()=>ty,uint8ArrayToBase64url:()=>D$,uint8ArrayToHex:()=>j$,unwrapMessage:()=>es});function m$(t){return t}function g$(t){return t}function y$(t){}function v$(t){throw new Error("Unexpected value in exhaustive check")}function _$(t){}function ts(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 sa(t,e="|"){return t.map(r=>ca(r)).join(e)}function Hn(t,e){return typeof e=="bigint"?e.toString():e}function Gn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function rs(t){return t==null}function ns(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function hd(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 Kg=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Kg)return n===void 0&&(n=Kg,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function S$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Sr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Qt(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function w$(t){return Qt(t._zod.def)}function b$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function R$(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function P$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ia(t){return JSON.stringify(t)}function md(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var aa="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Qr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var gd=Gn(()=>{if(qn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function wr(t){if(Qr(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Qr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Jg(t){return wr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function C$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var x$=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}`)}},yd=new Set(["string","number","symbol"]),Yg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function er(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function A(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 k$(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},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 ca(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function vd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var _d={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]},Xg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function E$(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 s=Qt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return Sr(this,"shape",i),i},checks:[]});return pt(t,s)}function T$(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 s=Qt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Sr(this,"shape",i),i},checks:[]});return pt(t,s)}function A$(t,e){if(!wr(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Sr(this,"shape",s),s}});return pt(t,o)}function $$(t,e){if(!wr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Qt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Sr(this,"shape",n),n}});return pt(t,r)}function M$(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=Qt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Sr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function I$(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 i=Qt(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 Sr(this,"shape",c),c},checks:[]});return pt(e,i)}function O$(t,e,r){let n=Qt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Sr(this,"shape",s),s}});return pt(e,n)}function br(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 Sd(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 tr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function es(t){return typeof t=="string"?t:t?.message}function ft(t,e,r){let n=t.message?t.message:es(t.inst?._zod.def?.error?.(t))??es(e?.error?.(t))??es(r.customError?.(t))??es(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function Qg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function os(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function wd(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 Zn(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function z$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function ey(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 ty(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function N$(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return ey(e+r)}function D$(t){return ty(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function L$(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 j$(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var fd=class{constructor(...e){}};var ry=(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,Hn,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ua=v("$ZodError",ry),bd=v("$ZodError",ry,{Parent:Error});function Rd(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 Pd(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));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(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return n(t),r}var da=t=>(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ut;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ft(c,s,Je())));throw aa(a,o?.callee),a}return i.value};var la=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ft(c,s,Je())));throw aa(a,o?.callee),a}return i.value};var ss=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(t??ua)(s.issues.map(i=>ft(i,o,Je())))}:{success:!0,data:s.value}},is=ss(bd),as=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ft(i,o,Je())))}:{success:!0,data:s.value}},pa=as(bd),ny=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return da(t)(e,r,o)};var oy=t=>(e,r,n)=>da(t)(e,r,n);var sy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return la(t)(e,r,o)};var iy=t=>async(e,r,n)=>la(t)(e,r,n);var ay=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ss(t)(e,r,o)};var cy=t=>(e,r,n)=>ss(t)(e,r,n);var uy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return as(t)(e,r,o)};var dy=t=>async(e,r,n)=>as(t)(e,r,n);var ly=/^[cC][0-9a-z]{6,}$/,py=/^[0-9a-z]+$/,fy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,hy=/^[0-9a-vA-V]{20}$/,my=/^[A-Za-z0-9]{27}$/,gy=/^[a-zA-Z0-9_-]{21}$/,yy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var vy=/^([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})$/,Cd=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 _y=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var U$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Sy(){return new RegExp(U$,"u")}var wy=/^(?:(?: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])$/,by=/^(([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 Ry=/^((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])$/,Py=/^(([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])$/,Cy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xd=/^[A-Za-z0-9_-]*$/;var xy=/^https?$/,ky=/^\+[1-9]\d{6,14}$/,Ey="(?:(?:\\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])))",Ty=new RegExp(`^${Ey}$`);function Ay(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 $y(t){return new RegExp(`^${Ay(t)}$`)}function My(t){let e=Ay({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(`^${Ey}T(?:${n})$`)}var Iy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Oy=/^-?\d+n?$/,zy=/^-?\d+$/,kd=/^-?\d+(?:\.\d+)?$/,Ny=/^(?:true|false)$/i,Dy=/^null$/i;var Ly=/^[^A-Z]*$/,jy=/^[^a-z]*$/;var Te=v("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Fy={number:"number",bigint:"bigint",object:"date"},Ed=v("$ZodCheckLessThan",(t,e)=>{Te.init(t,e);let r=Fy[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(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})}}),Td=v("$ZodCheckGreaterThan",(t,e)=>{Te.init(t,e);let r=Fy[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(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})}}),Uy=v("$ZodCheckMultipleOf",(t,e)=>{Te.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):hd(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})}}),qy=v("$ZodCheckNumberFormat",(t,e)=>{Te.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=_d[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=zy)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.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}):i.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&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Hy=v("$ZodCheckMaxLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!rs(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 i=os(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Gy=v("$ZodCheckMinLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!rs(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 i=os(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Zy=v("$ZodCheckLengthEquals",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!rs(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,s=o.length;if(s===e.length)return;let i=os(o),a=s>e.length;n.issues.push({origin:i,...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})}}),us=v("$ZodCheckStringFormat",(t,e)=>{var r,n;Te.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.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=()=>{})}),By=v("$ZodCheckRegex",(t,e)=>{us.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})}}),Vy=v("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ly),us.init(t,e)}),Wy=v("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=jy),us.init(t,e)}),Ky=v("$ZodCheckIncludes",(t,e)=>{Te.init(t,e);let r=er(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),Jy=v("$ZodCheckStartsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`^${er(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})}}),Yy=v("$ZodCheckEndsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`.*${er(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 Xy=v("$ZodCheckOverwrite",(t,e)=>{Te.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var fa=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 Vr(t){let e={name:Ho,label:Ho,description:wA(),parameters:Nm.Unsafe(mA),execute:(n,o,s,i,a)=>_A(t,a,o)},r={name:Br,label:Br,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:Nm.Unsafe(gA),execute:(n,o,s)=>SA(t,o,s)};zm(Ho,"mcp"),zm(Br,"mcp"),t.registerTool(e),t.registerTool(r),yr(e),yr(r),Lm.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as rU}from"@hermes/logger";import{logger as CA}from"@hermes/logger";import{logger as bA}from"@hermes/logger";function Wr(t){return new Promise(e=>setTimeout(e,t))}var Fm=bA.child({prefix:"pi-mcp"}),Go={maxTries:3,initialMs:500,mult:2,maxMs:2e3},Tu=3e4,Yt=200,dt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function Au(t){return t instanceof dt?t.statusCode>=500:!0}async function Kr(t){let e;for(let r=0;r<Go.maxTries;r++)try{return await t()}catch(n){if(e=n,!Au(n))throw n;if(r<Go.maxTries-1){let o=Math.min(Go.initialMs*Go.mult**r,Go.maxMs);await Wr(o)}}throw e}var Gi=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??Tu}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 s=await o.text().catch(()=>""),i=s.length>Yt?`${s.slice(0,Yt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return Kr(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return Kr(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function Um(t,e){let r=[],[n,o]=await Promise.allSettled([t.getMcpTenantConfigs(e),t.getMcpUserConfigs(e)]),s={},i={};if(n.status==="fulfilled")s=n.value;else{let a=`Failed to fetch tenant MCP configs: ${String(n.reason)}`;Fm.warn(a),r.push({message:a})}if(o.status==="fulfilled")i=o.value;else{let a=`Failed to fetch user MCP configs: ${String(o.reason)}`;Fm.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function RA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var qm=32;function PA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>qm&&(e=e.slice(0,qm)),e=e.replace(/_+$/,""),e}function Hm(t,e){let r=e?PA(e):"",n=RA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function Gm(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)}function Zm(t){let e=JSON.parse(t);if(typeof e.accessToken!="string")throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:e.accessToken,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,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 Lt=CA.child({prefix:"pi-mcp"}),B=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},Dn=class extends Error{},Vm=[100,500],xA=Vm.length+1,kA=t=>new Promise(e=>{setTimeout(e,t)});function Bm(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Mu="augment.mcp-access-token.",EA=JSON.stringify({retired:!0}),Zi=3;function jt(t){return`${Mu}${t}`}function Bi(t){return`legacy:${t}`}function Xt(t){return t?.id?Hm(t.id,t.name):void 0}function Vi(t){if(t?.id)return{type:t.type??null,id:t.id,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function _r(t){let e=Vi(t);return e?JSON.stringify(e):void 0}function TA(t){if(t)return JSON.stringify({type:t.type??null,id:t.id??null,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null})}function Iu(t){if(typeof t=="string")try{return Iu(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 typeof e.id!="string"||e.id.length===0?JSON.stringify(t):JSON.stringify({type:e.type??null,id:e.id,name:e.name??null,url:e.url??null,auth:e.auth??null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function AA(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function Nn(t){try{let e=JSON.parse(t);return{credentialIdentity:Iu(e.credentialIdentity),state:AA(e)}}catch{return{}}}function Zo(t,e){let r={...t,type:"oauth",credentialIdentity:Vi(e)};return JSON.stringify(r)}function Jr(t,e){let r=Gm({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:Vi(e),credentialState:"active"})}function $A(t){return JSON.stringify({credentialIdentity:Vi(t),credentialState:"retired",retired:!0})}function MA(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=TA(e),s=Iu(n.credentialIdentity);if(!(o&&s!==void 0&&s!==o)&&!(typeof n.accessToken!="string"||n.accessToken.length===0||typeof n.serverMetadata!="object"||n.serverMetadata===null||typeof n.client!="object"||n.client===null))return n}function $u(t){try{let e=Zm(t),r=e.serverMetadata,n=e.client;if(!r||!n||typeof e.accessToken!="string"||e.accessToken.length===0||typeof r.authorization_endpoint!="string"||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:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var Bo=class{_memory=new On;_getClient;_shouldPersist;_dirtyGenerations=new Map;_durableQueues=new Map;_registryMemoryWriteGenerations=new Map;_registryMemoryAuthorities=new Map;_registryMemoryCommittedAuthorities=new Map;_delay;_nextGeneration=0;constructor(e,r,n,o=kA){this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"&&this._memory.seed(n)}get(e){return this._memory.get(e)}commit(e,r){this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}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,o)}).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r,n),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,o)});return}await this._persist(e,r,n,!1),this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}_beginRegistryMemoryWrite(e,r){let n=_r(r);if(!n)throw new B;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){this._registryMemoryWriteGenerations.get(e)!==n.generation||this._registryMemoryAuthorities.get(e)!==n.identity||this._memory.credentialRetirementGeneration(e)!==n.retirementGeneration||(this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.set(e,n.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=Xt(e),n=_r(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 B}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<Zi;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new B}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=Nn(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new B;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=$u(i.value);if(!c)throw new B;try{await r.upsertUserSecret(n,Jr(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Xt(e),n=_r(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new B;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new B;let i=Nn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!$u(s.value))throw new B;return s.version})}catch{throw new B}}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 s=this._getClient(),i=Xt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,Jr(r,n),o)):void 0,c=this._shouldPersist()&&s?()=>this._writeLegacyKey(e,r,!1,n):void 0;if(a)return this._drainRegistryWrites(e,a,c,void 0,n);if(n?.id||this._shouldPersist()&&!s)throw new B;if(c)return{revision:await this._asPersistenceResult(c()),domain:Bi(e)}}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,s)}async restoreAfterSupersededAuthentication(e,r,n,o,s){let i=this._getClient(),a=Xt(o),c;if(a&&o){if(!i||s?.domain!==`private:${o.id}`)throw new B;if(c=await this._enqueueWrite(a,()=>this._restoreRegistryCredential({client:i,key:a,persistedToken:r,currentToken:n,registry:o,persistedRevision:s})),!c)return}if(!this._shouldPersist())return c;if(!i)throw new B;if(a&&o){try{await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredential({client:i,key:jt(e),persistedToken:r,currentToken:n,registry:o}))}catch{Lt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return c}if(s?.domain!==Bi(e))throw new B;try{return await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredentialExact({client:i,key:jt(e),serverName:e,persistedToken:r,currentToken:n,registry:o,persistedRevision:s}))}catch{throw new B}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:s,currentToken:i,registry:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==Zo(s,a)))try{return{revision:await r.upsertUserSecret(n,Zo(i,a),c.revision),domain:Bi(o)}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i,persistedRevision:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.version!==a.revision||c.value!==Jr(o,i)))try{return{revision:await r.upsertUserSecret(n,Jr(s,i),a.revision),domain:`private:${i.id}`}}catch(u){if(this._isVersionConflict(u))return;throw u}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i}=e,a=await r.getUserSecretWithVersion(n);if(!(!a||a.value!==Zo(o,i)))try{await r.upsertUserSecret(n,Zo(s,i),a.version)}catch(c){if(!this._isVersionConflict(c))throw c}}async _drainRegistryWrites(e,r,n,o,s){let i;try{i=await r}catch{throw new B}if(o?.(),s?.id&&!i)throw new B;try{await n?.()}catch{Lt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return s?.id&&i?{revision:i,domain:`private:${s.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let s=_r(o);if(!s)throw new B;for(let i=0;i<Zi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?Nn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new B;try{return await this._upsertUserSecretOnce(e,r,Jr(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new B}async _retireRegistryCredential(e,r,n){let o=_r(n);if(!o)throw new B;for(let s=0;s<Zi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?Nn(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new B;try{await this._upsertUserSecretOnce(e,r,$A(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new B}_isVersionConflict(e){return e instanceof dt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=Xt(n),c=a&&n&&i?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()&&i?()=>this._writeLegacyKey(e,r,o,n):void 0;if(c)return this._drainRegistryWrites(e,c,u,s,n);if(n?.id||this._shouldPersist()&&!i)throw new B;if(u)return{revision:await this._asPersistenceResult(u()),domain:Bi(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new B}}_enqueueWrite(e,r,n){let o=Bm(e),s=++this._nextGeneration;n?.onGeneration?.(s);let i=this._durableQueues.get(o),a=i??{latestGeneration:s,latestMutationGeneration:n?s:0,tail:Promise.resolve()};a.latestGeneration=s,n&&(a.latestMutationGeneration=s),i||this._durableQueues.set(o,a);let c=()=>this._runPersistence(a,s,r,n),u=i?a.tail.catch(()=>{}).then(c):c();return a.tail=u,u.finally(()=>{a.latestGeneration===s&&this._durableQueues.get(o)?.tail===u&&this._durableQueues.delete(o)}).catch(()=>{}),u}async _runPersistence(e,r,n,o){let s=o?xA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new Dn;try{return await n()}catch(a){this._throwIfPersistenceCanceled(e,r,o);let c=this._persistenceRetryDelay(a,i,o);if(c===void 0)throw a;await this._delay(c)}}throw new B}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new Dn}_persistenceRetryDelay(e,r,n){let o=n?Vm[r]:void 0,s=!(e instanceof B)&&Au(e);if(o===void 0||!s){n&&Lt.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 s=0,i=this._enqueueWrite(jt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,jt(e),Zo(r,o));return this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e),c},{credentialShape:"legacy",operation:"write",onGeneration:a=>{s=a,this._dirtyGenerations.set(e,a)}});return i.catch(a=>{(a instanceof Dn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=_r(r),s=this._registryMemoryCommittedAuthorities.get(e),i=n?.preserveNameState===!0&&(s===void 0||s!==o),a=(this._registryMemoryWriteGenerations.get(e)??0)+1;this._registryMemoryWriteGenerations.set(e,a),this._registryMemoryAuthorities.delete(e);let c=this._getClient(),u=Xt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let f=this._getClient();if(!f)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(f,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new B));let l=this._shouldPersist()&&!i,p;return l&&(c?p=this._enqueueWrite(jt(e),async()=>{let f=await c.upsertUserSecret(jt(e),EA)}):p=Promise.reject(new B)),this._awaitRetirements(e,d,p).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Lt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Lt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(s.status==="rejected")throw s.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=jt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let i=this._getClient();if(!i)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(i,n)},{credentialShape:"legacy",operation:"delete",onGeneration:i=>{o=i,this._dirtyGenerations.set(e,i)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(i=>{i instanceof Dn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Xt(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(()=>{Lt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(Bm(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=Xt(r),o=_r(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<Zi;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:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return{identityRejected:!1,authorityVersion:"0"};let a=Nn(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=$u(i.value);if(!c)return{identityRejected:!0};if(a.credentialIdentity===o&&a.state==="active")return{identityRejected:!1,token:c};try{return await r.upsertUserSecret(n,Jr(c,s),i.version),{identityRejected:!1,token:c}}catch(u){return this._isVersionConflict(u)?void 0:{identityRejected:!0}}}async _importLegacyToken(e,r,n,o){let s=Xt(n),i=_r(n);if(!s||!i||!n||o===void 0)return;let a=await this._loadLegacyToken(e,r,n);if(a)try{return await this._enqueueWrite(s,async()=>{let c=await e.getUserSecretWithVersion(s);if((c?.version??"0")===o){if(c){let u=Nn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,Jr(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(jt(r));return o?MA(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 s=this._memory.credentialRetirementGeneration(e),i=await this._loadRegistryToken(o,r);if(i.identityRejected)return;let a=i.token;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,i.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Lt.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)!==s||(this._memory.set(e,a),Lt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var Wm="Augment Code",Km="https://augmentcode.com",Jm="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var OA=1e3,zA=500;function zu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Vo(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Ou=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function Ym(t){return new URLSearchParams({k:t}).toString().slice(2)}function NA(t,e){let r=`${Ym(t)}:${Ym(e)}`;return`Basic ${btoa(r)}`}function tg(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function DA(t){return t.client.token_endpoint_auth_method==="none"||!tg(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function LA(t){return t==="basic"?"body":t==="body"?"basic":void 0}function jA(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var FA=401,rg=500;function Nu(t,...e){return t.status<rg&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function Xm(t){return Nu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===FA}async function Qm(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 s=tg(t);e==="basic"&&s?n.Authorization=NA(t.client.client_id,s):(o.set("client_id",t.client.client_id),e==="body"&&s&&o.set("client_secret",s));let i=await fetch(t.serverMetadata.token_endpoint,{method:"POST",headers:n,body:o.toString(),signal:AbortSignal.timeout(1e4)});if(!i.ok){let c=await i.text().catch(()=>""),u=jA(c),d=c.slice(0,zA);throw new Yr(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Ou;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*OA:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function eg(t,e){try{return await Qm(t,e,t.resource)}catch(r){if(r instanceof Yr&&t.resource&&Nu(r,"invalid_target"))return await Qm(t,e,void 0);throw r}}var Yr=class t extends Error{status;statusText;body;oauthErrorCode;clientAuthPlacementsExhausted;constructor(e,r,n,o,s=!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=s}withClientAuthPlacementsExhausted(){return new t(this.status,this.statusText,this.body,this.oauthErrorCode,!0)}};function Du(t){return!(t instanceof Yr)||t.status>=rg?!1:Nu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Lu(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=DA(t);try{return await eg(e,r)}catch(n){let o=LA(r);if(!(n instanceof Yr)||!o||!Xm(n))throw n;try{return await eg(e,o)}catch(s){throw s instanceof Yr&&Xm(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as O0}from"@hermes/logger";var Uu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Uu="oauth4webapi/v3.8.6");function Un(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 Ft="ERR_INVALID_ARG_VALUE",We="ERR_INVALID_ARG_TYPE";function le(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var Bu=Symbol(),UA=Symbol(),qA=Symbol(),Qr=Symbol();var ng=Symbol();var HA=new TextEncoder,GA=new TextDecoder;function qu(t){return typeof t=="string"?HA.encode(t):GA.decode(t)}var Hu;Uint8Array.prototype.toBase64?Hu=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Hu=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 Gu;Uint8Array.fromBase64?Gu=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw le("The input to be decoded is not correctly encoded.",Ft,e)}}:Gu=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 le("The input to be decoded is not correctly encoded.",Ft,e)}};function Ki(t){return typeof t=="string"?Gu(t):Hu(t)}var jn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=b0,Error.captureStackTrace?.(this,this.constructor)}},Wo=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 I(t,e,r){return new Wo(t,{code:e,cause:r})}function Ji(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Vu(t){Un(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Uu&&!e.has("user-agent")&&e.set("user-agent",Uu),e.has("authorization"))throw le('"options.headers" must not include the "authorization" header name',Ft);return e}function Wu(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw le('"options.signal" must return or be an instance of AbortSignal',We);return e}}function ZA(t){return t.includes("//")?t.replace("//","/"):t}function BA(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=ZA(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function VA(t,e,r,n){if(!(t instanceof URL))throw le(`"${e}" must be an instance of URL`,We);hg(t,n?.[Bu]!==!0);let o=r(new URL(t.href)),s=Vu(n?.headers);return s.set("accept","application/json"),(n?.[Qr]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:Wu(o,n?.signal)})}function Ln(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw le(`${r} must be a number`,We,o);if(t>0)return;if(e){if(t!==0)throw le(`${r} must be a non-negative number`,Ft,o);return}throw le(`${r} must be a positive number`,Ft,o)}catch(s){throw n?I(s.message,n,o):s}}function Ee(t,e,r,n){try{if(typeof t!="string")throw le(`${e} must be a string`,We,n);if(t.length===0)throw le(`${e} must not be empty`,Ft,n)}catch(o){throw r?I(o.message,r,n):o}}async function ig(t,e){let r=t;if(!(r instanceof URL)&&r!==Qi)throw le('"expectedIssuerIdentifier" must be an instance of URL',We);if(!Un(e,Response))throw le('"response" must be an instance of Response',We);if(e.status!==200)throw I('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',rd,e);Yo(e);let n=await na(e);if(Ee(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==Qi&&new URL(n.issuer).href!==r.href)throw I('"response" body "issuer" property does not match the expected value',ta,{expected:r.href,body:n,attribute:"issuer"});return n}function ag(t){KA(t,"application/json")}function WA(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 I(r,P0,t)}function KA(t,e){if(a0(t)!==e)throw WA(t,e)}function Ku(){return Ki(crypto.getRandomValues(new Uint8Array(32)))}function cg(){return Ku()}function ug(){return Ku()}function dg(){return Ku()}async function lg(t){return Ee(t,"codeVerifier"),Ki(await crypto.subtle.digest("SHA-256",qu(t)))}function Ju(t){let e=t?.[UA];return typeof e=="number"&&Number.isFinite(e)?e:0}function Yu(t){let e=t?.[qA];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Xu(){return Math.floor(Date.now()/1e3)}function ea(t){if(typeof t!="object"||t===null)throw le('"as" must be an object',We);Ee(t.issuer,'"as.issuer"')}function Qu(t){if(typeof t!="object"||t===null)throw le('"client" must be an object',We);Ee(t.client_id,'"client.client_id"')}function og(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 ed(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function pg(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{let s=og(r.client_id),i=og(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function fg(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var JA=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function hg(t,e){if(e&&t.protocol!=="https:")throw I("only requests to HTTPS are allowed",C0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw I("only HTTP and HTTPS requests are allowed",x0,t)}function sg(t,e,r,n){let o;if(typeof t!="string"||!(o=JA(t)))throw I(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?k0:E0,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return hg(o,n),o}function mg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?sg(t.mtls_endpoint_aliases[e],e,r,n):sg(t[e],e,r,n)}var Fn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=w0,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)}},Ko=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=R0,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)}},Jo=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=S0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Yi="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",YA="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",XA='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',QA="("+Yi+")\\s*=\\s*"+XA,e0="("+Yi+")\\s*=\\s*("+Yi+")",t0=new RegExp("^[,\\s]*("+Yi+")"),r0=new RegExp("^[,\\s]*"+QA+"[,\\s]*(.*)"),n0=new RegExp("^[,\\s]*"+e0+"[,\\s]*(.*)"),o0=new RegExp("^("+YA+")(?:$|[,\\s])(.*)");function s0(t){if(!Un(t,Response))throw le('"response" must be an instance of Response',We);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(t0),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let p,f;if(o=n.match(r0)){if([,p,f,n]=o,f.includes("\\"))try{f=JSON.parse(`"${f}"`)}catch{}u[p.toLowerCase()]=f;continue}if(o=n.match(n0)){[,p,f,n]=o,u[p.toLowerCase()]=f;continue}if(o=n.match(o0)){if(Object.keys(u).length)break;[,d,n]=o;break}return}else n=i||void 0;let l={scheme:s,parameters:u};d&&(l.token68=d),r.push(l)}if(r.length)return r}async function i0(t){if(t.status>399&&t.status<500){Yo(t),ag(t);try{let e=await t.clone().json();if(Ji(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function gg(t,e,r){if(t.status!==e){l0(t);let n;throw(n=await i0(t))?(await t.body?.cancel(),new Fn("server responded with an error in the response body",{cause:n,response:t})):I(`"response" is not a conform ${r} response (unexpected HTTP status code)`,rd,t)}}function yg(t){if(!td.has(t))throw le('"options.DPoP" is not a valid DPoPHandle',Ft)}function a0(t){return t.headers.get("content-type")?.split(";")[0]}async function c0(t,e,r,n,o,s,i){return await r(t,e,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(i?.[Qr]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Wu(n,i?.signal)})}async function u0(t,e,r,n,o,s){let i=mg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[Bu]!==!0);o.set("grant_type",n);let a=Vu(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(yg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await c0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var vg=new WeakMap,d0=new WeakMap;function _g(t){if(!t.id_token)return;let e=vg.get(t);if(!e)throw le('"ref" was already garbage collected or did not resolve from the proper sources',Ft);return e}async function Sg(t,e,r,n,o,s){if(ea(t),Qu(e),!Un(r,Response))throw le('"response" must be an instance of Response',We);await gg(r,200,"Token Endpoint"),Yo(r);let i=await na(r);if(Ee(i.access_token,'"response" body "access_token" property',V,{body:i}),Ee(i.token_type,'"response" body "token_type" property',V,{body:i}),i.token_type=i.token_type.toLowerCase(),i.expires_in!==void 0){let a=typeof i.expires_in!="number"?parseFloat(i.expires_in):i.expires_in;Ln(a,!0,'"response" body "expires_in" property',V,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ee(i.refresh_token,'"response" body "refresh_token" property',V,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw I('"response" body "scope" property must be a string',V,{body:i});if(i.id_token!==void 0){Ee(i.id_token,'"response" body "id_token" property',V,{body:i});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Ln(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await T0(i.id_token,A0.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Ju(e),Yu(e),o).then(y0.bind(void 0,a)).then(f0.bind(void 0,t)).then(p0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw I('ID Token "aud" (audience) claim includes additional untrusted audiences',Sr,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw I('unexpected ID Token "azp" (authorized party) claim value',Sr,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Ln(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),d0.set(r,u),vg.set(i,c)}if(s?.[i.token_type]!==void 0)s[i.token_type](r,i);else if(i.token_type!=="dpop"&&i.token_type!=="bearer")throw new jn("unsupported `token_type` value",{cause:{body:i}});return i}function l0(t){let e;if(e=s0(t))throw new Jo("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function p0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw I('unexpected JWT "aud" (audience) claim value',Sr,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw I('unexpected JWT "aud" (audience) claim value',Sr,{expected:t,claims:e.claims,claim:"aud"});return e}function f0(t,e){let r=t[I0]?.(e)??t.issuer;if(e.claims.iss!==r)throw I('unexpected JWT "iss" (issuer) claim value',Sr,{expected:r,claims:e.claims,claim:"iss"});return e}var td=new WeakSet;function h0(t){return td.add(t),t}var m0=Symbol();async function wg(t,e,r,n,o,s,i){if(ea(t),Qu(e),!td.has(n))throw le('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ft);Ee(o,'"redirectUri"');let a=Xr(n,"code");if(!a)throw I('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==m0&&(Ee(s,'"codeVerifier"'),c.set("code_verifier",s)),u0(t,e,r,"authorization_code",c,i)}var g0={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 y0(t,e){for(let r of t)if(e.claims[r]===void 0)throw I(`JWT "${r}" (${g0[r]}) claim missing`,V,{claims:e.claims});return e}var ju=Symbol(),Fu=Symbol();async function bg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?v0(t,e,r,n.expectedNonce,n.maxAge,n[ng],n.recognizedTokenTypes):_0(t,e,r,n?.[ng],n?.recognizedTokenTypes)}async function v0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=ju;break;case ju:break;default:Ee(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Fu;break;case Fu:break;default:Ln(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await Sg(t,e,r,a,s,i);Ee(c.id_token,'"response" body "id_token" property',V,{body:c});let u=_g(c);if(o!==Fu){let d=Xu()+Ju(e),l=Yu(e);if(u.auth_time+o<d-l)throw I("too much time has elapsed since the last End-User authentication",Xi,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===ju){if(u.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',Sr,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw I('unexpected ID Token "nonce" claim value',Sr,{expected:n,claims:u,claim:"nonce"});return c}async function _0(t,e,r,n,o){let s=await Sg(t,e,r,void 0,n,o),i=_g(s);if(i){if(e.default_max_age!==void 0){Ln(e.default_max_age,!0,'"client.default_max_age"');let a=Xu()+Ju(e),c=Yu(e);if(i.auth_time+e.default_max_age<a-c)throw I("too much time has elapsed since the last End-User authentication",Xi,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',Sr,{expected:void 0,claims:i,claim:"nonce"})}return s}var S0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",w0="OAUTH_RESPONSE_BODY_ERROR",b0="OAUTH_UNSUPPORTED_OPERATION",R0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Zu="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var P0="OAUTH_RESPONSE_IS_NOT_JSON",rd="OAUTH_RESPONSE_IS_NOT_CONFORM",C0="OAUTH_HTTP_REQUEST_FORBIDDEN",x0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Xi="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Sr="OAUTH_JWT_CLAIM_COMPARISON_FAILED",ta="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var k0="OAUTH_MISSING_SERVER_METADATA",E0="OAUTH_INVALID_SERVER_METADATA";function Yo(t){if(t.bodyUsed)throw le('"response" body has been used already',Ft)}async function T0(t,e,r,n,o){let{0:s,1:i,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:s,1:i,length:a}=t.split(".");else throw new jn("JWE decryption is not configured",{cause:t});if(a!==3)throw I("Invalid JWT",V,t);let c;try{c=JSON.parse(qu(Ki(s)))}catch(l){throw I("failed to parse JWT Header body as base64url encoded JSON",Zu,l)}if(!Ji(c))throw I("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new jn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(qu(Ki(i)))}catch(l){throw I("failed to parse JWT Payload body as base64url encoded JSON",Zu,l)}if(!Ji(u))throw I("JWT Payload must be a top level object",V,t);let d=Xu()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw I('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw I('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Xi,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw I('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw I('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw I('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw I('unexpected JWT "nbf" (not before) claim value',Xi,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw I('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function A0(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw I('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw I('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 I('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw I('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Xr(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw I(`"${e}" parameter must be provided only once`,V);return r}var $0=Symbol(),M0=Symbol();function Rg(t,e,r,n){if(ea(t),Qu(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw le('"parameters" must be an instance of URLSearchParams, or URL',We);if(Xr(r,"response"))throw I('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=Xr(r,"iss"),s=Xr(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw I('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw I('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case M0:if(s!==void 0)throw I('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case $0:break;default:if(Ee(n,'"expectedState" argument'),s!==n)throw I(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(Xr(r,"error"))throw new Ko("authorization response from the server is an error",{cause:r});let a=Xr(r,"id_token"),c=Xr(r,"token");if(a!==void 0||c!==void 0)throw new jn("implicit and hybrid flows are not supported");return h0(new URLSearchParams(r))}async function Pg(t,e,r){ea(t);let n=mg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[Bu]!==!0),o=Vu(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(yg(r.DPoP),await r.DPoP.addProof(n,o,s,r.initialAccessToken)),r?.initialAccessToken&&o.set("authorization",`${o.has("dpop")?"DPoP":"Bearer"} ${r.initialAccessToken}`);let i=await(r?.[Qr]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:Wu(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Cg(t){if(!Un(t,Response))throw le('"response" must be an instance of Response',We);await gg(t,201,"Dynamic Client Registration Endpoint"),Yo(t);let e=await na(t);return Ee(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&Ee(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&Ln(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function xg(t,e){return VA(t,"resourceIdentifier",r=>(BA(r,".well-known/oauth-protected-resource",!0),r),e)}async function ra(t,e){let r=t;if(!(r instanceof URL)&&r!==Qi)throw le('"expectedResourceIdentifier" must be an instance of URL',We);if(!Un(e,Response))throw le('"response" must be an instance of Response',We);if(e.status!==200)throw I('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',rd,e);Yo(e);let n=await na(e);if(Ee(n.resource,'"response" body "resource" property',V,{body:n}),r!==Qi&&new URL(n.resource).href!==r.href)throw I('"response" body "resource" property does not match the expected value',ta,{expected:r.href,body:n,attribute:"resource"});return n}async function na(t,e=ag){let r;try{r=await t.json()}catch(n){throw e(t),I('failed to parse "response" body as JSON',Zu,n)}if(!Ji(r))throw I('"response" body must be a top level object',V,{body:r});return r}var Qi=Symbol(),I0=Symbol();var Tg=O0.child({prefix:"pi-mcp"}),Xo=1e4,z0=1e3,N0=401,kg=200,D0=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,L0=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Ag;function qn(){return Ag??globalThis.fetch}function $g(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Mg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function od(t){let e=Mg(t);try{let r=await j0(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await G0(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw oa(r)}throw new Error("Failed to discover metadata URL")}async function j0(t){try{let e=await xg(t,{signal:AbortSignal.timeout(Xo),[Qr]:Ag??void 0});return e.ok?await ra(t,e):(e.body?.cancel().catch(()=>{}),await Ig(t,e.headers.get("www-authenticate"))??await Eg(t))}catch{return await Eg(t)}}async function Eg(t){for(let e of["HEAD","GET"])try{let r=await qn()(t,{method:e,signal:AbortSignal.timeout(Xo)});r.body?.cancel().catch(()=>{});let n=await Ig(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Ig(t,e){let r=H0(e);if(r)try{let n=await qn()(r,{signal:AbortSignal.timeout(Xo)});return await F0(t,n)}catch{return}}async function F0(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await ra(t,new Response(r,n))}catch(o){if(!(o instanceof Wo)||o.code!==ta)throw o;let s=U0(r);if(!s||!q0(s,t))throw o;return await ra(s,new Response(r,n))}}function U0(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function q0(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 H0(t){if(!t)return;let e=t.match(D0),r=t.match(L0),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function G0(t){for(let e of Z0(t))try{let r=new URL(e,t),n=await qn()(r,{signal:AbortSignal.timeout(Xo)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function Z0(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 sd(t){try{let e=await qn()(t,{signal:AbortSignal.timeout(Xo)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await B0(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await ig(o,new Response(r,n))}catch(e){throw oa(e)}}async function B0(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 nd=class extends Error{issuer;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 V0(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 id({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return V0({...t,clientId:n});if(!e.registration_endpoint)throw new nd(e.issuer);return await W0(e,r)}async function W0(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Pg(t,{client_name:Wm,client_uri:Km,logo_uri:Jm,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[Qr]:K0});return n.ok||Tg.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Cg(n)}catch(r){throw oa(r)}}async function K0(t,e){let r=await qn()(t,$g(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Tg.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${Y0(n)}`),r.status===200&&(o.status=201,o.statusText="Created"),o.status===201)try{let s=JSON.parse(n);s.client_secret_expires_at||(s.client_secret_expires_at=0),"client_secret"in s&&!s.client_secret&&(s.client_secret=void 0),n=JSON.stringify(s)}catch{}return new Response(n,o)}function J0(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}),qn()(t,$g(o))}function Y0(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>kg?`${t.slice(0,kg)}\u2026`:t}}async function ad(t,e,r,n,o,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let i=cg(),a=await lg(i),c=ug(),u,d=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean).join(" ")||void 0,l=Mg(s??t).toString(),p=new URL(r.authorization_endpoint);return p.searchParams.set("response_type","code"),p.searchParams.set("client_id",e.client_id),p.searchParams.set("code_challenge",a),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("redirect_uri",n),p.searchParams.set("resource",l),p.searchParams.set("state",c),d&&p.searchParams.set("scope",d),r.code_challenge_methods_supported?.includes("S256")||(u=dg(),p.searchParams.set("nonce",u)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:i,nonce:u,scope:d,state:c,resource:l,authUri:p}}async function X0(t,e,r){let n=await wg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[Qr]:J0,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return bg(t.serverMetadata,t.client,await Q0(n))}async function cd(t,e){try{let r=Rg(e.serverMetadata,e.client,t,e.state),n=await t$(e.client,o=>X0(e,r,o));return o$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw oa(r)}}async function Q0(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 Og(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function e$(t){let e=Og(t);return e===void 0?fg():t.token_endpoint_auth_method==="client_secret_basic"?pg(e):ed(e)}async function t$(t,e){try{return await e(e$(t))}catch(r){let n=r$(t);if(n&&n$(r))return await e(n);throw r}}function r$(t){let e=Og(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return ed(e)}function n$(t){return t instanceof Fn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof Jo?t.status===N0||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function o$(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*z0:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function oa(t){if(t instanceof Fn||t instanceof Ko){let e=t.error_description?` (${t.error_description})`:"";return new Error(`${t.message}${e}`,{cause:t})}return t instanceof Error?t:new Error(String(t))}var s$=/(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,zg=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,Ng=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,Dg=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Qo="[redacted]";function i$(t){return zg.test(t)||Ng.test(t)||Dg.test(t)}var a$=new RegExp(zg.source,"g"),c$=new RegExp(Ng.source,"gi"),u$=new RegExp(Dg.source,"g");function Lg(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function dd(t){return t&&Lg(t,8192).replace(a$,Qo).replace(c$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Qo}`).replace(u$,Qo)}function ud(t,e,r){if(e)return Qo;if(typeof t=="string")return i$(t)?Qo:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>ud(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=ud(s,s$.test(o),r+1);return n}function jg(t,e=500){if(t==null)return;let r=ud(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return Lg(n,e)}var Ug={reportError:()=>{}},Fg=Symbol.for("__pi_mcp_error_reporter_slot__");function qg(){let t=globalThis,e=t[Fg];return e||(e={reporter:null},t[Fg]=e),e}function Hg(t){let e=qg(),r=e.reporter??Ug;return e.reporter=t,r}function d$(){return qg().reporter??Ug}function ld(t,e){try{d$().reportError(t,e)}catch{}}import{logger as l$}from"@hermes/logger";var pd=l$.child({prefix:"pi-mcp"});function Gg(t,e,r){let n=0,o=0,s=r?.authoritative?{}:{...t.headerSecrets};for(let[i,a]of Object.entries(e))typeof a=="string"&&a!==""?(s[i]=a,n++):a===null||a===""?i in s&&(delete s[i],o++):pd.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];pd.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function Zg(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Mu)){let o=t.headerSecrets[e];if(o!==void 0)return o;let s=t.headerSecretFailures[e];if(s==="missing"||s==="permission_denied")return{reason:s}}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 Bg(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[s,i]of Object.entries(e))(i==="missing"||i==="permission_denied"||i==="transient")&&(n[s]=i,delete o[s]);t.headerSecrets=o,t.headerSecretFailures=n,pd.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function Vg(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as p$}from"@hermes/logger";var es=p$.child({prefix:"pi-mcp"}),f$="$augment-",ts=/\$augment-[a-zA-Z0-9_.-]+/g,h$=new RegExp(ts.source);function sa(t){return h$.test(t)}function ia(t){return t.slice(f$.length)}function fd(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(ts))e.add(ia(n[0]));return[...e].sort()}var m$=["permission_denied","missing","transient"];function Wg(t){let e=new Set(t);return m$.find(r=>e.has(r))??"missing"}var lt=class extends Error{serverName;missingKeys;reason;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 Kg(t,e,r,n,o,s,i){let a=[...t.matchAll(ts)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,p=ia(d);try{let f=await r(p);if(f===void 0||typeof f=="object"){n.add(p),s.set(p,f===void 0?"missing":f.reason),es.warn(`Secret "${p}" unavailable for "${e}"; leaving reference as-is`);continue}let h=f;h.trim()===""&&(o.add(p),es.warn(`Secret "${p}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),es.debug(`Resolved secret reference for "${e}"`)}catch(f){n.add(p),s.set(p,"transient"),es.error(`Failed to resolve secret "${p}" for "${e}" (${f instanceof Error?f.name:"non-Error"}); leaving reference as-is`)}}return c}async function Jg({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set,i=new Map;for(let[a,c]of Object.entries(t)){if(!sa(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){es.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await Kg(c,a,r,o,s,i)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var g$=/["$`\\]/g;function y$(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 v$(t,e){let r=y$(e);if(r==="double")return t.replace(g$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function Yg(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await Kg(t,"command",e,r,n,o,v$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as XF}from"node:async_hooks";var Xg,hd=Object.freeze({status:"aborted"});function v(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let p=d[l];p in a||(a[p]=u[p].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ut=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Hn=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Xg=globalThis).__zod_globalConfig??(Xg.__zod_globalConfig={});var Gn=globalThis.__zod_globalConfig;function Ke(t){return t&&Object.assign(Gn,t),Gn}var U={};cu(U,{BIGINT_FORMAT_RANGES:()=>ry,Class:()=>gd,NUMBER_FORMAT_RANGES:()=>bd,aborted:()=>Rr,allowsEval:()=>_d,assert:()=>R$,assertEqual:()=>_$,assertIs:()=>w$,assertNever:()=>b$,assertNotEqual:()=>S$,assignProp:()=>wr,base64ToUint8Array:()=>oy,base64urlToUint8Array:()=>F$,cached:()=>Bn,captureStackTrace:()=>ua,cleanEnum:()=>j$,cleanRegex:()=>ss,clone:()=>pt,cloneDef:()=>C$,createTransparentProxy:()=>$$,defineLazy:()=>Y,esc:()=>ca,escapeRegex:()=>er,explicitlyAborted:()=>Rd,extend:()=>O$,finalizeIssue:()=>ft,floatSafeRemainder:()=>yd,getElementAtPath:()=>x$,getEnumValues:()=>ns,getLengthableOrigin:()=>is,getParsedType:()=>A$,getSizableOrigin:()=>ny,hexToUint8Array:()=>q$,isObject:()=>en,isPlainObject:()=>br,issue:()=>Vn,joinValues:()=>aa,jsonStringifyReplacer:()=>Zn,merge:()=>N$,mergeDefs:()=>Qt,normalizeParams:()=>A,nullish:()=>os,numKeys:()=>T$,objectClone:()=>P$,omit:()=>I$,optionalKeys:()=>wd,parsedType:()=>Pd,partial:()=>D$,pick:()=>M$,prefixIssues:()=>tr,primitiveTypes:()=>ty,promiseAllObject:()=>k$,propertyKeyTypes:()=>Sd,randomString:()=>E$,required:()=>L$,safeExtend:()=>z$,shallowClone:()=>ey,slugify:()=>vd,stringifyPrimitive:()=>da,uint8ArrayToBase64:()=>sy,uint8ArrayToBase64url:()=>U$,uint8ArrayToHex:()=>H$,unwrapMessage:()=>rs});function _$(t){return t}function S$(t){return t}function w$(t){}function b$(t){throw new Error("Unexpected value in exhaustive check")}function R$(t){}function ns(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 aa(t,e="|"){return t.map(r=>da(r)).join(e)}function Zn(t,e){return typeof e=="bigint"?e.toString():e}function Bn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function os(t){return t==null}function ss(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function yd(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 Qg=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Qg)return n===void 0&&(n=Qg,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function P$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function wr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Qt(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function C$(t){return Qt(t._zod.def)}function x$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function k$(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function E$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ca(t){return JSON.stringify(t)}function vd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ua="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function en(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var _d=Bn(()=>{if(Gn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function br(t){if(en(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(en(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ey(t){return br(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function T$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var A$=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}`)}},Sd=new Set(["string","number","symbol"]),ty=new Set(["string","number","bigint","boolean","symbol","undefined"]);function er(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function A(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 $$(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},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 da(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var bd={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]},ry={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function M$(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 s=Qt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return wr(this,"shape",i),i},checks:[]});return pt(t,s)}function I$(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 s=Qt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return wr(this,"shape",i),i},checks:[]});return pt(t,s)}function O$(t,e){if(!br(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Qt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return wr(this,"shape",s),s}});return pt(t,o)}function z$(t,e){if(!br(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Qt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return wr(this,"shape",n),n}});return pt(t,r)}function N$(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=Qt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return wr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function D$(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 i=Qt(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 wr(this,"shape",c),c},checks:[]});return pt(e,i)}function L$(t,e,r){let n=Qt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return wr(this,"shape",s),s}});return pt(e,n)}function Rr(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 Rd(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 tr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function rs(t){return typeof t=="string"?t:t?.message}function ft(t,e,r){let n=t.message?t.message:rs(t.inst?._zod.def?.error?.(t))??rs(e?.error?.(t))??rs(r.customError?.(t))??rs(r.localeError?.(t))??"Invalid input",{inst:o,continue:s,input:i,...a}=t;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=i),a}function ny(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function is(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Pd(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 Vn(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function j$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function oy(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 sy(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function F$(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return oy(e+r)}function U$(t){return sy(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function q$(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 H$(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var gd=class{constructor(...e){}};var iy=(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,Zn,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},la=v("$ZodError",iy),Cd=v("$ZodError",iy,{Parent:Error});function xd(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 kd(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));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(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return n(t),r}var pa=t=>(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ut;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ft(c,s,Ke())));throw ua(a,o?.callee),a}return i.value};var fa=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ft(c,s,Ke())));throw ua(a,o?.callee),a}return i.value};var as=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ut;return s.issues.length?{success:!1,error:new(t??la)(s.issues.map(i=>ft(i,o,Ke())))}:{success:!0,data:s.value}},cs=as(Cd),us=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ft(i,o,Ke())))}:{success:!0,data:s.value}},ha=us(Cd),ay=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return pa(t)(e,r,o)};var cy=t=>(e,r,n)=>pa(t)(e,r,n);var uy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return fa(t)(e,r,o)};var dy=t=>async(e,r,n)=>fa(t)(e,r,n);var ly=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return as(t)(e,r,o)};var py=t=>(e,r,n)=>as(t)(e,r,n);var fy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return us(t)(e,r,o)};var hy=t=>async(e,r,n)=>us(t)(e,r,n);var my=/^[cC][0-9a-z]{6,}$/,gy=/^[0-9a-z]+$/,yy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,vy=/^[0-9a-vA-V]{20}$/,_y=/^[A-Za-z0-9]{27}$/,Sy=/^[a-zA-Z0-9_-]{21}$/,wy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var by=/^([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})$/,Ed=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 Ry=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Z$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Py(){return new RegExp(Z$,"u")}var Cy=/^(?:(?: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])$/,xy=/^(([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 ky=/^((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])$/,Ey=/^(([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])$/,Ty=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Td=/^[A-Za-z0-9_-]*$/;var Ay=/^https?$/,$y=/^\+[1-9]\d{6,14}$/,My="(?:(?:\\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])))",Iy=new RegExp(`^${My}$`);function Oy(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 zy(t){return new RegExp(`^${Oy(t)}$`)}function Ny(t){let e=Oy({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(`^${My}T(?:${n})$`)}var Dy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ly=/^-?\d+n?$/,jy=/^-?\d+$/,Ad=/^-?\d+(?:\.\d+)?$/,Fy=/^(?:true|false)$/i,Uy=/^null$/i;var qy=/^[^A-Z]*$/,Hy=/^[^a-z]*$/;var Te=v("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Gy={number:"number",bigint:"bigint",object:"date"},$d=v("$ZodCheckLessThan",(t,e)=>{Te.init(t,e);let r=Gy[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(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})}}),Md=v("$ZodCheckGreaterThan",(t,e)=>{Te.init(t,e);let r=Gy[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(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})}}),Zy=v("$ZodCheckMultipleOf",(t,e)=>{Te.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):yd(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})}}),By=v("$ZodCheckNumberFormat",(t,e)=>{Te.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=bd[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=jy)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",continue:!1,input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.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}):i.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&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}});var Vy=v("$ZodCheckMaxLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(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 i=is(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wy=v("$ZodCheckMinLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(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 i=is(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ky=v("$ZodCheckLengthEquals",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!os(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,s=o.length;if(s===e.length)return;let i=is(o),a=s>e.length;n.issues.push({origin:i,...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})}}),ls=v("$ZodCheckStringFormat",(t,e)=>{var r,n;Te.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.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=()=>{})}),Jy=v("$ZodCheckRegex",(t,e)=>{ls.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})}}),Yy=v("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=qy),ls.init(t,e)}),Xy=v("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Hy),ls.init(t,e)}),Qy=v("$ZodCheckIncludes",(t,e)=>{Te.init(t,e);let r=er(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),ev=v("$ZodCheckStartsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`^${er(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})}}),tv=v("$ZodCheckEndsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`.*${er(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 rv=v("$ZodCheckOverwrite",(t,e)=>{Te.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ma=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(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
26
- `))}};var ev={major:4,minor:4,patch:3};var ee=v("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ev;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=br(i),d;for(let l of a){if(l._zod.def.when){if(Sd(i)||!l._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=l._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new Ut;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=br(i,p)))});else{if(i.issues.length===p)continue;u||(u=br(i,p))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(br(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ut;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ut;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=is(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return pa(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),ga=v("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Iy(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}}),ae=v("$ZodStringFormat",(t,e)=>{us.init(t,e),ga.init(t,e)}),uv=v("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=vy),ae.init(t,e)}),dv=v("$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=Cd(n))}else e.pattern??(e.pattern=Cd());ae.init(t,e)}),lv=v("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=_y),ae.init(t,e)}),pv=v("$ZodURL",(t,e)=>{ae.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===xy.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})}}}),fv=v("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Sy()),ae.init(t,e)}),hv=v("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=gy),ae.init(t,e)}),mv=v("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ly),ae.init(t,e)}),gv=v("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=py),ae.init(t,e)}),yv=v("$ZodULID",(t,e)=>{e.pattern??(e.pattern=fy),ae.init(t,e)}),vv=v("$ZodXID",(t,e)=>{e.pattern??(e.pattern=hy),ae.init(t,e)}),_v=v("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=my),ae.init(t,e)}),Sv=v("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=My(e)),ae.init(t,e)}),wv=v("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ty),ae.init(t,e)}),bv=v("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=$y(e)),ae.init(t,e)}),Rv=v("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=yy),ae.init(t,e)}),Pv=v("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=wy),ae.init(t,e),t._zod.bag.format="ipv4"}),Cv=v("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=by),ae.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 xv=v("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ry),ae.init(t,e)}),kv=v("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Py),ae.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>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 Ev(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Tv=v("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Cy),ae.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Ev(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function G$(t){if(!xd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ev(r)}var Av=v("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=xd),ae.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{G$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),$v=v("$ZodE164",(t,e)=>{e.pattern??(e.pattern=ky),ae.init(t,e)});function Z$(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 Mv=v("$ZodJWT",(t,e)=>{ae.init(t,e),t._zod.check=r=>{Z$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var $d=v("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??kd,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 s=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,...s?{received:s}:{}}),r}}),Iv=v("$ZodNumberFormat",(t,e)=>{qy.init(t,e),$d.init(t,e)}),Ov=v("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=Ny,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}}),zv=v("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=Oy,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 Nv=v("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=Dy,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}}),Dv=v("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),Lv=v("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),jv=v("$ZodNever",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Fv=v("$ZodDate",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});function tv(t,e,r){t.issues.length&&e.issues.push(...tr(r,t.issues)),e.value[r]=t.value}var Uv=v("$ZodArray",(t,e)=>{ee.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 s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>tv(u,r,i))):tv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ma(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...tr(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function qv(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=vd(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Hv(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(h=>ma(h,r,p,e,d,l))):ma(f,r,p,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var B$=v("$ZodObject",(t,e)=>{if(ee.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=Gn(()=>qv(e));Y(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=Qr,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=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=i.shape;for(let p of i.keys){let f=l[p],h=f._zod.optin==="optional",m=f._zod.optout==="optional",y=f._zod.run({value:u[p],issues:[]},c);y instanceof Promise?d.push(y.then(S=>ma(S,a,p,u,h,m))):ma(y,a,p,u,h,m)}return s?Hv(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),Gv=v("$ZodObjectJIT",(t,e)=>{B$.init(t,e);let r=t._zod.parse,n=Gn(()=>qv(e)),o=p=>{let f=new fa(["shape","payload","ctx"]),h=n.value,m=b=>{let k=ia(b);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),S=0;for(let b of h.keys)y[b]=`key_${S++}`;f.write("const newResult = {};");for(let b of h.keys){let k=y[b],_=ia(b),P=p[b],O=P?._zod?.optin==="optional",ge=P?._zod?.optout==="optional";f.write(`const ${k} = ${m(b)};`),O&&ge?f.write(`
26
+ `))}};var ov={major:4,minor:4,patch:3};var ee=v("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ov;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=Rr(i),d;for(let l of a){if(l._zod.def.when){if(Rd(i)||!l._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=l._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new Ut;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=Rr(i,p)))});else{if(i.issues.length===p)continue;u||(u=Rr(i,p))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(Rr(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ut;return u.then(d=>t._zod.parse(d,c))}return t._zod.parse(u,c)};t._zod.run=(i,a)=>{if(a.skipChecks)return t._zod.parse(i,a);if(a.direction==="backward"){let u=t._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(d=>s(d,i,a)):s(u,i,a)}let c=t._zod.parse(i,a);if(c instanceof Promise){if(a.async===!1)throw new Ut;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=cs(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ha(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),va=v("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Dy(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}}),ae=v("$ZodStringFormat",(t,e)=>{ls.init(t,e),va.init(t,e)}),fv=v("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=by),ae.init(t,e)}),hv=v("$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=Ed(n))}else e.pattern??(e.pattern=Ed());ae.init(t,e)}),mv=v("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ry),ae.init(t,e)}),gv=v("$ZodURL",(t,e)=>{ae.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Ay.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})}}}),yv=v("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Py()),ae.init(t,e)}),vv=v("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Sy),ae.init(t,e)}),_v=v("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=my),ae.init(t,e)}),Sv=v("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=gy),ae.init(t,e)}),wv=v("$ZodULID",(t,e)=>{e.pattern??(e.pattern=yy),ae.init(t,e)}),bv=v("$ZodXID",(t,e)=>{e.pattern??(e.pattern=vy),ae.init(t,e)}),Rv=v("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=_y),ae.init(t,e)}),Pv=v("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ny(e)),ae.init(t,e)}),Cv=v("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Iy),ae.init(t,e)}),xv=v("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=zy(e)),ae.init(t,e)}),kv=v("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=wy),ae.init(t,e)}),Ev=v("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Cy),ae.init(t,e),t._zod.bag.format="ipv4"}),Tv=v("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xy),ae.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 Av=v("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ky),ae.init(t,e)}),$v=v("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ey),ae.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>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 Mv(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Iv=v("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ty),ae.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Mv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function W$(t){if(!Td.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Mv(r)}var Ov=v("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Td),ae.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{W$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),zv=v("$ZodE164",(t,e)=>{e.pattern??(e.pattern=$y),ae.init(t,e)});function K$(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 Nv=v("$ZodJWT",(t,e)=>{ae.init(t,e),t._zod.check=r=>{K$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Od=v("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ad,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 s=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,...s?{received:s}:{}}),r}}),Dv=v("$ZodNumberFormat",(t,e)=>{By.init(t,e),Od.init(t,e)}),Lv=v("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=Fy,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}}),jv=v("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=Ly,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 Fv=v("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=Uy,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}}),Uv=v("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),qv=v("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),Hv=v("$ZodNever",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Gv=v("$ZodDate",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});function sv(t,e,r){t.issues.length&&e.issues.push(...tr(r,t.issues)),e.value[r]=t.value}var Zv=v("$ZodArray",(t,e)=>{ee.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 s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>sv(u,r,i))):sv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ya(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...tr(r,t.issues))}if(!i&&!o){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}t.value===void 0?i&&(e.value[r]=void 0):e.value[r]=t.value}function Bv(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=wd(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Vv(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(h=>ya(h,r,p,e,d,l))):ya(f,r,p,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var J$=v("$ZodObject",(t,e)=>{if(ee.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=Bn(()=>Bv(e));Y(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=en,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=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=i.shape;for(let p of i.keys){let f=l[p],h=f._zod.optin==="optional",m=f._zod.optout==="optional",y=f._zod.run({value:u[p],issues:[]},c);y instanceof Promise?d.push(y.then(S=>ya(S,a,p,u,h,m))):ya(y,a,p,u,h,m)}return s?Vv(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),Wv=v("$ZodObjectJIT",(t,e)=>{J$.init(t,e);let r=t._zod.parse,n=Bn(()=>Bv(e)),o=p=>{let f=new ma(["shape","payload","ctx"]),h=n.value,m=b=>{let k=ca(b);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),S=0;for(let b of h.keys)y[b]=`key_${S++}`;f.write("const newResult = {};");for(let b of h.keys){let k=y[b],_=ca(b),P=p[b],O=P?._zod?.optin==="optional",ge=P?._zod?.optout==="optional";f.write(`const ${k} = ${m(b)};`),O&&ge?f.write(`
27
27
  if (${k}.issues.length) {
28
28
  if (${_} in input) {
29
29
  payload.issues = payload.issues.concat(${k}.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
- `)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,k)=>w(p,b,k)},s,i=Qr,a=!qn.jitless,u=a&&gd.value,d=e.catchall,l;t._zod.parse=(p,f)=>{l??(l=n.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),d?Hv([],h,p,f,l,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function rv(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!br(s));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(s=>s.issues.map(i=>ft(i,n,Je())))}),e)}var Md=v("$ZodUnion",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Y(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Y(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Y(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=>ns(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 s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>rv(a,n,t,o)):rv(i,n,t,o)}});var Zv=v("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Md.init(t,e);let r=t._zod.parse;Y(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Gn(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Qr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Bv=v("$ZodIntersection",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>nv(r,c,u)):nv(r,s,i)}});function Ad(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(wr(t)&&wr(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Ad(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.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],s=e[n],i=Ad(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function nv(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 s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),br(t))return t;let i=Ad(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Vv=v("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!wr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)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(f=>ft(f,n,Je())),input:u,path:[u],inst:t});continue}let l=d.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...tr(u,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...tr(u,p.issues)),r.value[l]=p.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"&&kd.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=>ft(l,n,Je())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&r.issues.push(...tr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...tr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Wv=v("$ZodEnum",(t,e)=>{ee.init(t,e);let r=ts(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>yd.has(typeof o)).map(o=>typeof o=="string"?er(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Kv=v("$ZodLiteral",(t,e)=>{if(ee.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"?er(n):n?er(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var Jv=v("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Un(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new Ut;return r.value=o,r.fallback=!0,r}});function ov(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Id=v("$ZodOptional",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Y(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ns(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>ov(i,o)):ov(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Yv=v("$ZodExactOptional",(t,e)=>{Id.init(t,e),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),Xv=v("$ZodNullable",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.innerType._zod.optin),Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ns(r.source)}|null)$`):void 0}),Y(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)}),Qv=v("$ZodDefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(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(s=>sv(s,e)):sv(o,e)}});function sv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var e_=v("$ZodPrefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(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))}),t_=v("$ZodNonOptional",(t,e)=>{ee.init(t,e),Y(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(s=>iv(s,t)):iv(o,t)}});function iv(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 r_=v("$ZodCatch",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(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(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ft(i,n,Je()))},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(s=>ft(s,n,Je()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Od=v("$ZodPipe",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>e.in._zod.values),Y(t._zod,"optin",()=>e.in._zod.optin),Y(t._zod,"optout",()=>e.out._zod.optout),Y(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>ha(i,e.in,n)):ha(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ha(s,e.out,n)):ha(o,e.out,n)}});function ha(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 n_=v("$ZodPreprocess",(t,e)=>{Od.init(t,e)}),o_=v("$ZodReadonly",(t,e)=>{ee.init(t,e),Y(t._zod,"propValues",()=>e.innerType._zod.propValues),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"optin",()=>e.innerType?._zod?.optin),Y(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(av):av(o)}});function av(t){return t.value=Object.freeze(t.value),t}var s_=v("$ZodCustom",(t,e)=>{Te.init(t,e),ee.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(s=>cv(s,r,n,t));cv(o,r,n,t)}});function cv(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(Zn(o))}}var V$=()=>{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 s=n[o.expected]??o.expected,i=wd(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${ca(o.values[0])}`:`Invalid option: expected one of ${sa(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${sa(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(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function i_(){return{localeError:V$()}}var a_;var zd=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 c_(){return new zd}(a_=globalThis).__zod_globalRegistry??(a_.__zod_globalRegistry=c_());var Rr=globalThis.__zod_globalRegistry;function u_(t,e){return new t({type:"string",...A(e)})}function d_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function l_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function Nd(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function p_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function f_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function h_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function m_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Dd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function g_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function y_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function v_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function __(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function S_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function w_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function b_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function R_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function P_(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function C_(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function x_(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function k_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function E_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function T_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function A_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function $_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function M_(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function I_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function O_(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function z_(t,e){return new t({type:"number",checks:[],...A(e)})}function N_(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function D_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function L_(t,e){return new t({type:"boolean",...A(e)})}function j_(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function F_(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function U_(t,e){return new t({type:"null",...A(e)})}function q_(t){return new t({type:"any"})}function H_(t){return new t({type:"unknown"})}function G_(t,e){return new t({type:"never",...A(e)})}function Z_(t,e){return new t({type:"date",coerce:!0,...A(e)})}function Bn(t,e){return new Ed({check:"less_than",...A(e),value:t,inclusive:!1})}function rr(t,e){return new Ed({check:"less_than",...A(e),value:t,inclusive:!0})}function Vn(t,e){return new Td({check:"greater_than",...A(e),value:t,inclusive:!1})}function Ct(t,e){return new Td({check:"greater_than",...A(e),value:t,inclusive:!0})}function ds(t,e){return new Uy({check:"multiple_of",...A(e),value:t})}function ya(t,e){return new Hy({check:"max_length",...A(e),maximum:t})}function Wn(t,e){return new Gy({check:"min_length",...A(e),minimum:t})}function va(t,e){return new Zy({check:"length_equals",...A(e),length:t})}function Ld(t,e){return new By({check:"string_format",format:"regex",...A(e),pattern:t})}function jd(t){return new Vy({check:"string_format",format:"lowercase",...A(t)})}function Fd(t){return new Wy({check:"string_format",format:"uppercase",...A(t)})}function Ud(t,e){return new Ky({check:"string_format",format:"includes",...A(e),includes:t})}function qd(t,e){return new Jy({check:"string_format",format:"starts_with",...A(e),prefix:t})}function Hd(t,e){return new Yy({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Pr(t){return new Xy({check:"overwrite",tx:t})}function Gd(t){return Pr(e=>e.normalize(t))}function Zd(){return Pr(t=>t.trim())}function Bd(){return Pr(t=>t.toLowerCase())}function Vd(){return Pr(t=>t.toUpperCase())}function Wd(){return Pr(t=>md(t))}function B_(t,e,r){return new t({type:"array",element:e,...A(r)})}function V_(t,e,r){let n=A(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,...A(r)})}function K_(t,e){let r=W$(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Zn(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Zn(s))}},t(n.value,n)),e);return r}function W$(t,e){let r=new Te({check:"custom",...A(e)});return r._zod.check=t,r}function Kd(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??Rr,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 ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&je(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Jd(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 i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[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,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);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 i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
85
+ `)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,k)=>w(p,b,k)},s,i=en,a=!Gn.jitless,u=a&&_d.value,d=e.catchall,l;t._zod.parse=(p,f)=>{l??(l=n.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),d?Vv([],h,p,f,l,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function iv(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!Rr(s));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(s=>s.issues.map(i=>ft(i,n,Ke())))}),e)}var zd=v("$ZodUnion",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Y(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Y(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Y(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=>ss(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 s=!1,i=[];for(let a of e.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}return s?Promise.all(i).then(a=>iv(a,n,t,o)):iv(i,n,t,o)}});var Kv=v("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,zd.init(t,e);let r=t._zod.parse;Y(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Bn(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!en(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Jv=v("$ZodIntersection",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>av(r,c,u)):av(r,s,i)}});function Id(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(br(t)&&br(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Id(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.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],s=e[n],i=Id(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function av(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 s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),Rr(t))return t;let i=Id(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}var Yv=v("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!br(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)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(f=>ft(f,n,Ke())),input:u,path:[u],inst:t});continue}let l=d.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...tr(u,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...tr(u,p.issues)),r.value[l]=p.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"&&Ad.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=>ft(l,n,Ke())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&r.issues.push(...tr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...tr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Xv=v("$ZodEnum",(t,e)=>{ee.init(t,e);let r=ns(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>Sd.has(typeof o)).map(o=>typeof o=="string"?er(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),Qv=v("$ZodLiteral",(t,e)=>{if(ee.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"?er(n):n?er(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var e_=v("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Hn(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new Ut;return r.value=o,r.fallback=!0,r}});function cv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Nd=v("$ZodOptional",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Y(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ss(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>{if(e.innerType._zod.optin==="optional"){let o=r.value,s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(i=>cv(i,o)):cv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),t_=v("$ZodExactOptional",(t,e)=>{Nd.init(t,e),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(r,n)=>e.innerType._zod.run(r,n)}),r_=v("$ZodNullable",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.innerType._zod.optin),Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ss(r.source)}|null)$`):void 0}),Y(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)}),n_=v("$ZodDefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(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(s=>uv(s,e)):uv(o,e)}});function uv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var o_=v("$ZodPrefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(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))}),s_=v("$ZodNonOptional",(t,e)=>{ee.init(t,e),Y(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(s=>dv(s,t)):dv(o,t)}});function dv(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 i_=v("$ZodCatch",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(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(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ft(i,n,Ke()))},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(s=>ft(s,n,Ke()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Dd=v("$ZodPipe",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>e.in._zod.values),Y(t._zod,"optin",()=>e.in._zod.optin),Y(t._zod,"optout",()=>e.out._zod.optout),Y(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>ga(i,e.in,n)):ga(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ga(s,e.out,n)):ga(o,e.out,n)}});function ga(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 a_=v("$ZodPreprocess",(t,e)=>{Dd.init(t,e)}),c_=v("$ZodReadonly",(t,e)=>{ee.init(t,e),Y(t._zod,"propValues",()=>e.innerType._zod.propValues),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"optin",()=>e.innerType?._zod?.optin),Y(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(lv):lv(o)}});function lv(t){return t.value=Object.freeze(t.value),t}var u_=v("$ZodCustom",(t,e)=>{Te.init(t,e),ee.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(s=>pv(s,r,n,t));pv(o,r,n,t)}});function pv(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(Vn(o))}}var Y$=()=>{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 s=n[o.expected]??o.expected,i=Pd(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${da(o.values[0])}`:`Invalid option: expected one of ${aa(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${aa(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(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function d_(){return{localeError:Y$()}}var l_;var Ld=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 p_(){return new Ld}(l_=globalThis).__zod_globalRegistry??(l_.__zod_globalRegistry=p_());var Pr=globalThis.__zod_globalRegistry;function f_(t,e){return new t({type:"string",...A(e)})}function h_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function m_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function jd(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function g_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function y_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function v_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function __(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Fd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function S_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function w_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function b_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function R_(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function P_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function C_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function x_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function k_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function E_(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function T_(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function A_(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function $_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function M_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function I_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function O_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function z_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function N_(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function D_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function L_(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function j_(t,e){return new t({type:"number",checks:[],...A(e)})}function F_(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function U_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function q_(t,e){return new t({type:"boolean",...A(e)})}function H_(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function G_(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function Z_(t,e){return new t({type:"null",...A(e)})}function B_(t){return new t({type:"any"})}function V_(t){return new t({type:"unknown"})}function W_(t,e){return new t({type:"never",...A(e)})}function K_(t,e){return new t({type:"date",coerce:!0,...A(e)})}function Wn(t,e){return new $d({check:"less_than",...A(e),value:t,inclusive:!1})}function rr(t,e){return new $d({check:"less_than",...A(e),value:t,inclusive:!0})}function Kn(t,e){return new Md({check:"greater_than",...A(e),value:t,inclusive:!1})}function Ct(t,e){return new Md({check:"greater_than",...A(e),value:t,inclusive:!0})}function ps(t,e){return new Zy({check:"multiple_of",...A(e),value:t})}function _a(t,e){return new Vy({check:"max_length",...A(e),maximum:t})}function Jn(t,e){return new Wy({check:"min_length",...A(e),minimum:t})}function Sa(t,e){return new Ky({check:"length_equals",...A(e),length:t})}function Ud(t,e){return new Jy({check:"string_format",format:"regex",...A(e),pattern:t})}function qd(t){return new Yy({check:"string_format",format:"lowercase",...A(t)})}function Hd(t){return new Xy({check:"string_format",format:"uppercase",...A(t)})}function Gd(t,e){return new Qy({check:"string_format",format:"includes",...A(e),includes:t})}function Zd(t,e){return new ev({check:"string_format",format:"starts_with",...A(e),prefix:t})}function Bd(t,e){return new tv({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Cr(t){return new rv({check:"overwrite",tx:t})}function Vd(t){return Cr(e=>e.normalize(t))}function Wd(){return Cr(t=>t.trim())}function Kd(){return Cr(t=>t.toLowerCase())}function Jd(){return Cr(t=>t.toUpperCase())}function Yd(){return Cr(t=>vd(t))}function J_(t,e,r){return new t({type:"array",element:e,...A(r)})}function Y_(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function X_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function Q_(t,e){let r=X$(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Vn(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Vn(s))}},t(n.value,n)),e);return r}function X$(t,e){let r=new Te({check:"custom",...A(e)});return r._zod.check=t,r}function Xd(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??Pr,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 ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&je(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Qd(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 i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[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,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);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 i of t.seen.entries()){let a=i[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 i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Yd(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 f=t.seen.get(l),h=f.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 y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.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 s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=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,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:ls(e,"input",t.processors),output:ls(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function je(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 je(n.element,r);if(n.type==="set")return je(n.valueType,r);if(n.type==="lazy")return je(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 je(n.innerType,r);if(n.type==="intersection")return je(n.left,r)||je(n.right,r);if(n.type==="record"||n.type==="map")return je(n.keyType,r)||je(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:je(n.in,r)||je(n.out,r);if(n.type==="object"){for(let o in n.shape)if(je(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(je(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(je(o,r))return!0;return!!(n.rest&&je(n.rest,r))}return!1}var J_=(t,e={})=>r=>{let n=Kd({...r,processors:e});return ve(t,n),Jd(n,t),Yd(n,t)},ls=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Kd({...o??{},target:s,io:e,processors:r});return ve(t,i),Jd(i,t),Yd(i,t)};var K$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Y_=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=K$[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}))])}},X_=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,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>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";l?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Q_=(t,e,r,n)=>{r.type="boolean"},eS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var tS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var rS=(t,e,r,n)=>{r.not={}},nS=(t,e,r,n)=>{},oS=(t,e,r,n)=>{},sS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},iS=(t,e,r,n)=>{let o=t._zod.def,s=ts(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},aS=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var cS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var uS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var dS=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=ve(s.element,e,{...n,path:[...n.path,"items"]})},lS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=ve(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=ve(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},pS=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ve(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},fS=(t,e,r,n)=>{let o=t._zod.def,s=ve(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=ve(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var hS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=ve(s.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=ve(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=ve(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},mS=(t,e,r,n)=>{let o=t._zod.def,s=ve(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},gS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},yS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},vS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},_S=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},SS=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;ve(i,e,n);let a=e.seen.get(t);a.ref=i},wS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var Xd=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function _a(t){return!!t._zod}function xt(t,e){return _a(t)?is(t,e):t.safeParse(e)}function Sa(t){if(!t)return;let e;if(_a(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function wa(t){if(_a(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.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 ps={};iu(ps,{ZodISODate:()=>RS,ZodISODateTime:()=>bS,ZodISODuration:()=>CS,ZodISOTime:()=>PS,date:()=>el,datetime:()=>Qd,duration:()=>rl,time:()=>tl});var bS=v("ZodISODateTime",(t,e)=>{Sv.init(t,e),pe.init(t,e)});function Qd(t){return $_(bS,t)}var RS=v("ZodISODate",(t,e)=>{wv.init(t,e),pe.init(t,e)});function el(t){return M_(RS,t)}var PS=v("ZodISOTime",(t,e)=>{bv.init(t,e),pe.init(t,e)});function tl(t){return I_(PS,t)}var CS=v("ZodISODuration",(t,e)=>{Rv.init(t,e),pe.init(t,e)});function rl(t){return O_(CS,t)}var nM=(t,e)=>{ua.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Pd(t,r)},flatten:{value:r=>Rd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Hn,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Hn,2)}},isEmpty:{get(){return t.issues.length===0}}})};var it=v("ZodError",nM,{Parent:Error});var kS=da(it),ES=la(it),TS=ss(it),AS=as(it),$S=ny(it),MS=oy(it),IS=sy(it),OS=iy(it),zS=ay(it),NS=cy(it),DS=uy(it),LS=dy(it);var jS=new WeakMap;function fs(t,e,r){let n=Object.getPrototypeOf(t),o=jS.get(n);if(o||(o=new Set,jS.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ne=v("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:ls(t,"input"),output:ls(t,"output")}}),t.toJSONSchema=J_(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>kS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>TS(t,r,n),t.parseAsync=async(r,n)=>ES(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>AS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>$S(t,r,n),t.decode=(r,n)=>MS(t,r,n),t.encodeAsync=async(r,n)=>IS(t,r,n),t.decodeAsync=async(r,n)=>OS(t,r,n),t.safeEncode=(r,n)=>zS(t,r,n),t.safeDecode=(r,n)=>NS(t,r,n),t.safeEncodeAsync=async(r,n)=>DS(t,r,n),t.safeDecodeAsync=async(r,n)=>LS(t,r,n),fs(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.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 pt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(ZM(r,n))},superRefine(r,n){return this.check(BM(r,n))},overwrite(r){return this.check(Pr(r))},optional(){return he(this)},exactOptional(){return IM(this)},nullable(){return HS(this)},nullish(){return he(HS(this))},nonoptional(r){return jM(this,r)},array(){return C(this)},or(r){return ce([this,r])},and(r){return Pa(this,r)},transform(r){return GS(this,ew(r))},default(r){return NM(this,r)},prefault(r){return LM(this,r)},catch(r){return UM(this,r)},pipe(r){return GS(this,r)},readonly(){return GM(this)},describe(r){let n=this.clone();return Rr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Rr.get(this);let n=this.clone();return Rr.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 Rr.get(t)?.description},configurable:!0}),t)),ZS=v("_ZodString",(t,e)=>{ga.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Y_(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,fs(t,"_ZodString",{regex(...n){return this.check(Ld(...n))},includes(...n){return this.check(Ud(...n))},startsWith(...n){return this.check(qd(...n))},endsWith(...n){return this.check(Hd(...n))},min(...n){return this.check(Wn(...n))},max(...n){return this.check(ya(...n))},length(...n){return this.check(va(...n))},nonempty(...n){return this.check(Wn(1,...n))},lowercase(n){return this.check(jd(n))},uppercase(n){return this.check(Fd(n))},trim(){return this.check(Zd())},normalize(...n){return this.check(Gd(...n))},toLowerCase(){return this.check(Bd())},toUpperCase(){return this.check(Vd())},slugify(){return this.check(Wd())}})}),ol=v("ZodString",(t,e)=>{ga.init(t,e),ZS.init(t,e),t.email=r=>t.check(l_(sM,r)),t.url=r=>t.check(Dd(BS,r)),t.jwt=r=>t.check(A_(SM,r)),t.emoji=r=>t.check(g_(iM,r)),t.guid=r=>t.check(Nd(FS,r)),t.uuid=r=>t.check(p_(ba,r)),t.uuidv4=r=>t.check(f_(ba,r)),t.uuidv6=r=>t.check(h_(ba,r)),t.uuidv7=r=>t.check(m_(ba,r)),t.nanoid=r=>t.check(y_(aM,r)),t.guid=r=>t.check(Nd(FS,r)),t.cuid=r=>t.check(v_(cM,r)),t.cuid2=r=>t.check(__(uM,r)),t.ulid=r=>t.check(S_(dM,r)),t.base64=r=>t.check(k_(yM,r)),t.base64url=r=>t.check(E_(vM,r)),t.xid=r=>t.check(w_(lM,r)),t.ksuid=r=>t.check(b_(pM,r)),t.ipv4=r=>t.check(R_(fM,r)),t.ipv6=r=>t.check(P_(hM,r)),t.cidrv4=r=>t.check(C_(mM,r)),t.cidrv6=r=>t.check(x_(gM,r)),t.e164=r=>t.check(T_(_M,r)),t.datetime=r=>t.check(Qd(r)),t.date=r=>t.check(el(r)),t.time=r=>t.check(tl(r)),t.duration=r=>t.check(rl(r))});function g(t){return u_(ol,t)}var pe=v("ZodStringFormat",(t,e)=>{ae.init(t,e),ZS.init(t,e)}),sM=v("ZodEmail",(t,e)=>{lv.init(t,e),pe.init(t,e)});var FS=v("ZodGUID",(t,e)=>{uv.init(t,e),pe.init(t,e)});var ba=v("ZodUUID",(t,e)=>{dv.init(t,e),pe.init(t,e)});var BS=v("ZodURL",(t,e)=>{pv.init(t,e),pe.init(t,e)});function VS(t){return Dd(BS,t)}var iM=v("ZodEmoji",(t,e)=>{fv.init(t,e),pe.init(t,e)});var aM=v("ZodNanoID",(t,e)=>{hv.init(t,e),pe.init(t,e)});var cM=v("ZodCUID",(t,e)=>{mv.init(t,e),pe.init(t,e)});var uM=v("ZodCUID2",(t,e)=>{gv.init(t,e),pe.init(t,e)});var dM=v("ZodULID",(t,e)=>{yv.init(t,e),pe.init(t,e)});var lM=v("ZodXID",(t,e)=>{vv.init(t,e),pe.init(t,e)});var pM=v("ZodKSUID",(t,e)=>{_v.init(t,e),pe.init(t,e)});var fM=v("ZodIPv4",(t,e)=>{Pv.init(t,e),pe.init(t,e)});var hM=v("ZodIPv6",(t,e)=>{Cv.init(t,e),pe.init(t,e)});var mM=v("ZodCIDRv4",(t,e)=>{xv.init(t,e),pe.init(t,e)});var gM=v("ZodCIDRv6",(t,e)=>{kv.init(t,e),pe.init(t,e)});var yM=v("ZodBase64",(t,e)=>{Tv.init(t,e),pe.init(t,e)});var vM=v("ZodBase64URL",(t,e)=>{Av.init(t,e),pe.init(t,e)});var _M=v("ZodE164",(t,e)=>{$v.init(t,e),pe.init(t,e)});var SM=v("ZodJWT",(t,e)=>{Mv.init(t,e),pe.init(t,e)});var Ra=v("ZodNumber",(t,e)=>{$d.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>X_(t,n,o,s),fs(t,"ZodNumber",{gt(n,o){return this.check(Vn(n,o))},gte(n,o){return this.check(Ct(n,o))},min(n,o){return this.check(Ct(n,o))},lt(n,o){return this.check(Bn(n,o))},lte(n,o){return this.check(rr(n,o))},max(n,o){return this.check(rr(n,o))},int(n){return this.check(US(n))},safe(n){return this.check(US(n))},positive(n){return this.check(Vn(0,n))},nonnegative(n){return this.check(Ct(0,n))},negative(n){return this.check(Bn(0,n))},nonpositive(n){return this.check(rr(0,n))},multipleOf(n,o){return this.check(ds(n,o))},step(n,o){return this.check(ds(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 W(t){return z_(Ra,t)}var wM=v("ZodNumberFormat",(t,e)=>{Iv.init(t,e),Ra.init(t,e)});function US(t){return D_(wM,t)}var sl=v("ZodBoolean",(t,e)=>{Ov.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Q_(t,r,n,o)});function oe(t){return L_(sl,t)}var WS=v("ZodBigInt",(t,e)=>{zv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>eS(t,n,o,s),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.gt=(n,o)=>t.check(Vn(n,o)),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.lt=(n,o)=>t.check(Bn(n,o)),t.lte=(n,o)=>t.check(rr(n,o)),t.max=(n,o)=>t.check(rr(n,o)),t.positive=n=>t.check(Vn(BigInt(0),n)),t.negative=n=>t.check(Bn(BigInt(0),n)),t.nonpositive=n=>t.check(rr(BigInt(0),n)),t.nonnegative=n=>t.check(Ct(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(ds(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var bM=v("ZodNull",(t,e)=>{Nv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tS(t,r,n,o)});function KS(t){return U_(bM,t)}var RM=v("ZodAny",(t,e)=>{Dv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nS(t,r,n,o)});function JS(){return q_(RM)}var PM=v("ZodUnknown",(t,e)=>{Lv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>oS(t,r,n,o)});function fe(){return H_(PM)}var CM=v("ZodNever",(t,e)=>{jv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rS(t,r,n,o)});function xM(t){return G_(CM,t)}var YS=v("ZodDate",(t,e)=>{Fv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>sS(t,n,o,s),t.min=(n,o)=>t.check(Ct(n,o)),t.max=(n,o)=>t.check(rr(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 kM=v("ZodArray",(t,e)=>{Uv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dS(t,r,n,o),t.element=e.element,fs(t,"ZodArray",{min(r,n){return this.check(Wn(r,n))},nonempty(r){return this.check(Wn(1,r))},max(r,n){return this.check(ya(r,n))},length(r,n){return this.check(va(r,n))},unwrap(){return this.element}})});function C(t,e){return B_(kM,t,e)}var XS=v("ZodObject",(t,e)=>{Gv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),fs(t,"ZodObject",{keyof(){return Ye(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:fe()})},loose(){return this.clone({...this._zod.def,catchall:fe()})},strict(){return this.clone({...this._zod.def,catchall:xM()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(tw,this,r[0])},required(...r){return U.required(rw,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new XS(r)}function Pe(t,e){return new XS({type:"object",shape:t,catchall:fe(),...U.normalizeParams(e)})}var QS=v("ZodUnion",(t,e)=>{Md.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o),t.options=e.options});function ce(t,e){return new QS({type:"union",options:t,...U.normalizeParams(e)})}var EM=v("ZodDiscriminatedUnion",(t,e)=>{QS.init(t,e),Zv.init(t,e)});function il(t,e,r){return new EM({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var TM=v("ZodIntersection",(t,e)=>{Bv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fS(t,r,n,o)});function Pa(t,e){return new TM({type:"intersection",left:t,right:e})}var qS=v("ZodRecord",(t,e)=>{Vv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ie(t,e,r){return!e||!e._zod?new qS({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new qS({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var nl=v("ZodEnum",(t,e)=>{Wv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>iS(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new nl({...e,checks:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new nl({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Ye(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new nl({type:"enum",entries:r,...U.normalizeParams(e)})}var AM=v("ZodLiteral",(t,e)=>{Kv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(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 E(t,e){return new AM({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var $M=v("ZodTransform",(t,e)=>{Jv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Un(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function ew(t){return new $M({type:"transform",transform:t})}var tw=v("ZodOptional",(t,e)=>{Id.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function he(t){return new tw({type:"optional",innerType:t})}var MM=v("ZodExactOptional",(t,e)=>{Yv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function IM(t){return new MM({type:"optional",innerType:t})}var OM=v("ZodNullable",(t,e)=>{Xv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function HS(t){return new OM({type:"nullable",innerType:t})}var zM=v("ZodDefault",(t,e)=>{Qv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>yS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function NM(t,e){return new zM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var DM=v("ZodPrefault",(t,e)=>{e_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function LM(t,e){return new DM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var rw=v("ZodNonOptional",(t,e)=>{t_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function jM(t,e){return new rw({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var FM=v("ZodCatch",(t,e)=>{r_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function UM(t,e){return new FM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var nw=v("ZodPipe",(t,e)=>{Od.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>SS(t,r,n,o),t.in=e.in,t.out=e.out});function GS(t,e){return new nw({type:"pipe",in:t,out:e})}var qM=v("ZodPreprocess",(t,e)=>{nw.init(t,e),n_.init(t,e)}),HM=v("ZodReadonly",(t,e)=>{o_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>wS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function GM(t){return new HM({type:"readonly",innerType:t})}var ow=v("ZodCustom",(t,e)=>{s_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cS(t,r,n,o)});function sw(t,e){return V_(ow,t??(()=>!0),e)}function ZM(t,e={}){return W_(ow,t,e)}function BM(t,e){return K_(t,e)}function al(t,e){return new qM({type:"pipe",in:ew(t),out:e})}var aw={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 iw;iw||(iw={});var Ca={};iu(Ca,{bigint:()=>JM,boolean:()=>KM,date:()=>YM,number:()=>WM,string:()=>VM});function VM(t){return d_(ol,t)}function WM(t){return N_(Ra,t)}function KM(t){return j_(sl,t)}function JM(t){return F_(WS,t)}function YM(t){return Z_(YS,t)}Je(i_());var Yn="2025-11-25";var cw=[Yn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cr="io.modelcontextprotocol/related-task",ka="2.0",Ce=sw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),uw=ce([g(),W().int()]),dw=g(),FB=Pe({ttl:W().optional(),pollInterval:W().optional()}),QM=x({ttl:W().optional()}),eI=x({taskId:g()}),ul=Pe({progressToken:uw.optional(),[Cr]:eI.optional()}),at=x({_meta:ul.optional()}),hs=at.extend({task:QM.optional()}),lw=t=>hs.safeParse(t).success,Ae=x({method:g(),params:at.loose().optional()}),ht=x({_meta:ul.optional()}),mt=x({method:g(),params:ht.loose().optional()}),xe=Pe({_meta:ul.optional()}),Ea=ce([g(),W().int()]),pw=x({jsonrpc:E(ka),id:Ea,...Ae.shape}).strict(),ms=t=>pw.safeParse(t).success,fw=x({jsonrpc:E(ka),...mt.shape}).strict(),hw=t=>fw.safeParse(t).success,dl=x({jsonrpc:E(ka),id:Ea,result:xe}).strict(),en=t=>dl.safeParse(t).success;var M;(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"})(M||(M={}));var ll=x({jsonrpc:E(ka),id:Ea.optional(),error:x({code:W().int(),message:g(),data:fe().optional()})}).strict();var mw=t=>ll.safeParse(t).success;var xr=ce([pw,fw,dl,ll]),UB=ce([dl,ll]),tn=xe.strict(),tI=ht.extend({requestId:Ea.optional(),reason:g().optional()}),Ta=mt.extend({method:E("notifications/cancelled"),params:tI}),rI=x({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Ye(["light","dark"]).optional()}),gs=x({icons:C(rI).optional()}),Jn=x({name:g(),title:g().optional()}),gw=Jn.extend({...Jn.shape,...gs.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),nI=Pa(x({applyDefaults:oe().optional()}),ie(g(),fe())),oI=al(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Pa(x({form:nI.optional(),url:Ce.optional()}),ie(g(),fe()).optional())),sI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({sampling:Pe({createMessage:Ce.optional()}).optional(),elicitation:Pe({create:Ce.optional()}).optional()}).optional()}),iI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({tools:Pe({call:Ce.optional()}).optional()}).optional()}),aI=x({experimental:ie(g(),Ce).optional(),sampling:x({context:Ce.optional(),tools:Ce.optional()}).optional(),elicitation:oI.optional(),roots:x({listChanged:oe().optional()}).optional(),tasks:sI.optional(),extensions:ie(g(),Ce).optional()}),cI=at.extend({protocolVersion:g(),capabilities:aI,clientInfo:gw}),uI=Ae.extend({method:E("initialize"),params:cI});var dI=x({experimental:ie(g(),Ce).optional(),logging:Ce.optional(),completions:Ce.optional(),prompts:x({listChanged:oe().optional()}).optional(),resources:x({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:x({listChanged:oe().optional()}).optional(),tasks:iI.optional(),extensions:ie(g(),Ce).optional()}),pl=xe.extend({protocolVersion:g(),capabilities:dI,serverInfo:gw,instructions:g().optional()}),yw=mt.extend({method:E("notifications/initialized"),params:ht.optional()}),vw=t=>yw.safeParse(t).success,Aa=Ae.extend({method:E("ping"),params:at.optional()}),lI=x({progress:W(),total:he(W()),message:he(g())}),pI=x({...ht.shape,...lI.shape,progressToken:uw}),$a=mt.extend({method:E("notifications/progress"),params:pI}),fI=at.extend({cursor:dw.optional()}),ys=Ae.extend({params:fI.optional()}),vs=xe.extend({nextCursor:dw.optional()}),hI=Ye(["working","input_required","completed","failed","cancelled"]),_s=x({taskId:g(),status:hI,ttl:ce([W(),KS()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:he(W()),statusMessage:he(g())}),rn=xe.extend({task:_s}),mI=ht.merge(_s),Ss=mt.extend({method:E("notifications/tasks/status"),params:mI}),Ma=Ae.extend({method:E("tasks/get"),params:at.extend({taskId:g()})}),Ia=xe.merge(_s),Oa=Ae.extend({method:E("tasks/result"),params:at.extend({taskId:g()})}),qB=xe.loose(),za=ys.extend({method:E("tasks/list")}),Na=vs.extend({tasks:C(_s)}),Da=Ae.extend({method:E("tasks/cancel"),params:at.extend({taskId:g()})}),_w=xe.merge(_s),Sw=x({uri:g(),mimeType:he(g()),_meta:ie(g(),fe()).optional()}),ww=Sw.extend({text:g()}),fl=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bw=Sw.extend({blob:fl}),ws=Ye(["user","assistant"]),Xn=x({audience:C(ws).optional(),priority:W().min(0).max(1).optional(),lastModified:ps.datetime({offset:!0}).optional()}),Rw=x({...Jn.shape,...gs.shape,uri:g(),description:he(g()),mimeType:he(g()),size:he(W()),annotations:Xn.optional(),_meta:he(Pe({}))}),gI=x({...Jn.shape,...gs.shape,uriTemplate:g(),description:he(g()),mimeType:he(g()),annotations:Xn.optional(),_meta:he(Pe({}))}),yI=ys.extend({method:E("resources/list")}),hl=vs.extend({resources:C(Rw)}),vI=ys.extend({method:E("resources/templates/list")}),ml=vs.extend({resourceTemplates:C(gI)}),gl=at.extend({uri:g()}),_I=gl,SI=Ae.extend({method:E("resources/read"),params:_I}),yl=xe.extend({contents:C(ce([ww,bw]))}),vl=mt.extend({method:E("notifications/resources/list_changed"),params:ht.optional()}),wI=gl,bI=Ae.extend({method:E("resources/subscribe"),params:wI}),RI=gl,PI=Ae.extend({method:E("resources/unsubscribe"),params:RI}),CI=ht.extend({uri:g()}),xI=mt.extend({method:E("notifications/resources/updated"),params:CI}),kI=x({name:g(),description:he(g()),required:he(oe())}),EI=x({...Jn.shape,...gs.shape,description:he(g()),arguments:he(C(kI)),_meta:he(Pe({}))}),TI=ys.extend({method:E("prompts/list")}),_l=vs.extend({prompts:C(EI)}),AI=at.extend({name:g(),arguments:ie(g(),g()).optional()}),$I=Ae.extend({method:E("prompts/get"),params:AI}),Sl=x({type:E("text"),text:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),wl=x({type:E("image"),data:fl,mimeType:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),bl=x({type:E("audio"),data:fl,mimeType:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),MI=x({type:E("tool_use"),name:g(),id:g(),input:ie(g(),fe()),_meta:ie(g(),fe()).optional()}),II=x({type:E("resource"),resource:ce([ww,bw]),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),OI=Rw.extend({type:E("resource_link")}),Rl=ce([Sl,wl,bl,OI,II]),zI=x({role:ws,content:Rl}),Pl=xe.extend({description:g().optional(),messages:C(zI)}),Cl=mt.extend({method:E("notifications/prompts/list_changed"),params:ht.optional()}),NI=x({title:g().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),DI=x({taskSupport:Ye(["required","optional","forbidden"]).optional()}),Pw=x({...Jn.shape,...gs.shape,description:g().optional(),inputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()),outputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()).optional(),annotations:NI.optional(),execution:DI.optional(),_meta:ie(g(),fe()).optional()}),LI=ys.extend({method:E("tools/list")}),xl=vs.extend({tools:C(Pw)}),nn=xe.extend({content:C(Rl).default([]),structuredContent:ie(g(),fe()).optional(),isError:oe().optional()}),HB=nn.or(xe.extend({toolResult:fe()})),jI=hs.extend({name:g(),arguments:ie(g(),fe()).optional()}),FI=Ae.extend({method:E("tools/call"),params:jI}),bs=mt.extend({method:E("notifications/tools/list_changed"),params:ht.optional()}),Cw=x({autoRefresh:oe().default(!0),debounceMs:W().int().nonnegative().default(300)}),xw=Ye(["debug","info","notice","warning","error","critical","alert","emergency"]),UI=at.extend({level:xw}),qI=Ae.extend({method:E("logging/setLevel"),params:UI}),HI=ht.extend({level:xw,logger:g().optional(),data:fe()}),GI=mt.extend({method:E("notifications/message"),params:HI}),ZI=x({name:g().optional()}),BI=x({hints:C(ZI).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),VI=x({mode:Ye(["auto","required","none"]).optional()}),WI=x({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(Rl).default([]),structuredContent:x({}).loose().optional(),isError:oe().optional(),_meta:ie(g(),fe()).optional()}),KI=il("type",[Sl,wl,bl]),xa=il("type",[Sl,wl,bl,MI,WI]),JI=x({role:ws,content:ce([xa,C(xa)]),_meta:ie(g(),fe()).optional()}),YI=hs.extend({messages:C(JI),modelPreferences:BI.optional(),systemPrompt:g().optional(),includeContext:Ye(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:C(g()).optional(),metadata:Ce.optional(),tools:C(Pw).optional(),toolChoice:VI.optional()}),kl=Ae.extend({method:E("sampling/createMessage"),params:YI}),El=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens"]).or(g())),role:ws,content:KI}),Tl=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:ws,content:ce([xa,C(xa)])}),XI=x({type:E("boolean"),title:g().optional(),description:g().optional(),default:oe().optional()}),QI=x({type:E("string"),title:g().optional(),description:g().optional(),minLength:W().optional(),maxLength:W().optional(),format:Ye(["email","uri","date","date-time"]).optional(),default:g().optional()}),eO=x({type:Ye(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),tO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),rO=x({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(x({const:g(),title:g()})),default:g().optional()}),nO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),oO=ce([tO,rO]),sO=x({type:E("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({type:E("string"),enum:C(g())}),default:C(g()).optional()}),iO=x({type:E("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({anyOf:C(x({const:g(),title:g()}))}),default:C(g()).optional()}),aO=ce([sO,iO]),cO=ce([nO,oO,aO]),uO=ce([cO,XI,QI,eO]),dO=hs.extend({mode:E("form").optional(),message:g(),requestedSchema:x({type:E("object"),properties:ie(g(),uO),required:C(g()).optional()})}),lO=hs.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),pO=ce([dO,lO]),Al=Ae.extend({method:E("elicitation/create"),params:pO}),fO=ht.extend({elicitationId:g()}),hO=mt.extend({method:E("notifications/elicitation/complete"),params:fO}),$l=xe.extend({action:Ye(["accept","decline","cancel"]),content:al(t=>t===null?void 0:t,ie(g(),ce([g(),W(),oe(),C(g())])).optional())}),mO=x({type:E("ref/resource"),uri:g()});var gO=x({type:E("ref/prompt"),name:g()}),yO=at.extend({ref:ce([gO,mO]),argument:x({name:g(),value:g()}),context:x({arguments:ie(g(),g()).optional()}).optional()}),vO=Ae.extend({method:E("completion/complete"),params:yO});var Ml=xe.extend({completion:Pe({values:C(g()).max(100),total:he(W().int()),hasMore:he(oe())})}),_O=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ie(g(),fe()).optional()}),SO=Ae.extend({method:E("roots/list"),params:at.optional()}),wO=xe.extend({roots:C(_O)}),bO=mt.extend({method:E("notifications/roots/list_changed"),params:ht.optional()}),GB=ce([Aa,uI,vO,qI,$I,TI,yI,vI,SI,bI,PI,FI,LI,Ma,Oa,za,Da]),ZB=ce([Ta,$a,yw,bO,Ss]),BB=ce([tn,El,Tl,$l,wO,Ia,Na,rn]),VB=ce([Aa,kl,Al,SO,Ma,Oa,za,Da]),WB=ce([Ta,$a,GI,xI,vl,bs,Cl,Ss,hO]),KB=ce([tn,pl,Ml,Pl,_l,hl,ml,yl,nn,xl,Ia,Na,rn]),$=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===M.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cl(o.elicitations,r)}return new t(e,r,n)}},cl=class extends ${constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function kr(t){return t==="completed"||t==="failed"||t==="cancelled"}var EV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Il(t){let r=Sa(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ol(t,e){let r=xt(t,e);if(!r.success)throw r.error;return r.data}var EO=6e4,La=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(Ta,r=>{this._oncancel(r)}),this.setNotificationHandler($a,r=>{this._onprogress(r)}),this.setRequestHandler(Aa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ma,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Oa,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,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,p=new $(l.error.code,l.error.message,l.error.data);d(p)}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 i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!kr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(kr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Cr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(za,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new $(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Da,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(kr(o.status))throw new $(M.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 s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new $(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof $?o:new $(M.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,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,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),$.fromError(M.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=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),en(s)||mw(s)?this._onresponse(s):ms(s)?this._onrequest(s,i):hw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},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=$.fromError(M.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,s=e.params?._meta?.[Cr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{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 i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=lw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,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(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{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)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),en(e))n(e);else{let i=new $(e.error.code,e.error.message,e.error.data);n(i)}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 s=!1;if(en(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),en(e))o(e);else{let i=$.fromError(e.error.code,e.error.message,e.error.data);o(i)}}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(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}return}let s;try{let i=await this.request(e,rn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new $(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},kr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,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 p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Cr]:c}});let h=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let b=w instanceof $?w:new $(M.RequestTimeout,String(w));d(b)};this._responseHandlers.set(p,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=xt(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??EO,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(p,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let w=b=>{let k=this._responseHandlers.get(p);k?k(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),d(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ia,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},Na,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},_w,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||{},[Cr]: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||{},[Cr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Cr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Il(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ol(e,o);return Promise.resolve(r(i,s))})}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=Il(e);this._notificationHandlers.set(n,o=>{let s=Ol(e,o);return Promise.resolve(r(s))})}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"&&ms(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new $(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} 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,s)=>{if(r.aborted){s(new $(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new $(M.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 s=await n.getTask(o,r);if(!s)throw new $(M.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Ss.parse({method:"notifications/tasks/status",params:a});await this.notification(c),kr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new $(M.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(kr(a.status))throw new $(M.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Ss.parse({method:"notifications/tasks/status",params:c});await this.notification(u),kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function kw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ew(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];kw(i)&&kw(s)?r[o]={...i,...s}:r[o]=s}return r}var vP=ki(wf(),1),_P=ki(yP(),1);function I1(){let t=new vP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,_P.default)(t),t}var wc=class{constructor(e){this._ajv=e??I1()}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 bc=class{constructor(e){this._client=e}async*callToolStream(e,r=nn,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:e},r,s),a=o.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new $(M.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 $(M.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof $){yield{type:"error",error:d};return}yield{type:"error",error:new $(M.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 SP(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 wP(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 Rc(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 s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Rc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Rc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Rc(r,e)}}function O1(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 Pc=class extends La{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 wc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",bs,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Cl,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",vl,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ew(this._capabilities,e)}setRequestHandler(e,r){let o=Sa(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=wa(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let d=xt(Al,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=O1(this._capabilities.elicitation);if(l.mode==="form"&&!p)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!f)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=xt(rn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new $(M.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let m=xt($l,h);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${w}`)}let y=m.data,S=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Rc(S,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=xt(kl,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let y=xt(rn,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=l.tools||l.toolChoice?Tl:El,m=xt(h,p);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}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:Yn,capabilities:this._capabilities,clientInfo:this._clientInfo}},pl,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!cw.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){SP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&wP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},tn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ml,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},tn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Pl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},_l,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},hl,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ml,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},yl,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},tn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},tn,r)}async callTool(e,r=nn,n){if(this.isToolTaskRequired(e.name))throw new $(M.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),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new $(M.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new $(M.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof $?i:new $(M.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}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},xl,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Cw.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let p=l instanceof Error?l:new Error(String(l));c(p,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Qs=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}},bP=10,z1=13,gn=32;function Tf(t){}function Cc(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=Tf,onError:r=Tf,onRetry:n=Tf,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,p,f=!1;function h(_){if(f)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))),i.length===0){let ge=y(_);ge!==""&&(i.push(ge),a=ge.length),m();return}if(_.indexOf(`
88
- `)===-1&&_.indexOf("\r")===-1){i.push(_),a+=_.length,m();return}i.push(_);let P=i.join("");i.length=0,a=0;let O=y(P);O!==""&&(i.push(O),a=O.length),m()}function m(){s!==void 0&&(a+d.length<=s||(f=!0,i.length=0,a=0,u=void 0,d="",l=0,p=void 0,r(new Qs(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(_){let P=0;if(_.indexOf("\r")===-1){let O=_.indexOf(`
87
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function el(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 f=t.seen.get(l),h=f.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 y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.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 s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=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,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:fs(e,"input",t.processors),output:fs(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function je(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 je(n.element,r);if(n.type==="set")return je(n.valueType,r);if(n.type==="lazy")return je(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 je(n.innerType,r);if(n.type==="intersection")return je(n.left,r)||je(n.right,r);if(n.type==="record"||n.type==="map")return je(n.keyType,r)||je(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:je(n.in,r)||je(n.out,r);if(n.type==="object"){for(let o in n.shape)if(je(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(je(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(je(o,r))return!0;return!!(n.rest&&je(n.rest,r))}return!1}var eS=(t,e={})=>r=>{let n=Xd({...r,processors:e});return ve(t,n),Qd(n,t),el(n,t)},fs=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Xd({...o??{},target:s,io:e,processors:r});return ve(t,i),Qd(i,t),el(i,t)};var Q$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},tS=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=Q$[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}))])}},rS=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,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>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";l?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},nS=(t,e,r,n)=>{r.type="boolean"},oS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var sS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var iS=(t,e,r,n)=>{r.not={}},aS=(t,e,r,n)=>{},cS=(t,e,r,n)=>{},uS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},dS=(t,e,r,n)=>{let o=t._zod.def,s=ns(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},lS=(t,e,r,n)=>{let o=t._zod.def,s=[];for(let i of o.values)if(i===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof i=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(i))}else s.push(i);if(s.length!==0)if(s.length===1){let i=s[0];r.type=i===null?"null":typeof i,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[i]:r.const=i}else s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),s.every(i=>typeof i=="boolean")&&(r.type="boolean"),s.every(i=>i===null)&&(r.type="null"),r.enum=s};var pS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var fS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var hS=(t,e,r,n)=>{let o=r,s=t._zod.def,{minimum:i,maximum:a}=t._zod.bag;typeof i=="number"&&(o.minItems=i),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=ve(s.element,e,{...n,path:[...n.path,"items"]})},mS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=ve(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=ve(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},gS=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ve(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},yS=(t,e,r,n)=>{let o=t._zod.def,s=ve(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=ve(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var vS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=ve(s.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=ve(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=ve(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},_S=(t,e,r,n)=>{let o=t._zod.def,s=ve(o.innerType,e,n),i=e.seen.get(t);e.target==="openapi-3.0"?(i.ref=o.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},SS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},wS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},bS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},RS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},PS=(t,e,r,n)=>{let o=t._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=e.io==="input"?s?o.out:o.in:o.out;ve(i,e,n);let a=e.seen.get(t);a.ref=i},CS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var tl=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function wa(t){return!!t._zod}function xt(t,e){return wa(t)?cs(t,e):t.safeParse(e)}function ba(t){if(!t)return;let e;if(wa(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ra(t){if(wa(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.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 hs={};cu(hs,{ZodISODate:()=>kS,ZodISODateTime:()=>xS,ZodISODuration:()=>TS,ZodISOTime:()=>ES,date:()=>nl,datetime:()=>rl,duration:()=>sl,time:()=>ol});var xS=v("ZodISODateTime",(t,e)=>{Pv.init(t,e),pe.init(t,e)});function rl(t){return z_(xS,t)}var kS=v("ZodISODate",(t,e)=>{Cv.init(t,e),pe.init(t,e)});function nl(t){return N_(kS,t)}var ES=v("ZodISOTime",(t,e)=>{xv.init(t,e),pe.init(t,e)});function ol(t){return D_(ES,t)}var TS=v("ZodISODuration",(t,e)=>{kv.init(t,e),pe.init(t,e)});function sl(t){return L_(TS,t)}var aM=(t,e)=>{la.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>kd(t,r)},flatten:{value:r=>xd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Zn,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Zn,2)}},isEmpty:{get(){return t.issues.length===0}}})};var at=v("ZodError",aM,{Parent:Error});var $S=pa(at),MS=fa(at),IS=as(at),OS=us(at),zS=ay(at),NS=cy(at),DS=uy(at),LS=dy(at),jS=ly(at),FS=py(at),US=fy(at),qS=hy(at);var HS=new WeakMap;function ms(t,e,r){let n=Object.getPrototypeOf(t),o=HS.get(n);if(o||(o=new Set,HS.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ne=v("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:fs(t,"input"),output:fs(t,"output")}}),t.toJSONSchema=eS(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>$S(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>IS(t,r,n),t.parseAsync=async(r,n)=>MS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>OS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>zS(t,r,n),t.decode=(r,n)=>NS(t,r,n),t.encodeAsync=async(r,n)=>DS(t,r,n),t.decodeAsync=async(r,n)=>LS(t,r,n),t.safeEncode=(r,n)=>jS(t,r,n),t.safeDecode=(r,n)=>FS(t,r,n),t.safeEncodeAsync=async(r,n)=>US(t,r,n),t.safeDecodeAsync=async(r,n)=>qS(t,r,n),ms(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.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 pt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(KM(r,n))},superRefine(r,n){return this.check(JM(r,n))},overwrite(r){return this.check(Cr(r))},optional(){return he(this)},exactOptional(){return DM(this)},nullable(){return VS(this)},nullish(){return he(VS(this))},nonoptional(r){return HM(this,r)},array(){return C(this)},or(r){return ce([this,r])},and(r){return xa(this,r)},transform(r){return WS(this,ow(r))},default(r){return FM(this,r)},prefault(r){return qM(this,r)},catch(r){return ZM(this,r)},pipe(r){return WS(this,r)},readonly(){return WM(this)},describe(r){let n=this.clone();return Pr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Pr.get(this);let n=this.clone();return Pr.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 Pr.get(t)?.description},configurable:!0}),t)),KS=v("_ZodString",(t,e)=>{va.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>tS(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,ms(t,"_ZodString",{regex(...n){return this.check(Ud(...n))},includes(...n){return this.check(Gd(...n))},startsWith(...n){return this.check(Zd(...n))},endsWith(...n){return this.check(Bd(...n))},min(...n){return this.check(Jn(...n))},max(...n){return this.check(_a(...n))},length(...n){return this.check(Sa(...n))},nonempty(...n){return this.check(Jn(1,...n))},lowercase(n){return this.check(qd(n))},uppercase(n){return this.check(Hd(n))},trim(){return this.check(Wd())},normalize(...n){return this.check(Vd(...n))},toLowerCase(){return this.check(Kd())},toUpperCase(){return this.check(Jd())},slugify(){return this.check(Yd())}})}),al=v("ZodString",(t,e)=>{va.init(t,e),KS.init(t,e),t.email=r=>t.check(m_(uM,r)),t.url=r=>t.check(Fd(JS,r)),t.jwt=r=>t.check(O_(PM,r)),t.emoji=r=>t.check(S_(dM,r)),t.guid=r=>t.check(jd(GS,r)),t.uuid=r=>t.check(g_(Pa,r)),t.uuidv4=r=>t.check(y_(Pa,r)),t.uuidv6=r=>t.check(v_(Pa,r)),t.uuidv7=r=>t.check(__(Pa,r)),t.nanoid=r=>t.check(w_(lM,r)),t.guid=r=>t.check(jd(GS,r)),t.cuid=r=>t.check(b_(pM,r)),t.cuid2=r=>t.check(R_(fM,r)),t.ulid=r=>t.check(P_(hM,r)),t.base64=r=>t.check($_(wM,r)),t.base64url=r=>t.check(M_(bM,r)),t.xid=r=>t.check(C_(mM,r)),t.ksuid=r=>t.check(x_(gM,r)),t.ipv4=r=>t.check(k_(yM,r)),t.ipv6=r=>t.check(E_(vM,r)),t.cidrv4=r=>t.check(T_(_M,r)),t.cidrv6=r=>t.check(A_(SM,r)),t.e164=r=>t.check(I_(RM,r)),t.datetime=r=>t.check(rl(r)),t.date=r=>t.check(nl(r)),t.time=r=>t.check(ol(r)),t.duration=r=>t.check(sl(r))});function g(t){return f_(al,t)}var pe=v("ZodStringFormat",(t,e)=>{ae.init(t,e),KS.init(t,e)}),uM=v("ZodEmail",(t,e)=>{mv.init(t,e),pe.init(t,e)});var GS=v("ZodGUID",(t,e)=>{fv.init(t,e),pe.init(t,e)});var Pa=v("ZodUUID",(t,e)=>{hv.init(t,e),pe.init(t,e)});var JS=v("ZodURL",(t,e)=>{gv.init(t,e),pe.init(t,e)});function YS(t){return Fd(JS,t)}var dM=v("ZodEmoji",(t,e)=>{yv.init(t,e),pe.init(t,e)});var lM=v("ZodNanoID",(t,e)=>{vv.init(t,e),pe.init(t,e)});var pM=v("ZodCUID",(t,e)=>{_v.init(t,e),pe.init(t,e)});var fM=v("ZodCUID2",(t,e)=>{Sv.init(t,e),pe.init(t,e)});var hM=v("ZodULID",(t,e)=>{wv.init(t,e),pe.init(t,e)});var mM=v("ZodXID",(t,e)=>{bv.init(t,e),pe.init(t,e)});var gM=v("ZodKSUID",(t,e)=>{Rv.init(t,e),pe.init(t,e)});var yM=v("ZodIPv4",(t,e)=>{Ev.init(t,e),pe.init(t,e)});var vM=v("ZodIPv6",(t,e)=>{Tv.init(t,e),pe.init(t,e)});var _M=v("ZodCIDRv4",(t,e)=>{Av.init(t,e),pe.init(t,e)});var SM=v("ZodCIDRv6",(t,e)=>{$v.init(t,e),pe.init(t,e)});var wM=v("ZodBase64",(t,e)=>{Iv.init(t,e),pe.init(t,e)});var bM=v("ZodBase64URL",(t,e)=>{Ov.init(t,e),pe.init(t,e)});var RM=v("ZodE164",(t,e)=>{zv.init(t,e),pe.init(t,e)});var PM=v("ZodJWT",(t,e)=>{Nv.init(t,e),pe.init(t,e)});var Ca=v("ZodNumber",(t,e)=>{Od.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>rS(t,n,o,s),ms(t,"ZodNumber",{gt(n,o){return this.check(Kn(n,o))},gte(n,o){return this.check(Ct(n,o))},min(n,o){return this.check(Ct(n,o))},lt(n,o){return this.check(Wn(n,o))},lte(n,o){return this.check(rr(n,o))},max(n,o){return this.check(rr(n,o))},int(n){return this.check(ZS(n))},safe(n){return this.check(ZS(n))},positive(n){return this.check(Kn(0,n))},nonnegative(n){return this.check(Ct(0,n))},negative(n){return this.check(Wn(0,n))},nonpositive(n){return this.check(rr(0,n))},multipleOf(n,o){return this.check(ps(n,o))},step(n,o){return this.check(ps(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 W(t){return j_(Ca,t)}var CM=v("ZodNumberFormat",(t,e)=>{Dv.init(t,e),Ca.init(t,e)});function ZS(t){return U_(CM,t)}var cl=v("ZodBoolean",(t,e)=>{Lv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nS(t,r,n,o)});function oe(t){return q_(cl,t)}var XS=v("ZodBigInt",(t,e)=>{jv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>oS(t,n,o,s),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.gt=(n,o)=>t.check(Kn(n,o)),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.lt=(n,o)=>t.check(Wn(n,o)),t.lte=(n,o)=>t.check(rr(n,o)),t.max=(n,o)=>t.check(rr(n,o)),t.positive=n=>t.check(Kn(BigInt(0),n)),t.negative=n=>t.check(Wn(BigInt(0),n)),t.nonpositive=n=>t.check(rr(BigInt(0),n)),t.nonnegative=n=>t.check(Ct(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(ps(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var xM=v("ZodNull",(t,e)=>{Fv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sS(t,r,n,o)});function QS(t){return Z_(xM,t)}var kM=v("ZodAny",(t,e)=>{Uv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(t,r,n,o)});function ew(){return B_(kM)}var EM=v("ZodUnknown",(t,e)=>{qv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cS(t,r,n,o)});function fe(){return V_(EM)}var TM=v("ZodNever",(t,e)=>{Hv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>iS(t,r,n,o)});function AM(t){return W_(TM,t)}var tw=v("ZodDate",(t,e)=>{Gv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>uS(t,n,o,s),t.min=(n,o)=>t.check(Ct(n,o)),t.max=(n,o)=>t.check(rr(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 $M=v("ZodArray",(t,e)=>{Zv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(t,r,n,o),t.element=e.element,ms(t,"ZodArray",{min(r,n){return this.check(Jn(r,n))},nonempty(r){return this.check(Jn(1,r))},max(r,n){return this.check(_a(r,n))},length(r,n){return this.check(Sa(r,n))},unwrap(){return this.element}})});function C(t,e){return J_($M,t,e)}var rw=v("ZodObject",(t,e)=>{Wv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),ms(t,"ZodObject",{keyof(){return Je(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:fe()})},loose(){return this.clone({...this._zod.def,catchall:fe()})},strict(){return this.clone({...this._zod.def,catchall:AM()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(sw,this,r[0])},required(...r){return U.required(iw,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new rw(r)}function Pe(t,e){return new rw({type:"object",shape:t,catchall:fe(),...U.normalizeParams(e)})}var nw=v("ZodUnion",(t,e)=>{zd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gS(t,r,n,o),t.options=e.options});function ce(t,e){return new nw({type:"union",options:t,...U.normalizeParams(e)})}var MM=v("ZodDiscriminatedUnion",(t,e)=>{nw.init(t,e),Kv.init(t,e)});function ul(t,e,r){return new MM({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var IM=v("ZodIntersection",(t,e)=>{Jv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>yS(t,r,n,o)});function xa(t,e){return new IM({type:"intersection",left:t,right:e})}var BS=v("ZodRecord",(t,e)=>{Yv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ie(t,e,r){return!e||!e._zod?new BS({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new BS({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var il=v("ZodEnum",(t,e)=>{Xv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>dS(t,n,o,s),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new il({...e,checks:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new il({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Je(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new il({type:"enum",entries:r,...U.normalizeParams(e)})}var OM=v("ZodLiteral",(t,e)=>{Qv.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(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 E(t,e){return new OM({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var zM=v("ZodTransform",(t,e)=>{e_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Hn(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function ow(t){return new zM({type:"transform",transform:t})}var sw=v("ZodOptional",(t,e)=>{Nd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function he(t){return new sw({type:"optional",innerType:t})}var NM=v("ZodExactOptional",(t,e)=>{t_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function DM(t){return new NM({type:"optional",innerType:t})}var LM=v("ZodNullable",(t,e)=>{r_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function VS(t){return new LM({type:"nullable",innerType:t})}var jM=v("ZodDefault",(t,e)=>{n_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>wS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function FM(t,e){return new jM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var UM=v("ZodPrefault",(t,e)=>{o_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function qM(t,e){return new UM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var iw=v("ZodNonOptional",(t,e)=>{s_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>SS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function HM(t,e){return new iw({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var GM=v("ZodCatch",(t,e)=>{i_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>RS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ZM(t,e){return new GM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var aw=v("ZodPipe",(t,e)=>{Dd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>PS(t,r,n,o),t.in=e.in,t.out=e.out});function WS(t,e){return new aw({type:"pipe",in:t,out:e})}var BM=v("ZodPreprocess",(t,e)=>{aw.init(t,e),a_.init(t,e)}),VM=v("ZodReadonly",(t,e)=>{c_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>CS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function WM(t){return new VM({type:"readonly",innerType:t})}var cw=v("ZodCustom",(t,e)=>{u_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o)});function uw(t,e){return Y_(cw,t??(()=>!0),e)}function KM(t,e={}){return X_(cw,t,e)}function JM(t,e){return Q_(t,e)}function dl(t,e){return new BM({type:"pipe",in:ow(t),out:e})}var lw={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 dw;dw||(dw={});var ka={};cu(ka,{bigint:()=>eI,boolean:()=>QM,date:()=>tI,number:()=>XM,string:()=>YM});function YM(t){return h_(al,t)}function XM(t){return F_(Ca,t)}function QM(t){return H_(cl,t)}function eI(t){return G_(XS,t)}function tI(t){return K_(tw,t)}Ke(d_());var Qn="2025-11-25";var pw=[Qn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xr="io.modelcontextprotocol/related-task",Ta="2.0",Ce=uw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),fw=ce([g(),W().int()]),hw=g(),ZB=Pe({ttl:W().optional(),pollInterval:W().optional()}),nI=x({ttl:W().optional()}),oI=x({taskId:g()}),pl=Pe({progressToken:fw.optional(),[xr]:oI.optional()}),ct=x({_meta:pl.optional()}),gs=ct.extend({task:nI.optional()}),mw=t=>gs.safeParse(t).success,Ae=x({method:g(),params:ct.loose().optional()}),ht=x({_meta:pl.optional()}),mt=x({method:g(),params:ht.loose().optional()}),xe=Pe({_meta:pl.optional()}),Aa=ce([g(),W().int()]),gw=x({jsonrpc:E(Ta),id:Aa,...Ae.shape}).strict(),ys=t=>gw.safeParse(t).success,yw=x({jsonrpc:E(Ta),...mt.shape}).strict(),vw=t=>yw.safeParse(t).success,fl=x({jsonrpc:E(Ta),id:Aa,result:xe}).strict(),tn=t=>fl.safeParse(t).success;var M;(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"})(M||(M={}));var hl=x({jsonrpc:E(Ta),id:Aa.optional(),error:x({code:W().int(),message:g(),data:fe().optional()})}).strict();var _w=t=>hl.safeParse(t).success;var kr=ce([gw,yw,fl,hl]),BB=ce([fl,hl]),rn=xe.strict(),sI=ht.extend({requestId:Aa.optional(),reason:g().optional()}),$a=mt.extend({method:E("notifications/cancelled"),params:sI}),iI=x({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Je(["light","dark"]).optional()}),vs=x({icons:C(iI).optional()}),Xn=x({name:g(),title:g().optional()}),Sw=Xn.extend({...Xn.shape,...vs.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),aI=xa(x({applyDefaults:oe().optional()}),ie(g(),fe())),cI=dl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,xa(x({form:aI.optional(),url:Ce.optional()}),ie(g(),fe()).optional())),uI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({sampling:Pe({createMessage:Ce.optional()}).optional(),elicitation:Pe({create:Ce.optional()}).optional()}).optional()}),dI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({tools:Pe({call:Ce.optional()}).optional()}).optional()}),lI=x({experimental:ie(g(),Ce).optional(),sampling:x({context:Ce.optional(),tools:Ce.optional()}).optional(),elicitation:cI.optional(),roots:x({listChanged:oe().optional()}).optional(),tasks:uI.optional(),extensions:ie(g(),Ce).optional()}),pI=ct.extend({protocolVersion:g(),capabilities:lI,clientInfo:Sw}),fI=Ae.extend({method:E("initialize"),params:pI});var hI=x({experimental:ie(g(),Ce).optional(),logging:Ce.optional(),completions:Ce.optional(),prompts:x({listChanged:oe().optional()}).optional(),resources:x({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:x({listChanged:oe().optional()}).optional(),tasks:dI.optional(),extensions:ie(g(),Ce).optional()}),ml=xe.extend({protocolVersion:g(),capabilities:hI,serverInfo:Sw,instructions:g().optional()}),ww=mt.extend({method:E("notifications/initialized"),params:ht.optional()}),bw=t=>ww.safeParse(t).success,Ma=Ae.extend({method:E("ping"),params:ct.optional()}),mI=x({progress:W(),total:he(W()),message:he(g())}),gI=x({...ht.shape,...mI.shape,progressToken:fw}),Ia=mt.extend({method:E("notifications/progress"),params:gI}),yI=ct.extend({cursor:hw.optional()}),_s=Ae.extend({params:yI.optional()}),Ss=xe.extend({nextCursor:hw.optional()}),vI=Je(["working","input_required","completed","failed","cancelled"]),ws=x({taskId:g(),status:vI,ttl:ce([W(),QS()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:he(W()),statusMessage:he(g())}),nn=xe.extend({task:ws}),_I=ht.merge(ws),bs=mt.extend({method:E("notifications/tasks/status"),params:_I}),Oa=Ae.extend({method:E("tasks/get"),params:ct.extend({taskId:g()})}),za=xe.merge(ws),Na=Ae.extend({method:E("tasks/result"),params:ct.extend({taskId:g()})}),VB=xe.loose(),Da=_s.extend({method:E("tasks/list")}),La=Ss.extend({tasks:C(ws)}),ja=Ae.extend({method:E("tasks/cancel"),params:ct.extend({taskId:g()})}),Rw=xe.merge(ws),Pw=x({uri:g(),mimeType:he(g()),_meta:ie(g(),fe()).optional()}),Cw=Pw.extend({text:g()}),gl=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),xw=Pw.extend({blob:gl}),Rs=Je(["user","assistant"]),eo=x({audience:C(Rs).optional(),priority:W().min(0).max(1).optional(),lastModified:hs.datetime({offset:!0}).optional()}),kw=x({...Xn.shape,...vs.shape,uri:g(),description:he(g()),mimeType:he(g()),size:he(W()),annotations:eo.optional(),_meta:he(Pe({}))}),SI=x({...Xn.shape,...vs.shape,uriTemplate:g(),description:he(g()),mimeType:he(g()),annotations:eo.optional(),_meta:he(Pe({}))}),wI=_s.extend({method:E("resources/list")}),yl=Ss.extend({resources:C(kw)}),bI=_s.extend({method:E("resources/templates/list")}),vl=Ss.extend({resourceTemplates:C(SI)}),_l=ct.extend({uri:g()}),RI=_l,PI=Ae.extend({method:E("resources/read"),params:RI}),Sl=xe.extend({contents:C(ce([Cw,xw]))}),wl=mt.extend({method:E("notifications/resources/list_changed"),params:ht.optional()}),CI=_l,xI=Ae.extend({method:E("resources/subscribe"),params:CI}),kI=_l,EI=Ae.extend({method:E("resources/unsubscribe"),params:kI}),TI=ht.extend({uri:g()}),AI=mt.extend({method:E("notifications/resources/updated"),params:TI}),$I=x({name:g(),description:he(g()),required:he(oe())}),MI=x({...Xn.shape,...vs.shape,description:he(g()),arguments:he(C($I)),_meta:he(Pe({}))}),II=_s.extend({method:E("prompts/list")}),bl=Ss.extend({prompts:C(MI)}),OI=ct.extend({name:g(),arguments:ie(g(),g()).optional()}),zI=Ae.extend({method:E("prompts/get"),params:OI}),Rl=x({type:E("text"),text:g(),annotations:eo.optional(),_meta:ie(g(),fe()).optional()}),Pl=x({type:E("image"),data:gl,mimeType:g(),annotations:eo.optional(),_meta:ie(g(),fe()).optional()}),Cl=x({type:E("audio"),data:gl,mimeType:g(),annotations:eo.optional(),_meta:ie(g(),fe()).optional()}),NI=x({type:E("tool_use"),name:g(),id:g(),input:ie(g(),fe()),_meta:ie(g(),fe()).optional()}),DI=x({type:E("resource"),resource:ce([Cw,xw]),annotations:eo.optional(),_meta:ie(g(),fe()).optional()}),LI=kw.extend({type:E("resource_link")}),xl=ce([Rl,Pl,Cl,LI,DI]),jI=x({role:Rs,content:xl}),kl=xe.extend({description:g().optional(),messages:C(jI)}),El=mt.extend({method:E("notifications/prompts/list_changed"),params:ht.optional()}),FI=x({title:g().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),UI=x({taskSupport:Je(["required","optional","forbidden"]).optional()}),Ew=x({...Xn.shape,...vs.shape,description:g().optional(),inputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()),outputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()).optional(),annotations:FI.optional(),execution:UI.optional(),_meta:ie(g(),fe()).optional()}),qI=_s.extend({method:E("tools/list")}),Tl=Ss.extend({tools:C(Ew)}),on=xe.extend({content:C(xl).default([]),structuredContent:ie(g(),fe()).optional(),isError:oe().optional()}),WB=on.or(xe.extend({toolResult:fe()})),HI=gs.extend({name:g(),arguments:ie(g(),fe()).optional()}),GI=Ae.extend({method:E("tools/call"),params:HI}),Ps=mt.extend({method:E("notifications/tools/list_changed"),params:ht.optional()}),Tw=x({autoRefresh:oe().default(!0),debounceMs:W().int().nonnegative().default(300)}),Aw=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),ZI=ct.extend({level:Aw}),BI=Ae.extend({method:E("logging/setLevel"),params:ZI}),VI=ht.extend({level:Aw,logger:g().optional(),data:fe()}),WI=mt.extend({method:E("notifications/message"),params:VI}),KI=x({name:g().optional()}),JI=x({hints:C(KI).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),YI=x({mode:Je(["auto","required","none"]).optional()}),XI=x({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(xl).default([]),structuredContent:x({}).loose().optional(),isError:oe().optional(),_meta:ie(g(),fe()).optional()}),QI=ul("type",[Rl,Pl,Cl]),Ea=ul("type",[Rl,Pl,Cl,NI,XI]),eO=x({role:Rs,content:ce([Ea,C(Ea)]),_meta:ie(g(),fe()).optional()}),tO=gs.extend({messages:C(eO),modelPreferences:JI.optional(),systemPrompt:g().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:C(g()).optional(),metadata:Ce.optional(),tools:C(Ew).optional(),toolChoice:YI.optional()}),Al=Ae.extend({method:E("sampling/createMessage"),params:tO}),$l=xe.extend({model:g(),stopReason:he(Je(["endTurn","stopSequence","maxTokens"]).or(g())),role:Rs,content:QI}),Ml=xe.extend({model:g(),stopReason:he(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Rs,content:ce([Ea,C(Ea)])}),rO=x({type:E("boolean"),title:g().optional(),description:g().optional(),default:oe().optional()}),nO=x({type:E("string"),title:g().optional(),description:g().optional(),minLength:W().optional(),maxLength:W().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:g().optional()}),oO=x({type:Je(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),sO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),iO=x({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(x({const:g(),title:g()})),default:g().optional()}),aO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),cO=ce([sO,iO]),uO=x({type:E("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({type:E("string"),enum:C(g())}),default:C(g()).optional()}),dO=x({type:E("array"),title:g().optional(),description:g().optional(),minItems:W().optional(),maxItems:W().optional(),items:x({anyOf:C(x({const:g(),title:g()}))}),default:C(g()).optional()}),lO=ce([uO,dO]),pO=ce([aO,cO,lO]),fO=ce([pO,rO,nO,oO]),hO=gs.extend({mode:E("form").optional(),message:g(),requestedSchema:x({type:E("object"),properties:ie(g(),fO),required:C(g()).optional()})}),mO=gs.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),gO=ce([hO,mO]),Il=Ae.extend({method:E("elicitation/create"),params:gO}),yO=ht.extend({elicitationId:g()}),vO=mt.extend({method:E("notifications/elicitation/complete"),params:yO}),Ol=xe.extend({action:Je(["accept","decline","cancel"]),content:dl(t=>t===null?void 0:t,ie(g(),ce([g(),W(),oe(),C(g())])).optional())}),_O=x({type:E("ref/resource"),uri:g()});var SO=x({type:E("ref/prompt"),name:g()}),wO=ct.extend({ref:ce([SO,_O]),argument:x({name:g(),value:g()}),context:x({arguments:ie(g(),g()).optional()}).optional()}),bO=Ae.extend({method:E("completion/complete"),params:wO});var zl=xe.extend({completion:Pe({values:C(g()).max(100),total:he(W().int()),hasMore:he(oe())})}),RO=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ie(g(),fe()).optional()}),PO=Ae.extend({method:E("roots/list"),params:ct.optional()}),CO=xe.extend({roots:C(RO)}),xO=mt.extend({method:E("notifications/roots/list_changed"),params:ht.optional()}),KB=ce([Ma,fI,bO,BI,zI,II,wI,bI,PI,xI,EI,GI,qI,Oa,Na,Da,ja]),JB=ce([$a,Ia,ww,xO,bs]),YB=ce([rn,$l,Ml,Ol,CO,za,La,nn]),XB=ce([Ma,Al,Il,PO,Oa,Na,Da,ja]),QB=ce([$a,Ia,WI,AI,wl,Ps,El,bs,vO]),eV=ce([rn,ml,zl,kl,bl,yl,vl,Sl,on,Tl,za,La,nn]),$=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===M.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ll(o.elicitations,r)}return new t(e,r,n)}},ll=class extends ${constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Er(t){return t==="completed"||t==="failed"||t==="cancelled"}var IV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nl(t){let r=ba(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ra(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Dl(t,e){let r=xt(t,e);if(!r.success)throw r.error;return r.data}var MO=6e4,Fa=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($a,r=>{this._oncancel(r)}),this.setNotificationHandler(Ia,r=>{this._onprogress(r)}),this.setRequestHandler(Ma,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Oa,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Na,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,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,p=new $(l.error.code,l.error.message,l.error.data);d(p)}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 i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!Er(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Er(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[xr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Da,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new $(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ja,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(Er(o.status))throw new $(M.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 s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new $(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof $?o:new $(M.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,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,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),$.fromError(M.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=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),tn(s)||_w(s)?this._onresponse(s):ys(s)?this._onrequest(s,i):vw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},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=$.fromError(M.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,s=e.params?._meta?.[xr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{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 i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=mw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,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(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{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)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),tn(e))n(e);else{let i=new $(e.error.code,e.error.message,e.error.data);n(i)}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 s=!1;if(tn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),tn(e))o(e);else{let i=$.fromError(e.error.code,e.error.message,e.error.data);o(i)}}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(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}return}let s;try{let i=await this.request(e,nn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new $(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Er(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,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 p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[xr]:c}});let h=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let b=w instanceof $?w:new $(M.RequestTimeout,String(w));d(b)};this._responseHandlers.set(p,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=xt(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??MO,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(p,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let w=b=>{let k=this._responseHandlers.get(p);k?k(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),d(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},za,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},La,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Rw,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||{},[xr]: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||{},[xr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[xr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Nl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Dl(e,o);return Promise.resolve(r(i,s))})}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=Nl(e);this._notificationHandlers.set(n,o=>{let s=Dl(e,o);return Promise.resolve(r(s))})}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"&&ys(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new $(M.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} 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,s)=>{if(r.aborted){s(new $(M.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new $(M.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 s=await n.getTask(o,r);if(!s)throw new $(M.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=bs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Er(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new $(M.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Er(a.status))throw new $(M.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=bs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Er(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function $w(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Mw(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];$w(i)&&$w(s)?r[o]={...i,...s}:r[o]=s}return r}var bP=Ti(Pf(),1),RP=Ti(wP(),1);function D1(){let t=new bP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,RP.default)(t),t}var Rc=class{constructor(e){this._ajv=e??D1()}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 Pc=class{constructor(e){this._client=e}async*callToolStream(e,r=on,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:e},r,s),a=o.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new $(M.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 $(M.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof $){yield{type:"error",error:d};return}yield{type:"error",error:new $(M.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 PP(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 CP(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 Cc(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 s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Cc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Cc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Cc(r,e)}}function L1(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 xc=class extends Fa{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 Rc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ps,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",El,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",wl,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Pc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Mw(this._capabilities,e)}setRequestHandler(e,r){let o=ba(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ra(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let d=xt(Il,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=L1(this._capabilities.elicitation);if(l.mode==="form"&&!p)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!f)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=xt(nn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new $(M.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let m=xt(Ol,h);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${w}`)}let y=m.data,S=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Cc(S,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=xt(Al,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let y=xt(nn,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=l.tools||l.toolChoice?Ml:$l,m=xt(h,p);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}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:Qn,capabilities:this._capabilities,clientInfo:this._clientInfo}},ml,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!pw.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){PP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&CP(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},zl,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},kl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},bl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},yl,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},vl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Sl,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=on,n){if(this.isToolTaskRequired(e.name))throw new $(M.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),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new $(M.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new $(M.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof $?i:new $(M.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}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},Tl,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Tw.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let p=l instanceof Error?l:new Error(String(l));c(p,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var ti=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}},xP=10,j1=13,yn=32;function Mf(t){}function kc(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=Mf,onError:r=Mf,onRetry:n=Mf,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,p,f=!1;function h(_){if(f)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))),i.length===0){let ge=y(_);ge!==""&&(i.push(ge),a=ge.length),m();return}if(_.indexOf(`
88
+ `)===-1&&_.indexOf("\r")===-1){i.push(_),a+=_.length,m();return}i.push(_);let P=i.join("");i.length=0,a=0;let O=y(P);O!==""&&(i.push(O),a=O.length),m()}function m(){s!==void 0&&(a+d.length<=s||(f=!0,i.length=0,a=0,u=void 0,d="",l=0,p=void 0,r(new ti(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(_){let P=0;if(_.indexOf("\r")===-1){let O=_.indexOf(`
89
89
  `,P);for(;O!==-1;){if(P===O){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0,P=O+1,O=_.indexOf(`
90
- `,P);continue}let ge=_.charCodeAt(P);if(RP(_,P,ge)){let ye=_.charCodeAt(P+5)===gn?P+6:P+5,Ze=_.slice(ye,O);if(l===0&&_.charCodeAt(O+1)===bP){e({id:u,event:p,data:Ze}),u=void 0,d="",p=void 0,P=O+2,O=_.indexOf(`
90
+ `,P);continue}let ge=_.charCodeAt(P);if(kP(_,P,ge)){let ye=_.charCodeAt(P+5)===yn?P+6:P+5,Ze=_.slice(ye,O);if(l===0&&_.charCodeAt(O+1)===xP){e({id:u,event:p,data:Ze}),u=void 0,d="",p=void 0,P=O+2,O=_.indexOf(`
91
91
  `,P);continue}d=l===0?Ze:`${d}
92
- ${Ze}`,l++}else PP(_,P,ge)?p=_.slice(_.charCodeAt(P+6)===gn?P+7:P+6,O)||void 0:S(_,P,O);P=O+1,O=_.indexOf(`
92
+ ${Ze}`,l++}else EP(_,P,ge)?p=_.slice(_.charCodeAt(P+6)===yn?P+7:P+6,O)||void 0:S(_,P,O);P=O+1,O=_.indexOf(`
93
93
  `,P)}return _.slice(P)}for(;P<_.length;){let O=_.indexOf("\r",P),ge=_.indexOf(`
94
- `,P),ye=-1;if(O!==-1&&ge!==-1?ye=O<ge?O:ge:O!==-1?O===_.length-1?ye=-1:ye=O:ge!==-1&&(ye=ge),ye===-1)break;S(_,P,ye),P=ye+1,_.charCodeAt(P-1)===z1&&_.charCodeAt(P)===bP&&P++}return _.slice(P)}function S(_,P,O){if(P===O){b();return}let ge=_.charCodeAt(P);if(RP(_,P,ge)){let lr=_.charCodeAt(P+5)===gn?P+6:P+5,Uh=_.slice(lr,O);d=l===0?Uh:`${d}
95
- ${Uh}`,l++;return}if(PP(_,P,ge)){p=_.slice(_.charCodeAt(P+6)===gn?P+7:P+6,O)||void 0;return}if(ge===105&&_.charCodeAt(P+1)===100&&_.charCodeAt(P+2)===58){let lr=_.slice(_.charCodeAt(P+3)===gn?P+4:P+3,O);u=lr.includes("\0")?void 0:lr;return}if(ge===58){if(o){let lr=_.slice(P,O);o(lr.slice(_.charCodeAt(P+1)===gn?2:1))}return}let ye=_.slice(P,O),Ze=ye.indexOf(":");if(Ze===-1){w(ye,"",ye);return}let Ao=ye.slice(0,Ze),Ci=ye.charCodeAt(Ze+1)===gn?2:1,xi=ye.slice(Ze+Ci);w(Ao,xi,ye)}function w(_,P,O){switch(_){case"event":p=P||void 0;break;case"data":d=l===0?P:`${d}
96
- ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new Qs(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:O}));break;default:r(new Qs(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:P,line:O}));break}}function b(){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0}function k(_={}){if(_.consume&&i.length>0){let P=i.join("");S(P,0,P.length)}c=!0,u=void 0,d="",l=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:k}}function RP(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 PP(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 kc=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(CP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(CP(this),r)}};function N1(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Af(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Af).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Af(t.cause)}`:t.message:`${t}`}function CP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var kP=t=>{throw TypeError(t)},Lf=(t,e,r)=>e.has(t)||kP("Cannot "+r),F=(t,e,r)=>(Lf(t,e,"read from private field"),r?r.call(t):e.get(t)),ke=(t,e,r)=>e.has(t)?kP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),me=(t,e,r,n)=>(Lf(t,e,"write to private field"),e.set(t,r),r),cr=(t,e,r)=>(Lf(t,e,"access private method"),r),rt,yn,yo,xc,Ec,ri,So,ni,Nr,vo,wo,_o,ei,Mt,$f,Mf,If,xP,Of,zf,ti,Nf,Df,vn=class extends EventTarget{constructor(e,r){var n,o;super(),ke(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ke(this,rt),ke(this,yn),ke(this,yo),ke(this,xc),ke(this,Ec),ke(this,ri),ke(this,So),ke(this,ni,null),ke(this,Nr),ke(this,vo),ke(this,wo,null),ke(this,_o,null),ke(this,ei,null),ke(this,Mf,async s=>{var i;F(this,vo).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){cr(this,Mt,ti).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?me(this,yo,new URL(s.url)):me(this,yo,void 0),u!==200){cr(this,Mt,ti).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){cr(this,Mt,ti).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,rt)===this.CLOSED)return;me(this,rt,this.OPEN);let l=new Event("open");if((i=F(this,ei))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){cr(this,Mt,ti).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,f=a.getReader(),h=!0;do{let{done:m,value:y}=await f.read();y&&F(this,vo).feed(p.decode(y,{stream:!m})),m&&(h=!1,F(this,vo).reset(),cr(this,Mt,Nf).call(this))}while(h)}),ke(this,If,s=>{me(this,Nr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&cr(this,Mt,Nf).call(this,Af(s))}),ke(this,Of,s=>{typeof s.id=="string"&&me(this,ni,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,yo)?F(this,yo).origin:F(this,yn).origin,lastEventId:s.id||""});F(this,_o)&&(!s.event||s.event==="message")&&F(this,_o).call(this,i),this.dispatchEvent(i)}),ke(this,zf,s=>{me(this,ri,s)}),ke(this,Df,()=>{me(this,So,void 0),F(this,rt)===this.CONNECTING&&cr(this,Mt,$f).call(this)});try{if(e instanceof URL)me(this,yn,e);else if(typeof e=="string")me(this,yn,new URL(e,D1()));else throw new Error("Invalid URL")}catch{throw N1("An invalid or illegal string was specified")}me(this,vo,Cc({onEvent:F(this,Of),onRetry:F(this,zf)})),me(this,rt,this.CONNECTING),me(this,ri,3e3),me(this,Ec,(n=r?.fetch)!=null?n:globalThis.fetch),me(this,xc,(o=r?.withCredentials)!=null?o:!1),cr(this,Mt,$f).call(this)}get readyState(){return F(this,rt)}get url(){return F(this,yn).href}get withCredentials(){return F(this,xc)}get onerror(){return F(this,wo)}set onerror(e){me(this,wo,e)}get onmessage(){return F(this,_o)}set onmessage(e){me(this,_o,e)}get onopen(){return F(this,ei)}set onopen(e){me(this,ei,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(){F(this,So)&&clearTimeout(F(this,So)),F(this,rt)!==this.CLOSED&&(F(this,Nr)&&F(this,Nr).abort(),me(this,rt,this.CLOSED),me(this,Nr,void 0))}};rt=new WeakMap,yn=new WeakMap,yo=new WeakMap,xc=new WeakMap,Ec=new WeakMap,ri=new WeakMap,So=new WeakMap,ni=new WeakMap,Nr=new WeakMap,vo=new WeakMap,wo=new WeakMap,_o=new WeakMap,ei=new WeakMap,Mt=new WeakSet,$f=function(){me(this,rt,this.CONNECTING),me(this,Nr,new AbortController),F(this,Ec)(F(this,yn),cr(this,Mt,xP).call(this)).then(F(this,Mf)).catch(F(this,If))},Mf=new WeakMap,If=new WeakMap,xP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,ni)?{"Last-Event-ID":F(this,ni)}:void 0},cache:"no-store",signal:(t=F(this,Nr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Of=new WeakMap,zf=new WeakMap,ti=function(t,e){var r;F(this,rt)!==this.CLOSED&&me(this,rt,this.CLOSED);let n=new kc("error",{code:e,message:t});(r=F(this,wo))==null||r.call(this,n),this.dispatchEvent(n)},Nf=function(t,e){var r;if(F(this,rt)===this.CLOSED)return;me(this,rt,this.CONNECTING);let n=new kc("error",{code:e,message:t});(r=F(this,wo))==null||r.call(this,n),this.dispatchEvent(n),me(this,So,setTimeout(F(this,Df),F(this,ri)))},Df=new WeakMap,vn.CONNECTING=0,vn.OPEN=1,vn.CLOSED=2;function D1(){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 bo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Tc(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...bo(e.headers),...bo(n.headers)}:e.headers};return t(r,o)}:t}var jf;jf=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function L1(t){return(await jf).getRandomValues(new Uint8Array(t))}async function j1(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await L1(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function F1(t){return await j1(t)}async function U1(t){let e=await(await jf).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Ff(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await F1(t),r=await U1(e);return{code_verifier:e,code_challenge:r}}var Oe=VS().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:aw.custom,message:"URL must be parseable",fatal:!0}),ld}).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"}),TP=Pe({resource:g().url(),authorization_servers:C(Oe).optional(),jwks_uri:g().url().optional(),scopes_supported:C(g()).optional(),bearer_methods_supported:C(g()).optional(),resource_signing_alg_values_supported:C(g()).optional(),resource_name:g().optional(),resource_documentation:g().optional(),resource_policy_uri:g().url().optional(),resource_tos_uri:g().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:oe().optional()}),Uf=Pe({issuer:g(),authorization_endpoint:Oe,token_endpoint:Oe,registration_endpoint:Oe.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),service_documentation:Oe.optional(),revocation_endpoint:Oe.optional(),revocation_endpoint_auth_methods_supported:C(g()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(g()).optional(),introspection_endpoint:g().optional(),introspection_endpoint_auth_methods_supported:C(g()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(g()).optional(),code_challenge_methods_supported:C(g()).optional(),client_id_metadata_document_supported:oe().optional()}),q1=Pe({issuer:g(),authorization_endpoint:Oe,token_endpoint:Oe,userinfo_endpoint:Oe.optional(),jwks_uri:Oe,registration_endpoint:Oe.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),acr_values_supported:C(g()).optional(),subject_types_supported:C(g()),id_token_signing_alg_values_supported:C(g()),id_token_encryption_alg_values_supported:C(g()).optional(),id_token_encryption_enc_values_supported:C(g()).optional(),userinfo_signing_alg_values_supported:C(g()).optional(),userinfo_encryption_alg_values_supported:C(g()).optional(),userinfo_encryption_enc_values_supported:C(g()).optional(),request_object_signing_alg_values_supported:C(g()).optional(),request_object_encryption_alg_values_supported:C(g()).optional(),request_object_encryption_enc_values_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),display_values_supported:C(g()).optional(),claim_types_supported:C(g()).optional(),claims_supported:C(g()).optional(),service_documentation:g().optional(),claims_locales_supported:C(g()).optional(),ui_locales_supported:C(g()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Oe.optional(),op_tos_uri:Oe.optional(),client_id_metadata_document_supported:oe().optional()}),AP=x({...q1.shape,...Uf.pick({code_challenge_methods_supported:!0}).shape}),$P=x({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:Ca.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),MP=x({error:g(),error_description:g().optional(),error_uri:g().optional()}),EP=Oe.optional().or(E("").transform(()=>{})),H1=x({redirect_uris:C(Oe),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:Oe.optional(),logo_uri:EP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:EP,policy_uri:g().optional(),jwks_uri:Oe.optional(),jwks:JS().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),G1=x({client_id:g(),client_secret:g().optional(),client_id_issued_at:W().optional(),client_secret_expires_at:W().optional()}).strip(),IP=H1.merge(G1),o5=x({error:g(),error_description:g().optional()}).strip(),s5=x({token:g(),token_type_hint:g().optional()}).strip();function OP(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function zP({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+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Se=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}},oi=class extends Se{};oi.errorCode="invalid_request";var _n=class extends Se{};_n.errorCode="invalid_client";var Sn=class extends Se{};Sn.errorCode="invalid_grant";var wn=class extends Se{};wn.errorCode="unauthorized_client";var si=class extends Se{};si.errorCode="unsupported_grant_type";var ii=class extends Se{};ii.errorCode="invalid_scope";var ai=class extends Se{};ai.errorCode="access_denied";var ur=class extends Se{};ur.errorCode="server_error";var ci=class extends Se{};ci.errorCode="temporarily_unavailable";var ui=class extends Se{};ui.errorCode="unsupported_response_type";var di=class extends Se{};di.errorCode="unsupported_token_type";var li=class extends Se{};li.errorCode="invalid_token";var pi=class extends Se{};pi.errorCode="method_not_allowed";var fi=class extends Se{};fi.errorCode="too_many_requests";var bn=class extends Se{};bn.errorCode="invalid_client_metadata";var hi=class extends Se{};hi.errorCode="insufficient_scope";var mi=class extends Se{};mi.errorCode="invalid_target";var NP={[oi.errorCode]:oi,[_n.errorCode]:_n,[Sn.errorCode]:Sn,[wn.errorCode]:wn,[si.errorCode]:si,[ii.errorCode]:ii,[ai.errorCode]:ai,[ur.errorCode]:ur,[ci.errorCode]:ci,[ui.errorCode]:ui,[di.errorCode]:di,[li.errorCode]:li,[pi.errorCode]:pi,[fi.errorCode]:fi,[bn.errorCode]:bn,[hi.errorCode]:hi,[mi.errorCode]:mi};var qe=class extends Error{constructor(e){super(e??"Unauthorized")}};function Z1(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var qf="code",Hf="S256";function B1(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Z1(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 V1(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":W1(o,s,r);return;case"client_secret_post":K1(o,s,n);return;case"none":J1(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function W1(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 K1(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function J1(t,e){e.set("client_id",t)}async function LP(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=MP.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=NP[o]||ur;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ur(o)}}async function dr(t,e){try{return await Gf(t,e)}catch(r){if(r instanceof _n||r instanceof wn)return await t.invalidateCredentials?.("all"),await Gf(t,e);if(r instanceof Sn)return await t.invalidateCredentials?.("tokens"),await Gf(t,e);throw r}}async function Gf(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,d=o;if(!d&&i?.resourceMetadataUrl&&(d=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await FP(c,{fetchFn:s}),!a)try{a=await jP(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await nF(e,{resourceMetadataUrl:d,fetchFn:s});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 X1(e,t,a),p=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){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,k=t.clientMetadataUrl;if(k&&!Y1(k))throw new bn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(b&&k)f={client_id:k},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await cF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:s});await t.saveClientInformation(P),f=P}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await aF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let b=await iF(c,{metadata:u,clientInformation:f,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Se)||b instanceof ur))throw b}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:w}=await oF(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:p,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(S),"REDIRECT"}function Y1(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function X1(t,e,r){let n=OP(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!zP({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 Ro(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Zf(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Zf(t,"scope")||void 0,a=Zf(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Zf(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 jP(t,e,r=fetch){let n=await tF(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 TP.parse(await n.json())}async function Bf(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Bf(t,void 0,r):void 0;throw n}}function Q1(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function DP(t,e,r=fetch){return await Bf(t,{"MCP-Protocol-Version":e},r)}function eF(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function tF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??Yn,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=Q1(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await DP(i,s,r);if(!n?.metadataUrl&&eF(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await DP(c,s,r)}return a}function rF(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 FP(t,{fetchFn:e=fetch,protocolVersion:r=Yn}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=rF(t);for(let{url:s,type:i}of o){let a=await Bf(s,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 ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Uf.parse(await a.json()):AP.parse(await a.json())}}}async function nF(t,e){let r,n;try{r=await jP(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 FP(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function oF(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(qf))throw new Error(`Incompatible auth server: does not support response type ${qf}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Hf))throw new Error(`Incompatible auth server: does not support code challenge method ${Hf}`)}else a=new URL("/authorize",t);let c=await Ff(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",qf),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Hf),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function sF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function UP(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){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(s&&r.set("resource",s.href),o)await o(c,r,a,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],l=B1(n,d);V1(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await LP(u);return $P.parse(await u.json())}async function iF(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await UP(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function aF(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(i)),!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=sF(o,u,t.redirectUrl)}let c=await t.clientInformation();return UP(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function cF(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);let i=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await LP(i);return IP.parse(await i.json())}var gi=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Ac=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=Tc(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._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=bo(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 vn(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(o,{...s,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=Ro(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 s=new gi(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{let s=o,i;try{i=xr.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}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 qe("No auth provider");if(await dr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._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 s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=Ro(o);if(this._resourceMetadataUrl=i,this._scope=a,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var $C=ki(TC(),1);import rh from"node:process";import{PassThrough as DF}from"node:stream";var zF=10*1024*1024,Mc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??zF}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),NF(r)}clear(){this._buffer=void 0}};function NF(t){return xr.parse(JSON.parse(t))}function AC(t){return JSON.stringify(t)+`
98
- `}var LF=rh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Oc(){let t={};for(let e of LF){let r=rh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ic=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Mc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new DF)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,$C.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Oc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:rh.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",n=>{r(n),this.onerror?.(n)}),this._process.on("spawn",()=>{e()}),this._process.on("close",n=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",n=>{this.onerror?.(n)}),this._process.stdout?.on("data",n=>{try{this._readBuffer.append(n),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}}),this._process.stdout?.on("error",n=>{this.onerror?.(n)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){return this._stderrStream?this._stderrStream:this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){if(this._process){let e=this._process;this._process=void 0;let r=new Promise(n=>{e.once("close",()=>{n()})});try{e.stdin?.end()}catch{}if(await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())]),e.exitCode===null){try{e.kill("SIGTERM")}catch{}await Promise.race([r,new Promise(n=>setTimeout(n,2e3).unref())])}if(e.exitCode===null)try{e.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send(e){return new Promise(r=>{if(!this._process?.stdin)throw new Error("Not connected");let n=AC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var NC=ki(zC(),1);function DC(t){if(t)try{return NC.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var zc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Cc({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var VF={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},It=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Nc=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Tc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??VF}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=bo(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new It(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new zc({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await d.read();if(h)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let m=xr.parse(JSON.parse(f.data));en(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await dr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ms(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=Ro(a);if(this._resourceMetadataUrl=h,this._scope=m,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=Ro(a);if(y==="insufficient_scope"){let S=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new It(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=S??void 0,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qe;return this.send(e)}}throw new It(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),vw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,l=a.headers.get("content-type"),p=DC(l);if(d)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(m=>xr.parse(m)):[xr.parse(f)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new It(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new It(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};function LC(t){return t.useShellInterpolation?process.platform==="win32"?{command:"cmd.exe",args:["/c",t.command]}:{command:"/bin/sh",args:["-c",t.command]}:{command:t.command,args:t.args}}var KF={NO_UPDATE_NOTIFIER:"1",npm_config_update_notifier:"false",npm_config_loglevel:"silent",npm_config_fund:"false",npm_config_audit:"false",npm_config_yes:"true",CI:"1"};function jC(t){return{...Oc(),...KF,...t??{}}}function FC(){return Oc()}var oh=class t extends Ic{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
94
+ `,P),ye=-1;if(O!==-1&&ge!==-1?ye=O<ge?O:ge:O!==-1?O===_.length-1?ye=-1:ye=O:ge!==-1&&(ye=ge),ye===-1)break;S(_,P,ye),P=ye+1,_.charCodeAt(P-1)===j1&&_.charCodeAt(P)===xP&&P++}return _.slice(P)}function S(_,P,O){if(P===O){b();return}let ge=_.charCodeAt(P);if(kP(_,P,ge)){let lr=_.charCodeAt(P+5)===yn?P+6:P+5,Gh=_.slice(lr,O);d=l===0?Gh:`${d}
95
+ ${Gh}`,l++;return}if(EP(_,P,ge)){p=_.slice(_.charCodeAt(P+6)===yn?P+7:P+6,O)||void 0;return}if(ge===105&&_.charCodeAt(P+1)===100&&_.charCodeAt(P+2)===58){let lr=_.slice(_.charCodeAt(P+3)===yn?P+4:P+3,O);u=lr.includes("\0")?void 0:lr;return}if(ge===58){if(o){let lr=_.slice(P,O);o(lr.slice(_.charCodeAt(P+1)===yn?2:1))}return}let ye=_.slice(P,O),Ze=ye.indexOf(":");if(Ze===-1){w(ye,"",ye);return}let Mo=ye.slice(0,Ze),ki=ye.charCodeAt(Ze+1)===yn?2:1,Ei=ye.slice(Ze+ki);w(Mo,Ei,ye)}function w(_,P,O){switch(_){case"event":p=P||void 0;break;case"data":d=l===0?P:`${d}
96
+ ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new ti(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:O}));break;default:r(new ti(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:P,line:O}));break}}function b(){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0}function k(_={}){if(_.consume&&i.length>0){let P=i.join("");S(P,0,P.length)}c=!0,u=void 0,d="",l=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:k}}function kP(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 EP(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 Tc=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(TP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(TP(this),r)}};function F1(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function If(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(If).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${If(t.cause)}`:t.message:`${t}`}function TP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var $P=t=>{throw TypeError(t)},Uf=(t,e,r)=>e.has(t)||$P("Cannot "+r),F=(t,e,r)=>(Uf(t,e,"read from private field"),r?r.call(t):e.get(t)),ke=(t,e,r)=>e.has(t)?$P("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),me=(t,e,r,n)=>(Uf(t,e,"write to private field"),e.set(t,r),r),cr=(t,e,r)=>(Uf(t,e,"access private method"),r),tt,vn,_o,Ec,Ac,oi,bo,si,Dr,So,Ro,wo,ri,Mt,Of,zf,Nf,AP,Df,Lf,ni,jf,Ff,_n=class extends EventTarget{constructor(e,r){var n,o;super(),ke(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ke(this,tt),ke(this,vn),ke(this,_o),ke(this,Ec),ke(this,Ac),ke(this,oi),ke(this,bo),ke(this,si,null),ke(this,Dr),ke(this,So),ke(this,Ro,null),ke(this,wo,null),ke(this,ri,null),ke(this,zf,async s=>{var i;F(this,So).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){cr(this,Mt,ni).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?me(this,_o,new URL(s.url)):me(this,_o,void 0),u!==200){cr(this,Mt,ni).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){cr(this,Mt,ni).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,tt)===this.CLOSED)return;me(this,tt,this.OPEN);let l=new Event("open");if((i=F(this,ri))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){cr(this,Mt,ni).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,f=a.getReader(),h=!0;do{let{done:m,value:y}=await f.read();y&&F(this,So).feed(p.decode(y,{stream:!m})),m&&(h=!1,F(this,So).reset(),cr(this,Mt,jf).call(this))}while(h)}),ke(this,Nf,s=>{me(this,Dr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&cr(this,Mt,jf).call(this,If(s))}),ke(this,Df,s=>{typeof s.id=="string"&&me(this,si,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,_o)?F(this,_o).origin:F(this,vn).origin,lastEventId:s.id||""});F(this,wo)&&(!s.event||s.event==="message")&&F(this,wo).call(this,i),this.dispatchEvent(i)}),ke(this,Lf,s=>{me(this,oi,s)}),ke(this,Ff,()=>{me(this,bo,void 0),F(this,tt)===this.CONNECTING&&cr(this,Mt,Of).call(this)});try{if(e instanceof URL)me(this,vn,e);else if(typeof e=="string")me(this,vn,new URL(e,U1()));else throw new Error("Invalid URL")}catch{throw F1("An invalid or illegal string was specified")}me(this,So,kc({onEvent:F(this,Df),onRetry:F(this,Lf)})),me(this,tt,this.CONNECTING),me(this,oi,3e3),me(this,Ac,(n=r?.fetch)!=null?n:globalThis.fetch),me(this,Ec,(o=r?.withCredentials)!=null?o:!1),cr(this,Mt,Of).call(this)}get readyState(){return F(this,tt)}get url(){return F(this,vn).href}get withCredentials(){return F(this,Ec)}get onerror(){return F(this,Ro)}set onerror(e){me(this,Ro,e)}get onmessage(){return F(this,wo)}set onmessage(e){me(this,wo,e)}get onopen(){return F(this,ri)}set onopen(e){me(this,ri,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(){F(this,bo)&&clearTimeout(F(this,bo)),F(this,tt)!==this.CLOSED&&(F(this,Dr)&&F(this,Dr).abort(),me(this,tt,this.CLOSED),me(this,Dr,void 0))}};tt=new WeakMap,vn=new WeakMap,_o=new WeakMap,Ec=new WeakMap,Ac=new WeakMap,oi=new WeakMap,bo=new WeakMap,si=new WeakMap,Dr=new WeakMap,So=new WeakMap,Ro=new WeakMap,wo=new WeakMap,ri=new WeakMap,Mt=new WeakSet,Of=function(){me(this,tt,this.CONNECTING),me(this,Dr,new AbortController),F(this,Ac)(F(this,vn),cr(this,Mt,AP).call(this)).then(F(this,zf)).catch(F(this,Nf))},zf=new WeakMap,Nf=new WeakMap,AP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,si)?{"Last-Event-ID":F(this,si)}:void 0},cache:"no-store",signal:(t=F(this,Dr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Df=new WeakMap,Lf=new WeakMap,ni=function(t,e){var r;F(this,tt)!==this.CLOSED&&me(this,tt,this.CLOSED);let n=new Tc("error",{code:e,message:t});(r=F(this,Ro))==null||r.call(this,n),this.dispatchEvent(n)},jf=function(t,e){var r;if(F(this,tt)===this.CLOSED)return;me(this,tt,this.CONNECTING);let n=new Tc("error",{code:e,message:t});(r=F(this,Ro))==null||r.call(this,n),this.dispatchEvent(n),me(this,bo,setTimeout(F(this,Ff),F(this,oi)))},Ff=new WeakMap,_n.CONNECTING=0,_n.OPEN=1,_n.CLOSED=2;function U1(){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 Po(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function $c(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Po(e.headers),...Po(n.headers)}:e.headers};return t(r,o)}:t}var qf;qf=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function q1(t){return(await qf).getRandomValues(new Uint8Array(t))}async function H1(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await q1(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function G1(t){return await H1(t)}async function Z1(t){let e=await(await qf).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Hf(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await G1(t),r=await Z1(e);return{code_verifier:e,code_challenge:r}}var Oe=YS().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:lw.custom,message:"URL must be parseable",fatal:!0}),hd}).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"}),IP=Pe({resource:g().url(),authorization_servers:C(Oe).optional(),jwks_uri:g().url().optional(),scopes_supported:C(g()).optional(),bearer_methods_supported:C(g()).optional(),resource_signing_alg_values_supported:C(g()).optional(),resource_name:g().optional(),resource_documentation:g().optional(),resource_policy_uri:g().url().optional(),resource_tos_uri:g().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:oe().optional()}),Gf=Pe({issuer:g(),authorization_endpoint:Oe,token_endpoint:Oe,registration_endpoint:Oe.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),service_documentation:Oe.optional(),revocation_endpoint:Oe.optional(),revocation_endpoint_auth_methods_supported:C(g()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(g()).optional(),introspection_endpoint:g().optional(),introspection_endpoint_auth_methods_supported:C(g()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(g()).optional(),code_challenge_methods_supported:C(g()).optional(),client_id_metadata_document_supported:oe().optional()}),B1=Pe({issuer:g(),authorization_endpoint:Oe,token_endpoint:Oe,userinfo_endpoint:Oe.optional(),jwks_uri:Oe,registration_endpoint:Oe.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),acr_values_supported:C(g()).optional(),subject_types_supported:C(g()),id_token_signing_alg_values_supported:C(g()),id_token_encryption_alg_values_supported:C(g()).optional(),id_token_encryption_enc_values_supported:C(g()).optional(),userinfo_signing_alg_values_supported:C(g()).optional(),userinfo_encryption_alg_values_supported:C(g()).optional(),userinfo_encryption_enc_values_supported:C(g()).optional(),request_object_signing_alg_values_supported:C(g()).optional(),request_object_encryption_alg_values_supported:C(g()).optional(),request_object_encryption_enc_values_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),display_values_supported:C(g()).optional(),claim_types_supported:C(g()).optional(),claims_supported:C(g()).optional(),service_documentation:g().optional(),claims_locales_supported:C(g()).optional(),ui_locales_supported:C(g()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Oe.optional(),op_tos_uri:Oe.optional(),client_id_metadata_document_supported:oe().optional()}),OP=x({...B1.shape,...Gf.pick({code_challenge_methods_supported:!0}).shape}),zP=x({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:ka.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),NP=x({error:g(),error_description:g().optional(),error_uri:g().optional()}),MP=Oe.optional().or(E("").transform(()=>{})),V1=x({redirect_uris:C(Oe),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:Oe.optional(),logo_uri:MP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:MP,policy_uri:g().optional(),jwks_uri:Oe.optional(),jwks:ew().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),W1=x({client_id:g(),client_secret:g().optional(),client_id_issued_at:W().optional(),client_secret_expires_at:W().optional()}).strip(),DP=V1.merge(W1),u5=x({error:g(),error_description:g().optional()}).strip(),d5=x({token:g(),token_type_hint:g().optional()}).strip();function LP(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function jP({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+"/",s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return o.startsWith(s)}var Se=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}},ii=class extends Se{};ii.errorCode="invalid_request";var Sn=class extends Se{};Sn.errorCode="invalid_client";var wn=class extends Se{};wn.errorCode="invalid_grant";var bn=class extends Se{};bn.errorCode="unauthorized_client";var ai=class extends Se{};ai.errorCode="unsupported_grant_type";var ci=class extends Se{};ci.errorCode="invalid_scope";var ui=class extends Se{};ui.errorCode="access_denied";var ur=class extends Se{};ur.errorCode="server_error";var di=class extends Se{};di.errorCode="temporarily_unavailable";var li=class extends Se{};li.errorCode="unsupported_response_type";var pi=class extends Se{};pi.errorCode="unsupported_token_type";var fi=class extends Se{};fi.errorCode="invalid_token";var hi=class extends Se{};hi.errorCode="method_not_allowed";var mi=class extends Se{};mi.errorCode="too_many_requests";var Rn=class extends Se{};Rn.errorCode="invalid_client_metadata";var gi=class extends Se{};gi.errorCode="insufficient_scope";var yi=class extends Se{};yi.errorCode="invalid_target";var FP={[ii.errorCode]:ii,[Sn.errorCode]:Sn,[wn.errorCode]:wn,[bn.errorCode]:bn,[ai.errorCode]:ai,[ci.errorCode]:ci,[ui.errorCode]:ui,[ur.errorCode]:ur,[di.errorCode]:di,[li.errorCode]:li,[pi.errorCode]:pi,[fi.errorCode]:fi,[hi.errorCode]:hi,[mi.errorCode]:mi,[Rn.errorCode]:Rn,[gi.errorCode]:gi,[yi.errorCode]:yi};var qe=class extends Error{constructor(e){super(e??"Unauthorized")}};function K1(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Zf="code",Bf="S256";function J1(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&K1(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 Y1(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":X1(o,s,r);return;case"client_secret_post":Q1(o,s,n);return;case"none":eF(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function X1(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 Q1(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function eF(t,e){e.set("client_id",t)}async function qP(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=NP.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=FP[o]||ur;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new ur(o)}}async function dr(t,e){try{return await Vf(t,e)}catch(r){if(r instanceof Sn||r instanceof bn)return await t.invalidateCredentials?.("all"),await Vf(t,e);if(r instanceof wn)return await t.invalidateCredentials?.("tokens"),await Vf(t,e);throw r}}async function Vf(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,d=o;if(!d&&i?.resourceMetadataUrl&&(d=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await GP(c,{fetchFn:s}),!a)try{a=await HP(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await aF(e,{resourceMetadataUrl:d,fetchFn:s});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 rF(e,t,a),p=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){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,k=t.clientMetadataUrl;if(k&&!tF(k))throw new Rn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(b&&k)f={client_id:k},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await pF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:s});await t.saveClientInformation(P),f=P}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await lF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let b=await dF(c,{metadata:u,clientInformation:f,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Se)||b instanceof ur))throw b}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:w}=await cF(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:p,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(S),"REDIRECT"}function tF(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function rF(t,e,r){let n=LP(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!jP({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 Co(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Wf(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Wf(t,"scope")||void 0,a=Wf(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Wf(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 HP(t,e,r=fetch){let n=await sF(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 IP.parse(await n.json())}async function Kf(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Kf(t,void 0,r):void 0;throw n}}function nF(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function UP(t,e,r=fetch){return await Kf(t,{"MCP-Protocol-Version":e},r)}function oF(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function sF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??Qn,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=nF(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await UP(i,s,r);if(!n?.metadataUrl&&oF(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await UP(c,s,r)}return a}function iF(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 GP(t,{fetchFn:e=fetch,protocolVersion:r=Qn}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=iF(t);for(let{url:s,type:i}of o){let a=await Kf(s,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 ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Gf.parse(await a.json()):OP.parse(await a.json())}}}async function aF(t,e){let r,n;try{r=await HP(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 GP(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function cF(t,{metadata:e,clientInformation:r,redirectUrl:n,scope:o,state:s,resource:i}){let a;if(e){if(a=new URL(e.authorization_endpoint),!e.response_types_supported.includes(Zf))throw new Error(`Incompatible auth server: does not support response type ${Zf}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Bf))throw new Error(`Incompatible auth server: does not support code challenge method ${Bf}`)}else a=new URL("/authorize",t);let c=await Hf(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Zf),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Bf),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function uF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function ZP(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){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(s&&r.set("resource",s.href),o)await o(c,r,a,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],l=J1(n,d);Y1(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await qP(u);return zP.parse(await u.json())}async function dF(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await ZP(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function lF(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(i)),!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=uF(o,u,t.redirectUrl)}let c=await t.clientInformation();return ZP(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function pF(t,{metadata:e,clientMetadata:r,scope:n,fetchFn:o}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);let i=await(o??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...n!==void 0?{scope:n}:{}})});if(!i.ok)throw await qP(i);return DP.parse(await i.json())}var vi=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Mc=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=$c(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._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=Po(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 _n(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(o,{...s,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=Co(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 s=new vi(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{let s=o,i;try{i=kr.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}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 qe("No auth provider");if(await dr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._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 s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=Co(o);if(this._resourceMetadataUrl=i,this._scope=a,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var zC=Ti(IC(),1);import sh from"node:process";import{PassThrough as UF}from"node:stream";var jF=10*1024*1024,Oc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??jF}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),FF(r)}clear(){this._buffer=void 0}};function FF(t){return kr.parse(JSON.parse(t))}function OC(t){return JSON.stringify(t)+`
98
+ `}var qF=sh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Nc(){let t={};for(let e of qF){let r=sh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var zc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Oc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new UF)}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,zC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Nc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:sh.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=OC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var FC=Ti(jC(),1);function UC(t){if(t)try{return FC.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Dc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=kc({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var YF={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},It=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Lc=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=$c(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??YF}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=Po(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new It(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new Dc({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await d.read();if(h)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let m=kr.parse(JSON.parse(f.data));tn(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await dr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:ys(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=Co(a);if(this._resourceMetadataUrl=h,this._scope=m,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=Co(a);if(y==="insufficient_scope"){let S=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new It(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=S??void 0,await dr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qe;return this.send(e)}}throw new It(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),bw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,l=a.headers.get("content-type"),p=UC(l);if(d)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(m=>kr.parse(m)):[kr.parse(f)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new It(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new It(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};function qC(t){return t.useShellInterpolation?process.platform==="win32"?{command:"cmd.exe",args:["/c",t.command]}:{command:"/bin/sh",args:["-c",t.command]}:{command:t.command,args:t.args}}var QF={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 HC(t){return{...Nc(),...QF,...t??{}}}function GC(){return Nc()}var ah=class t extends zc{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
99
99
  `);this._lineBuffer=r.at(-1)??"",this._lineBuffer.length>t.MAX_LINE_BUFFER_CHARS&&(this._lineBuffer=this._lineBuffer.slice(-t.MAX_LINE_BUFFER_CHARS));for(let n of r.slice(0,-1))this.pushCapturedLine(`${n}
100
- `)}pushCapturedLine(e){this._captured.push(e),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(e),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let e=this._captured.join("");return this._captured=[],e}getLogHistory(){return[...this._logHistory]}};function UC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new oh(e)}var Rn=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},sh=new WF;function ih(t,e){return sh.run(t,e)}function JF(t){sh.getStore()?.onFailure?.(t)}function qC({getHeaders:t,transport:e}){if(t)return async(r,n)=>{let o=r instanceof Request?r.headers:void 0,s=new Headers(o);for(let[u,d]of new Headers(n?.headers).entries())s.set(u,d);for(let[u,d]of Object.entries(t()))s.set(u,d);let i=await fetch(r,{...n,headers:s});if(i.ok||n?.method?.toUpperCase()!=="POST")return i;await i.body?.cancel().catch(()=>{});let a=sh.getStore(),c=new Rn({status:i.status,transport:e,operation:a?.operation??"transport"});throw JF(c),c}}function HC(t,e){let r=qC({getHeaders:e.getHeaders,transport:"http"});return new Nc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function GC(t,e){let r=qC({getHeaders:e.getHeaders,transport:"sse"});return new Ac(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function ZC(){return new Pc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var BC=bs,VC=xe;function St(t){return t instanceof Rn&&t.status===401||(t instanceof It||t instanceof gi)&&t.code===401}function WC(t){return t instanceof $&&t.code===M.MethodNotFound}function ah(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var YF=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function KC(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return YF.some(r=>e.includes(r))}function JC(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function ch(t){return t instanceof Rn&&t.transport==="http"&&t.status===404||t instanceof It&&t.code===404}var X=XF.child({prefix:"pi-mcp"});function QF(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function eU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&QF(r,o)})}var tU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),rU=/^Node\.js v\d/,nU=/^[\w$.]*error[\w$]*:/i,YC=400,oU=63e3,XC=3,sU=/[\\/]lib[\\/]cli\.js/,iU="npx/npm launcher is broken in this environment (Cannot find module .../lib/cli.js). This usually means npm/npx/corepack are file copies instead of symlinks in the base image; every npx-launched stdio MCP server will fail until the launcher symlinks are restored.",ox=Symbol("mcpReinitReported");function aU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,ox,{value:!0,enumerable:!1,configurable:!0})}function cU(t){return typeof t=="object"&&t!==null&&t[ox]===!0}function uU(t){let e=t.filter(a=>!rU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>sU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return iU;let o=r.findIndex(a=>nU.test(a)),i=(o===-1?r.slice(-XC):r.slice(o,o+XC)).join(" / ");return i.length>YC?`${i.slice(0,YC)}\u2026`:i}function dU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(tU,"").split(`
101
- `).map(s=>s.trim()).filter(s=>s.length>0),o=uU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var lU=6e5,pU=18e5,QC=2147483647,fU=3e4,ex=1e4,sx=[250,1e3,2e3],Pn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},yi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},hU=250,tx=3,mU=[200,500];function gU(t){for(let e of Object.values(t))if(na(e))return!0;return!1}function ix(t){let e=new Set;for(let r of t.matchAll(Qo))e.add(oa(r[0]));return[...e].sort()}function lh(t){return[...new Set(t)].sort()}function rx(t,e){return Gg(e.map(r=>t?.[r]??"missing"))}function yU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return lh([...e&&t?dd(t):[],...n&&r?ix(r):[]])}var Dc="${augmentToken}";function vU(t){try{let e=new URL(t);if(e.protocol!=="https:")return!1;let{hostname:r}=e;return r==="augmentcode.com"||r.endsWith(".augmentcode.com")}catch{return!1}}function _U(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var ax="(unknown uri)",ph="unknown",nx=/=+$/,SU=/\s+/g,wU=/[-_]/g,bU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Cn(t,e){return typeof t=="string"?t:e}function cx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function RU(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function PU(t){let e=t.replace(SU,"").replace(wU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(nx,"");if(r.toString("base64").replace(nx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function ux(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function CU(t){let e=ux(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Cn(e.uri,ax),n=Cn(e.mimeType,ph);if(typeof e.blob=="string"&&RU(n)){let s=PU(e.blob);if(s!==void 0)return s}let o=cx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function xU(t){let e=Cn(t.type,"unknown");if(e==="resource")return CU(t);if(e==="audio"){let r=Cn(t.mimeType,ph),n=cx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Cn(t.uri,ax),n=Cn(t.name,""),o=Cn(t.mimeType,ph);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function kU(t){if(t.type!=="resource")return;let e=ux(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&bU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function EU(t){if(t.type==="text"&&typeof t.text=="string")return{type:"text",text:t.text};if(t.type==="image"&&typeof t.data=="string"&&typeof t.mimeType=="string")return{type:"image",mimeType:t.mimeType,data:t.data};let e=kU(t);return e||{type:"text",text:xU(t)}}function TU(t){let e=[];if(!Array.isArray(t))return e;for(let r of t){if(typeof r!="object"||r===null)continue;let n=r;typeof n.type=="string"&&e.push(EU(n))}return e}function AU(t){return zg(t,oU)}function $U(t,e){let r=TU(t);if(r.length===0){let o=AU(e);o!==void 0&&r.push({type:"text",text:o})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}var dx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),MU=new Set([502,503,504]),vi=sx.length+1,IU=2;function OU(t){let r=t?.cause?.code;if(typeof r=="string")return r;let n=t?.status;if(typeof n=="number")return String(n);let o=t?.code;return typeof o=="number"?String(o):void 0}function zU(t){if(St(t)||ch(t)||t instanceof lt)return;let e=t?.cause?.code;if(typeof e=="string")return dx.has(e)?{totalAttempts:vi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:IU}:MU.has(r)?{totalAttempts:vi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:vi}:void 0}var NU=80,DU=10,LU=/[^a-zA-Z0-9_.()-]/g,jU=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Lc(t){return t.replace(LU,"_").slice(0,NU)||"unknown"}function FU(t){let e=OU(t);if(e!==void 0&&(/^\d{3}$/.test(e)||dx.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=jU.has(e)?e:"Error",n=FU(t);return n===void 0?r:`${r}(${n})`}function uh(t,e,r){return t instanceof lt?new lt(Lc(t.serverName),t.missingKeys.slice(0,DU).map(Lc),void 0,t.reason).message:t instanceof Rn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function dh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Lc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var jc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Fc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>ad(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=uh(r,"connect",this._config.type),o=this._config.type==="stdio"&&!St(r)?ad(dU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=vi,r={available:!0};for(let n=1;n<=vi;n++)try{let o=await this._attemptConnect(r);return n>1&&X.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let s=zU(o);if(s===void 0||this._disposed||(e=Math.min(e,s.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let s=(sx[r-1]??0)+Math.floor(Math.random()*(hU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Vr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return St(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!re().tokens.get(this.name)?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new Pn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=ZC();this._client=s;let i;try{if(await ih({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(BC,()=>{X.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let a=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=a.tools??[],this._status="success",this._lastError=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=re();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&st(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=uh(e,r,this._config.type)){if(e instanceof lt){this._status="failed";let o=re();$o(o,this.name,e.reason,Jt(o,this.name,this._config.id))}else if(e instanceof yi||e instanceof Pn)this._status="failed";else if(St(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(St(e)){this._status="auth_required";let o=re(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=uh(e,r,this._config.type);cd(dh(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=LC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=jC(this._resolvedEnv??e.env);return UC({command:r.command,args:r.args,env:n,cwd:e.cwd})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return GC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=HC(e,{headers:r,getHeaders:()=>this._buildAuthHeaders()});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?gU(r):!1,o=e.type==="stdio"&&na(e.command);if(!(n||o))return;let s=re();if(!Hg(s)){let a=yU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new lt(this.name,a)}let i=Ug(s);n&&r&&await this._resolveMapSecretRefs(r,i,e.type==="stdio"),o&&e.type==="stdio"&&await this._resolveCommandSecretRefs(e.command,i)}async _resolveMapSecretRefs(e,r,n){let o;try{o=await Bg({configEnv:e,localEnv:n?FC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new lt(this.name,dd(e),i,"transient")}let s=lh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new lt(this.name,s,void 0,rx(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Vg(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new lt(this.name,ix(e),s,"transient")}let o=lh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new lt(this.name,o,void 0,rx(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Dc)))return;let o;if(vU(e.url)){let i=re().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Dc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Dc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${_U(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Dc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=re();if(n.diagnostics.some(i=>i.server===this.name&&i.message===e))return;n.diagnostics.push({server:this.name,message:e});let s=`MCP server "${this.name}": ${e}`;r==="error"?X.error(s):X.warn(s)}_usableToken(){let e=re(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Be(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=re().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&Mu(o)&&re().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Zo(o)&&re().tokens.markAuthRequired(this.name))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=re(),r=e.refreshes.get(this.name);if(r)return r.then(a=>a??{kind:"refreshed"});let n={state:e,tokenStore:e.tokens,serverGeneration:e.serverGenerations.get(this.name)??0,configRevision:e.configRevisions.get(this.name)??0,credential:e.credentialRevisions.get(this.name),localRefreshEnabled:e.shouldProactivelyRefreshTokens,failureScope:Jt(e,this.name,this._config.id),token:this._usableToken(),hostWasUntracked:e.servers.get(this.name)===void 0},o=JSON.stringify([this.name,n.serverGeneration,n.configRevision,n.credential?.domain??null,n.credential?.revision??null]),s=e.refreshes.get(o);if(s)return s.then(a=>a??{kind:"refreshed"});let i=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===i&&e.refreshes.delete(o),this._refreshPromise===i&&(this._refreshPromise=void 0)});return this._refreshPromise=i,e.refreshes.set(o,i),i}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=Z(r,this.name)?.retirement?.incumbent.host,s=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&s&&(r.serverGenerations.get(this.name)??0)===e.serverGeneration&&(r.configRevisions.get(this.name)??0)===e.configRevision&&this._ownsRefreshCredential(e,n)&&(e.localRefreshEnabled===r.shouldProactivelyRefreshTokens||this._refreshPersisting)}_ownsRefreshCredential(e,r){return e.state.tokens===e.tokenStore&&e.tokenStore.get(this.name)===e.token&&r?.domain===e.credential?.domain&&r?.revision===e.credential?.revision}async _restoreAfterSupersededRefresh(e,r,n,o){let s=e.state.servers.get(this.name),i=e.state.tokens,a=i.get(this.name),c=e.state.credentialRevisions.get(this.name);if(!(i!==e.tokenStore||!s||!a||!Be(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),Fr({state:e.state,name:this.name,revision:o});return}let u=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o);if(!u||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain)return;Fr({state:e.state,name:this.name,revision:u});let d=e.state.currentLoad?.latestPi;d&&J(d,e.state)}catch{X.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof B?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof B)&&Ou(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&$o(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),$o(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await zu(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let s=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,s),{kind:"transient_failure"};e.tokenStore.commit(this.name,o),Fr({state:e.state,name:this.name,revision:s}),st(e.state,this.name);let i=e.state.currentLoad?.latestPi;return i&&J(i,e.state),X.debug(`MCP server "${this.name}" token refreshed`),{kind:"refreshed"}}catch(r){return this._handleRefreshFailure(r,e)}}_isSessionExpiredError(e){return this._config.type!=="http"||this._activeTransport?.sessionId===void 0?!1:ch(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),aU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Pn}async _withAuthRetry(e,r,n){let o=this._config,s=re(),i=Jt(s,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),ih({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!St(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new yi;if(this._hostedCredentialProvenance!==void 0)throw new Pn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw St(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=re();$o(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new jc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new jc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},fU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=re(),r=Jt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=tx&&n.outcome==="transient";i++)await Vr(mU[i-2]??0),n=await this._runProbe();let o=Jt(e,this.name,this._config.id),s=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return s&&n.outcome==="alive"&&st(e,this.name,r),s&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?X.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&X.debug(`MCP server "${this.name}" startup verification ping remained transient after ${tx} attempts; not caching as failed: ${n.error}`),n}getLastProbeResult(){return this._lastProbeResult}async _runProbe(){let e=!this._client||this._disposed;if(e)return{ok:!1,outcome:"transient",error:"MCP client is not available",isAuthError:!1};try{return await this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.ping({timeout:ex})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":WC(e)||ah(e)?"alive":St(e)?"authFailure":KC(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!(!e||this._disposed))try{await e.ping({timeout:ex})}catch(r){if(this._reinitializingPromise||this._disposed||ah(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return St(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!St(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!eU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>QC)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${QC}.`);let s={timeout:this._config.timeoutMs??lU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??pU,onprogress:d=>{X.debug(`MCP server "${this.name}" tool "${e}" progress: ${d.progress}${d.total===void 0?"":`/${d.total}`}${d.message?` - ${d.message}`:""}`)}},i,a=new Promise((d,l)=>{i={reject:l,livenessRejected:!1,sessionRecoveryOwned:!1}});a.catch(()=>{}),i&&this._inFlightCalls.add(i);let u=this._withSessionRetry(()=>this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.callTool({name:e,arguments:r??{}},VC,s)},"tool_call",{call:i})).then(d=>(i&&this._settleInFlightCall(i,!0,void 0),d),d=>{throw i&&this._settleInFlightCall(i,!1,d),d});try{let d=await Promise.race([u,a]),l=$U(d.content,d.structuredContent);return{isError:d.isError===!0,content:l.content,rawItemCount:l.rawItemCount}}catch(d){if(n?.aborted||d instanceof Error&&d.name==="AbortError")throw d;return this._reportAndThrowToolError(d,e)}finally{i&&!this._wedgeRecoveryOwners.has(i)&&(i.failure=void 0,this._inFlightCalls.delete(i))}}_reportAndThrowToolError(e,r){if(e instanceof Pn||e instanceof yi)throw e;if(St(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Lc(r),s=He(e),i=JC(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw cU(e)||cd(dh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),dh(a,s)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._stopHeartbeat(),this._failInFlightCalls(new Error(`MCP server "${this.name}" is being disposed`),!1),this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1}async dispose(e){this.beginDisposal(),await this._refreshPromise,this._stopHeartbeat();let r=this._client;if(this._client=void 0,this._activeTransport=void 0,this._reinitializingPromise=void 0,this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1,this._stdioTransport=void 0,!!r)try{await r.close()}catch(n){if(X.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var lx=qU.child({prefix:"pi-mcp"}),HU=3,GU=6e4;function ZU(t,e){let r=Date.now(),n=r-GU,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=HU?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function px(t){Br(t),Fi(t)}async function BU(t,e,r){if(!ZU(e,t)){lx.warn(`MCP server "${t}" automatic restart rate-limited`);return}lx.warn(`MCP server "${t}" wedged; recycling transport`),await Dr(t,e,r)}function Uc(t,e,r){if(VU(e)){px(t);return}bu(t,r),In(e)&&px(t)}function VU(t){return Lo()||t.toolSearchLatched}function Vt(t,e,r){return Vh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function fh(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,st(t,e),t.authRefreshNeededReportKeys.delete(e),r}function WU(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name);return o!==void 0&&s!==void 0&&i!==void 0&&i.revision===o.revision&&i.domain===o.domain&&e.oauthCredentialDomains.get(r.name)===o.domain&&ut(o.domain)===We(r.id)?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function hh(t){let{state:e,config:r,generation:n}=t;return new Fc(r,WU({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function mh(t,e){if(e.id&&e.registrySource!==void 0){let r={...e};t.registryConfigNamesById.set(e.id,e.name),t.registryCredentialConfigs.set(e.name,r),t.registryCredentialConfigsById.set(e.id,r)}}function gh(t,e,r){return t.configDesiredRevisions.get(e)===r}function fx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function yh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Vt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(UU,c)},t.onWedged=()=>{if(!Vt(t,e,r))return;let i=r.currentLoad?.latestPi??n;BU(t.name,r,i)};let o=t.hostedCredentialProvenance,s=o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0?{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}:void 0;t.onAuthRefreshNeeded=()=>{if(!Vt(t,e,r)||!s)return;let i=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==i&&(r.authRefreshNeededReportKeys.set(t.name,i),J(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!Vt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&st(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Vt(t,e,r)&&t.status==="success"&&Uc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Ru(i,t,e),i!==n&&Ru(n,t,e)}}async function hx(t,e,r,n){let o=setTimeout(()=>{Vt(t,e,r)&&J(n(),r)},Ei);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Vt(t,e,r)&&J(n(),r)}}async function mx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function qc(t,e){if(e.status!=="installed")return!1;let r=Z(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function KU(t){let{state:e,config:r,displaced:n,retirement:o}=t;mh(e,n.config),zo(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():ct(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function JU(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=bt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function YU(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Vt(r,o,e)?a?.(n)===!1?(await JU({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Uc(c(),e,r),J(c(),e),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:i}):{status:"superseded",config:n}}function XU(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=Z(e,r.name);if(!gh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=fh(e,r.name),l=hh({state:e,config:r,generation:d});return yh(l,d,e,o),$i({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:YU({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function QU(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!gh(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):Z(r,a.name),l=En(a,s),p=Oo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>XU({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await KU({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await uu(p.retirement),h());return p.retirement?m():h()}async function wt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await QU({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Ei);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function eq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!fx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);mh(e,s),zo(e,t);let a=bt({state:e,name:t,owner:i.owner,revision:i.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),we({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw we({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(Z(e,t)?.revision!==i.revision||!fx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=fh(e,t),u=hh({state:e,config:s,generation:c});if(yh(u,c,e,r),!$i({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await hx(u,c,e,d),Vt(u,c,e)&&u.status==="success"&&Uc(d(),e,u),!0}function Dr(t,e,r){e.reconnects??=new Map,e.configRevisions??=new Map,e.reconnectDesiredGenerations??=new Map,e.statusFailureCategories??=new Map;let n=(e.reconnectDesiredGenerations.get(t)??0)+1;e.reconnectDesiredGenerations.set(t,n);let o=e.reconnects.get(t);if(o)return o;let s=(async()=>{let i=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await eq({name:t,state:e,pi:r,configRevision:a}))return;i=c}while(i<(e.reconnectDesiredGenerations.get(t)??i))})().finally(()=>{e.reconnects.get(t)===s&&e.reconnects.delete(t)});return e.reconnects.set(t,s),s}async function tq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;mh(e,n.config),zo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():ct(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function gx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=$n(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=Oo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await tq({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await uu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!gh(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=fh(e,t),h=hh({state:e,config:a,generation:f});yh(h,f,e,r),$i({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await hx(h,f,e,s),Vt(h,f,e)&&h.status==="success"&&Uc(s(),e,h))}async function _i(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Dr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as rq}from"@hermes/logger";var vh=rq.child({prefix:"pi-mcp"}),nq=1e6,oq=1e3,sq=/^\d+$/;function yx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function xn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(!(typeof e!="string"||!sq.test(e)||typeof r!="string"||r.length===0))return{revision:e.replace(/^0+(?=\d)/,""),domain:yx(r)}}function iq(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function aq(t,e,r,n){let o=e.credential_revision??e.credentialRevision,s=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||s!==void 0)&&r===void 0)return vh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";if(i?.kind==="blocked"||i?.kind==="domain"&&ut(r.domain)!==i.domain)return"reject";let a=n?.acceptedDomains?.get(t);if(a!==void 0&&yx(a)!==r.domain)return"reject";let c=iq(n?.acceptedRevisions,r.domain,s);if(c===void 0)return"apply";let u=mr(r.revision,c);return u>0||u===0&&a===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":u===0?"equal":"reject"}function cq(t,e,r,n){if(n!==void 0)return!1;let o=t.get(e);return o===void 0?!1:r.expiresAt===void 0||o.expiresAt===void 0||r.expiresAt<=o.expiresAt}function uq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function dq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*oq+Math.floor(t.access_token_expires_at.nanos/nq):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret,...t.token_endpoint_auth_method===void 0?{}:{token_endpoint_auth_method:t.token_endpoint_auth_method}}}}function Hc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!uq(s)){vh.warn(`Skipping MCP OAuth credentials for "${o}": entry is not an object with a non-empty access_token`),n.rejected.push(o);continue}let i=xn(s),a=aq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=dq(s);if(cq(t,o,c,i)){vh.warn(`Skipping MCP OAuth credentials for "${o}": legacy payload cannot prove freshness`),n.rejected.push(o);continue}t.set(o,c),r?.equalRevisionRebindDomains?.delete(o),i!==void 0&&(r?.acceptedRevisions?.set(i.domain,i.revision),r?.acceptedDomains?.set(o,i.domain)),n.applied.push(o)}return n}var pq=lq.child({prefix:"pi-mcp"});function fq(t,e){let r;for(let[n,o]of t.servers){if(o.config.id!==e)continue;let s=Q(t,n,o);if(!(s.host!==o||s.owner.kind!=="registry"||s.owner.identity!==`user:${e}`)){if(r)return;r={name:n,server:o}}}return r}function hq(t,e){let r=Object.values(t).filter(n=>{let o=xn(n);return o!==void 0&&ut(o.domain)===`user:${e}`});return r.length===1?r[0]:void 0}async function vx(t){let{pi:e,state:r,update:n}=t,o=fq(r,n.configId),s=hq(n.credentials,n.configId);if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=Hc(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let p=xn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Dr,l=t.report??J;await d(o.name,r,u).catch(p=>{pq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),ze(r)}import{logger as Pq}from"@hermes/logger";import{execFile as mq}from"node:child_process";import{logger as gq}from"@hermes/logger";var yq=5e3;function vq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function _x(t,e=yq){let r=gq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=vq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=mq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as _q}from"node:http";function Gc(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Sx(t){let e=Gc(t.title),r=Gc(t.heading),n=Gc(t.message),o=t.details?Gc(t.details):void 0,s=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
100
+ `)}pushCapturedLine(e){this._captured.push(e),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(e),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let e=this._captured.join("");return this._captured=[],e}getLogHistory(){return[...this._logHistory]}};function ZC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new ah(e)}var Pn=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},ch=new XF;function uh(t,e){return ch.run(t,e)}function eU(t){ch.getStore()?.onFailure?.(t)}function BC({getHeaders:t,transport:e}){if(t)return async(r,n)=>{let o=r instanceof Request?r.headers:void 0,s=new Headers(o);for(let[u,d]of new Headers(n?.headers).entries())s.set(u,d);for(let[u,d]of Object.entries(t()))s.set(u,d);let i=await fetch(r,{...n,headers:s});if(i.ok||n?.method?.toUpperCase()!=="POST")return i;await i.body?.cancel().catch(()=>{});let a=ch.getStore(),c=new Pn({status:i.status,transport:e,operation:a?.operation??"transport"});throw eU(c),c}}function VC(t,e){let r=BC({getHeaders:e.getHeaders,transport:"http"});return new Lc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function WC(t,e){let r=BC({getHeaders:e.getHeaders,transport:"sse"});return new Mc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function KC(){return new xc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var JC=Ps,YC=xe;function St(t){return t instanceof Pn&&t.status===401||(t instanceof It||t instanceof vi)&&t.code===401}function XC(t){return t instanceof $&&t.code===M.MethodNotFound}function dh(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var tU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function QC(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return tU.some(r=>e.includes(r))}function ex(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function lh(t){return t instanceof Pn&&t.transport==="http"&&t.status===404||t instanceof It&&t.code===404}var X=rU.child({prefix:"pi-mcp"});function nU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function oU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&nU(r,o)})}var sU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),iU=/^Node\.js v\d/,aU=/^[\w$.]*error[\w$]*:/i,tx=400,cU=63e3,rx=3,uU=/[\\/]lib[\\/]cli\.js/,dU="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.",cx=Symbol("mcpReinitReported");function lU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,cx,{value:!0,enumerable:!1,configurable:!0})}function pU(t){return typeof t=="object"&&t!==null&&t[cx]===!0}function fU(t){let e=t.filter(a=>!iU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>uU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return dU;let o=r.findIndex(a=>aU.test(a)),i=(o===-1?r.slice(-rx):r.slice(o,o+rx)).join(" / ");return i.length>tx?`${i.slice(0,tx)}\u2026`:i}function hU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(sU,"").split(`
101
+ `).map(s=>s.trim()).filter(s=>s.length>0),o=fU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var mU=6e5,gU=18e5,nx=2147483647,yU=3e4,ox=1e4,ux=[250,1e3,2e3],Cn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},_i=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},vU=250,sx=3,_U=[200,500];function SU(t){for(let e of Object.values(t))if(sa(e))return!0;return!1}function dx(t){let e=new Set;for(let r of t.matchAll(ts))e.add(ia(r[0]));return[...e].sort()}function hh(t){return[...new Set(t)].sort()}function ix(t,e){return Wg(e.map(r=>t?.[r]??"missing"))}function wU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return hh([...e&&t?fd(t):[],...n&&r?dx(r):[]])}var jc="${augmentToken}";function bU(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 RU(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var lx="(unknown uri)",mh="unknown",ax=/=+$/,PU=/\s+/g,CU=/[-_]/g,xU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function xn(t,e){return typeof t=="string"?t:e}function px(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function kU(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function EU(t){let e=t.replace(PU,"").replace(CU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(ax,"");if(r.toString("base64").replace(ax,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function fx(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function TU(t){let e=fx(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=xn(e.uri,lx),n=xn(e.mimeType,mh);if(typeof e.blob=="string"&&kU(n)){let s=EU(e.blob);if(s!==void 0)return s}let o=px(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function AU(t){let e=xn(t.type,"unknown");if(e==="resource")return TU(t);if(e==="audio"){let r=xn(t.mimeType,mh),n=px(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=xn(t.uri,lx),n=xn(t.name,""),o=xn(t.mimeType,mh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function $U(t){if(t.type!=="resource")return;let e=fx(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&xU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function MU(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=$U(t);return e||{type:"text",text:AU(t)}}function IU(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(MU(n))}return e}function OU(t){return jg(t,cU)}function zU(t,e){let r=IU(t);if(r.length===0){let o=OU(e);o!==void 0&&r.push({type:"text",text:o})}let n=0;return Array.isArray(t)?n=t.length:t!=null&&(n=1),{content:r,rawItemCount:n}}var 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"]),NU=new Set([502,503,504]),Si=ux.length+1,DU=2;function LU(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 jU(t){if(St(t)||lh(t)||t instanceof lt)return;let e=t?.cause?.code;if(typeof e=="string")return hx.has(e)?{totalAttempts:Si}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:DU}:NU.has(r)?{totalAttempts:Si}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Si}:void 0}var FU=80,UU=10,qU=/[^a-zA-Z0-9_.()-]/g,HU=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Fc(t){return t.replace(qU,"_").slice(0,FU)||"unknown"}function GU(t){let e=LU(t);if(e!==void 0&&(/^\d{3}$/.test(e)||hx.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=HU.has(e)?e:"Error",n=GU(t);return n===void 0?r:`${r}(${n})`}function ph(t,e,r){return t instanceof lt?new lt(Fc(t.serverName),t.missingKeys.slice(0,UU).map(Fc),void 0,t.reason).message:t instanceof Pn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function fh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Fc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Uc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},qc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>dd(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=ph(r,"connect",this._config.type),o=this._config.type==="stdio"&&!St(r)?dd(hU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=Si,r={available:!0};for(let n=1;n<=Si;n++)try{let o=await this._attemptConnect(r);return n>1&&X.info(`MCP server "${this.name}" connected on attempt ${n}/${e}`),o}catch(o){if(!r.available)throw o;let s=jU(o);if(s===void 0||this._disposed||(e=Math.min(e,s.totalAttempts),n>=e))throw o;if(await this._backoffBeforeRetry(o,n,e),this._disposed)return}}async _backoffBeforeRetry(e,r,n){let s=(ux[r-1]??0)+Math.floor(Math.random()*(vU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Wr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return St(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!re().tokens.get(this.name)?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new Cn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=KC();this._client=s;let i;try{if(await uh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(JC,()=>{X.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let a=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=a.tools??[],this._status="success",this._lastError=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=re();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&ot(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=ph(e,r,this._config.type)){if(e instanceof lt){this._status="failed";let o=re();Io(o,this.name,e.reason,Jt(o,this.name,this._config.id))}else if(e instanceof _i||e instanceof Cn)this._status="failed";else if(St(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(St(e)){this._status="auth_required";let o=re(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=ph(e,r,this._config.type);ld(fh(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=qC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=HC(this._resolvedEnv??e.env);return ZC({command:r.command,args:r.args,env:n,cwd:e.cwd})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return WC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=VC(e,{headers:r,getHeaders:()=>this._buildAuthHeaders()});return this._activeTransport=n,n}async _resolveSecretRefs(){let e=this._config,r=e.type==="stdio"?e.env:this._resolvedHeaders??e.headers,n=r?SU(r):!1,o=e.type==="stdio"&&sa(e.command);if(!(n||o))return;let s=re();if(!Vg(s)){let a=wU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new lt(this.name,a)}let i=Zg(s);n&&r&&await this._resolveMapSecretRefs(r,i,e.type==="stdio"),o&&e.type==="stdio"&&await this._resolveCommandSecretRefs(e.command,i)}async _resolveMapSecretRefs(e,r,n){let o;try{o=await Jg({configEnv:e,localEnv:n?GC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new lt(this.name,fd(e),i,"transient")}let s=hh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new lt(this.name,s,void 0,ix(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Yg(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new lt(this.name,dx(e),s,"transient")}let o=hh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new lt(this.name,o,void 0,ix(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(jc)))return;let o;if(bU(e.url)){let i=re().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${jc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${jc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${RU(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(jc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=re();if(n.diagnostics.some(i=>i.server===this.name&&i.message===e))return;n.diagnostics.push({server:this.name,message:e});let s=`MCP server "${this.name}": ${e}`;r==="error"?X.error(s):X.warn(s)}_usableToken(){let e=re(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Be(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=re().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&zu(o)&&re().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Vo(o)&&re().tokens.markAuthRequired(this.name))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=re(),r=e.refreshes.get(this.name);if(r)return r.then(a=>a??{kind:"refreshed"});let n={state:e,tokenStore:e.tokens,serverGeneration:e.serverGenerations.get(this.name)??0,configRevision:e.configRevisions.get(this.name)??0,credential:e.credentialRevisions.get(this.name),localRefreshEnabled:e.shouldProactivelyRefreshTokens,failureScope:Jt(e,this.name,this._config.id),token:this._usableToken(),hostWasUntracked:e.servers.get(this.name)===void 0},o=JSON.stringify([this.name,n.serverGeneration,n.configRevision,n.credential?.domain??null,n.credential?.revision??null]),s=e.refreshes.get(o);if(s)return s.then(a=>a??{kind:"refreshed"});let i=this._performTokenRefresh(n).finally(()=>{this._refreshPersisting=!1,e.refreshes.get(o)===i&&e.refreshes.delete(o),this._refreshPromise===i&&(this._refreshPromise=void 0)});return this._refreshPromise=i,e.refreshes.set(o,i),i}_ownsRefresh(e){let{state:r}=e,n=r.credentialRevisions.get(this.name),o=Z(r,this.name)?.retirement?.incumbent.host,s=r.servers.get(this.name)===this||this._refreshPersisting&&o===this||e.hostWasUntracked&&r.servers.get(this.name)===void 0;return(!this._disposing||this._refreshPersisting)&&s&&(r.serverGenerations.get(this.name)??0)===e.serverGeneration&&(r.configRevisions.get(this.name)??0)===e.configRevision&&this._ownsRefreshCredential(e,n)&&(e.localRefreshEnabled===r.shouldProactivelyRefreshTokens||this._refreshPersisting)}_ownsRefreshCredential(e,r){return e.state.tokens===e.tokenStore&&e.tokenStore.get(this.name)===e.token&&r?.domain===e.credential?.domain&&r?.revision===e.credential?.revision}async _restoreAfterSupersededRefresh(e,r,n,o){let s=e.state.servers.get(this.name),i=e.state.tokens,a=i.get(this.name),c=e.state.credentialRevisions.get(this.name);if(!(i!==e.tokenStore||!s||!a||!Be(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),Fr({state:e.state,name:this.name,revision:o});return}let u=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o);if(!u||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain)return;Fr({state:e.state,name:this.name,revision:u});let d=e.state.currentLoad?.latestPi;d&&J(d,e.state)}catch{X.error(`Failed to restore authoritative MCP OAuth token for "${this.name}" after superseded refresh`)}}_refreshFailureCategory(e,r){return r?"auth_terminal":e instanceof B?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof B)&&Du(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&Io(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),Io(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Lu(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let s=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,s),{kind:"transient_failure"};e.tokenStore.commit(this.name,o),Fr({state:e.state,name:this.name,revision:s}),ot(e.state,this.name);let i=e.state.currentLoad?.latestPi;return i&&J(i,e.state),X.debug(`MCP server "${this.name}" token refreshed`),{kind:"refreshed"}}catch(r){return this._handleRefreshFailure(r,e)}}_isSessionExpiredError(e){return this._config.type!=="http"||this._activeTransport?.sessionId===void 0?!1:lh(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),lU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Cn}async _withAuthRetry(e,r,n){let o=this._config,s=re(),i=Jt(s,this.name,this._config.id),a=n?.call;if(o.type!=="http"&&o.type!=="sse")return e();let c=()=>(a&&(a.failure=void 0),uh({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!St(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new _i;if(this._hostedCredentialProvenance!==void 0)throw new Cn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw St(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=re();Io(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new Uc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Uc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},yU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=re(),r=Jt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=sx&&n.outcome==="transient";i++)await Wr(_U[i-2]??0),n=await this._runProbe();let o=Jt(e,this.name,this._config.id),s=o.serverGeneration===r.serverGeneration&&o.mcpConfigId===r.mcpConfigId&&o.credentialRevision===r.credentialRevision&&o.credentialRevisionDomain===r.credentialRevisionDomain;return s&&n.outcome==="alive"&&ot(e,this.name,r),s&&(n.outcome==="alive"||n.outcome==="authFailure")?this._lastProbeResult=n:n.outcome==="inconclusive"?X.warn(`MCP server "${this.name}" startup verification ping was inconclusive; leaving handshake status intact: ${n.error}`):n.outcome==="transient"&&X.debug(`MCP server "${this.name}" startup verification ping remained transient after ${sx} 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:ox})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":XC(e)||dh(e)?"alive":St(e)?"authFailure":QC(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!(!e||this._disposed))try{await e.ping({timeout:ox})}catch(r){if(this._reinitializingPromise||this._disposed||dh(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return St(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!St(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!oU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>nx)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${nx}.`);let s={timeout:this._config.timeoutMs??mU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??gU,onprogress:d=>{X.debug(`MCP server "${this.name}" tool "${e}" progress: ${d.progress}${d.total===void 0?"":`/${d.total}`}${d.message?` - ${d.message}`:""}`)}},i,a=new Promise((d,l)=>{i={reject:l,livenessRejected:!1,sessionRecoveryOwned:!1}});a.catch(()=>{}),i&&this._inFlightCalls.add(i);let u=this._withSessionRetry(()=>this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.callTool({name:e,arguments:r??{}},YC,s)},"tool_call",{call:i})).then(d=>(i&&this._settleInFlightCall(i,!0,void 0),d),d=>{throw i&&this._settleInFlightCall(i,!1,d),d});try{let d=await Promise.race([u,a]),l=zU(d.content,d.structuredContent);return{isError:d.isError===!0,content:l.content,rawItemCount:l.rawItemCount}}catch(d){if(n?.aborted||d instanceof Error&&d.name==="AbortError")throw d;return this._reportAndThrowToolError(d,e)}finally{i&&!this._wedgeRecoveryOwners.has(i)&&(i.failure=void 0,this._inFlightCalls.delete(i))}}_reportAndThrowToolError(e,r){if(e instanceof Cn||e instanceof _i)throw e;if(St(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Fc(r),s=He(e),i=ex(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw pU(e)||ld(fh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),fh(a,s)}beginDisposal(){this._disposing||this.onToolsWithdraw?.(),this._disposing=!0,this._disposed=!0,this._stopHeartbeat(),this._failInFlightCalls(new Error(`MCP server "${this.name}" is being disposed`),!1),this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1}async dispose(e){this.beginDisposal(),await this._refreshPromise,this._stopHeartbeat();let r=this._client;if(this._client=void 0,this._activeTransport=void 0,this._reinitializingPromise=void 0,this._wedgeRecoveryOwners.clear(),this._wedgePending=!1,this._wedgeRequired=!1,this._stdioTransport=void 0,!!r)try{await r.close()}catch(n){if(X.debug(`MCP server "${this.name}" close error: ${n instanceof Error?n.message:String(n)}`),e?.strict)throw n}}};var mx=BU.child({prefix:"pi-mcp"}),VU=3,WU=6e4;function KU(t,e){let r=Date.now(),n=r-WU,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=VU?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function gx(t){Vr(t),qi(t)}async function JU(t,e,r){if(!KU(e,t)){mx.warn(`MCP server "${t}" automatic restart rate-limited`);return}mx.warn(`MCP server "${t}" wedged; recycling transport`),await Lr(t,e,r)}function Hc(t,e,r){if(YU(e)){gx(t);return}Cu(t,r),zn(e)&&gx(t)}function YU(t){return Fo()||t.toolSearchLatched}function Vt(t,e,r){return Jh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function gh(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,ot(t,e),t.authRefreshNeededReportKeys.delete(e),r}function XU(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name),a=o!==void 0&&i?.revision===o.revision,c=o!==void 0&&i?.domain===o.domain,u=o!==void 0&&i?.ownerDomain===o.ownerDomain,d=o!==void 0&&e.oauthCredentialDomains.get(r.name)===o.domain,l=o!==void 0&&om(o.domain,r.id,o.ownerDomain);return o!==void 0&&s!==void 0&&i!==void 0&&a&&c&&u&&d&&l?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function yh(t){let{state:e,config:r,generation:n}=t;return new qc(r,XU({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function vh(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 _h(t,e,r){return t.configDesiredRevisions.get(e)===r}function yx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function Sh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Vt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(ZU,c)},t.onWedged=()=>{if(!Vt(t,e,r))return;let i=r.currentLoad?.latestPi??n;JU(t.name,r,i)};let o=t.hostedCredentialProvenance,s=o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0?{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}:void 0;t.onAuthRefreshNeeded=()=>{if(!Vt(t,e,r)||!s)return;let i=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==i&&(r.authRefreshNeededReportKeys.set(t.name,i),J(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!Vt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&ot(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Vt(t,e,r)&&t.status==="success"&&Hc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;xu(i,t,e),i!==n&&xu(n,t,e)}}async function vx(t,e,r,n){let o=setTimeout(()=>{Vt(t,e,r)&&J(n(),r)},Ai);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Vt(t,e,r)&&J(n(),r)}}async function _x(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function Gc(t,e){if(e.status!=="installed")return!1;let r=Z(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function QU(t){let{state:e,config:r,displaced:n,retirement:o}=t;vh(e,n.config),Do(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():ut(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function eq(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=bt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function tq(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Vt(r,o,e)?a?.(n)===!1?(await eq({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Hc(c(),e,r),J(c(),e),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:i}):{status:"superseded",config:n}}function rq(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=Z(e,r.name);if(!_h(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=gh(e,r.name),l=yh({state:e,config:r,generation:d});return Sh(l,d,e,o),Ii({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:tq({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function nq(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!_h(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):Z(r,a.name),l=Tn(a,s),p=No({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>rq({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await QU({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await lu(p.retirement),h());return p.retirement?m():h()}async function wt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await nq({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Ai);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function oq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!yx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);vh(e,s),Do(e,t);let a=bt({state:e,name:t,owner:i.owner,revision:i.revision,host:o});if(!a)return!1;o.beginDisposal?.();try{await o.dispose({strict:!0}),we({state:e,name:t,retirement:a,result:{status:"retired"}})}catch(l){throw we({state:e,name:t,retirement:a,result:{status:"failed",error:l}}),l}if(Z(e,t)?.revision!==i.revision||!yx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=gh(e,t),u=yh({state:e,config:s,generation:c});if(Sh(u,c,e,r),!Ii({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await vx(u,c,e,d),Vt(u,c,e)&&u.status==="success"&&Hc(d(),e,u),!0}function Lr(t,e,r){e.reconnects??=new Map,e.configRevisions??=new Map,e.reconnectDesiredGenerations??=new Map,e.statusFailureCategories??=new Map;let n=(e.reconnectDesiredGenerations.get(t)??0)+1;e.reconnectDesiredGenerations.set(t,n);let o=e.reconnects.get(t);if(o)return o;let s=(async()=>{let i=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await oq({name:t,state:e,pi:r,configRevision:a}))return;i=c}while(i<(e.reconnectDesiredGenerations.get(t)??i))})().finally(()=>{e.reconnects.get(t)===s&&e.reconnects.delete(t)});return e.reconnects.set(t,s),s}async function sq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;vh(e,n.config),Do(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():ut(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function Sx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=In(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=No({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await sq({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await lu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!_h(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=gh(e,t),h=yh({state:e,config:a,generation:f});Sh(h,f,e,r),Ii({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await vx(h,f,e,s),Vt(h,f,e)&&h.status==="success"&&Hc(s(),e,h))}async function wi(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Lr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as iq}from"@hermes/logger";var wh=iq.child({prefix:"pi-mcp"}),aq=1e6,cq=1e3,uq=/^\d+$/;function wx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function kn(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"||!uq.test(e)||typeof r!="string"||r.length===0)return;let n=tm(t);return{revision:e.replace(/^0+(?=\d)/,""),domain:wx(r),...n===void 0?{}:{ownerDomain:n}}}function dq(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function lq(t,e,r){if(t===void 0)return!0;let n=wx(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain?!0:r?.kind==="domain"&&!it(n)&&it(e.domain)&&An(n)===r.domain}function pq(t,e,r,n){let o=e.credential_revision??e.credentialRevision,s=e.credential_revision_domain??e.credentialRevisionDomain;if((o!==void 0||s!==void 0)&&r===void 0)return wh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";let a=An(r.domain);if(i?.kind==="blocked"||i?.kind==="domain"&&r.ownerDomain!==void 0&&r.ownerDomain!==i.domain||i?.kind==="domain"&&r.ownerDomain===void 0&&!it(r.domain)&&a!==i.domain)return"reject";let c=n?.acceptedDomains?.get(t);if(!lq(c,r,i))return"reject";let u=dq(n?.acceptedRevisions,r.domain,s);if(u===void 0)return"apply";let d=mr(r.revision,u);return d>0||d===0&&c===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":d===0?"equal":"reject"}function fq(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 hq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function mq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*cq+Math.floor(t.access_token_expires_at.nanos/aq):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 Zc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!hq(s)){wh.warn(`Skipping MCP OAuth credentials for "${o}": entry is not an object with a non-empty access_token`),n.rejected.push(o);continue}let i=kn(s),a=pq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=mq(s);if(fq(t,o,c,i)){wh.warn(`Skipping MCP OAuth credentials for "${o}": legacy payload cannot prove freshness`),n.rejected.push(o);continue}t.set(o,c),r?.equalRevisionRebindDomains?.delete(o),i!==void 0&&(r?.acceptedRevisions?.set(i.domain,i.revision),r?.acceptedDomains?.set(o,i.domain)),n.applied.push(o)}return n}var yq=gq.child({prefix:"pi-mcp"});function vq(t,e){let r;for(let[n,o]of t.servers){if(o.config.id!==e)continue;let s=Q(t,n,o);if(!(s.host!==o||s.owner.kind!=="registry"||s.owner.identity!==`user:${e}`)){if(r)return;r={name:n,server:o}}}return r}function _q(t,e,r){let n=Object.entries(t).filter(([o,s])=>{let i=kn(s);if(i===void 0)return!1;let a=Ur(i);return i.ownerDomain!==void 0?a===`user:${e}`:o===r&&it(i.domain)||a===`user:${e}`});return n.length===1?n[0]?.[1]:void 0}async function bx(t){let{pi:e,state:r,update:n}=t,o=vq(r,n.configId),s=o?_q(n.credentials,n.configId,o.server.config.name):void 0;if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=Zc(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let p=kn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Lr,l=t.report??J;await d(o.name,r,u).catch(p=>{yq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),ze(r)}import{logger as Tq}from"@hermes/logger";import{execFile as Sq}from"node:child_process";import{logger as wq}from"@hermes/logger";var bq=5e3;function Rq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function Rx(t,e=bq){let r=wq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=Rq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=Sq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as Pq}from"node:http";function Bc(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Px(t){let e=Bc(t.title),r=Bc(t.heading),n=Bc(t.message),o=t.details?Bc(t.details):void 0,s=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
102
102
  <html lang="en">
103
103
  <head>
104
104
  <meta charset="utf-8" />
@@ -140,13 +140,13 @@ ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.t
140
140
  </main>
141
141
  ${s}
142
142
  </body>
143
- </html>`}function wx(t){return Sx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Zc(t,e){return Sx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var Sq="127.0.0.1",Px="/callback",bx=3e3,Rx=3010,wq="Authentication successful. You can close this window.",Bc={"Content-Type":"text/html; charset=utf-8"};function Cx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function xx(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n,o;try{let s=new URL(r);n=s.searchParams.get("code")??void 0,o=s.searchParams.get("state")??void 0}catch{if(r.includes("code=")){let s=new URLSearchParams(r);n=s.get("code")??void 0,o=s.get("state")??void 0}else n=r}if(!n)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{code:n,state:o??e}}function bq(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==Px){e.writeHead(404,Bc),e.end(Zc("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){e.writeHead(400,Bc),e.end(Zc("Authentication did not complete.",`Error: ${i}`));let a=n.searchParams.get("error_description");r.onError(new Error(`Authentication did not complete: ${i}${a?`: ${a}`:""}`));return}if(!o||!s){e.writeHead(400,Bc),e.end(Zc("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Bc),e.end(wx(wq)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function Rq(t){for(let e=bx;e<=Rx;e++)if(await new Promise(n=>{let o=()=>{t.removeListener("listening",s),n(!1)},s=()=>{t.removeListener("error",o),n(!0)};t.once("error",o),t.once("listening",s),t.listen(e,Sq)}))return e;throw new Error(`No free port in ${bx}-${Rx} for the OAuth callback server`)}async function kx(){let t=!1,e,r,n=new Promise((i,a)=>{e=c=>{t||(t=!0,i(c))},r=c=>{t||(t=!0,a(c))}}),o=_q((i,a)=>{bq(i,a,{onSuccess:c=>e?.(c),onError:c=>r?.(c)})}),s=await Rq(o);return{port:s,redirectUri:`http://localhost:${s}${Px}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>o.close()}}var Tx=Pq.child({prefix:"pi-mcp"}),Cq=300*1e3,Ax="MCP authentication was superseded";function xq(){return Cx()?"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 kn(t){if(t.aborted)throw new Error("Authentication cancelled")}function $x(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&&Mx(t.credentialRevisions.get(e),r.credentialRevision)}function Mx(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Ex(t,e,r){if(!$x(t,e,r))throw new Error(Ax)}async function kq(t,e,r,n,o,s){let i=t.servers.get(e),a=t.tokens,c=a.get(e),u=t.credentialRevisions.get(e);if(a!==r.tokenStore||!i||!c||!Be(r.server.config,i.config))return;let d=i.config,l=hr(d);try{let p=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(p===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!Mx(t.credentialRevisions.get(e),u))return;Fr({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??s,t)}catch{Tx.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function Eq(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 Tq(t,e,r){return new Promise((n,o)=>{let s=!1,i=()=>{clearTimeout(u),e.signal.removeEventListener("abort",c),t.cancelWait()},a=d=>{s||(s=!0,i(),d())},c=()=>a(()=>o(new Error("Authentication cancelled"))),u=setTimeout(()=>a(()=>o(new Error("Authentication timed out"))),Cq);if(e.signal.aborted){a(()=>o(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",c),t.waitForCode().then(d=>{d&&a(()=>n(new URLSearchParams({code:d.code,state:d.state})))}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d))))),e.waitForManualCode().then(d=>{if(d)try{let l=xx(d,r);a(()=>n(new URLSearchParams({code:l.code,state:l.state})))}catch(l){let p=l instanceof Error?l.message:String(l);a(()=>o(new Error(`Could not read the pasted authorization code (${p}). Restart sign-in and paste the full redirect URL.`)))}}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d)))))})}async function Ix(t){let{serverName:e,state:r,pi:n,controller:o}=t,s=r.servers.get(e);if(!s)throw new Error(`Unknown MCP server "${e}"`);let i=s.config;if(i.type!=="http"&&i.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:s,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=hr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Ex(r,e,c),kn(o.signal),d=await kx(),kn(o.signal);let p=new URL(i.url),f=await td(p);kn(o.signal);let h=await rd(f);kn(o.signal);let m=await nd({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});kn(o.signal);let y=await od(p,m,h,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);kn(o.signal),o.onAuthUrl({url:y.authUri.toString(),instructions:xq()}),kn(o.signal),await _x(y.authUri.toString());let S=await Tq(d,o,y.state),w=await sd(S,y);Ex(r,e,c);let b=Eq(w),k=await c.tokenStore.persistAuthenticated(e,b,u,l);if(!$x(r,e,c))throw await kq(r,e,c,b,k,n),new Error(Ax);c.tokenStore.commit(e,b),r.preservedCredentialIdentities?.delete(e),Fr({state:r,name:e,revision:k}),r.tokens.clearAuthRequired(e),st(r,e),await _i([e],r,n),J(r.currentLoad?.latestPi??n,r),Tx.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as Zq}from"@augmentcode/auggie-v2";import{resolveTargetFiles as Aq,SETTINGS_TARGET_ORDER as $q,SettingsManager as Mq,scopeToSettingsTarget as Iq,settingsTargetToScope as _h}from"@augmentcode/auggie-v2";var Oq=$q.map(t=>_h(t)),Ox=(t,e)=>Mq.create(t,e);function zx(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 Nx(t,e,r){let n=Ox(e,r);return Oq.filter(o=>zx(n,o)?.[t])}function Dx(t){let e=t.map(n=>({target:Iq(n),path:n,exists:!0})),r=Aq({files:e});return"directTarget"in r?{scopes:t,direct:_h(r.directTarget)}:{scopes:r.files.map(n=>_h(n.target)),direct:null}}function zq(t,e,r){let{servers:n}=$n(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Lx(t,e,r,n,o){try{let s=Ox(n,o);if(!zx(s,r)?.[t])return{ok:!1,error:`Server "${t}" not found in ${r} settings`};s.update(r,{path:["mcpServers",t,"disabled"],value:e})}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}return{ok:!0,overridden:zq(t,n,o)!==e}}function Sh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function jx(t,e,r){return Sh(t)}function Fx(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as Nq}from"@hermes/logger";var bh=Nq.child({prefix:"pi-mcp"}),Ux="hermes:mcp:register-server-source";function Dq(t,e){return t.type==="stdio"?Dt(t,e):Nt(t,e)}function qx(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Lq(t,e){return{...t,disabled:e}}function jq(t){try{return t.getServers()}catch(e){return bh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function Fq(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Hx(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 Uq(t,e,r,n){let o=new Map;if(!t)return o;for(let s of jq(t)){let i=e.servers.get(s.name),a=Dq(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=Lq(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=Z(e,s.name),p=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,f=i!==void 0&&d===void 0&&n.has(s.name)&&qx(i.config,u);f&&(Q(e,s.name,i),Zh({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(p||f||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),Hx(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function qq(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=Z(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){be({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=bt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=ct(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),be({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Gx(t,e){Hx(t,e)}function Hq(t){let{state:e,desired:r,previousNames:n,previousHosts:o}=t,s=[],i=new Map;for(let[a,c]of r){let u=e.servers.get(a),d=u?Q(e,a,u):Z(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){Gx(e,a);continue}u===o.get(a)&&n.has(a)&&qx(u.config,c)||(i.set(a,Ge(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function Gq(t,e,r){let n=r?.connect??wt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&Fq(o,e);let i=new Set(e.pluginServerNames);e.pluginServerHosts??=new Map;for(let[h,m]of e.pluginServerHosts){let y=e.servers.get(h);(y===void 0||y===m)&&Q(e,h,m)}let a=Uq(o,e,s,i);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 qq(a,u,e);let{reservedRevisions:d,toConnect:l}=Hq({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;bh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let p=()=>e.currentLoad?.latestPi??t,f=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),S=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return S||Gx(e,h.name),S};try{await n(l,e,p(),f,d,"plugin");for(let h of l)f(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(p(),e),ze(e)}}function wh(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>Gq(t,e,r)).catch(s=>{bh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function Zx(t,e){let{name:r,disabled:n,state:o,pi:s}=t,i=o.servers.get(r),a=i?Q(o,r,i):Z(o,r);return a?.owner.kind!=="plugin"||a.host!==i?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),wh(o.currentLoad?.latestPi??s,o,e))}function Bx(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,wh(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,wh(e.currentLoad?.latestPi??t,e))})}}function Bq(t,e){let n=Zq.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function Vx(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(Bq(n,o).has(e))return{kind:"blocked",message:`Cannot toggle "${e}": server is managed and cannot be modified`};let s=r.servers.get(e);if(!s)return{kind:"blocked",message:Sh(e)};if(yu(r.mcpConfigOverride).has(e))return{kind:"session"};if(fr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=Nx(e,n,o);if(i.length===0)return{kind:"blocked",message:jx(e,n,o)};let{scopes:a,direct:c}=Dx(i);return{kind:"local",scopes:a,direct:c}}async function Wx(t){let{server:e,disable:r,state:n,pi:o}=t,s=n.servers.get(e);if(!s)return;let i=n.hostLeases?.get(e)??(n.pluginServerHosts?.get(e)===s?Q(n,e,s):void 0);if(i?.owner.kind==="plugin"&&i.host===s){await Zx({name:e,disabled:r,state:n,pi:o});return}yu(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),s.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...s.config,disabled:r};await wt([a],n,o,void 0,void 0,i?.owner.kind),ze(n)}async function Kx(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=Lx(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await gx(e,o,s,i,a),ze(o),c.overridden?{notice:Fx(e)}:{}}import{Key as pH,matchesKey as fH,SpinnerTimer as hH,wrapTextWithAnsi as mH}from"@earendil-works/pi-tui";import{Key as Qq,matchesKey as eH}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as Vq,scopeToSettingsTarget as Wq}from"@augmentcode/auggie-v2";import{truncateToWidth as Kq,visibleWidth as Jx}from"@earendil-works/pi-tui";var Jq=15,Yq=2;function Yx(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 Rh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Xx(t){return Math.max(Ph(t),Jq)}function Ph(t){return t.reduce((r,n)=>Math.max(r,Jx(n)),0)+Yq}function Si(t,e){let r=e-Jx(t);return r>0?t+" ".repeat(r):t}function Qx(t,e){return Kq(t,Math.max(1,e),"\u2026")}function ek(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 Xq(t,e){return Math.max(0,t-e)}function Ch(t,e,r){return Math.max(0,Math.min(t,Xq(e,r)))}function tk(t,e,r){let n=t,o=Math.min(e,t+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Lines ${n+1}-${o} of ${e}`}}function rk(t,e){return String(t+1).padStart(String(e).length," ")}function nk(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function xh(t){return Vq(Wq(t))}function Vc(t){if(t.source==="plugin"&&t.disabled)return["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.isOAuth&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function ok(){return{step:"serverList",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var xo=15;var tH="k",rH="j";function ko(t,e){return(t%e+e)%e}function nt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function sk(t,e){return e.matches(t,"tui.select.up")||t===tH?{kind:"up"}:e.matches(t,"tui.select.down")||t===rH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:eH(t,Qq.backspace)?{kind:"back"}:{kind:"ignore"}}function nH(t,e,r){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=ko(nt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=ko(nt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[nt(r,t.selectedServer)];return o?.status==="auth_required"&&o.isOAuth?{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 oH(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Vc(n);switch(e.kind){case"up":return{state:{...t,actionIndex:ko(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:ko(t.actionIndex+1,o.length)}};case"cancel":case"back":return{state:{...t,step:"serverList"}};case"confirm":{let s=o[t.actionIndex];return s==="viewTools"?{state:{...t,step:"viewTools",toolIndex:0}}:s==="viewLogs"?{state:{...t,step:"viewLogs",logScrollOffset:0}}:s==="authenticate"?{state:t,effect:{kind:"authenticate",server:n.name}}:s==="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 sH(t,e,r){let n=r.snapshots[nt(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 iH(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)]?.logLines().length??0;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Ch(t.logScrollOffset-1,n,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Ch(t.logScrollOffset+1,n,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function aH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Wc(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function cH(t,e){let r=t.targetScopes.length;if(r===0)return{state:Wc(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:ko(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:ko(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Wc(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Wc({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Wc(t,"serverActions")}}default:return{state:t}}}function ik(t,e,r){switch(t.step){case"serverList":return nH(t,e,r.snapshots);case"serverActions":return oH(t,e,r);case"viewTools":return sH(t,e,r);case"viewLogs":return iH(t,e,r);case"pasteAuthCode":return aH(t,e);case"selectTarget":return cH(t,e);default:return{state:t}}}var kh="\u2192 ",Kc=" ";function uH(t,e,r){return t.disabled?r.fg("muted",t.name):e?r.bold(r.fg("accent",t.name)):r.fg("text",t.name)}function ak(t,e,r){if(e.length===0)return[r.fg("muted","No MCP servers available")];let n=Xx(e.map(c=>c.name)),o=Ph(["Source",...e.map(Rh)]),s=nt(e,t.selectedServer),a=[Kc+Si(r.bold(r.fg("accent","Name")),n)+Si(r.bold(r.fg("accent","Source")),o)+r.bold(r.fg("accent","Status"))];for(let[c,u]of e.entries()){let d=c===s,l=Yx(u),p=r.fg(l.color,l.label)+(l.hint?r.fg("muted",l.hint):"");a.push((d?kh:Kc)+Si(uH(u,d,r),n)+Si(r.fg("muted",Rh(u)),o)+p)}return a}var dH={authenticate:{label:"Authenticate",description:"Sign in to this server with OAuth"},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 lH(t,e){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 dH[t]}function ck(t,e,r,n){let o=e[nt(e,t.selectedServer)];if(!o)return[r.fg("muted","No MCP servers available")];let s=o.transport==="stdio"?"Command: ":"URL: ",i=[r.fg("muted",Qx(s+o.connectionInfo,n))];o.source==="plugin"&&i.push(r.fg("muted","Source: plugin (toggles apply to this session only)")),i.push("");let a=Vc(o);for(let[c,u]of a.entries()){let d=c===t.actionIndex,l=lH(u,o),p=u==="authenticate"?nk(o.status):l.label,f=d?r.bold(r.fg("accent",p)):r.fg("text",p);i.push((d?kh:Kc)+f+r.fg("muted",` - ${l.description}`))}return i}function uk(t,e,r){let n=e[nt(e,t.selectedServer)];if(!n)return[r.fg("muted","No tools available.")];if(n.disabled)return[r.fg("muted","Server is disabled; no tools are currently available.")];if(n.tools.length===0)return[r.fg("muted","No tools available.")];let o=n.tools.length,{start:s,end:i}=ek(t.toolIndex,o,xo),a=[];for(let c=s;c<i;c++){let u=n.tools[c];if(!u)continue;let l=c===t.toolIndex?r.bold(r.fg("accent",u.name)):r.fg("text",u.name);a.push(r.fg("muted",`${rk(c,o)} `)+l+(u.disabled?r.fg("muted"," (disabled)"):""))}return a}function dk(t,e,r){let o=e[nt(e,t.selectedServer)]?.logLines()??[];if(o.length===0)return[r.fg("muted","No logs available yet.")];let s=o.length,i=tk(t.logScrollOffset,s,xo),a=[];s>xo&&a.push(r.fg("muted",i.rangeLabel)),i.aboveCount>0&&a.push(r.fg("dim",`\u2191 ${i.aboveCount} more`));for(let c of o.slice(i.start,i.end))a.push(r.fg("text",c));return i.belowCount>0&&a.push(r.fg("dim",`\u2193 ${i.belowCount} more`)),a}function lk(t,e,r){let n=e[nt(e,t.selectedServer)]?.name??"",o=[r.fg("muted",`Save the toggle for "${n}" to which settings file?`),""];for(let[s,i]of t.targetScopes.entries()){let a=s===t.targetIndex,c=a?r.bold(r.fg("accent",xh(i))):r.fg("text",xh(i));o.push((a?kh:Kc)+c)}return o}function gH(t){return t.type==="stdio"?t.command:t.url}function yH(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
143
+ </html>`}function Cx(t){return Px({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Vc(t,e){return Px({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var Cq="127.0.0.1",Ex="/callback",xx=3e3,kx=3010,xq="Authentication successful. You can close this window.",Wc={"Content-Type":"text/html; charset=utf-8"};function Tx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function Ax(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n,o;try{let s=new URL(r);n=s.searchParams.get("code")??void 0,o=s.searchParams.get("state")??void 0}catch{if(r.includes("code=")){let s=new URLSearchParams(r);n=s.get("code")??void 0,o=s.get("state")??void 0}else n=r}if(!n)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{code:n,state:o??e}}function kq(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==Ex){e.writeHead(404,Wc),e.end(Vc("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){e.writeHead(400,Wc),e.end(Vc("Authentication did not complete.",`Error: ${i}`));let a=n.searchParams.get("error_description");r.onError(new Error(`Authentication did not complete: ${i}${a?`: ${a}`:""}`));return}if(!o||!s){e.writeHead(400,Wc),e.end(Vc("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Wc),e.end(Cx(xq)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function Eq(t){for(let e=xx;e<=kx;e++)if(await new Promise(n=>{let o=()=>{t.removeListener("listening",s),n(!1)},s=()=>{t.removeListener("error",o),n(!0)};t.once("error",o),t.once("listening",s),t.listen(e,Cq)}))return e;throw new Error(`No free port in ${xx}-${kx} for the OAuth callback server`)}async function $x(){let t=!1,e,r,n=new Promise((i,a)=>{e=c=>{t||(t=!0,i(c))},r=c=>{t||(t=!0,a(c))}}),o=Pq((i,a)=>{kq(i,a,{onSuccess:c=>e?.(c),onError:c=>r?.(c)})}),s=await Eq(o);return{port:s,redirectUri:`http://localhost:${s}${Ex}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>o.close()}}var Ix=Tq.child({prefix:"pi-mcp"}),Aq=300*1e3,Ox="MCP authentication was superseded";function $q(){return Tx()?"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 En(t){if(t.aborted)throw new Error("Authentication cancelled")}function zx(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&&Nx(t.credentialRevisions.get(e),r.credentialRevision)}function Nx(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Mx(t,e,r){if(!zx(t,e,r))throw new Error(Ox)}async function Mq(t,e,r,n,o,s){let i=t.servers.get(e),a=t.tokens,c=a.get(e),u=t.credentialRevisions.get(e);if(a!==r.tokenStore||!i||!c||!Be(r.server.config,i.config))return;let d=i.config,l=hr(d);try{let p=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(p===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!Nx(t.credentialRevisions.get(e),u))return;Fr({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??s,t)}catch{Ix.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function Iq(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 Oq(t,e,r){return new Promise((n,o)=>{let s=!1,i=()=>{clearTimeout(u),e.signal.removeEventListener("abort",c),t.cancelWait()},a=d=>{s||(s=!0,i(),d())},c=()=>a(()=>o(new Error("Authentication cancelled"))),u=setTimeout(()=>a(()=>o(new Error("Authentication timed out"))),Aq);if(e.signal.aborted){a(()=>o(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",c),t.waitForCode().then(d=>{d&&a(()=>n(new URLSearchParams({code:d.code,state:d.state})))}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d))))),e.waitForManualCode().then(d=>{if(d)try{let l=Ax(d,r);a(()=>n(new URLSearchParams({code:l.code,state:l.state})))}catch(l){let p=l instanceof Error?l.message:String(l);a(()=>o(new Error(`Could not read the pasted authorization code (${p}). Restart sign-in and paste the full redirect URL.`)))}}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d)))))})}async function Dx(t){let{serverName:e,state:r,pi:n,controller:o}=t,s=r.servers.get(e);if(!s)throw new Error(`Unknown MCP server "${e}"`);let i=s.config;if(i.type!=="http"&&i.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:s,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=hr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Mx(r,e,c),En(o.signal),d=await $x(),En(o.signal);let p=new URL(i.url),f=await od(p);En(o.signal);let h=await sd(f);En(o.signal);let m=await id({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});En(o.signal);let y=await ad(p,m,h,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);En(o.signal),o.onAuthUrl({url:y.authUri.toString(),instructions:$q()}),En(o.signal),await Rx(y.authUri.toString());let S=await Oq(d,o,y.state),w=await cd(S,y);Mx(r,e,c);let b=Iq(w),k=await c.tokenStore.persistAuthenticated(e,b,u,l);if(!zx(r,e,c))throw await Mq(r,e,c,b,k,n),new Error(Ox);c.tokenStore.commit(e,b),r.preservedCredentialIdentities?.delete(e),Fr({state:r,name:e,revision:k}),r.tokens.clearAuthRequired(e),ot(r,e),await wi([e],r,n),J(r.currentLoad?.latestPi??n,r),Ix.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as Jq}from"@augmentcode/auggie-v2";import{resolveTargetFiles as zq,SETTINGS_TARGET_ORDER as Nq,SettingsManager as Dq,scopeToSettingsTarget as Lq,settingsTargetToScope as bh}from"@augmentcode/auggie-v2";var jq=Nq.map(t=>bh(t)),Lx=(t,e)=>Dq.create(t,e);function jx(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 Fx(t,e,r){let n=Lx(e,r);return jq.filter(o=>jx(n,o)?.[t])}function Ux(t){let e=t.map(n=>({target:Lq(n),path:n,exists:!0})),r=zq({files:e});return"directTarget"in r?{scopes:t,direct:bh(r.directTarget)}:{scopes:r.files.map(n=>bh(n.target)),direct:null}}function Fq(t,e,r){let{servers:n}=In(e,r);return n.find(o=>o.name===t)?.disabled===!0}function qx(t,e,r,n,o){try{let s=Lx(n,o);if(!jx(s,r)?.[t])return{ok:!1,error:`Server "${t}" not found in ${r} settings`};s.update(r,{path:["mcpServers",t,"disabled"],value:e})}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}return{ok:!0,overridden:Fq(t,n,o)!==e}}function Rh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function Hx(t,e,r){return Rh(t)}function Gx(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as Uq}from"@hermes/logger";var Ch=Uq.child({prefix:"pi-mcp"}),Zx="hermes:mcp:register-server-source";function qq(t,e){return t.type==="stdio"?Dt(t,e):Nt(t,e)}function Bx(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Hq(t,e){return{...t,disabled:e}}function Gq(t){try{return t.getServers()}catch(e){return Ch.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function Zq(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Vx(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 Bq(t,e,r,n){let o=new Map;if(!t)return o;for(let s of Gq(t)){let i=e.servers.get(s.name),a=qq(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=Hq(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=Z(e,s.name),p=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,f=i!==void 0&&d===void 0&&n.has(s.name)&&Bx(i.config,u);f&&(Q(e,s.name,i),Wh({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(p||f||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),Vx(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function Vq(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=Z(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){be({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=bt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=ut(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),be({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Wx(t,e){Vx(t,e)}function Wq(t){let{state:e,desired:r,previousNames:n,previousHosts:o}=t,s=[],i=new Map;for(let[a,c]of r){let u=e.servers.get(a),d=u?Q(e,a,u):Z(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){Wx(e,a);continue}u===o.get(a)&&n.has(a)&&Bx(u.config,c)||(i.set(a,Ge(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function Kq(t,e,r){let n=r?.connect??wt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&Zq(o,e);let i=new Set(e.pluginServerNames);e.pluginServerHosts??=new Map;for(let[h,m]of e.pluginServerHosts){let y=e.servers.get(h);(y===void 0||y===m)&&Q(e,h,m)}let a=Bq(o,e,s,i);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 Vq(a,u,e);let{reservedRevisions:d,toConnect:l}=Wq({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Ch.info(`Plugin MCP source: connecting ${l.length} server(s)`);let p=()=>e.currentLoad?.latestPi??t,f=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),S=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return S||Wx(e,h.name),S};try{await n(l,e,p(),f,d,"plugin");for(let h of l)f(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(p(),e),ze(e)}}function Ph(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>Kq(t,e,r)).catch(s=>{Ch.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function Kx(t,e){let{name:r,disabled:n,state:o,pi:s}=t,i=o.servers.get(r),a=i?Q(o,r,i):Z(o,r);return a?.owner.kind!=="plugin"||a.host!==i?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),Ph(o.currentLoad?.latestPi??s,o,e))}function Jx(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Ph(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Ph(e.currentLoad?.latestPi??t,e))})}}function Yq(t,e){let n=Jq.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function Yx(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(Yq(n,o).has(e))return{kind:"blocked",message:`Cannot toggle "${e}": server is managed and cannot be modified`};let s=r.servers.get(e);if(!s)return{kind:"blocked",message:Rh(e)};if(Su(r.mcpConfigOverride).has(e))return{kind:"session"};if(fr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=Fx(e,n,o);if(i.length===0)return{kind:"blocked",message:Hx(e,n,o)};let{scopes:a,direct:c}=Ux(i);return{kind:"local",scopes:a,direct:c}}async function Xx(t){let{server:e,disable:r,state:n,pi:o}=t,s=n.servers.get(e);if(!s)return;let i=n.hostLeases?.get(e)??(n.pluginServerHosts?.get(e)===s?Q(n,e,s):void 0);if(i?.owner.kind==="plugin"&&i.host===s){await Kx({name:e,disabled:r,state:n,pi:o});return}Su(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),s.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...s.config,disabled:r};await wt([a],n,o,void 0,void 0,i?.owner.kind),ze(n)}async function Qx(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=qx(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await Sx(e,o,s,i,a),ze(o),c.overridden?{notice:Gx(e)}:{}}import{Key as yH,matchesKey as vH,SpinnerTimer as _H,wrapTextWithAnsi as SH}from"@earendil-works/pi-tui";import{Key as oH,matchesKey as sH}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as Xq,scopeToSettingsTarget as Qq}from"@augmentcode/auggie-v2";import{truncateToWidth as eH,visibleWidth as ek}from"@earendil-works/pi-tui";var tH=15,rH=2;function tk(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 xh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function rk(t){return Math.max(kh(t),tH)}function kh(t){return t.reduce((r,n)=>Math.max(r,ek(n)),0)+rH}function bi(t,e){let r=e-ek(t);return r>0?t+" ".repeat(r):t}function nk(t,e){return eH(t,Math.max(1,e),"\u2026")}function ok(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 nH(t,e){return Math.max(0,t-e)}function Eh(t,e,r){return Math.max(0,Math.min(t,nH(e,r)))}function sk(t,e,r){let n=t,o=Math.min(e,t+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Lines ${n+1}-${o} of ${e}`}}function ik(t,e){return String(t+1).padStart(String(e).length," ")}function ak(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function Th(t){return Xq(Qq(t))}function Kc(t){if(t.source==="plugin"&&t.disabled)return["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.isOAuth&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function ck(){return{step:"serverList",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var Eo=15;var iH="k",aH="j";function To(t,e){return(t%e+e)%e}function rt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function uk(t,e){return e.matches(t,"tui.select.up")||t===iH?{kind:"up"}:e.matches(t,"tui.select.down")||t===aH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:sH(t,oH.backspace)?{kind:"back"}:{kind:"ignore"}}function cH(t,e,r){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=To(rt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=To(rt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[rt(r,t.selectedServer)];return o?.status==="auth_required"&&o.isOAuth?{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 uH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Kc(n);switch(e.kind){case"up":return{state:{...t,actionIndex:To(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:To(t.actionIndex+1,o.length)}};case"cancel":case"back":return{state:{...t,step:"serverList"}};case"confirm":{let s=o[t.actionIndex];return s==="viewTools"?{state:{...t,step:"viewTools",toolIndex:0}}:s==="viewLogs"?{state:{...t,step:"viewLogs",logScrollOffset:0}}:s==="authenticate"?{state:t,effect:{kind:"authenticate",server:n.name}}:s==="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 dH(t,e,r){let n=r.snapshots[rt(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 lH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)]?.logLines().length??0;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Eh(t.logScrollOffset-1,n,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Eh(t.logScrollOffset+1,n,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function pH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Jc(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function fH(t,e){let r=t.targetScopes.length;if(r===0)return{state:Jc(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:To(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:To(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Jc(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Jc({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Jc(t,"serverActions")}}default:return{state:t}}}function dk(t,e,r){switch(t.step){case"serverList":return cH(t,e,r.snapshots);case"serverActions":return uH(t,e,r);case"viewTools":return dH(t,e,r);case"viewLogs":return lH(t,e,r);case"pasteAuthCode":return pH(t,e);case"selectTarget":return fH(t,e);default:return{state:t}}}var Ah="\u2192 ",Yc=" ";function hH(t,e,r){return t.disabled?r.fg("muted",t.name):e?r.bold(r.fg("accent",t.name)):r.fg("text",t.name)}function lk(t,e,r){if(e.length===0)return[r.fg("muted","No MCP servers available")];let n=rk(e.map(c=>c.name)),o=kh(["Source",...e.map(xh)]),s=rt(e,t.selectedServer),a=[Yc+bi(r.bold(r.fg("accent","Name")),n)+bi(r.bold(r.fg("accent","Source")),o)+r.bold(r.fg("accent","Status"))];for(let[c,u]of e.entries()){let d=c===s,l=tk(u),p=r.fg(l.color,l.label)+(l.hint?r.fg("muted",l.hint):"");a.push((d?Ah:Yc)+bi(hH(u,d,r),n)+bi(r.fg("muted",xh(u)),o)+p)}return a}var mH={authenticate:{label:"Authenticate",description:"Sign in to this server with OAuth"},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 gH(t,e){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 mH[t]}function pk(t,e,r,n){let o=e[rt(e,t.selectedServer)];if(!o)return[r.fg("muted","No MCP servers available")];let s=o.transport==="stdio"?"Command: ":"URL: ",i=[r.fg("muted",nk(s+o.connectionInfo,n))];o.source==="plugin"&&i.push(r.fg("muted","Source: plugin (toggles apply to this session only)")),i.push("");let a=Kc(o);for(let[c,u]of a.entries()){let d=c===t.actionIndex,l=gH(u,o),p=u==="authenticate"?ak(o.status):l.label,f=d?r.bold(r.fg("accent",p)):r.fg("text",p);i.push((d?Ah:Yc)+f+r.fg("muted",` - ${l.description}`))}return i}function fk(t,e,r){let n=e[rt(e,t.selectedServer)];if(!n)return[r.fg("muted","No tools available.")];if(n.disabled)return[r.fg("muted","Server is disabled; no tools are currently available.")];if(n.tools.length===0)return[r.fg("muted","No tools available.")];let o=n.tools.length,{start:s,end:i}=ok(t.toolIndex,o,Eo),a=[];for(let c=s;c<i;c++){let u=n.tools[c];if(!u)continue;let l=c===t.toolIndex?r.bold(r.fg("accent",u.name)):r.fg("text",u.name);a.push(r.fg("muted",`${ik(c,o)} `)+l+(u.disabled?r.fg("muted"," (disabled)"):""))}return a}function hk(t,e,r){let o=e[rt(e,t.selectedServer)]?.logLines()??[];if(o.length===0)return[r.fg("muted","No logs available yet.")];let s=o.length,i=sk(t.logScrollOffset,s,Eo),a=[];s>Eo&&a.push(r.fg("muted",i.rangeLabel)),i.aboveCount>0&&a.push(r.fg("dim",`\u2191 ${i.aboveCount} more`));for(let c of o.slice(i.start,i.end))a.push(r.fg("text",c));return i.belowCount>0&&a.push(r.fg("dim",`\u2193 ${i.belowCount} more`)),a}function mk(t,e,r){let n=e[rt(e,t.selectedServer)]?.name??"",o=[r.fg("muted",`Save the toggle for "${n}" to which settings file?`),""];for(let[s,i]of t.targetScopes.entries()){let a=s===t.targetIndex,c=a?r.bold(r.fg("accent",Th(i))):r.fg("text",Th(i));o.push((a?Ah:Yc)+c)}return o}function wH(t){return t.type==="stdio"?t.command:t.url}function bH(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 pk(t){return t.disabled?2:t.status==="auth_required"?0:1}function vH(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:fr(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,isOAuth:r.config.type!=="stdio"&&r.config.auth==="oauth",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:gH(r.config),logLines:()=>yH(r)});return e.sort((r,n)=>pk(r)-pk(n)),e}function _H(t,e){let r=e[nt(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 SH(t){switch(t){case"serverList":return"\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 wH(t,e,r,n){switch(t.step){case"serverActions":return ck(t,e,r,n);case"viewTools":return uk(t,e,r);case"viewLogs":return dk(t,e,r);case"selectTarget":return lk(t,e,r);default:return ak(t,e,r)}}function bH(t,e,r,n){let o=r.bold(r.fg("accent",_H(t,e))),s=wH(t,e,r,n);return[o,"",...s,"",r.fg("muted",SH(t.step))]}function RH(t,e,r,n){let o=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),s=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[o,"",s]}function PH(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function CH(t,e,r){let n=i=>i.flatMap(a=>mH(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 s=[o,"",e.fg("text","Opening your browser to sign in\u2026")];return t.url&&s.push(e.fg("accent",t.url)),t.instructions&&s.push(e.fg("muted",t.instructions)),s.push("",`${e.fg("text","Paste code or redirect URL: ")}${e.fg("accent",t.input)}`,"",e.fg("muted","Enter Submit \xB7 Esc Cancel")),n(s)}function xH(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function fk(t){return t?"Disabling":"Enabling"}function hk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Eh=class{state=ok();config;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;authInPaste=!1;authPasteBuffer="";authDone;component;constructor(e){this.config=e,this.component={render:r=>this.render(r),handleInput:r=>this.dispatch(r),invalidate:()=>{}}}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){return this.busy?RH(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme):this.authenticating?CH({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,e):bH(this.state,this.config.snapshots(),this.config.theme,e)}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots(),n=sk(e,this.config.keybindings),o=ik(this.state,n,{snapshots:r,windowSize:xo});this.state=o.state,o.effect&&this.runEffect(o.effect),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,fk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(hk(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,fk(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(hk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new hH(()=>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=PH();let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>this.manualCode?this.manualCode.promise:Promise.resolve(null),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();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();n&&this.manualCode?.resolve(n);return}if(fH(e,pH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),this.authInPaste){this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n!==-1){let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}return}xH(e)&&(this.state={...this.state,authInput:this.state.authInput+e},this.config.tui.requestRender())}exitAuth(){this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode=void 0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function mk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new Eh({tui:s,theme:i,keybindings:a,snapshots:()=>vH(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Ah=["list"];function gk(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 kH(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var EH="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function Th(t,e){return e.length>0?[t,...e]:null}function TH(t){let e=[],r=[];for(let o of t.servers.values())(fr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[Th("MCP Server Status:",e.map(gk)),Th("Plugin MCP servers:",r.map(gk)),Th("Diagnostics:",t.diagnostics.map(kH))];return t.servers.size===0&&n.unshift([EH]),n.filter(o=>o!==null).map(o=>o.join(`
145
+ `)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function gk(t){return t.disabled?2:t.status==="auth_required"?0:1}function RH(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:fr(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,isOAuth:r.config.type!=="stdio"&&r.config.auth==="oauth",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:wH(r.config),logLines:()=>bH(r)});return e.sort((r,n)=>gk(r)-gk(n)),e}function PH(t,e){let r=e[rt(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 CH(t){switch(t){case"serverList":return"\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 xH(t,e,r,n){switch(t.step){case"serverActions":return pk(t,e,r,n);case"viewTools":return fk(t,e,r);case"viewLogs":return hk(t,e,r);case"selectTarget":return mk(t,e,r);default:return lk(t,e,r)}}function kH(t,e,r,n){let o=r.bold(r.fg("accent",PH(t,e))),s=xH(t,e,r,n);return[o,"",...s,"",r.fg("muted",CH(t.step))]}function EH(t,e,r,n){let o=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),s=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[o,"",s]}function TH(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function AH(t,e,r){let n=i=>i.flatMap(a=>SH(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 s=[o,"",e.fg("text","Opening your browser to sign in\u2026")];return t.url&&s.push(e.fg("accent",t.url)),t.instructions&&s.push(e.fg("muted",t.instructions)),s.push("",`${e.fg("text","Paste code or redirect URL: ")}${e.fg("accent",t.input)}`,"",e.fg("muted","Enter Submit \xB7 Esc Cancel")),n(s)}function $H(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function yk(t){return t?"Disabling":"Enabling"}function vk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var $h=class{state=ck();config;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;authInPaste=!1;authPasteBuffer="";authDone;component;constructor(e){this.config=e,this.component={render:r=>this.render(r),handleInput:r=>this.dispatch(r),invalidate:()=>{}}}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){return this.busy?EH(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme):this.authenticating?AH({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,e):kH(this.state,this.config.snapshots(),this.config.theme,e)}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots(),n=uk(e,this.config.keybindings),o=dk(this.state,n,{snapshots:r,windowSize:Eo});this.state=o.state,o.effect&&this.runEffect(o.effect),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,yk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(vk(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,yk(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(vk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new _H(()=>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=TH();let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>this.manualCode?this.manualCode.promise:Promise.resolve(null),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();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();n&&this.manualCode?.resolve(n);return}if(vH(e,yH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),this.authInPaste){this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n!==-1){let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}return}$H(e)&&(this.state={...this.state,authInput:this.state.authInput+e},this.config.tui.requestRender())}exitAuth(){this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode=void 0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function _k(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new $h({tui:s,theme:i,keybindings:a,snapshots:()=>RH(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Ih=["list"];function Sk(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 MH(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var IH="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function Mh(t,e){return e.length>0?[t,...e]:null}function OH(t){let e=[],r=[];for(let o of t.servers.values())(fr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[Mh("MCP Server Status:",e.map(Sk)),Mh("Plugin MCP servers:",r.map(Sk)),Mh("Diagnostics:",t.diagnostics.map(MH))];return t.servers.size===0&&n.unshift([IH]),n.filter(o=>o!==null).map(o=>o.join(`
147
147
  `)).join(`
148
148
 
149
- `)}function AH(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Ah.includes(e))return e}async function $H(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=_i([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function yk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Ah.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 mk(n,e,i=>_i([i],e,t),{classify:i=>Vx({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>Wx({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Kx({server:i,disable:a,scope:c,state:e,pi:t,cwd:n.cwd,agentDir:n.agentDir}),notify:i=>n.ui.notify(i,"info")},(i,a)=>Ix({serverName:i,state:e,pi:t,controller:a}));return}let s=AH(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Ah.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(TH(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await $H(n,e,t)}})}import{logger as MH}from"@hermes/logger";var vk=MH.child({prefix:"pi-mcp"}),$h="augment:feature-flags";function IH(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 _k(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on($h,r=>{let n=IH(r);if(n===void 0){vk.warn(`${$h} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,vk.debug(`Received feature-flag snapshot via ${$h} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as OH}from"@hermes/logger";var Jc=OH.child({prefix:"pi-mcp"}),Mh="augment:mcp-attach-result";function Sk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(Mh,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){Jc.warn(`${Mh} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){Jc.debug(`${Mh}: no pending resolver for request ${o} (already timed out?)`);return}let i={...typeof n?.status=="string"?{status:n.status}:{},...typeof n?.error=="string"?{error:n.error}:{}};s(i)}))}function Yc(t,e){if(!e.mcpAttachCloudSignaled||e.mcpAttachDisabled||!e.credentials)return Promise.resolve();if(e.catalogRefreshInFlight)return e.catalogRefreshInFlight;let r=e.credentials,n=(async()=>{let o=await Cm(r);o.ok?(e.mcpCatalog=o.entries,Jc.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,Jc.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),In(e)&&Br(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as zH}from"@hermes/logger";var wi=zH.child({prefix:"pi-mcp"}),wk=300*1e3,Ih=600*1e3;function NH(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||n.auth!=="oauth")continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(Zo(o,e)||o.expiresAt>e+Ih||(wi.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Ih}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&wi.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{wi.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function bk(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{NH(t)},wk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,wi.debug(`Started background MCP OAuth refresh loop (interval ${wk}ms, buffer ${Ih}ms)`)}function Rk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,wi.debug("Stopped background MCP OAuth refresh loop"))}import{logger as JH}from"@hermes/logger";function DH(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case jo.OAUTH:return"oauth";case jo.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 LH(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Hr.CLI:return"cli";case Hr.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 Xc(t){if(t==null)return;if(t.length===0)return[];let e=t.map(LH).filter(r=>r!==void 0);return e.length===0?void 0:e}function Qc(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=DH(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},s=Tn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...An(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Pt?i.message:String(i)}}}function jH(t){let e=t.config?.auth_type;return e===jo.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function FH(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 Oh(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 UH(t,e,r){if(r!==void 0&&t.added_by===r)return Xc(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?Xc(n):[]}function qH(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let f=Oh(e,r,()=>!0);return{selected:[],filteredOutIds:f.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let f=new Set(s),h=Oh(e,r,()=>!0),m=new Set(h.map(b=>b.id)),y=h.filter(b=>f.has(b.id)),S=h.filter(b=>!f.has(b.id)).map(b=>b.id),w=s.filter(b=>!m.has(b));return{selected:y,filteredOutIds:S,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let f of e)a.has(f.id)||c.push(f.id);let u=Oh(e,r,f=>a.has(f)),d=new Set(r.map(f=>f.id)),l=[],p=[];for(let f of u){let m=!d.has(f.id)&&a.has(f.id)?UH(f,o,i):Xc(f.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(f):(c.push(f.id),f.config?.name&&p.push(f.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:p}}function HH(t){return t==null?Hr.CLOUD_AGENT:void 0}function GH(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 ZH(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Dt(t,n):Nt(t,n)}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${s}`}}}}function BH(t){let{payload:e,userIds:r,localServerNames:n,seenNames:o,workspaceRoot:s}=t;if(e.config?.disabled)return e.config.name?{kind:"retained",name:e.config.name}:{kind:"dropped"};let i=r.has(e.id)?"user":"tenant",a=Qc(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){let d=n.has(c.name)?`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`;return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:d}}}let u=ZH(c,e.id,i,s);return u.ok?(o.add(c.name),{kind:"connected",server:u.server}):{kind:"retained",name:c.name,diagnostic:u.diagnostic}}function VH(t){let e=[],r=[],n=[];for(let o of t)jH(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 WH(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=FH(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}async function eu(t){let e=t.client??new qi(t.creds),{tenant:r,user:n,diagnostics:o}=await Dm(e,HH(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=qH({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=VH(a),p=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...GH(u));let f=[],h=new Set(t.localServerNames),m=[...p.filter(w=>i.has(w.id)),...p.filter(w=>!i.has(w.id))];for(let w of m){let b=BH({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:h,workspaceRoot:t.workspaceRoot});b.kind!=="connected"&&b.diagnostic&&o.push(b.diagnostic),b.kind==="connected"?f.push(b.server):b.kind==="retained"&&d.push(b.name)}let y=WH(f);d.push(...y.droppedNames),o.push(...y.diagnostics);let S=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&S.set(w.id,w.config.name);return{servers:y.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:S}}import{logger as KH}from"@hermes/logger";var Eo=KH.child({prefix:"pi-mcp"});function Pk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Eo.warn("Embedded MCP config is missing an id; ignoring");return}let n=Qc(r,"tenant");if(!n.ok){Eo.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Dt(n.server,o):Nt(n.server,o)}catch(s){Eo.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function Ck(t,e){let r;try{r=JSON.parse(t)}catch(n){Eo.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return Pk(r,e)}function tu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Eo.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Eo.warn("Embedded MCP configs payload is not an array; ignoring");return}let n=[],o=new Map,s=!1;for(let i of r){let a=i,c=Pk(i,e);if(a&&typeof a=="object"&&a.id&&a.config?.name&&o.set(a.id,{name:a.config.name,...c?{config:c}:{}}),a?.config?.disabled){s=!0;continue}c&&n.push(c)}if(!(n.length===0&&!s))return{servers:n,allConfigsById:o}}var Ot=JH.child({prefix:"pi-mcp"});function YH(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 Wt(t){Ve({state:t.state,domain:We(t.configId),epoch:t.intentEpoch})}function XH(t){let e=new Set;for(let[r,n]of t.servers){let o=Q(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 xk(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function kk(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),Ot.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function bi(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Wt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Ot.warn(i),!o()){if(r.diagnostics.push({message:i,origin:"registry"}),!s()){r.failedAddConfigIds.add(n);return}r.dynamicallyAddedConfigIds.add(n),r.sessionRemovedConfigIds.delete(n)}}function QH(t,e){return e.flatMap(r=>qc(t,r)?[r.config]:[])}function eG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function tG(t,e){let r=eG(e);if(r){if(bi(t,r.error),r.error instanceof Rt)throw r.error;return}let n=QH(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){YH(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 Ek(t,e){try{tG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function rG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t,i=r.servers.get(e.name);if(!i)return!1;let a=Q(r,e.name,i);if(a.owner.kind==="plugin"||a.owner.kind==="vfs")return!1;if(s())return Ot.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 Ot.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 nG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await Do(t.state,t.configId),t.superseded()){Wt(t);return}if(rG(t,e)){Wt(t);return}try{if(!await qr({state:t.state,config:e,pi:t.activePi})){Wt(t);return}}catch(r){throw bi(t,r),r}Ot.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);Ek(t,r??[])}catch(r){if(bi(t,r),r instanceof Rt)throw r}}async function oG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Wt(t),Ot.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){kk(r,e),Ot.info(`Live MCP add-server: config id ${n} resolved to no new server (already connected, not opted in, or unknown id)`),s()||r.failedAddConfigIds.add(n),Wt(t);return}if(await Do(r,n),o()){Wt(t);return}try{if((await Promise.all(e.servers.map(c=>qr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Wt(t);return}}catch(a){throw bi(t,a),a}Ot.info(`Live MCP add-server: connecting ${e.servers.length} server(s) for config id ${n}`);let i=await t.connect(e.servers,r,t.activePi,t.sourceOwnership);if(o()){Wt(t);return}kk(r,e),Ek(t,i??[])}function sG(t,e){if(typeof e=="string")return Ck(e,t.workspaceRoot??process.cwd())}function Tk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Ot.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();if(!Ni({state:r,configId:i,generation:s?.attachmentGeneration}))return Ot.info(`Ignoring stale live MCP add-server command for config id ${i}`),Promise.resolve();r.sessionRemovedConfigIds.delete(i);let a=Mi({state:r,domain:We(i),forceNew:!0}),c=XH(r),u=r.currentLoad?.latestPi??e,d=r.registryGeneration;r.liveEditGenerations??=new Map;let l=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,l);let p=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,f={state:r,configId:i,activePi:u,connect:o?.connect??wt,report:o?.report??J,intentEpoch:a.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>xk(r,i)},h=sG(r,s?.embeddedConfig),m;if(h)m=nG(f,h);else{let y=r.credentials;y?m=(o?.discover??eu)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(w=>oG(f,w)).catch(w=>{if(!(w instanceof Rt)){bi(f,w);return}throw w}):(Ot.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Wt(f),m=Promise.resolve())}return Di({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>xk(r,i)})}import{logger as iG}from"@hermes/logger";var Kt=iG.child({prefix:"pi-mcp"});function $k(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function Mk(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?bt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ge(e,r),"retiring"):void 0:(be({state:e,name:r,owner:n.owner,revision:n.revision}),Ge(e,r),"released");let c=a.get(r),u=Oo({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return s&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ge(e,r),leaseRevision:u.lease.revision}}function aG(t){let{state:e,name:r,server:n,selectedIds:o,replacementOwners:s,slotReservations:i,processedNames:a}=t,c=Q(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=Mk({state:e,name:r,lease:c,host:n,isDeselected:$k({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:s});if(d===void 0)return;d!=="released"&&d!=="retiring"&&i.set(r,d);let l=Z(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&be({state:e,name:r,owner:c.owner,revision:c.revision})},p=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:p}}),p})}function cG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=Mk({state:e,name:r,lease:n,isDeselected:$k({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function uG(t,e,r){let n=e?new Set(e):void 0,o=new Map,s=[],i=new Set;for(let[a,c]of t.servers){let u=aG({state:t,name:a,server:c,selectedIds:n,replacementOwners:r,slotReservations:o,processedNames:i});u&&s.push(u)}for(let[a,c]of t.hostLeases)i.has(a)||c.owner.kind!=="registry"||c.host!==void 0||cG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function Ik(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let p=t.registryConfigNamesById.get(l);return p===void 0?[]:[p]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,p]of t.registryCredentialConfigs){let f=i.get(l);if(f===void 0&&p.id!==void 0&&n.has(p.id)&&!u.has(p.id)){i.set(l,p);continue}let h=p.id===void 0?c.has(l):a.has(p.id);f===void 0&&!h&&s.push(ct(t,l,p.id,p))}try{await Promise.all(s)}catch(l){let p=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Rt(p)}let d=new Map;for(let[l,p]of i){let f=t.registryCredentialConfigs.get(l);f&&(d.set(l,{...f}),Be(f,p)&&p.id!==void 0&&t.registryCredentialConfigsById.set(p.id,{...p}))}t.registryCredentialConfigs=d}function dG(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:p}]of t.allConfigsById)n&&!n.has(l)||u.has(p)||d.has(p)||(d.add(p),a.push(p));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function lG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return tu(n,e.workspaceRoot??process.cwd())}async function pG(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),s=[],i=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(We(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(ct(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)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 Rt(c)}}function fG(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 hG(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.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function mG(t){let e=new Set;for(let[r,n]of t.servers){let o=Q(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 gG(t){let{state:e,result:r,previousSelectedIds:n,selection:o}=t,s=new Set([...o??[],...r.servers.flatMap(i=>i.id===void 0?[]:[i.id]),...r.namesById?.keys()??[]]);return Ik(e,r.servers,n,s,o!==void 0)}async function Ok(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():Do(t,r.id)))}async function Ak(t){return await Ok(t.state,t.result),t.state.registryGeneration===t.generation&&await gG(t),t.result}function yG(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Kt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=dG(n,r,s);return Ak({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})}return o?u({configIds:r,creds:o,currentUserId:o.userId,workspaceRoot:e.workspaceRoot??process.cwd(),localServerNames:s}).then(l=>Ak({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function vG(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Kt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Kt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function _G(t){let{state:e,result:r}=t,n=r.servers.map(s=>{let i=e.sessionRegistryDisabledOverrides.get(s.name);return i===void 0?s:{...s,disabled:i}}),o=new Set([...n.map(s=>s.name),...r.retainedNames??[]]);for(let s of e.sessionRegistryDisabledOverrides.keys())o.has(s)||e.sessionRegistryDisabledOverrides.delete(s);return n}function SG(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 zh(t){let{state:e,result:r,selection:n,slotReservations:o}=t,s=new Set([...r.servers.map(i=>i.name),...r.retainedNames??[],...(n??[]).flatMap(i=>{let a=e.registryConfigNamesById.get(i);return a?[a]:[]})]);for(let[i,a]of o){if(s.has(i))continue;let c=Z(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&be({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function wG(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){zh({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),Kt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await Ok(e,r),e.registryGeneration!==o)return;let c=SG({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>qr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;vG({state:e,result:r,selection:n}),zh({state:e,result:r,selection:n,slotReservations:a});let l=_G({state:e,result:{...r,servers:u}});if(l.length===0)return;let p=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):Z(e,m.name))?.owner.kind==="local")return Kt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let w=a.get(m.name)?.configRevision;if(w===void 0)return!0;let b=e.configDesiredRevisions.get(m.name);return b!==w?(Kt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${w} to ${b} by a concurrent operation`),!1):!0});if(p.length===0)return;Kt.info(`Registry discovery: connecting ${p.length} server(s)`);let h=(await s(p,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error))}async function bG(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Kt.warn(i),e.registryGeneration===n&&(await Ik(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function RG(t,e){for(let r of e??[]){let n=We(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Ve({state:t,domain:n,epoch:o?.epoch})}}async function PG(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await wG({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),zh({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 Rt)throw RG(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 bG({...t.resultArgs,error:r})}}function zk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??eu,i=o?.connect??wt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Kt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&nm(r,new Set(a.configIds.map(We)));let c=lG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Kt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let S of a.configIds??[])Ve({state:r,domain:We(S)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=pG({state:r,previousSelectedIds:d,configIds:a.configIds}),p=fG({parsedEmbedded:c,configIds:a.configIds}),f=++r.registryGeneration,h=Promise.all([uG(r,a.configIds,p),l]).then(([S])=>S);hG(r);let m=a.configIds?[...a.configIds]:void 0,y=yG({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:mG(r),previousSelectedIds:d,selection:m,generation:f,discover:s});return y?PG({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:f,connect:i,pi:e}}):Promise.resolve()}import{logger as CG}from"@hermes/logger";var Lr=CG.child({prefix:"pi-mcp"});function xG(t,e){Ve({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 kG(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function jk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function EG(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function Nk(t){let{state:e,configId:r,fence:n,operation:o,retryPreviousFailureOnly:s=!1}=t,i=e.missingHostRemovals.get(r),a=(async()=>{let c=!1;if(i)try{await i.promise}catch{c=!0}s&&!c||await o()})().finally(()=>{e.missingHostRemovals.get(r)?.promise===a&&(EG({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 Fk(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){let o=Q(t,r,n);if(n.config.id===e&&o.owner.kind==="registry"&&o.host===n)return r}}function Uk(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function TG(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?En(n):void 0;if(s===void 0){Ge(e,r);return}let a=s.host===void 0&&s.owner.kind==="registry"&&i?.kind==="registry"&&s.owner.identity===i.identity,c=o?.incumbent.owner.kind==="registry"&&i?.kind==="registry"&&o.incumbent.owner.identity===i.identity;if(!a&&!c)return;(o?.settled&&s.retirement===o?Bh({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):be({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(Uk(e,r),Ge(e,r))}async function Nh(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Lr.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=En(i),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,p=e.configDesiredRevisions.get(a),f=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ge(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=Z(e,a)?.retirement===d?d:void 0,S=y?.result;if(d&&S?.status==="failed"&&S.transportDisposed!==!0){let w=S.error instanceof Error?S.error:new Error(String(S.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Lr.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await No(e,a,r,i)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(p===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,p),f===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,f));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw Lr.warn(b),e.diagnostics.push({server:a,message:b}),w}jk({state:e,configId:r,fence:s})&&(Fk(e,r),TG({state:e,name:a,config:i,retirement:y})),Lr.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 s=`Live MCP remove-server failed to ${n} ${r}: ${o.reason instanceof Error?o.reason.message:String(o.reason)}`;Lr.warn(s),e.diagnostics.push({server:r,message:s})}async function AG(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(Lk({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([No(e,r,n,o.config)]);return Lk({state:e,name:r,operation:"detach",result:i}),i.status==="fulfilled"?{removed:!0,failure:void 0,transportDisposed:!0}:{removed:!1,failure:i.reason,transportDisposed:!0}}async function $G(t){let{state:e,configId:r,name:n,pi:o,report:s,sourceFence:i}=t,a=e.servers.get(n),c=a?Q(e,n,a):Z(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=Ge(e,n),p=bt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!p)return;a.beginDisposal?.(),Lr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let f=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await AG({state:e,name:n,configId:r,server:a});if(h&&jk({state:e,configId:r,fence:i})?Fk(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)),we({state:e,name:n,retirement:p,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&be({state:e,name:n,owner:c.owner,revision:c.revision})&&Uk(e,n),s(f,e),!h)throw m}function qk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Lr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Ni({state:r,configId:i,generation:s?.attachmentGeneration}))return Lr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Di({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=Dk(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,p=r.missingHostRemovals.get(i),f=p?.registryGeneration===r.registryGeneration&&p?.liveEditGeneration===r.liveEditGenerations.get(i);if(f&&l===void 0)return a(p.promise);if(f&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(Nk({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>Nh({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=xG(r,i);if(u===void 0&&d===void 0)return a(Nh({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=kG({state:r,configId:i,liveEditGeneration:h});return a(Nk({state:r,configId:i,fence:m,operation:()=>{let y=Dk(r,i);return y===void 0?Nh({state:r,configId:i,pi:e,report:c,sourceFence:m}):$G({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as MG}from"@hermes/logger";var Ri=MG.child({prefix:"pi-mcp"}),Hk=3,Gk=6e4,IG=1e3,OG=8e3;function Dh(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Dr,i=o?.now??Date.now,a=o?.sleep??Vr,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return Ri.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return Ri.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),p=r.mcpRestartState.get(d),f=p&&l-p.lastRestart<Gk?p.count+1:1,h=r.currentLoad?.latestPi??e;if(f>Hk)return Ri.warn(`augment:mcp-restart-server: ${d} exceeded ${Hk} restarts within ${Gk}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:f,lastRestart:l});let m=Math.min(IG*2**(f-1),OG);return(f>1?a(m):Promise.resolve()).then(()=>(Ri.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(S=>{let w=`Live MCP restart-server failed for ${d}: ${S instanceof Error?S.message:String(S)}`;Ri.warn(w),r.diagnostics.push({server:d,message:w})}).then(()=>{c(h,r)})}import{logger as zG}from"@hermes/logger";var Pi=zG.child({prefix:"pi-mcp"}),NG=/^\d+$/,Lh=1,Zk="AUGMENT_ACTIVE_SPACE_ID",DG="augment-mcp-access-token-";function ru(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function Bk(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 nu=class{apiKey;apiUrl;userAgent;fetchImpl;timeoutMs;cache=new Map;inflight=new Map;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??xu}lookupBody(e){let r={name:e};return!e.startsWith(DG)&&Object.hasOwn(process.env,Zk)&&(r.active_space_id=process.env[Zk]??""),r}getSecret(e){let r=ru(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 Wr(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=ru(e),i=(await this._callUpsert({name:o,value:r,scope:Lh,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!NG.test(i))throw new Error("user secret upsert response contained an invalid persisted version");let a=BigInt(i).toString();return this.cache.set(o,r),Pi.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await Wr(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=ru(e);this.cache.delete(r),await this._callDelete({name:r,scope:Lh}),Pi.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Yt?`${o.slice(0,Yt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Yt?`${o.slice(0,Yt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=ru(e);try{let n=await Wr(()=>this._callApi("/mcp-secrets/get",this.lookupBody(r))),o=n.secret?.value,s=n.secret?.version;if(o===void 0||s===void 0)return;let i=n.secret?.scope===Lh||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:Bk(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof dt&&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&&Pi.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await Wr(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:Bk(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof dt&&o.statusCode===404)return Pi.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Pi.debug(`Secret "${n}" lookup via ${e} failed: ${s}`),{errored:!0}}}async _callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let s=await o.text().catch(()=>""),i=s.length>Yt?`${s.slice(0,Yt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}};function jh(t){return{latestPi:t}}import{randomUUID as LG}from"node:crypto";import{setToolSource as jG}from"@augmentcode/auggie-v2";import{logger as FG}from"@hermes/logger";import{Type as UG}from"@sinclair/typebox";var Wk=FG.child({prefix:"pi-mcp"}),ou="attach-mcp-server",qG="augment:mcp-attach-request",HG=15e3,GG={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 ZG(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[];return o.find(s=>s.id===r)??o.find(s=>s.name.toLowerCase()===n)}function BG(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},HG);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function Vk(t){let e=Fo(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function VG(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return Re(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return Re(`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.`)}function WG(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return Re(`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,Re("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 Re(`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 Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return Re(`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 Re(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return Re(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.`);case"NO_ACTIVE_VM":return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return Re(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function KG(t,e,r){if(e.mcpAttachDisabled)return Re("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(`${ou} requires a string "config_id" parameter. ${Vk(e)}`);let o=ZG(e,n);if(!o)return Re(`No MCP server matching "${n}" is available to attach. ${Vk(e)}`);let s=VG({entry:o,state:e});if(s!==void 0)return s;if(Pu(e,o))return Re(`MCP server "${o.name}" is already attached to this session. Use find-tool to discover its tools.`);if(o.state!=="available"&&o.state!=="opt_in_required")return Re(`MCP server "${o.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let i=LG();Wk.info(`attach-mcp-server: requesting attach of "${o.name}" (config=${o.id} request=${i})`);let a=BG(e,i);t.events.emit(qG,{configId:o.id,requestId:i});let c=await a;return WG({entry:o,result:c,state:e})}function Fh(t,e){let r={name:ou,label:ou,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:UG.Unsafe(GG),execute:(n,o)=>KG(t,e,o)};jG(ou,"mcp"),t.registerTool(r),gr(r),Wk.debug("Registered attach-mcp-server tool")}import{logger as JG}from"@hermes/logger";var To=JG.child({prefix:"pi-mcp"});async function YG(t){let e=[];for(let[r,n]of t.servers){let o=Q(t,r,n);if(o.owner.kind!=="vfs"||o.host!==n)continue;let s=bt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ge(t,r);let i=ct(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),be({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function XG(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),To.warn(r.message))}function QG(t){let{state:e,name:r,stored:n,higherPriorityNames:o,blockedNames:s,workspaceRoot:i}=t;if(o.has(r)){s.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"}),To.warn(a);return}try{let a=An(r,n);return{...a.type==="stdio"?Dt(a,i):Nt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Pt?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"}),To.warn(c);return}}function eZ(t,e){let r=new Set;for(let[i,a]of t.servers){let c=Q(t,i,a);c.owner.kind!=="vfs"&&c.host===a&&r.add(i)}for(let[i,a]of t.hostLeases)a.owner.kind!=="vfs"&&r.add(i);let n=t.workspaceRoot??process.cwd(),o=[],s=new Set;for(let[i,a]of Object.entries(e.servers??{})){if(a===null)continue;let c=QG({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function tZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function Kk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??wt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return To.warn("augment:mcp-vfs-servers payload is not an object"),Promise.resolve();let a=typeof i.signature=="string"?i.signature:void 0;if(a!==void 0&&a===r.lastSuccessfulVfsMcpSignature&&tZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=YG(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;XG(r,i.diagnostics);let{servers:l,blockedNames:p}=eZ(r,i);return u=p,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=p),!1):(To.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(f=>{let h=f?.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=>(f??[]).some(y=>y.config===m&&qc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let p=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;To.warn(p),r.vfsGeneration===c&&r.diagnostics.push({message:p,origin:"vfs"})})}var ot=rZ.child({prefix:"pi-mcp"}),eE="augment:mcp-oauth-credentials",Jk="augment:mcp-header-secrets",Yk="augment:mcp-header-secret-failures",Xk="augment:credentials",nZ="augment:mcp-config-ids",Qk="augment:mcp-configs",oZ="augment:mcp-vfs-servers",sZ="augment:mcp-add-server",iZ="augment:mcp-restart-server",aZ="augment:mcp-remove-server";function cZ(t){if(!t.secretsClient||t.tokens instanceof Go)return;let e=t.tokens;t.tokens=new Go(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),ot.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function uZ(t){if(!t||typeof t!="object"){ot.warn(`${eE} 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 dZ(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){vx({pi:e,state:r,update:{configId:n.targetConfigId,credentials:n.credentials}});return}Object.keys(n.credentials).length>0&&(r.shouldProactivelyRefreshTokens=!1);let o=new Set;for(let i of Object.keys(n.credentials)){let a=r.servers.get(i)?.getRefreshInFlight?.();a&&o.add(a)}let s=()=>{let i=yZ({pi:e,state:r,credentials:n.credentials,suppressReconnect:n.suppressReconnect}),{restart:a}=n;if(!(typeof a?.serverName!="string"||typeof a.requestId!="string")){if(i.applied.includes(a.serverName)){Dh({pi:e,state:r,data:{serverName:a.serverName,requestId:a.requestId}});return}if(Object.hasOwn(n.credentials,a.serverName)&&!i.equal.includes(a.serverName)){let c="MCP restart credential was rejected; keeping the existing host";ot.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function lZ(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(eE,r=>{let n=uZ(r);n&&dZ({pi:t,state:e,payload:n})}))}function pZ(t){let{state:e,name:r,revision:n}=t,o=ut(n.domain);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id;return s===void 0&&i===void 0?a?.config.registrySource!==void 0&&c!==void 0&&We(c)===o:s?.kind==="domain"&&s.domain===o||i===n.domain}function fZ(t){let{state:e,domain:r}=t,n=ut(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function hZ(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=xn(i);if(a===void 0){o[s]=i;continue}if(fZ({state:e,domain:a.domain})){om({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(pZ({state:e,name:s,revision:a})){o[s]=i;continue}rm({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function mZ(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=xn(s);i===void 0?(e.credentialRevisions.delete(o),e.hostedCredentialOwnership.delete(o)):(e.credentialRevisions.set(o,i),e.hostedCredentialOwnership.set(o,{...i,accessTokenOnly:s?.refresh_token===void 0})),e.statusFailureCategories.delete(o),e.authRefreshNeededReportKeys.delete(o),e.tokens.clearAuthRequired(o)}}function gZ(t){let{pi:e,state:r,seeded:n,suppressReconnect:o}=t;if(o)return;let s=r.currentLoad?.latestPi??e;for(let i of n){let a=r.servers.get(i),c=r.expectedCredentialDomains.get(i),u=Z(r,i),d=c?.kind!=="domain"||u?.owner.kind==="registry"&&u.owner.identity===c.domain;a&&d&&a.config.type!=="stdio"&&a.config.auth==="oauth"&&Dr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),ze(r)})}}function yZ(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 s=hZ({state:r,credentials:n,suppressReconnect:o}),i=Hc(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return mZ({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(ot.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),gZ({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function vZ(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(Jk,r=>{if(!r||typeof r!="object"||Array.isArray(r)){ot.warn(`${Jk} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);Fg(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(Yk,r=>{if(!r||typeof r!="object"||Array.isArray(r)){ot.warn(`${Yk} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);qg(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}))}function _Z(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(Xk,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){ot.warn(`${Xk} 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 nu(e.credentials),cZ(e)}),t.events.on(nZ,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,Fh(e.currentLoad?.latestPi??t,e)),zk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{ot.warn(`Registry config apply did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),J(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Yc(n,e)})}))}function SZ(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(Qk,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){ot.warn(`${Qk} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=tu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&qr({state:e,config:i,pi:t}).catch(a=>{ot.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}ot.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function wZ(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(oZ,r=>{Kk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),ze(e)})}))}function bZ(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(sZ,r=>{Tk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{ot.warn(`Live MCP add-server did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),J(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Yc(n,e)})}))}function RZ(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(iZ,r=>{Dh({pi:t,state:e,data:r}).then(()=>{ze(e)})}))}function PZ(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(aZ,r=>{qk({pi:t,state:e,data:r}).catch(n=>{ot.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Yc(n,e)})}))}function JY(t){return jg(t)}var tE=t=>{let e=re();e.currentLoad=jh(t);let r=!1;yk(t,e),lZ(t,e),vZ(t,e),_Z(t,e),SZ(t,e),wZ(t,e),bZ(t,e),RZ(t,e),PZ(t,e),_k(t,e),Sk(t,e),e.mcpAttachCloudSignaled&&Fh(t,e),t.on("session_start",(n,o)=>{e.currentLoad=jh(t),e.workspaceRoot=o.cwd;let s=o.mcpConfigOverride;if(e.mcpConfigOverride=Array.isArray(s)&&s.length>0?s:void 0,e.ui=o.ui,bk(e),e.connectStarted)In(e)?(Br(t),Fi(t)):wm(t,e),ze(e);else{e.connectStarted=!0,Lo()&&Br(t);let{servers:i,diagnostics:a}=$n(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),ot.warn(c.message);wt(i,e,t).then(()=>mx(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),ze(e)})}r||(r=!0,t.events.emit(Ux,Bx(t,e)))}),t.on("session_shutdown",()=>{Rk(e)})};ym(tE);var YY=tE;export{YY as default,JY as setMcpErrorReporter};
149
+ `)}function zH(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Ih.includes(e))return e}async function NH(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=wi([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function wk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Ih.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 _k(n,e,i=>wi([i],e,t),{classify:i=>Yx({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>Xx({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Qx({server:i,disable:a,scope:c,state:e,pi:t,cwd:n.cwd,agentDir:n.agentDir}),notify:i=>n.ui.notify(i,"info")},(i,a)=>Dx({serverName:i,state:e,pi:t,controller:a}));return}let s=zH(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Ih.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(OH(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await NH(n,e,t)}})}import{logger as DH}from"@hermes/logger";var bk=DH.child({prefix:"pi-mcp"}),Oh="augment:feature-flags";function LH(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 Rk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Oh,r=>{let n=LH(r);if(n===void 0){bk.warn(`${Oh} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,bk.debug(`Received feature-flag snapshot via ${Oh} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as jH}from"@hermes/logger";var Xc=jH.child({prefix:"pi-mcp"}),zh="augment:mcp-attach-result";function Pk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(zh,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){Xc.warn(`${zh} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){Xc.debug(`${zh}: no pending resolver for request ${o} (already timed out?)`);return}let i={...typeof n?.status=="string"?{status:n.status}:{},...typeof n?.error=="string"?{error:n.error}:{}};s(i)}))}function Qc(t,e){if(!e.mcpAttachCloudSignaled||e.mcpAttachDisabled||!e.credentials)return Promise.resolve();if(e.catalogRefreshInFlight)return e.catalogRefreshInFlight;let r=e.credentials,n=(async()=>{let o=await Tm(r);o.ok?(e.mcpCatalog=o.entries,Xc.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,Xc.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),zn(e)&&Vr(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as FH}from"@hermes/logger";var Ri=FH.child({prefix:"pi-mcp"}),Ck=300*1e3,Nh=600*1e3;function UH(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||n.auth!=="oauth")continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(Vo(o,e)||o.expiresAt>e+Nh||(Ri.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Nh}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&Ri.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{Ri.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function xk(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{UH(t)},Ck);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,Ri.debug(`Started background MCP OAuth refresh loop (interval ${Ck}ms, buffer ${Nh}ms)`)}function kk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,Ri.debug("Stopped background MCP OAuth refresh loop"))}import{logger as tG}from"@hermes/logger";function qH(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Uo.OAUTH:return"oauth";case Uo.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 HH(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Gr.CLI:return"cli";case Gr.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 eu(t){if(t==null)return;if(t.length===0)return[];let e=t.map(HH).filter(r=>r!==void 0);return e.length===0?void 0:e}function tu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=qH(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},s=$n(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Mn(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Pt?i.message:String(i)}}}function GH(t){let e=t.config?.auth_type;return e===Uo.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function ZH(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 Dh(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 BH(t,e,r){if(r!==void 0&&t.added_by===r)return eu(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?eu(n):[]}function VH(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let f=Dh(e,r,()=>!0);return{selected:[],filteredOutIds:f.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let f=new Set(s),h=Dh(e,r,()=>!0),m=new Set(h.map(b=>b.id)),y=h.filter(b=>f.has(b.id)),S=h.filter(b=>!f.has(b.id)).map(b=>b.id),w=s.filter(b=>!m.has(b));return{selected:y,filteredOutIds:S,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let f of e)a.has(f.id)||c.push(f.id);let u=Dh(e,r,f=>a.has(f)),d=new Set(r.map(f=>f.id)),l=[],p=[];for(let f of u){let m=!d.has(f.id)&&a.has(f.id)?BH(f,o,i):eu(f.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(f):(c.push(f.id),f.config?.name&&p.push(f.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:p}}function WH(t){return t==null?Gr.CLOUD_AGENT:void 0}function KH(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 JH(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Dt(t,n):Nt(t,n)}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${s}`}}}}function YH(t){let{payload:e,userIds:r,localServerNames:n,seenNames:o,workspaceRoot:s}=t;if(e.config?.disabled)return e.config.name?{kind:"retained",name:e.config.name}:{kind:"dropped"};let i=r.has(e.id)?"user":"tenant",a=tu(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){let d=n.has(c.name)?`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`;return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:d}}}let u=JH(c,e.id,i,s);return u.ok?(o.add(c.name),{kind:"connected",server:u.server}):{kind:"retained",name:c.name,diagnostic:u.diagnostic}}function XH(t){let e=[],r=[],n=[];for(let o of t)GH(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 QH(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=ZH(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}async function ru(t){let e=t.client??new Gi(t.creds),{tenant:r,user:n,diagnostics:o}=await Um(e,WH(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=VH({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=XH(a),p=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...KH(u));let f=[],h=new Set(t.localServerNames),m=[...p.filter(w=>i.has(w.id)),...p.filter(w=>!i.has(w.id))];for(let w of m){let b=YH({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:h,workspaceRoot:t.workspaceRoot});b.kind!=="connected"&&b.diagnostic&&o.push(b.diagnostic),b.kind==="connected"?f.push(b.server):b.kind==="retained"&&d.push(b.name)}let y=QH(f);d.push(...y.droppedNames),o.push(...y.diagnostics);let S=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&S.set(w.id,w.config.name);return{servers:y.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:S}}import{logger as eG}from"@hermes/logger";var Ao=eG.child({prefix:"pi-mcp"});function Ek(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Ao.warn("Embedded MCP config is missing an id; ignoring");return}let n=tu(r,"tenant");if(!n.ok){Ao.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Dt(n.server,o):Nt(n.server,o)}catch(s){Ao.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function Tk(t,e){let r;try{r=JSON.parse(t)}catch(n){Ao.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return Ek(r,e)}function nu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Ao.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Ao.warn("Embedded MCP configs payload is not an array; ignoring");return}let n=[],o=new Map,s=!1;for(let i of r){let a=i,c=Ek(i,e);if(a&&typeof a=="object"&&a.id&&a.config?.name&&o.set(a.id,{name:a.config.name,...c?{config:c}:{}}),a?.config?.disabled){s=!0;continue}c&&n.push(c)}if(!(n.length===0&&!s))return{servers:n,allConfigsById:o}}var Ot=tG.child({prefix:"pi-mcp"});function rG(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 Wt(t){Ve({state:t.state,domain:st(t.configId),epoch:t.intentEpoch})}function nG(t){let e=new Set;for(let[r,n]of t.servers){let o=Q(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 Ak(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function $k(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),Ot.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function Pi(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Wt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Ot.warn(i),!o()){if(r.diagnostics.push({message:i,origin:"registry"}),!s()){r.failedAddConfigIds.add(n);return}r.dynamicallyAddedConfigIds.add(n),r.sessionRemovedConfigIds.delete(n)}}function oG(t,e){return e.flatMap(r=>Gc(t,r)?[r.config]:[])}function sG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function iG(t,e){let r=sG(e);if(r){if(Pi(t,r.error),r.error instanceof Rt)throw r.error;return}let n=oG(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){rG(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 Mk(t,e){try{iG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function aG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t,i=r.servers.get(e.name);if(!i)return!1;let a=Q(r,e.name,i);if(a.owner.kind==="plugin"||a.owner.kind==="vfs")return!1;if(s())return Ot.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 Ot.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 cG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await jo(t.state,t.configId),t.superseded()){Wt(t);return}if(aG(t,e)){Wt(t);return}try{if(!await Hr({state:t.state,config:e,pi:t.activePi})){Wt(t);return}}catch(r){throw Pi(t,r),r}Ot.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);Mk(t,r??[])}catch(r){if(Pi(t,r),r instanceof Rt)throw r}}async function uG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Wt(t),Ot.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){$k(r,e),Ot.info(`Live MCP add-server: config id ${n} resolved to no new server (already connected, not opted in, or unknown id)`),s()||r.failedAddConfigIds.add(n),Wt(t);return}if(await jo(r,n),o()){Wt(t);return}try{if((await Promise.all(e.servers.map(c=>Hr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Wt(t);return}}catch(a){throw Pi(t,a),a}Ot.info(`Live MCP add-server: connecting ${e.servers.length} server(s) for config id ${n}`);let i=await t.connect(e.servers,r,t.activePi,t.sourceOwnership);if(o()){Wt(t);return}$k(r,e),Mk(t,i??[])}function dG(t,e){if(typeof e=="string")return Tk(e,t.workspaceRoot??process.cwd())}function Ik(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Ot.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();if(!Li({state:r,configId:i,generation:s?.attachmentGeneration}))return Ot.info(`Ignoring stale live MCP add-server command for config id ${i}`),Promise.resolve();r.sessionRemovedConfigIds.delete(i);let a=Oi({state:r,domain:st(i),forceNew:!0}),c=nG(r),u=r.currentLoad?.latestPi??e,d=r.registryGeneration;r.liveEditGenerations??=new Map;let l=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,l);let p=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,f={state:r,configId:i,activePi:u,connect:o?.connect??wt,report:o?.report??J,intentEpoch:a.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>Ak(r,i)},h=dG(r,s?.embeddedConfig),m;if(h)m=cG(f,h);else{let y=r.credentials;y?m=(o?.discover??ru)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(w=>uG(f,w)).catch(w=>{if(!(w instanceof Rt)){Pi(f,w);return}throw w}):(Ot.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Wt(f),m=Promise.resolve())}return ji({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>Ak(r,i)})}import{logger as lG}from"@hermes/logger";var Kt=lG.child({prefix:"pi-mcp"});function zk(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function Nk(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?bt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ge(e,r),"retiring"):void 0:(be({state:e,name:r,owner:n.owner,revision:n.revision}),Ge(e,r),"released");let c=a.get(r),u=No({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return s&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ge(e,r),leaseRevision:u.lease.revision}}function pG(t){let{state:e,name:r,server:n,selectedIds:o,replacementOwners:s,slotReservations:i,processedNames:a}=t,c=Q(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=Nk({state:e,name:r,lease:c,host:n,isDeselected:zk({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:s});if(d===void 0)return;d!=="released"&&d!=="retiring"&&i.set(r,d);let l=Z(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&be({state:e,name:r,owner:c.owner,revision:c.revision})},p=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:p}}),p})}function fG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=Nk({state:e,name:r,lease:n,isDeselected:zk({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function hG(t,e,r){let n=e?new Set(e):void 0,o=new Map,s=[],i=new Set;for(let[a,c]of t.servers){let u=pG({state:t,name:a,server:c,selectedIds:n,replacementOwners:r,slotReservations:o,processedNames:i});u&&s.push(u)}for(let[a,c]of t.hostLeases)i.has(a)||c.owner.kind!=="registry"||c.host!==void 0||fG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function Dk(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let p=t.registryConfigNamesById.get(l);return p===void 0?[]:[p]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,p]of t.registryCredentialConfigs){let f=i.get(l);if(f===void 0&&p.id!==void 0&&n.has(p.id)&&!u.has(p.id)){i.set(l,p);continue}let h=p.id===void 0?c.has(l):a.has(p.id);f===void 0&&!h&&s.push(ut(t,l,p.id,p))}try{await Promise.all(s)}catch(l){let p=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Rt(p)}let d=new Map;for(let[l,p]of i){let f=t.registryCredentialConfigs.get(l);f&&(d.set(l,{...f}),Be(f,p)&&p.id!==void 0&&t.registryCredentialConfigsById.set(p.id,{...p}))}t.registryCredentialConfigs=d}function mG(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:p}]of t.allConfigsById)n&&!n.has(l)||u.has(p)||d.has(p)||(d.add(p),a.push(p));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function gG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return nu(n,e.workspaceRoot??process.cwd())}async function yG(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),s=[],i=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(st(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(ut(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)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 Rt(c)}}function vG(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 _G(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.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function SG(t){let e=new Set;for(let[r,n]of t.servers){let o=Q(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 wG(t){let{state:e,result:r,previousSelectedIds:n,selection:o}=t,s=new Set([...o??[],...r.servers.flatMap(i=>i.id===void 0?[]:[i.id]),...r.namesById?.keys()??[]]);return Dk(e,r.servers,n,s,o!==void 0)}async function Lk(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():jo(t,r.id)))}async function Ok(t){return await Lk(t.state,t.result),t.state.registryGeneration===t.generation&&await wG(t),t.result}function bG(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Kt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=mG(n,r,s);return Ok({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})}return o?u({configIds:r,creds:o,currentUserId:o.userId,workspaceRoot:e.workspaceRoot??process.cwd(),localServerNames:s}).then(l=>Ok({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function RG(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Kt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Kt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function PG(t){let{state:e,result:r}=t,n=r.servers.map(s=>{let i=e.sessionRegistryDisabledOverrides.get(s.name);return i===void 0?s:{...s,disabled:i}}),o=new Set([...n.map(s=>s.name),...r.retainedNames??[]]);for(let s of e.sessionRegistryDisabledOverrides.keys())o.has(s)||e.sessionRegistryDisabledOverrides.delete(s);return n}function CG(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 Lh(t){let{state:e,result:r,selection:n,slotReservations:o}=t,s=new Set([...r.servers.map(i=>i.name),...r.retainedNames??[],...(n??[]).flatMap(i=>{let a=e.registryConfigNamesById.get(i);return a?[a]:[]})]);for(let[i,a]of o){if(s.has(i))continue;let c=Z(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&be({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function xG(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){Lh({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),Kt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await Lk(e,r),e.registryGeneration!==o)return;let c=CG({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>Hr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;RG({state:e,result:r,selection:n}),Lh({state:e,result:r,selection:n,slotReservations:a});let l=PG({state:e,result:{...r,servers:u}});if(l.length===0)return;let p=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):Z(e,m.name))?.owner.kind==="local")return Kt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let w=a.get(m.name)?.configRevision;if(w===void 0)return!0;let b=e.configDesiredRevisions.get(m.name);return b!==w?(Kt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${w} to ${b} by a concurrent operation`),!1):!0});if(p.length===0)return;Kt.info(`Registry discovery: connecting ${p.length} server(s)`);let h=(await s(p,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error))}async function kG(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Kt.warn(i),e.registryGeneration===n&&(await Dk(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function EG(t,e){for(let r of e??[]){let n=st(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Ve({state:t,domain:n,epoch:o?.epoch})}}async function TG(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await xG({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),Lh({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 Rt)throw EG(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 kG({...t.resultArgs,error:r})}}function jk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??ru,i=o?.connect??wt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Kt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&am(r,new Set(a.configIds.map(st)));let c=gG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Kt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let S of a.configIds??[])Ve({state:r,domain:st(S)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=yG({state:r,previousSelectedIds:d,configIds:a.configIds}),p=vG({parsedEmbedded:c,configIds:a.configIds}),f=++r.registryGeneration,h=Promise.all([hG(r,a.configIds,p),l]).then(([S])=>S);_G(r);let m=a.configIds?[...a.configIds]:void 0,y=bG({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:SG(r),previousSelectedIds:d,selection:m,generation:f,discover:s});return y?TG({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:f,connect:i,pi:e}}):Promise.resolve()}import{logger as AG}from"@hermes/logger";var jr=AG.child({prefix:"pi-mcp"});function $G(t,e){Ve({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 MG(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function Hk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function IG(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function Fk(t){let{state:e,configId:r,fence:n,operation:o,retryPreviousFailureOnly:s=!1}=t,i=e.missingHostRemovals.get(r),a=(async()=>{let c=!1;if(i)try{await i.promise}catch{c=!0}s&&!c||await o()})().finally(()=>{e.missingHostRemovals.get(r)?.promise===a&&(IG({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 Gk(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function Uk(t,e){for(let[r,n]of t.servers){let o=Q(t,r,n);if(n.config.id===e&&o.owner.kind==="registry"&&o.host===n)return r}}function Zk(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function OG(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?Tn(n):void 0;if(s===void 0){Ge(e,r);return}let a=s.host===void 0&&s.owner.kind==="registry"&&i?.kind==="registry"&&s.owner.identity===i.identity,c=o?.incumbent.owner.kind==="registry"&&i?.kind==="registry"&&o.incumbent.owner.identity===i.identity;if(!a&&!c)return;(o?.settled&&s.retirement===o?Kh({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):be({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(Zk(e,r),Ge(e,r))}async function jh(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw jr.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=Tn(i),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,p=e.configDesiredRevisions.get(a),f=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ge(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=Z(e,a)?.retirement===d?d:void 0,S=y?.result;if(d&&S?.status==="failed"&&S.transportDisposed!==!0){let w=S.error instanceof Error?S.error:new Error(String(S.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw jr.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await Lo(e,a,r,i)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(p===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,p),f===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,f));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw jr.warn(b),e.diagnostics.push({server:a,message:b}),w}Hk({state:e,configId:r,fence:s})&&(Gk(e,r),OG({state:e,name:a,config:i,retirement:y})),jr.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 qk(t){let{state:e,name:r,operation:n,result:o}=t;if(o.status!=="rejected")return;let s=`Live MCP remove-server failed to ${n} ${r}: ${o.reason instanceof Error?o.reason.message:String(o.reason)}`;jr.warn(s),e.diagnostics.push({server:r,message:s})}async function zG(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(qk({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Lo(e,r,n,o.config)]);return qk({state:e,name:r,operation:"detach",result:i}),i.status==="fulfilled"?{removed:!0,failure:void 0,transportDisposed:!0}:{removed:!1,failure:i.reason,transportDisposed:!0}}async function NG(t){let{state:e,configId:r,name:n,pi:o,report:s,sourceFence:i}=t,a=e.servers.get(n),c=a?Q(e,n,a):Z(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=Ge(e,n),p=bt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!p)return;a.beginDisposal?.(),jr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let f=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await zG({state:e,name:n,configId:r,server:a});if(h&&Hk({state:e,configId:r,fence:i})?Gk(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)),we({state:e,name:n,retirement:p,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&be({state:e,name:n,owner:c.owner,revision:c.revision})&&Zk(e,n),s(f,e),!h)throw m}function Bk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return jr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Li({state:r,configId:i,generation:s?.attachmentGeneration}))return jr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>ji({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=Uk(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,p=r.missingHostRemovals.get(i),f=p?.registryGeneration===r.registryGeneration&&p?.liveEditGeneration===r.liveEditGenerations.get(i);if(f&&l===void 0)return a(p.promise);if(f&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(Fk({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>jh({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=$G(r,i);if(u===void 0&&d===void 0)return a(jh({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=MG({state:r,configId:i,liveEditGeneration:h});return a(Fk({state:r,configId:i,fence:m,operation:()=>{let y=Uk(r,i);return y===void 0?jh({state:r,configId:i,pi:e,report:c,sourceFence:m}):NG({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as DG}from"@hermes/logger";var Ci=DG.child({prefix:"pi-mcp"}),Vk=3,Wk=6e4,LG=1e3,jG=8e3;function Fh(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Lr,i=o?.now??Date.now,a=o?.sleep??Wr,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return Ci.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return Ci.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),p=r.mcpRestartState.get(d),f=p&&l-p.lastRestart<Wk?p.count+1:1,h=r.currentLoad?.latestPi??e;if(f>Vk)return Ci.warn(`augment:mcp-restart-server: ${d} exceeded ${Vk} restarts within ${Wk}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:f,lastRestart:l});let m=Math.min(LG*2**(f-1),jG);return(f>1?a(m):Promise.resolve()).then(()=>(Ci.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(S=>{let w=`Live MCP restart-server failed for ${d}: ${S instanceof Error?S.message:String(S)}`;Ci.warn(w),r.diagnostics.push({server:d,message:w})}).then(()=>{c(h,r)})}import{logger as FG}from"@hermes/logger";var xi=FG.child({prefix:"pi-mcp"}),UG=/^\d+$/,Uh=1,Kk="AUGMENT_ACTIVE_SPACE_ID",qG="augment-mcp-access-token-";function ou(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function Jk(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 su=class{apiKey;apiUrl;userAgent;fetchImpl;timeoutMs;cache=new Map;inflight=new Map;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??Tu}lookupBody(e){let r={name:e};return!e.startsWith(qG)&&Object.hasOwn(process.env,Kk)&&(r.active_space_id=process.env[Kk]??""),r}getSecret(e){let r=ou(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 Kr(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=ou(e),i=(await this._callUpsert({name:o,value:r,scope:Uh,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!UG.test(i))throw new Error("user secret upsert response contained an invalid persisted version");let a=BigInt(i).toString();return this.cache.set(o,r),xi.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await Kr(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=ou(e);this.cache.delete(r),await this._callDelete({name:r,scope:Uh}),xi.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Yt?`${o.slice(0,Yt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Yt?`${o.slice(0,Yt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=ou(e);try{let n=await Kr(()=>this._callApi("/mcp-secrets/get",this.lookupBody(r))),o=n.secret?.value,s=n.secret?.version;if(o===void 0||s===void 0)return;let i=n.secret?.scope===Uh||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:Jk(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof dt&&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&&xi.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await Kr(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:Jk(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof dt&&o.statusCode===404)return xi.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return xi.debug(`Secret "${n}" lookup via ${e} failed: ${s}`),{errored:!0}}}async _callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let s=await o.text().catch(()=>""),i=s.length>Yt?`${s.slice(0,Yt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}};function qh(t){return{latestPi:t}}import{randomUUID as HG}from"node:crypto";import{setToolSource as GG}from"@augmentcode/auggie-v2";import{logger as ZG}from"@hermes/logger";import{Type as BG}from"@sinclair/typebox";var Xk=ZG.child({prefix:"pi-mcp"}),iu="attach-mcp-server",VG="augment:mcp-attach-request",WG=15e3,KG={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 JG(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[];return o.find(s=>s.id===r)??o.find(s=>s.name.toLowerCase()===n)}function YG(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},WG);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function Yk(t){let e=qo(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function XG(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return Re(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return Re(`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.`)}function QG(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return Re(`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,Re("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 Re(`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 Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return Re(`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 Re(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return Re(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.`);case"NO_ACTIVE_VM":return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return Re(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function eZ(t,e,r){if(e.mcpAttachDisabled)return Re("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(`${iu} requires a string "config_id" parameter. ${Yk(e)}`);let o=JG(e,n);if(!o)return Re(`No MCP server matching "${n}" is available to attach. ${Yk(e)}`);let s=XG({entry:o,state:e});if(s!==void 0)return s;if(ku(e,o))return Re(`MCP server "${o.name}" is already attached to this session. Use find-tool to discover its tools.`);if(o.state!=="available"&&o.state!=="opt_in_required")return Re(`MCP server "${o.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let i=HG();Xk.info(`attach-mcp-server: requesting attach of "${o.name}" (config=${o.id} request=${i})`);let a=YG(e,i);t.events.emit(VG,{configId:o.id,requestId:i});let c=await a;return QG({entry:o,result:c,state:e})}function Hh(t,e){let r={name:iu,label:iu,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:BG.Unsafe(KG),execute:(n,o)=>eZ(t,e,o)};GG(iu,"mcp"),t.registerTool(r),yr(r),Xk.debug("Registered attach-mcp-server tool")}import{logger as tZ}from"@hermes/logger";var $o=tZ.child({prefix:"pi-mcp"});async function rZ(t){let e=[];for(let[r,n]of t.servers){let o=Q(t,r,n);if(o.owner.kind!=="vfs"||o.host!==n)continue;let s=bt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ge(t,r);let i=ut(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),be({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function nZ(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),$o.warn(r.message))}function oZ(t){let{state:e,name:r,stored:n,higherPriorityNames:o,blockedNames:s,workspaceRoot:i}=t;if(o.has(r)){s.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"}),$o.warn(a);return}try{let a=Mn(r,n);return{...a.type==="stdio"?Dt(a,i):Nt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Pt?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"}),$o.warn(c);return}}function sZ(t,e){let r=new Set;for(let[i,a]of t.servers){let c=Q(t,i,a);c.owner.kind!=="vfs"&&c.host===a&&r.add(i)}for(let[i,a]of t.hostLeases)a.owner.kind!=="vfs"&&r.add(i);let n=t.workspaceRoot??process.cwd(),o=[],s=new Set;for(let[i,a]of Object.entries(e.servers??{})){if(a===null)continue;let c=oZ({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function iZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function Qk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??wt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return $o.warn("augment:mcp-vfs-servers payload is not an object"),Promise.resolve();let a=typeof i.signature=="string"?i.signature:void 0;if(a!==void 0&&a===r.lastSuccessfulVfsMcpSignature&&iZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=rZ(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;nZ(r,i.diagnostics);let{servers:l,blockedNames:p}=sZ(r,i);return u=p,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=p),!1):($o.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(f=>{let h=f?.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=>(f??[]).some(y=>y.config===m&&Gc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let p=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;$o.warn(p),r.vfsGeneration===c&&r.diagnostics.push({message:p,origin:"vfs"})})}var nt=aZ.child({prefix:"pi-mcp"}),oE="augment:mcp-oauth-credentials",eE="augment:mcp-header-secrets",tE="augment:mcp-header-secret-failures",rE="augment:credentials",cZ="augment:mcp-config-ids",nE="augment:mcp-configs",uZ="augment:mcp-vfs-servers",dZ="augment:mcp-add-server",lZ="augment:mcp-restart-server",pZ="augment:mcp-remove-server";function fZ(t){if(!t.secretsClient||t.tokens instanceof Bo)return;let e=t.tokens;t.tokens=new Bo(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),nt.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function hZ(t){if(!t||typeof t!="object"){nt.warn(`${oE} 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 mZ(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){bx({pi:e,state:r,update:{configId:n.targetConfigId,credentials:n.credentials}});return}Object.keys(n.credentials).length>0&&(r.shouldProactivelyRefreshTokens=!1);let o=new Set;for(let i of Object.keys(n.credentials)){let a=r.servers.get(i)?.getRefreshInFlight?.();a&&o.add(a)}let s=()=>{let i=bZ({pi:e,state:r,credentials:n.credentials,suppressReconnect:n.suppressReconnect}),{restart:a}=n;if(!(typeof a?.serverName!="string"||typeof a.requestId!="string")){if(i.applied.includes(a.serverName)){Fh({pi:e,state:r,data:{serverName:a.serverName,requestId:a.requestId}});return}if(Object.hasOwn(n.credentials,a.serverName)&&!i.equal.includes(a.serverName)){let c="MCP restart credential was rejected; keeping the existing host";nt.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function gZ(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(oE,r=>{let n=hZ(r);n&&mZ({pi:t,state:e,payload:n})}))}function yZ(t){let{state:e,name:r,revision:n}=t,o=Ur(n);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id,u=a?.config.registrySource!==void 0&&c!==void 0&&st(c)===o;return n.ownerDomain!==void 0?s?.kind==="domain"?s.domain===o:u:s===void 0&&i===void 0?u:s?.kind==="domain"&&(s.domain===o||it(n.domain))||i===n.domain}function vZ(t){let{state:e,revision:r}=t,n=Ur(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function _Z(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=kn(i);if(a===void 0){o[s]=i;continue}if(vZ({state:e,revision:a})){cm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(yZ({state:e,name:s,revision:a})){o[s]=i;continue}im({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function SZ(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=kn(s);i===void 0?(e.credentialRevisions.delete(o),e.hostedCredentialOwnership.delete(o)):(e.credentialRevisions.set(o,i),e.hostedCredentialOwnership.set(o,{...i,accessTokenOnly:s?.refresh_token===void 0})),e.statusFailureCategories.delete(o),e.authRefreshNeededReportKeys.delete(o),e.tokens.clearAuthRequired(o)}}function wZ(t){let{pi:e,state:r,seeded:n,suppressReconnect:o}=t;if(o)return;let s=r.currentLoad?.latestPi??e;for(let i of n){let a=r.servers.get(i),c=r.expectedCredentialDomains.get(i),u=Z(r,i),d=c?.kind!=="domain"||u?.owner.kind==="registry"&&u.owner.identity===c.domain;a&&d&&a.config.type!=="stdio"&&a.config.auth==="oauth"&&Lr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),ze(r)})}}function bZ(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 s=_Z({state:r,credentials:n,suppressReconnect:o}),i=Zc(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return SZ({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(nt.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),wZ({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function RZ(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(eE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${eE} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);Gg(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(tE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${tE} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);Bg(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}))}function PZ(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(rE,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){nt.warn(`${rE} 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 su(e.credentials),fZ(e)}),t.events.on(cZ,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,Hh(e.currentLoad?.latestPi??t,e)),jk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{nt.warn(`Registry config apply did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),J(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Qc(n,e)})}))}function CZ(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(nE,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){nt.warn(`${nE} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=nu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&Hr({state:e,config:i,pi:t}).catch(a=>{nt.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}nt.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function xZ(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(uZ,r=>{Qk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),ze(e)})}))}function kZ(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(dZ,r=>{Ik({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{nt.warn(`Live MCP add-server did not retire credentials durably: ${n instanceof Error?n.message:String(n)}`),J(e.currentLoad?.latestPi??t,e)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Qc(n,e)})}))}function EZ(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(lZ,r=>{Fh({pi:t,state:e,data:r}).then(()=>{ze(e)})}))}function TZ(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(pZ,r=>{Bk({pi:t,state:e,data:r}).catch(n=>{nt.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;ze(e),Qc(n,e)})}))}function tX(t){return Hg(t)}var sE=t=>{let e=re();e.currentLoad=qh(t);let r=!1;wk(t,e),gZ(t,e),RZ(t,e),PZ(t,e),CZ(t,e),xZ(t,e),kZ(t,e),EZ(t,e),TZ(t,e),Rk(t,e),Pk(t,e),e.mcpAttachCloudSignaled&&Hh(t,e),t.on("session_start",(n,o)=>{e.currentLoad=qh(t),e.workspaceRoot=o.cwd;let s=o.mcpConfigOverride;if(e.mcpConfigOverride=Array.isArray(s)&&s.length>0?s:void 0,e.ui=o.ui,xk(e),e.connectStarted)zn(e)?(Vr(t),qi(t)):Cm(t,e),ze(e);else{e.connectStarted=!0,Fo()&&Vr(t);let{servers:i,diagnostics:a}=In(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),nt.warn(c.message);wt(i,e,t).then(()=>_x(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),ze(e)})}r||(r=!0,t.events.emit(Zx,Jx(t,e)))}),t.on("session_shutdown",()=>{kk(e)})};wm(sE);var rX=sE;export{rX as default,tX as setMcpErrorReporter};
150
150
  /*! Bundled license information:
151
151
 
152
152
  content-type/index.js: