@augmentcode/auggie 1.2.0-prerelease.202609011216 → 1.2.0-prerelease.202609020922

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,71 +1,71 @@
1
- var gE=Object.create;var uu=Object.defineProperty;var yE=Object.getOwnPropertyDescriptor;var vE=Object.getOwnPropertyNames;var _E=Object.getPrototypeOf,SE=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}},du=(t,e)=>{for(var r in e)uu(t,r,{get:e[r],enumerable:!0})},wE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vE(e))!SE.call(t,o)&&o!==r&&uu(t,o,{get:()=>e[o],enumerable:!(n=yE(e,o))||n.enumerable});return t};var Ti=(t,e,r)=>(r=t!=null?gE(_E(t)):{},wE(e||!t||!t.__esModule?uu(r,"default",{value:t,enumerable:!0}):r,t));var As=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 Es=class{};K._CodeOrName=Es;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var dn=class extends Es{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=dn;var yt=class extends Es{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 dn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=yt;K.nil=new yt("");function Uw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ql(r,e[n]),r.push(t[++n]);return new yt(r)}K._=Uw;var Ul=new yt("+");function qw(t,...e){let r=[Ts(t[0])],n=0;for(;n<e.length;)r.push(Ul),ql(r,e[n]),r.push(Ul,Ts(t[++n]));return YO(r),new yt(r)}K.str=qw;function ql(t,e){e instanceof yt?t.push(...e._items):e instanceof dn?t.push(e):t.push(ez(e))}K.addCodeArg=ql;function YO(t){let e=1;for(;e<t.length-1;){if(t[e]===Ul){let r=XO(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function XO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof dn||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 dn))return`"${t}${e.slice(1)}`}function QO(t,e){return e.emptyStr()?t:t.emptyStr()?e:qw`${t}${e}`}K.strConcat=QO;function ez(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ts(Array.isArray(t)?t.join(","):t)}function tz(t){return new yt(Ts(t))}K.stringify=tz;function Ts(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Ts;function rz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new yt(`.${t}`):Uw`[${t}]`}K.getProperty=rz;function nz(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=nz;function oz(t){return new yt(t.toString())}K.regexpCode=oz});var Zl=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=As(),Hl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ha;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ha||(Xe.UsedValueState=Ha={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Ga=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=Ga;var Za=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=Za;var sz=(0,Ye._)`\n`,Gl=class extends Ga{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sz:Ye.nil}}get(){return this._scope}name(e){return new Za(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,Ha.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 Hl(u);c.set(u,Ha.Completed)})}return s}};Xe.ValueScope=Gl});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=As(),Et=Zl(),$r=As();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return $r._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return $r.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return $r.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return $r.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return $r.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return $r.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return $r.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return $r.Name}});var Ka=Zl();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Ka.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Ka.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Ka.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Ka.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 sr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Bl=class extends sr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Et.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=io(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},Ba=class extends sr{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=io(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return Wa(e,this.rhs)}},Vl=class extends Ba{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wl=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Kl=class extends sr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jl=class extends sr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yl=class extends sr{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=io(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},$s=class extends sr{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)||(iz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>pn(e,r.names),{})}},ir=class extends $s{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xl=class extends $s{},so=class extends ir{};so.kind="else";var ln=class t extends ir{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 so(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Hw(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=io(this.condition,e,r),this}get names(){let e=super.names;return Wa(e,this.condition),this.else&&pn(e,this.else.names),e}};ln.kind="if";var fn=class extends ir{};fn.kind="for";var Ql=class extends fn{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=io(this.iteration,e,r),this}get names(){return pn(super.names,this.iteration.names)}},ef=class extends fn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Et.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=Wa(super.names,this.from);return Wa(e,this.to)}},Va=class extends fn{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=io(this.iterable,e,r),this}get names(){return pn(super.names,this.iterable.names)}},Ms=class extends ir{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)}};Ms.kind="func";var Is=class extends $s{render(e){return"return "+super.render(e)}};Is.kind="return";var tf=class extends ir{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&&pn(e,this.catch.names),this.finally&&pn(e,this.finally.names),e}},Os=class extends ir{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Os.kind="catch";var zs=class extends ir{render(e){return"finally"+super.render(e)}};zs.kind="finally";var rf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=e,this._scope=new Et.Scope({parent:e}),this._nodes=[new Xl]}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 Bl(e,s,n)),s}const(e,r,n){return this._def(Et.varKinds.const,e,r,n)}let(e,r,n){return this._def(Et.varKinds.let,e,r,n)}var(e,r,n){return this._def(Et.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ba(e,r,n))}add(e,r){return this._leafNode(new Vl(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new Yl(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 ln(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 ln(e))}else(){return this._elseNode(new so)}endIf(){return this._endBlockNode(ln,so)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ql(e),r)}forRange(e,r,n,o,s=this.opts.es5?Et.varKinds.var:Et.varKinds.let){let i=this._scope.toName(e);return this._for(new ef(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Et.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 Va("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Et.varKinds.var:Et.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 Va("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(fn)}label(e){return this._leafNode(new Wl(e))}break(e){return this._leafNode(new Kl(e))}return(e){let r=new Is;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Is)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new tf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Os(s),r(s)}return n&&(this._currNode=o.finally=new zs,this.code(n)),this._endBlockNode(Os,zs)}throw(e){return this._leafNode(new Jl(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 Ms(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Ms)}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 ln))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=rf;function pn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Wa(t,e){return e instanceof q._CodeOrName?pn(t,e.names):t}function io(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 iz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Hw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${nf(t)}`}L.not=Hw;var az=Gw(L.operators.AND);function cz(...t){return t.reduce(az)}L.and=cz;var uz=Gw(L.operators.OR);function dz(...t){return t.reduce(uz)}L.or=dz;function Gw(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${nf(e)} ${t} ${nf(r)}`}function nf(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 ie=D(),lz=As();function fz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=fz;function pz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Vw(t,e),!Ww(e,t.self.RULES.all))}j.alwaysValidSchema=pz;function Vw(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]||Yw(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=Vw;function Ww(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=Ww;function hz(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=hz;function mz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ie._)`${r}`}return(0,ie._)`${t}${e}${(0,ie.getProperty)(n)}`}j.schemaRefOrVal=mz;function gz(t){return Kw(decodeURIComponent(t))}j.unescapeFragment=gz;function yz(t){return encodeURIComponent(sf(t))}j.escapeFragment=yz;function sf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=sf;function Kw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Kw;function vz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=vz;function Zw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ie.Name?(s instanceof ie.Name?t(o,s,i):e(o,s,i),i):s instanceof ie.Name?(e(o,i,s),s):r(s,i);return a===ie.Name&&!(c instanceof ie.Name)?n(o,c):c}}j.mergeEvaluated={props:Zw({mergeNames:(t,e,r)=>t.if((0,ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ie._)`${r} || {}`).code((0,ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ie._)`${r} || {}`),af(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Jw}),items:Zw({mergeNames:(t,e,r)=>t.if((0,ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Jw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ie._)`{}`);return e!==void 0&&af(t,r,e),r}j.evaluatedPropsToName=Jw;function af(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ie._)`${e}${(0,ie.getProperty)(n)}`,!0))}j.setEvaluated=af;var Bw={};function _z(t,e){return t.scopeValue("func",{ref:e,code:Bw[e.code]||(Bw[e.code]=new lz._Code(e.code))})}j.useFunc=_z;var of;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(of||(j.Type=of={}));function Sz(t,e,r){if(t instanceof ie.Name){let n=e===of.Num;return r?n?(0,ie._)`"[" + ${t} + "]"`:(0,ie._)`"['" + ${t} + "']"`:n?(0,ie._)`"/" + ${t}`:(0,ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ie.getProperty)(t).toString():"/"+sf(t)}j.getErrorPath=Sz;function Yw(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=Yw});var ar=R(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var De=D(),wz={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};cf.default=wz});var Ns=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var G=D(),Ja=H(),Ue=ar();Le.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};Le.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 bz(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=eb(t,e,r);n??(i||a)?Xw(s,c):Qw(o,(0,G._)`[${c}]`)}Le.reportError=bz;function Rz(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=eb(t,e,r);Xw(o,a),s||i||Qw(n,Ue.default.vErrors)}Le.reportExtraError=Rz;function Pz(t,e){t.assign(Ue.default.errors,e),t.if((0,G._)`${Ue.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,G._)`${Ue.default.vErrors}.length`,e),()=>t.assign(Ue.default.vErrors,null)))}Le.resetErrorsCount=Pz;function Cz({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,Ue.default.errors,a=>{t.const(i,(0,G._)`${Ue.default.vErrors}[${a}]`),t.if((0,G._)`${i}.instancePath === undefined`,()=>t.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Ue.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))})}Le.extendErrors=Cz;function Xw(t,e){let r=t.const("err",e);t.if((0,G._)`${Ue.default.vErrors} === null`,()=>t.assign(Ue.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Ue.default.vErrors}.push(${r})`),t.code((0,G._)`${Ue.default.errors}++`)}function Qw(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 hn={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 eb(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:xz(t,e,r)}function xz(t,e,r={}){let{gen:n,it:o}=t,s=[kz(o,r),Ez(t,r)];return Tz(t,e,s),n.object(...s)}function kz({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,Ja.getErrorPath)(e,Ja.Type.Str)}`:t;return[Ue.default.instancePath,(0,G.strConcat)(Ue.default.instancePath,r)]}function Ez({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,Ja.getErrorPath)(r,Ja.Type.Str)}`),[hn.schemaPath,o]}function Tz(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([hn.keyword,o],[hn.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([hn.schema,i],[hn.parentSchema,(0,G._)`${d}${l}`],[Ue.default.data,s]),u&&n.push([hn.propertyName,u])}});var rb=R(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.boolOrEmptySchema=ao.topBoolOrEmptySchema=void 0;var Az=Ns(),$z=D(),Mz=ar(),Iz={message:"boolean schema is false"};function Oz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?tb(t,!1):typeof r=="object"&&r.$async===!0?e.return(Mz.default.data):(e.assign((0,$z._)`${n}.errors`,null),e.return(!0))}ao.topBoolOrEmptySchema=Oz;function zz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),tb(t)):r.var(e,!0)}ao.boolOrEmptySchema=zz;function tb(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,Az.reportError)(o,Iz,void 0,e)}});var uf=R(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.getRules=co.isJSONType=void 0;var Nz=["string","number","integer","boolean","null","object","array"],Dz=new Set(Nz);function Lz(t){return typeof t=="string"&&Dz.has(t)}co.isJSONType=Lz;function jz(){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:{}}}co.getRules=jz});var df=R(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.shouldUseRule=Mr.shouldUseGroup=Mr.schemaHasRulesForType=void 0;function Fz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&nb(t,n)}Mr.schemaHasRulesForType=Fz;function nb(t,e){return e.rules.some(r=>ob(t,r))}Mr.shouldUseGroup=nb;function ob(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))}Mr.shouldUseRule=ob});var Ds=R(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var Uz=uf(),qz=df(),Hz=Ns(),N=D(),sb=H(),uo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(uo||(je.DataType=uo={}));function Gz(t){let e=ib(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}je.getSchemaTypes=Gz;function ib(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Uz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=ib;function Zz(t,e){let{gen:r,data:n,opts:o}=t,s=Bz(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,qz.schemaHasRulesForType)(t,e[0]));if(i){let a=ff(e,n,o.strictNumbers,uo.Wrong);r.if(a,()=>{s.length?Vz(t,e,s):pf(t)})}return i}je.coerceAndCheckDataType=Zz;var ab=new Set(["string","number","integer","boolean","null"]);function Bz(t,e){return e?t.filter(r=>ab.has(r)||e==="array"&&r==="array"):[]}function Vz(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(ff(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(ab.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),pf(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),Wz(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 CE=Object.create;var _u=Object.defineProperty;var xE=Object.getOwnPropertyDescriptor;var kE=Object.getOwnPropertyNames;var EE=Object.getPrototypeOf,TE=Object.prototype.hasOwnProperty;var mr=(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}},Su=(t,e)=>{for(var r in e)_u(t,r,{get:e[r],enumerable:!0})},AE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kE(e))!TE.call(t,o)&&o!==r&&_u(t,o,{get:()=>e[o],enumerable:!(n=xE(e,o))||n.enumerable});return t};var zi=(t,e,r)=>(r=t!=null?CE(EE(t)):{},AE(e||!t||!t.__esModule?_u(r,"default",{value:t,enumerable:!0}):r,t));var Ds=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 zs=class{};K._CodeOrName=zs;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends zs{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=pn;var yt=class extends zs{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 pn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=yt;K.nil=new yt("");function Xw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Xl(r,e[n]),r.push(t[++n]);return new yt(r)}K._=Xw;var Yl=new yt("+");function Qw(t,...e){let r=[Ns(t[0])],n=0;for(;n<e.length;)r.push(Yl),Xl(r,e[n]),r.push(Yl,Ns(t[++n]));return iz(r),new yt(r)}K.str=Qw;function Xl(t,e){e instanceof yt?t.push(...e._items):e instanceof pn?t.push(e):t.push(uz(e))}K.addCodeArg=Xl;function iz(t){let e=1;for(;e<t.length-1;){if(t[e]===Yl){let r=az(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function az(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof pn||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 pn))return`"${t}${e.slice(1)}`}function cz(t,e){return e.emptyStr()?t:t.emptyStr()?e:Qw`${t}${e}`}K.strConcat=cz;function uz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ns(Array.isArray(t)?t.join(","):t)}function dz(t){return new yt(Ns(t))}K.stringify=dz;function Ns(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Ns;function lz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new yt(`.${t}`):Xw`[${t}]`}K.getProperty=lz;function fz(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=fz;function pz(t){return new yt(t.toString())}K.regexpCode=pz});var tf=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Ds(),Ql=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ka;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ka||(Xe.UsedValueState=Ka={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Ja=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=Ja;var Ya=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=Ya;var hz=(0,Ye._)`\n`,ef=class extends Ja{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?hz:Ye.nil}}get(){return this._scope}name(e){return new Ya(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,Ka.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 Ql(u);c.set(u,Ka.Completed)})}return s}};Xe.ValueScope=ef});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=Ds(),Et=tf(),Or=Ds();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Or._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Or.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Or.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Or.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Or.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Or.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Or.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Or.Name}});var tc=tf();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return tc.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return tc.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return tc.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return tc.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 ir=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},rf=class extends ir{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Et.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=po(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},Xa=class extends ir{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=po(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return ec(e,this.rhs)}},nf=class extends Xa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},of=class extends ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sf=class extends ir{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},af=class extends ir{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},cf=class extends ir{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=po(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Ls=class extends ir{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)||(mz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>gn(e,r.names),{})}},ar=class extends Ls{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},uf=class extends Ls{},fo=class extends ar{};fo.kind="else";var hn=class t extends ar{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 fo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(eb(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=po(this.condition,e,r),this}get names(){let e=super.names;return ec(e,this.condition),this.else&&gn(e,this.else.names),e}};hn.kind="if";var mn=class extends ar{};mn.kind="for";var df=class extends mn{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=po(this.iteration,e,r),this}get names(){return gn(super.names,this.iteration.names)}},lf=class extends mn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Et.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=ec(super.names,this.from);return ec(e,this.to)}},Qa=class extends mn{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=po(this.iterable,e,r),this}get names(){return gn(super.names,this.iterable.names)}},js=class extends ar{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)}};js.kind="func";var Fs=class extends Ls{render(e){return"return "+super.render(e)}};Fs.kind="return";var ff=class extends ar{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&&gn(e,this.catch.names),this.finally&&gn(e,this.finally.names),e}},Us=class extends ar{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Us.kind="catch";var qs=class extends ar{render(e){return"finally"+super.render(e)}};qs.kind="finally";var pf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new Et.Scope({parent:e}),this._nodes=[new uf]}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 rf(e,s,n)),s}const(e,r,n){return this._def(Et.varKinds.const,e,r,n)}let(e,r,n){return this._def(Et.varKinds.let,e,r,n)}var(e,r,n){return this._def(Et.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Xa(e,r,n))}add(e,r){return this._leafNode(new nf(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new cf(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 hn(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 hn(e))}else(){return this._elseNode(new fo)}endIf(){return this._endBlockNode(hn,fo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new df(e),r)}forRange(e,r,n,o,s=this.opts.es5?Et.varKinds.var:Et.varKinds.let){let i=this._scope.toName(e);return this._for(new lf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Et.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 Qa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Et.varKinds.var:Et.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 Qa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(mn)}label(e){return this._leafNode(new of(e))}break(e){return this._leafNode(new sf(e))}return(e){let r=new Fs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Fs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ff;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Us(s),r(s)}return n&&(this._currNode=o.finally=new qs,this.code(n)),this._endBlockNode(Us,qs)}throw(e){return this._leafNode(new af(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 js(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(js)}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 hn))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=pf;function gn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ec(t,e){return e instanceof q._CodeOrName?gn(t,e.names):t}function po(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 mz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function eb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${hf(t)}`}L.not=eb;var gz=tb(L.operators.AND);function yz(...t){return t.reduce(gz)}L.and=yz;var vz=tb(L.operators.OR);function _z(...t){return t.reduce(vz)}L.or=_z;function tb(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${hf(e)} ${t} ${hf(r)}`}function hf(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 ie=D(),Sz=Ds();function wz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=wz;function bz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ob(t,e),!sb(e,t.self.RULES.all))}j.alwaysValidSchema=bz;function ob(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]||cb(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=ob;function sb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=sb;function Rz(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=Rz;function Pz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ie._)`${r}`}return(0,ie._)`${t}${e}${(0,ie.getProperty)(n)}`}j.schemaRefOrVal=Pz;function Cz(t){return ib(decodeURIComponent(t))}j.unescapeFragment=Cz;function xz(t){return encodeURIComponent(gf(t))}j.escapeFragment=xz;function gf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=gf;function ib(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=ib;function kz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=kz;function rb({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ie.Name?(s instanceof ie.Name?t(o,s,i):e(o,s,i),i):s instanceof ie.Name?(e(o,i,s),s):r(s,i);return a===ie.Name&&!(c instanceof ie.Name)?n(o,c):c}}j.mergeEvaluated={props:rb({mergeNames:(t,e,r)=>t.if((0,ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ie._)`${r} || {}`).code((0,ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ie._)`${r} || {}`),yf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ab}),items:rb({mergeNames:(t,e,r)=>t.if((0,ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function ab(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ie._)`{}`);return e!==void 0&&yf(t,r,e),r}j.evaluatedPropsToName=ab;function yf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ie._)`${e}${(0,ie.getProperty)(n)}`,!0))}j.setEvaluated=yf;var nb={};function Ez(t,e){return t.scopeValue("func",{ref:e,code:nb[e.code]||(nb[e.code]=new Sz._Code(e.code))})}j.useFunc=Ez;var mf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(mf||(j.Type=mf={}));function Tz(t,e,r){if(t instanceof ie.Name){let n=e===mf.Num;return r?n?(0,ie._)`"[" + ${t} + "]"`:(0,ie._)`"['" + ${t} + "']"`:n?(0,ie._)`"/" + ${t}`:(0,ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ie.getProperty)(t).toString():"/"+gf(t)}j.getErrorPath=Tz;function cb(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=cb});var cr=R(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var De=D(),Az={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};vf.default=Az});var Hs=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var G=D(),rc=H(),Ue=cr();Le.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};Le.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 $z(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=lb(t,e,r);n??(i||a)?ub(s,c):db(o,(0,G._)`[${c}]`)}Le.reportError=$z;function Mz(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=lb(t,e,r);ub(o,a),s||i||db(n,Ue.default.vErrors)}Le.reportExtraError=Mz;function Iz(t,e){t.assign(Ue.default.errors,e),t.if((0,G._)`${Ue.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,G._)`${Ue.default.vErrors}.length`,e),()=>t.assign(Ue.default.vErrors,null)))}Le.resetErrorsCount=Iz;function Oz({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,Ue.default.errors,a=>{t.const(i,(0,G._)`${Ue.default.vErrors}[${a}]`),t.if((0,G._)`${i}.instancePath === undefined`,()=>t.assign((0,G._)`${i}.instancePath`,(0,G.strConcat)(Ue.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))})}Le.extendErrors=Oz;function ub(t,e){let r=t.const("err",e);t.if((0,G._)`${Ue.default.vErrors} === null`,()=>t.assign(Ue.default.vErrors,(0,G._)`[${r}]`),(0,G._)`${Ue.default.vErrors}.push(${r})`),t.code((0,G._)`${Ue.default.errors}++`)}function db(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 yn={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 lb(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:zz(t,e,r)}function zz(t,e,r={}){let{gen:n,it:o}=t,s=[Nz(o,r),Dz(t,r)];return Lz(t,e,s),n.object(...s)}function Nz({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,rc.getErrorPath)(e,rc.Type.Str)}`:t;return[Ue.default.instancePath,(0,G.strConcat)(Ue.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,rc.getErrorPath)(r,rc.Type.Str)}`),[yn.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([yn.keyword,o],[yn.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([yn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([yn.schema,i],[yn.parentSchema,(0,G._)`${d}${l}`],[Ue.default.data,s]),u&&n.push([yn.propertyName,u])}});var pb=R(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.boolOrEmptySchema=ho.topBoolOrEmptySchema=void 0;var jz=Hs(),Fz=D(),Uz=cr(),qz={message:"boolean schema is false"};function Hz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?fb(t,!1):typeof r=="object"&&r.$async===!0?e.return(Uz.default.data):(e.assign((0,Fz._)`${n}.errors`,null),e.return(!0))}ho.topBoolOrEmptySchema=Hz;function Gz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),fb(t)):r.var(e,!0)}ho.boolOrEmptySchema=Gz;function fb(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,jz.reportError)(o,qz,void 0,e)}});var _f=R(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.getRules=mo.isJSONType=void 0;var Zz=["string","number","integer","boolean","null","object","array"],Wz=new Set(Zz);function Bz(t){return typeof t=="string"&&Wz.has(t)}mo.isJSONType=Bz;function Vz(){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:{}}}mo.getRules=Vz});var Sf=R(zr=>{"use strict";Object.defineProperty(zr,"__esModule",{value:!0});zr.shouldUseRule=zr.shouldUseGroup=zr.schemaHasRulesForType=void 0;function Kz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hb(t,n)}zr.schemaHasRulesForType=Kz;function hb(t,e){return e.rules.some(r=>mb(t,r))}zr.shouldUseGroup=hb;function mb(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))}zr.shouldUseRule=mb});var Gs=R(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var Jz=_f(),Yz=Sf(),Xz=Hs(),N=D(),gb=H(),go;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(go||(je.DataType=go={}));function Qz(t){let e=yb(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}je.getSchemaTypes=Qz;function yb(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Jz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=yb;function eN(t,e){let{gen:r,data:n,opts:o}=t,s=tN(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Yz.schemaHasRulesForType)(t,e[0]));if(i){let a=bf(e,n,o.strictNumbers,go.Wrong);r.if(a,()=>{s.length?rN(t,e,s):Rf(t)})}return i}je.coerceAndCheckDataType=eN;var vb=new Set(["string","number","integer","boolean","null"]);function tN(t,e){return e?t.filter(r=>vb.has(r)||e==="array"&&r==="array"):[]}function rN(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(bf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(vb.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Rf(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),nN(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 Wz({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function lf(t,e,r,n=uo.Correct){let o=n===uo.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===uo.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)}}je.checkDataType=lf;function ff(t,e,r,n){if(t.length===1)return lf(t[0],e,r,n);let o,s=(0,sb.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,lf(i,e,r,n));return o}je.checkDataTypes=ff;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 pf(t){let e=Jz(t);(0,Hz.reportError)(e,Kz)}je.reportTypeError=pf;function Jz(t){let{gen:e,data:r,schema:n}=t,o=(0,sb.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ub=R(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.assignDefaults=void 0;var lo=D(),Yz=H();function Xz(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)cb(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>cb(t,s,o.default))}Ya.assignDefaults=Xz;function cb(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,lo._)`${s}${(0,lo.getProperty)(e)}`;if(o){(0,Yz.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,lo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,lo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,lo._)`${a} = ${(0,lo.stringify)(r)}`)}});var vt=R(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.validateUnion=re.validateArray=re.usePattern=re.callValidateCode=re.schemaProperties=re.allSchemaProperties=re.noPropertyInData=re.propertyInData=re.isOwnProperty=re.hasPropFunc=re.reportMissingProp=re.checkMissingProp=re.checkReportMissingProp=void 0;var de=D(),hf=H(),Ir=ar(),Qz=H();function eN(t,e){let{gen:r,data:n,it:o}=t;r.if(gf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}re.checkReportMissingProp=eN;function tN({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(gf(t,e,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}re.checkMissingProp=tN;function rN(t,e){t.setParams({missingProperty:e},!0),t.error()}re.reportMissingProp=rN;function db(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}re.hasPropFunc=db;function mf(t,e,r){return(0,de._)`${db(t)}.call(${e}, ${r})`}re.isOwnProperty=mf;function nN(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${mf(t,e,r)}`:o}re.propertyInData=nN;function gf(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(mf(t,e,r))):o}re.noPropertyInData=gf;function lb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}re.allSchemaProperties=lb;function oN(t,e){return lb(e).filter(r=>!(0,hf.alwaysValidSchema)(t,e[r]))}re.schemaProperties=oN;function sN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[Ir.default.instancePath,(0,de.strConcat)(Ir.default.instancePath,s)],[Ir.default.parentData,i.parentData],[Ir.default.parentDataProperty,i.parentDataProperty],[Ir.default.rootData,Ir.default.rootData]];i.opts.dynamicRef&&l.push([Ir.default.dynamicAnchors,Ir.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}re.callValidateCode=sN;var iN=(0,de._)`new RegExp`;function aN({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,de._)`${o.code==="new RegExp"?iN:(0,Qz.useFunc)(t,o)}(${r}, ${n})`})}re.usePattern=aN;function cN(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,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:hf.Type.Num},s),e.if((0,de.not)(s),a)})}}re.validateArray=cN;function uN(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,hf.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,de._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}re.validateUnion=uN});var hb=R(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateKeywordUsage=Gt.validSchemaType=Gt.funcKeywordCode=Gt.macroKeywordCode=void 0;var qe=D(),mn=ar(),dN=vt(),lN=Ns();function fN(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=pb(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:qe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Gt.macroKeywordCode=fN;function pN(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;mN(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=pb(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&fb(t),y(()=>t.error());else{let _=e.async?p():h();e.modifying&&fb(t),y(()=>hN(t,_))}}function p(){let _=n.let("ruleErrs",null);return n.try(()=>m((0,qe._)`await `),b=>n.assign(l,!1).if((0,qe._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,qe._)`${b}.errors`),()=>n.throw(b))),_}function h(){let _=(0,qe._)`${d}.errors`;return n.assign(_,null),m(qe.nil),_}function m(_=e.async?(0,qe._)`await `:qe.nil){let b=c.opts.passContext?mn.default.this:mn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,qe._)`${_}${(0,dN.callValidateCode)(t,d,b,w)}`,e.modifying)}function y(_){var b;n.if((0,qe.not)((b=e.valid)!==null&&b!==void 0?b:l),_)}}Gt.funcKeywordCode=pN;function fb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,qe._)`${n.parentData}[${n.parentDataProperty}]`))}function hN(t,e){let{gen:r}=t;r.if((0,qe._)`Array.isArray(${e})`,()=>{r.assign(mn.default.vErrors,(0,qe._)`${mn.default.vErrors} === null ? ${e} : ${mn.default.vErrors}.concat(${e})`).assign(mn.default.errors,(0,qe._)`${mn.default.vErrors}.length`),(0,lN.extendErrors)(t)},()=>t.error())}function mN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function pb(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,qe.stringify)(r)})}function gN(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")}Gt.validSchemaType=gN;function yN({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)}}Gt.validateKeywordUsage=yN});var gb=R(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.extendSubschemaMode=Or.extendSubschemaData=Or.getSubschema=void 0;var Zt=D(),mb=H();function vN(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,Zt._)`${t.schemaPath}${(0,Zt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Zt._)`${t.schemaPath}${(0,Zt.getProperty)(e)}${(0,Zt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,mb.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')}Or.getSubschema=vN;function _N(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,f=a.let("data",(0,Zt._)`${e.data}${(0,Zt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Zt.str)`${u}${(0,mb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Zt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Zt.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]}}Or.extendSubschemaData=_N;function SN(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}Or.extendSubschemaMode=SN});var yf=R((hJ,yb)=>{"use strict";yb.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 _b=R((mJ,vb)=>{"use strict";var zr=vb.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(){};Xa(e,n,o,t,"",t)};zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};zr.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 Xa(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 zr.arrayKeywords)for(var f=0;f<l.length;f++)Xa(t,e,r,l[f],o+"/"+d+"/"+f,s,o,d,n,f)}else if(d in zr.propsKeywords){if(l&&typeof l=="object")for(var p in l)Xa(t,e,r,l[p],o+"/"+d+"/"+wN(p),s,o,d,n,p)}else(d in zr.keywords||t.allKeys&&!(d in zr.skipKeywords))&&Xa(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function wN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ls=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 bN=H(),RN=yf(),PN=_b(),CN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function xN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!vf(t):e?Sb(t)<=e:!1}Qe.inlineRef=xN;var kN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function vf(t){for(let e in t){if(kN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(vf)||typeof r=="object"&&vf(r))return!0}return!1}function Sb(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!CN.has(r)&&(typeof t[r]=="object"&&(0,bN.eachItem)(t[r],n=>e+=Sb(n)),e===1/0))return 1/0}return e}function wb(t,e="",r){r!==!1&&(e=fo(e));let n=t.parse(e);return bb(t,n)}Qe.getFullPath=wb;function bb(t,e){return t.serialize(e).split("#")[0]+"#"}Qe._getFullPath=bb;var EN=/#\/?$/;function fo(t){return t?t.replace(EN,""):""}Qe.normalizeId=fo;function TN(t,e,r){return r=fo(r),t.resolve(e,r)}Qe.resolveUrl=TN;var AN=/^[a-z_][-a-z0-9._]*$/i;function $N(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=fo(t[r]||e),s={"":o},i=wb(n,o,!1),a={},c=new Set;return PN(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let m=i+f,y=s[h];typeof l[r]=="string"&&(y=_.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),s[f]=y;function _(w){let k=this.opts.uriResolver.resolve;if(w=fo(y?k(y,w):w),c.has(w))throw d(w);c.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,w):w!==fo(m)&&(w[0]==="#"?(u(l,a[w],w),a[w]=l):this.refs[w]=m),w}function b(w){if(typeof w=="string"){if(!AN.test(w))throw new Error(`invalid anchor "${w}"`);_.call(this,`#${w}`)}}}),a;function u(l,f,p){if(f!==void 0&&!RN(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Qe.getSchemaRefs=$N});var Us=R(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getData=Nr.KeywordCxt=Nr.validateFunctionCode=void 0;var kb=rb(),Rb=Ds(),Sf=df(),Qa=Ds(),MN=ub(),Fs=hb(),_f=gb(),T=D(),z=ar(),IN=Ls(),cr=H(),js=Ns();function ON(t){if(Ab(t)&&($b(t),Tb(t))){DN(t);return}Eb(t,()=>(0,kb.topBoolOrEmptySchema)(t))}Nr.validateFunctionCode=ON;function Eb({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)}`),NN(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${zN(o)}`,n.$async,()=>t.code(Pb(r,o)).code(s))}function zN(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 NN(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 DN(t){let{schema:e,opts:r,gen:n}=t;Eb(t,()=>{r.$comment&&e.$comment&&Ib(t),qN(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&LN(t),Mb(t),ZN(t)})}function LN(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 jN(t,e){if(Ab(t)&&($b(t),Tb(t))){FN(t,e);return}(0,kb.boolOrEmptySchema)(t,e)}function Tb({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 Ab(t){return typeof t.schema!="boolean"}function FN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Ib(t),HN(t),GN(t);let s=n.const("_errs",z.default.errors);Mb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function $b(t){(0,cr.checkUnknownRules)(t),UN(t)}function Mb(t,e){if(t.opts.jtd)return Cb(t,[],!1,e);let r=(0,Rb.getSchemaTypes)(t.schema),n=(0,Rb.coerceAndCheckDataType)(t,r);Cb(t,r,!n,e)}function UN(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,cr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function qN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,cr.checkStrictMode)(t,"default is ignored in the schema root")}function HN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,IN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function GN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Ib({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 ZN(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&&BN(t),e.return((0,T._)`${z.default.errors} === 0`))}function BN({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 Cb(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,cr.schemaHasRulesButRef)(s,d))){o.block(()=>zb(t,"$ref",d.all.$ref.definition));return}c.jtd||VN(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Sf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Qa.checkDataType)(f.type,i,c.strictNumbers)),xb(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,Qa.reportTypeError)(t)),o.endIf()):xb(t,f),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function xb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,MN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sf.shouldUseRule)(n,s)&&zb(t,s.keyword,s.definition,e.type)})}function VN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(WN(t,e),t.opts.allowUnionTypes||KN(t,e),JN(t,t.dataTypes))}function WN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ob(t.dataTypes,r)||wf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),XN(t,e)}}function KN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&wf(t,"use allowUnionTypes to allow union type keyword")}function JN(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>YN(e,i))&&wf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function YN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ob(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function XN(t,e){let r=[];for(let n of t.dataTypes)Ob(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function wf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,cr.checkStrictMode)(t,e,t.opts.strictTypes)}var ec=class{constructor(e,r,n){if((0,Fs.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,cr.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",Nb(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Fs.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?js.reportExtraError:js.reportError)(this,this.def.error,r)}$dataError(){(0,js.reportError)(this,this.def.$dataError||js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,js.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,Qa.checkDataTypes)(c,r,s.opts.strictNumbers,Qa.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,_f.getSubschema)(this.it,e);(0,_f.extendSubschemaData)(n,this.it,e),(0,_f.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return jN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=cr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=cr.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}};Nr.KeywordCxt=ec;function zb(t,e,r,n){let o=new ec(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Fs.funcKeywordCode)(o,r):"macro"in r?(0,Fs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Fs.funcKeywordCode)(o,r)}var QN=/^\/(?:[^~]|~0|~1)*$/,eD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Nb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!QN.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=eD.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,cr.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Nr.getData=Nb});var tc=R(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var bf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Rf.default=bf});var qs=R(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var Pf=Ls(),Cf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Pf.resolveUrl)(e,r,n),this.missingSchema=(0,Pf.normalizeId)((0,Pf.getFullPath)(e,this.missingRef))}};xf.default=Cf});var nc=R(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;var Tt=D(),tD=tc(),gn=ar(),At=Ls(),Db=H(),rD=Us(),po=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,At.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_t.SchemaEnv=po;function Ef(t){let e=Lb.call(this,t);if(e)return e;let r=(0,At.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Tt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:tD.default,code:(0,Tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:gn.default.data,parentData:gn.default.parentData,parentDataProperty:gn.default.parentDataProperty,dataNames:[gn.default.data],dataPathArr:[Tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Tt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Tt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,rD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(gn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${gn.default.self}`,`${gn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;p.evaluated={props:h instanceof Tt.Name?void 0:h,items:m instanceof Tt.Name?void 0:m,dynamicProps:h instanceof Tt.Name,dynamicItems:m instanceof Tt.Name},p.source&&(p.source.evaluated=(0,Tt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}_t.compileSchema=Ef;function nD(t,e,r){var n;r=(0,At.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=iD.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 po({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=oD.call(this,s)}_t.resolveRef=nD;function oD(t){return(0,At.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ef.call(this,t)}function Lb(t){for(let e of this._compilations)if(sD(e,t))return e}_t.getCompilingSchema=Lb;function sD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function iD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||rc.call(this,t,e)}function rc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,At._getFullPath)(this.opts.uriResolver,r),o=(0,At.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return kf.call(this,r,t);let s=(0,At.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=rc.call(this,t,i);return typeof a?.schema!="object"?void 0:kf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ef.call(this,i),s===(0,At.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,At.resolveUrl)(this.opts.uriResolver,o,u)),new po({schema:a,schemaId:c,root:t,baseId:o})}return kf.call(this,r,i)}}_t.resolveSchema=rc;var aD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function kf(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,Db.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!aD.has(a)&&u&&(e=(0,At.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Db.schemaHasRulesButRef)(r,this.RULES)){let a=(0,At.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=rc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new po({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var jb=R((wJ,cD)=>{cD.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 $f=R((bJ,Zb)=>{"use strict";var uD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ub=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),Tf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),qb=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),dD=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Af(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 lD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Fb(t){return t.length=0,!0}function fD(t,e,r){if(t.length){let n=Af(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function pD(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=fD;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=Fb}else{o.push(u);continue}}return o.length&&(a===Fb?r.zone=o.join(""):i?n.push(o.join("")):n.push(Af(o))),r.address=n.join(""),r}function Hb(t){if(hD(t,":")<2)return{host:t,isIPV6:!1};let e=pD(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 hD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function mD(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 gD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},yD=/[@/?#:]/g,vD=/[@/?#]/g;function Gb(t,e){let r=e?vD:yD;return r.lastIndex=0,t.replace(r,n=>gD[n])}function _D(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(Tf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&qb(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function SD(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(Tf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&qb(s)?e+=s:e+="%"+o,r+=2;continue}}dD(t[r])?e+=t[r]:e+=escape(t[r])}return e}function wD(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(Tf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function bD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ub(r)){let n=Hb(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Gb(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}Zb.exports={nonSimpleDomain:lD,recomposeAuthority:bD,reescapeHostDelimiters:Gb,normalizePercentEncoding:_D,normalizePathEncoding:SD,escapePreservingEscapes:wD,removeDotSegments:mD,isIPv4:Ub,isUUID:uD,normalizeIPv6:Hb,stringArrayToHexStripped:Af}});var Jb=R((RJ,Kb)=>{"use strict";var{isUUID:RD}=$f(),PD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,CD=["http","https","ws","wss","urn","urn:uuid"];function xD(t){return CD.indexOf(t)!==-1}function Mf(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 Bb(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Vb(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 kD(t){return t.secure=Mf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function ED(t){if((t.port===(Mf(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 TD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(PD);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=If(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function AD(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=If(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 $D(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!RD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function MD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Wb={scheme:"http",domainHost:!0,parse:Bb,serialize:Vb},ID={scheme:"https",domainHost:Wb.domainHost,parse:Bb,serialize:Vb},oc={scheme:"ws",domainHost:!0,parse:kD,serialize:ED},OD={scheme:"wss",domainHost:oc.domainHost,parse:oc.parse,serialize:oc.serialize},zD={scheme:"urn",parse:TD,serialize:AD,skipNormalize:!0},ND={scheme:"urn:uuid",parse:$D,serialize:MD,skipNormalize:!0},sc={http:Wb,https:ID,ws:oc,wss:OD,urn:zD,"urn:uuid":ND};Object.setPrototypeOf(sc,null);function If(t){return t&&(sc[t]||sc[t.toLowerCase()])||void 0}Kb.exports={wsIsSecure:Mf,SCHEMES:sc,isValidSchemeName:xD,getSchemeHandler:If}});var tR=R((PJ,cc)=>{"use strict";var{normalizeIPv6:DD,removeDotSegments:Hs,recomposeAuthority:LD,normalizePercentEncoding:jD,normalizePathEncoding:FD,escapePreservingEscapes:UD,reescapeHostDelimiters:qD,isIPv4:HD,nonSimpleDomain:GD}=$f(),{SCHEMES:ZD,getSchemeHandler:Xb}=Jb();function BD(t,e){return typeof t=="string"?t=QD(t,e):typeof t=="object"&&(t=ac(yn(t,e),e)),t}function VD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=ic(t,n),{parsed:i,malformedAuthorityOrPort:a}=ic(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=Qb(o,i,n,!0);return n.skipEscape=!0,yn(c,n)}function Qb(t,e,r,n){let o={};return n||(t=ac(yn(t,r),r),e=ac(yn(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=Hs(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=Hs(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Hs(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=Hs(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 WD(t,e,r){let n=Yb(t,r),o=Yb(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function yn(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=Xb(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=jD(r.path):(r.path=UD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=LD(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=Hs(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,JD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,YD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function XD(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 ic(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(JD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(YD);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=XD(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(HD(n.host)===!1){let f=DD(n.host);n.host=f.host.toLowerCase(),s=f.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=Xb(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&GD(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=qD(unescape(n.host),s))),n.path&&(n.path=FD(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 ac(t,e){return ic(t,e).parsed}function QD(t,e){return eR(t,e).normalized}function eR(t,e){let{parsed:r,malformedAuthorityOrPort:n}=ic(t,e);return{normalized:n?t:yn(r,e),malformedAuthorityOrPort:n}}function Yb(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=eR(t,e);return n?void 0:r}if(typeof t=="object")return yn(t,e)}var Of={SCHEMES:ZD,normalize:BD,resolve:VD,resolveComponent:Qb,equal:WD,serialize:yn,parse:ac};cc.exports=Of;cc.exports.default=Of;cc.exports.fastUri=Of});var nR=R(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var rR=tR();rR.code='require("ajv/dist/runtime/uri").default';zf.default=rR});var lR=R(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var eL=Us();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return eL.KeywordCxt}});var ho=D();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return ho._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return ho.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return ho.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return ho.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return ho.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return ho.CodeGen}});var tL=tc(),cR=qs(),rL=uf(),Gs=nc(),nL=D(),Zs=Ls(),uc=Ds(),Df=H(),oR=jb(),oL=nR(),uR=(t,e)=>new RegExp(t,e);uR.code="new RegExp";var sL=["removeAdditional","useDefaults","coerceTypes"],iL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),aL={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."},cL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},sR=200;function uL(t){var e,r,n,o,s,i,a,c,u,d,l,f,p,h,m,y,_,b,w,k,S,P,I,ne,fe;let Re=t.strict,qr=(e=t.code)===null||e===void 0?void 0:e.optimize,Hr=qr===!0||qr===void 0?1:qr||0,ut=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:uR,fr=(o=t.uriResolver)!==null&&o!==void 0?o:oL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:Re)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Hr,regExp:ut}:{optimize:Hr,regExp:ut},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:sR,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:sR,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(ne=t.unicodeRegExp)!==null&&ne!==void 0?ne:!0,int32range:(fe=t.int32range)!==null&&fe!==void 0?fe:!0,uriResolver:fr}}var Bs=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,...uL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new nL.ValueScope({scope:{},prefixes:iL,es5:r,lines:n}),this.logger=mL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,rL.getRules)(),iR.call(this,aL,e,"NOT SUPPORTED"),iR.call(this,cL,e,"DEPRECATED","warn"),this._metaOpts=pL.call(this),e.formats&&lL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&fL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),dL.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=oR;n==="id"&&(o={...oR},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 f=this._addSchema(d,l);return f.validate||i.call(this,f)}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 cR.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,Zs.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=aR.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Gs.SchemaEnv({schema:{},schemaId:n});if(r=Gs.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=aR.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,Zs.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(yL.call(this,n,r),!r)return(0,Df.eachItem)(n,s=>Nf.call(this,s)),this;_L.call(this,r);let o={...r,type:(0,uc.getJSONTypes)(r.type),schemaType:(0,uc.getJSONTypes)(r.schemaType)};return(0,Df.eachItem)(n,o.type.length===0?s=>Nf.call(this,s,o):s=>o.type.forEach(i=>Nf.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]=dR(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,Zs.normalizeId)(i||n);let u=Zs.getSchemaRefs.call(this,e,n);return c=new Gs.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):Gs.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{Gs.compileSchema.call(this,e)}finally{this.opts=r}}};Bs.ValidationError=tL.default;Bs.MissingRefError=cR.default;Ie.default=Bs;function iR(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 aR(t){return t=(0,Zs.normalizeId)(t),this.schemas[t]||this.refs[t]}function dL(){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 lL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function fL(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 pL(){let t={...this.opts};for(let e of sL)delete t[e];return t}var hL={log(){},warn(){},error(){}};function mL(t){if(t===!1)return hL;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 gL=/^[a-z_$][a-z0-9_$:-]*$/i;function yL(t,e){let{RULES:r}=this;if((0,Df.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!gL.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 Nf(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,uc.getJSONTypes)(e.type),schemaType:(0,uc.getJSONTypes)(e.schemaType)}};e.before?vL.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 vL(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 _L(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=dR(e)),t.validateSchema=this.compile(e,!0))}var SL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function dR(t){return{anyOf:[t,SL]}}});var fR=R(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var wL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Lf.default=wL});var gR=R(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var bL=qs(),pR=vt(),et=D(),mo=ar(),hR=nc(),dc=H(),RL={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=hR.resolveRef.call(c,u,o,r);if(d===void 0)throw new bL.default(n.opts.uriResolver,o,r);if(d instanceof hR.SchemaEnv)return f(d);return p(d);function l(){if(s===u)return lc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return lc(t,(0,et._)`${h}.validate`,u,u.$async)}function f(h){let m=mR(t,h);lc(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,et.stringify)(h)}:{ref:h}),y=e.name("valid"),_=t.subschema({schema:h,dataTypes:[],schemaPath:et.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function mR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=mR;function lc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?mo.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,pR.callValidateCode)(t,e,u)}`),p(e),i||o.assign(h,!0)},m=>{o.if((0,et._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,pR.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let m=(0,et._)`${h}.errors`;o.assign(mo.default.vErrors,(0,et._)`${mo.default.vErrors} === null ? ${m} : ${mo.default.vErrors}.concat(${m})`),o.assign(mo.default.errors,(0,et._)`${mo.default.vErrors}.length`)}function p(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=dc.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${h}.evaluated.props`);s.props=dc.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=dc.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${h}.evaluated.items`);s.items=dc.mergeEvaluated.items(o,_,s.items,et.Name)}}}vn.callRef=lc;vn.default=RL});var yR=R(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var PL=fR(),CL=gR(),xL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",PL.default,CL.default];jf.default=xL});var vR=R(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var fc=D(),Dr=fc.operators,pc={maximum:{okStr:"<=",ok:Dr.LTE,fail:Dr.GT},minimum:{okStr:">=",ok:Dr.GTE,fail:Dr.LT},exclusiveMaximum:{okStr:"<",ok:Dr.LT,fail:Dr.GTE},exclusiveMinimum:{okStr:">",ok:Dr.GT,fail:Dr.LTE}},kL={message:({keyword:t,schemaCode:e})=>(0,fc.str)`must be ${pc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,fc._)`{comparison: ${pc[t].okStr}, limit: ${e}}`},EL={keyword:Object.keys(pc),type:"number",schemaType:"number",$data:!0,error:kL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,fc._)`${r} ${pc[e].fail} ${n} || isNaN(${r})`)}};Ff.default=EL});var _R=R(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Vs=D(),TL={message:({schemaCode:t})=>(0,Vs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Vs._)`{multipleOf: ${t}}`},AL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:TL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Vs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Vs._)`${i} !== parseInt(${i})`;t.fail$data((0,Vs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Uf.default=AL});var wR=R(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});function SR(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}qf.default=SR;SR.code='require("ajv/dist/runtime/ucs2length").default'});var bR=R(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var _n=D(),$L=H(),ML=wR(),IL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,_n.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,_n._)`{limit: ${t}}`},OL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:IL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?_n.operators.GT:_n.operators.LT,i=o.opts.unicode===!1?(0,_n._)`${r}.length`:(0,_n._)`${(0,$L.useFunc)(t.gen,ML.default)}(${r})`;t.fail$data((0,_n._)`${i} ${s} ${n}`)}};Hf.default=OL});var RR=R(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var zL=vt(),NL=H(),go=D(),DL={message:({schemaCode:t})=>(0,go.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,go._)`{pattern: ${t}}`},LL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:DL,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,go._)`new RegExp`:(0,NL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,go._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,go._)`!${d}`)}else{let c=(0,zL.usePattern)(t,o);t.fail$data((0,go._)`!${c}.test(${r})`)}}};Gf.default=LL});var PR=R(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Ws=D(),jL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ws.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ws._)`{limit: ${t}}`},FL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ws.operators.GT:Ws.operators.LT;t.fail$data((0,Ws._)`Object.keys(${r}).length ${o} ${n}`)}};Zf.default=FL});var CR=R(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var Ks=vt(),Js=D(),UL=H(),qL={message:({params:{missingProperty:t}})=>(0,Js.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Js._)`{missingProperty: ${t}}`},HL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qL,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 p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,UL.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Js.nil,l);else for(let p of r)(0,Ks.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,Ks.checkMissingProp)(t,r,p)),(0,Ks.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,Ks.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,Ks.propertyInData)(e,o,p,a.ownProperties)),e.if((0,Js.not)(h),()=>{t.error(),e.break()})},Js.nil)}}};Bf.default=HL});var xR=R(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var Ys=D(),GL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ys.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ys._)`{limit: ${t}}`},ZL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:GL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ys.operators.GT:Ys.operators.LT;t.fail$data((0,Ys._)`${r}.length ${o} ${n}`)}};Vf.default=ZL});var hc=R(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var kR=yf();kR.code='require("ajv/dist/runtime/equal").default';Wf.default=kR});var ER=R(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Kf=Ds(),Oe=D(),BL=H(),VL=hc(),WL={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},KL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:WL,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,Kf.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Oe._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Oe._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Oe._)`${h} > 1`,()=>(l()?f:p)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),_=(0,Kf.checkDataTypes)(u,y,a.opts.strictNumbers,Kf.DataType.Wrong),b=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${h}--;`,()=>{e.let(y,(0,Oe._)`${r}[${h}]`),e.if(_,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${y} == "string"`,(0,Oe._)`${y} += "_"`),e.if((0,Oe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,Oe._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,BL.useFunc)(e,VL.default),_=e.name("outer");e.label(_).for((0,Oe._)`;${h}--;`,()=>e.for((0,Oe._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Oe._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Jf.default=KL});var TR=R(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var Yf=D(),JL=H(),YL=hc(),XL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Yf._)`{allowedValue: ${t}}`},QL={keyword:"const",$data:!0,error:XL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Yf._)`!${(0,JL.useFunc)(e,YL.default)}(${r}, ${o})`):t.fail((0,Yf._)`${s} !== ${r}`)}};Xf.default=QL});var AR=R(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Xs=D(),ej=H(),tj=hc(),rj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Xs._)`{allowedValues: ${t}}`},nj={keyword:"enum",schemaType:"array",$data:!0,error:rj,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,ej.useFunc)(e,tj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,Xs.or)(...o.map((h,m)=>f(p,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,Xs._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=o[h];return typeof m=="object"&&m!==null?(0,Xs._)`${u()}(${r}, ${p}[${h}])`:(0,Xs._)`${r} === ${m}`}}};Qf.default=nj});var $R=R(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var oj=vR(),sj=_R(),ij=bR(),aj=RR(),cj=PR(),uj=CR(),dj=xR(),lj=ER(),fj=TR(),pj=AR(),hj=[oj.default,sj.default,ij.default,aj.default,cj.default,uj.default,dj.default,lj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},fj.default,pj.default];ep.default=hj});var rp=R(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.validateAdditionalItems=void 0;var Sn=D(),tp=H(),mj={message:({params:{len:t}})=>(0,Sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sn._)`{limit: ${t}}`},gj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:mj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,tp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}MR(t,n)}};function MR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Sn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,tp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Sn._)`${a} <= ${e.length}`);r.if((0,Sn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:tp.Type.Num},u),i.allErrors||r.if((0,Sn.not)(u),()=>r.break())})}}Qs.validateAdditionalItems=MR;Qs.default=gj});var np=R(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.validateTuple=void 0;var IR=D(),mc=H(),yj=vt(),vj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return OR(t,"additionalItems",e);r.items=!0,!(0,mc.alwaysValidSchema)(r,e)&&t.ok((0,yj.validateArray)(t))}};function OR(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=mc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,IR._)`${s}.length`);r.forEach((l,f)=>{(0,mc.alwaysValidSchema)(a,l)||(n.if((0,IR._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,mc.checkStrictMode)(a,y,f.strictTuples)}}}ei.validateTuple=OR;ei.default=vj});var zR=R(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var _j=np(),Sj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,_j.validateTuple)(t,"items")};op.default=Sj});var DR=R(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var NR=D(),wj=H(),bj=vt(),Rj=rp(),Pj={message:({params:{len:t}})=>(0,NR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,NR._)`{limit: ${t}}`},Cj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Pj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,wj.alwaysValidSchema)(n,e)&&(o?(0,Rj.validateAdditionalItems)(t,o):t.ok((0,bj.validateArray)(t)))}};sp.default=Cj});var LR=R(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var St=D(),gc=H(),xj={message:({params:{min:t,max:e}})=>e===void 0?(0,St.str)`must contain at least ${t} valid item(s)`:(0,St.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,St._)`{minContains: ${t}}`:(0,St._)`{minContains: ${t}, maxContains: ${e}}`},kj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:xj,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,St._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gc.alwaysValidSchema)(s,r)){let m=(0,St._)`${d} >= ${i}`;a!==void 0&&(m=(0,St._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?p(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,St._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:gc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,St._)`${m}++`),a===void 0?e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,St._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};ip.default=kj});var UR=R(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateSchemaDeps=Bt.validatePropertyDeps=Bt.error=void 0;var ap=D(),Ej=H(),ti=vt();Bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ap.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ap._)`{property: ${t},
5
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function nN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function wf(t,e,r,n=go.Correct){let o=n===go.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===go.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)}}je.checkDataType=wf;function bf(t,e,r,n){if(t.length===1)return wf(t[0],e,r,n);let o,s=(0,gb.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,wf(i,e,r,n));return o}je.checkDataTypes=bf;var oN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function Rf(t){let e=sN(t);(0,Xz.reportError)(e,oN)}je.reportTypeError=Rf;function sN(t){let{gen:e,data:r,schema:n}=t,o=(0,gb.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Sb=R(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});nc.assignDefaults=void 0;var yo=D(),iN=H();function aN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)_b(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>_b(t,s,o.default))}nc.assignDefaults=aN;function _b(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,yo._)`${s}${(0,yo.getProperty)(e)}`;if(o){(0,iN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,yo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,yo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,yo._)`${a} = ${(0,yo.stringify)(r)}`)}});var vt=R(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.validateUnion=re.validateArray=re.usePattern=re.callValidateCode=re.schemaProperties=re.allSchemaProperties=re.noPropertyInData=re.propertyInData=re.isOwnProperty=re.hasPropFunc=re.reportMissingProp=re.checkMissingProp=re.checkReportMissingProp=void 0;var de=D(),Pf=H(),Nr=cr(),cN=H();function uN(t,e){let{gen:r,data:n,it:o}=t;r.if(xf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}re.checkReportMissingProp=uN;function dN({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(xf(t,e,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}re.checkMissingProp=dN;function lN(t,e){t.setParams({missingProperty:e},!0),t.error()}re.reportMissingProp=lN;function wb(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}re.hasPropFunc=wb;function Cf(t,e,r){return(0,de._)`${wb(t)}.call(${e}, ${r})`}re.isOwnProperty=Cf;function fN(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Cf(t,e,r)}`:o}re.propertyInData=fN;function xf(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Cf(t,e,r))):o}re.noPropertyInData=xf;function bb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}re.allSchemaProperties=bb;function pN(t,e){return bb(e).filter(r=>!(0,Pf.alwaysValidSchema)(t,e[r]))}re.schemaProperties=pN;function hN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[Nr.default.instancePath,(0,de.strConcat)(Nr.default.instancePath,s)],[Nr.default.parentData,i.parentData],[Nr.default.parentDataProperty,i.parentDataProperty],[Nr.default.rootData,Nr.default.rootData]];i.opts.dynamicRef&&l.push([Nr.default.dynamicAnchors,Nr.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}re.callValidateCode=hN;var mN=(0,de._)`new RegExp`;function gN({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,de._)`${o.code==="new RegExp"?mN:(0,cN.useFunc)(t,o)}(${r}, ${n})`})}re.usePattern=gN;function yN(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,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Pf.Type.Num},s),e.if((0,de.not)(s),a)})}}re.validateArray=yN;function vN(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,Pf.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,de._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}re.validateUnion=vN});var Cb=R(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateKeywordUsage=Zt.validSchemaType=Zt.funcKeywordCode=Zt.macroKeywordCode=void 0;var qe=D(),vn=cr(),_N=vt(),SN=Hs();function wN(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Pb(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:qe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Zt.macroKeywordCode=wN;function bN(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;PN(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=Pb(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&Rb(t),y(()=>t.error());else{let v=e.async?p():h();e.modifying&&Rb(t),y(()=>RN(t,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,qe._)`await `),b=>n.assign(l,!1).if((0,qe._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,qe._)`${b}.errors`),()=>n.throw(b))),v}function h(){let v=(0,qe._)`${d}.errors`;return n.assign(v,null),m(qe.nil),v}function m(v=e.async?(0,qe._)`await `:qe.nil){let b=c.opts.passContext?vn.default.this:vn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,qe._)`${v}${(0,_N.callValidateCode)(t,d,b,w)}`,e.modifying)}function y(v){var b;n.if((0,qe.not)((b=e.valid)!==null&&b!==void 0?b:l),v)}}Zt.funcKeywordCode=bN;function Rb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,qe._)`${n.parentData}[${n.parentDataProperty}]`))}function RN(t,e){let{gen:r}=t;r.if((0,qe._)`Array.isArray(${e})`,()=>{r.assign(vn.default.vErrors,(0,qe._)`${vn.default.vErrors} === null ? ${e} : ${vn.default.vErrors}.concat(${e})`).assign(vn.default.errors,(0,qe._)`${vn.default.vErrors}.length`),(0,SN.extendErrors)(t)},()=>t.error())}function PN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Pb(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,qe.stringify)(r)})}function CN(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")}Zt.validSchemaType=CN;function xN({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)}}Zt.validateKeywordUsage=xN});var kb=R(Dr=>{"use strict";Object.defineProperty(Dr,"__esModule",{value:!0});Dr.extendSubschemaMode=Dr.extendSubschemaData=Dr.getSubschema=void 0;var Wt=D(),xb=H();function kN(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,Wt._)`${t.schemaPath}${(0,Wt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Wt._)`${t.schemaPath}${(0,Wt.getProperty)(e)}${(0,Wt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,xb.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')}Dr.getSubschema=kN;function EN(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,f=a.let("data",(0,Wt._)`${e.data}${(0,Wt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Wt.str)`${u}${(0,xb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Wt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Wt.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]}}Dr.extendSubschemaData=EN;function TN(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}Dr.extendSubschemaMode=TN});var kf=R((xJ,Eb)=>{"use strict";Eb.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((kJ,Tb)=>{"use strict";var Lr=Tb.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};oc(e,n,o,t,"",t)};Lr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Lr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Lr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Lr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function oc(t,e,r,n,o,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 Lr.arrayKeywords)for(var f=0;f<l.length;f++)oc(t,e,r,l[f],o+"/"+d+"/"+f,s,o,d,n,f)}else if(d in Lr.propsKeywords){if(l&&typeof l=="object")for(var p in l)oc(t,e,r,l[p],o+"/"+d+"/"+AN(p),s,o,d,n,p)}else(d in Lr.keywords||t.allKeys&&!(d in Lr.skipKeywords))&&oc(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function AN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zs=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 $N=H(),MN=kf(),IN=Ab(),ON=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ef(t):e?$b(t)<=e:!1}Qe.inlineRef=zN;var NN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ef(t){for(let e in t){if(NN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ef)||typeof r=="object"&&Ef(r))return!0}return!1}function $b(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!ON.has(r)&&(typeof t[r]=="object"&&(0,$N.eachItem)(t[r],n=>e+=$b(n)),e===1/0))return 1/0}return e}function Mb(t,e="",r){r!==!1&&(e=vo(e));let n=t.parse(e);return Ib(t,n)}Qe.getFullPath=Mb;function Ib(t,e){return t.serialize(e).split("#")[0]+"#"}Qe._getFullPath=Ib;var DN=/#\/?$/;function vo(t){return t?t.replace(DN,""):""}Qe.normalizeId=vo;function LN(t,e,r){return r=vo(r),t.resolve(e,r)}Qe.resolveUrl=LN;var jN=/^[a-z_][-a-z0-9._]*$/i;function FN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=vo(t[r]||e),s={"":o},i=Mb(n,o,!1),a={},c=new Set;return IN(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let m=i+f,y=s[h];typeof l[r]=="string"&&(y=v.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),s[f]=y;function v(w){let x=this.opts.uriResolver.resolve;if(w=vo(y?x(y,w):w),c.has(w))throw d(w);c.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,w):w!==vo(m)&&(w[0]==="#"?(u(l,a[w],w),a[w]=l):this.refs[w]=m),w}function b(w){if(typeof w=="string"){if(!jN.test(w))throw new Error(`invalid anchor "${w}"`);v.call(this,`#${w}`)}}}),a;function u(l,f,p){if(f!==void 0&&!MN(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Qe.getSchemaRefs=FN});var Vs=R(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.getData=jr.KeywordCxt=jr.validateFunctionCode=void 0;var Lb=pb(),Ob=Gs(),Af=Sf(),sc=Gs(),UN=Sb(),Bs=Cb(),Tf=kb(),T=D(),z=cr(),qN=Zs(),ur=H(),Ws=Hs();function HN(t){if(Ub(t)&&(qb(t),Fb(t))){WN(t);return}jb(t,()=>(0,Lb.topBoolOrEmptySchema)(t))}jr.validateFunctionCode=HN;function jb({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"; ${zb(r,o)}`),ZN(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${GN(o)}`,n.$async,()=>t.code(zb(r,o)).code(s))}function GN(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 ZN(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 WN(t){let{schema:e,opts:r,gen:n}=t;jb(t,()=>{r.$comment&&e.$comment&&Gb(t),YN(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&BN(t),Hb(t),eD(t)})}function BN(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 zb(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 VN(t,e){if(Ub(t)&&(qb(t),Fb(t))){KN(t,e);return}(0,Lb.boolOrEmptySchema)(t,e)}function Fb({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 Ub(t){return typeof t.schema!="boolean"}function KN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Gb(t),XN(t),QN(t);let s=n.const("_errs",z.default.errors);Hb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function qb(t){(0,ur.checkUnknownRules)(t),JN(t)}function Hb(t,e){if(t.opts.jtd)return Nb(t,[],!1,e);let r=(0,Ob.getSchemaTypes)(t.schema),n=(0,Ob.coerceAndCheckDataType)(t,r);Nb(t,r,!n,e)}function JN(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ur.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function YN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ur.checkStrictMode)(t,"default is ignored in the schema root")}function XN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,qN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function QN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gb({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 eD(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&&tD(t),e.return((0,T._)`${z.default.errors} === 0`))}function tD({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 Nb(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,ur.schemaHasRulesButRef)(s,d))){o.block(()=>Wb(t,"$ref",d.all.$ref.definition));return}c.jtd||rD(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Af.shouldUseGroup)(s,f)&&(f.type?(o.if((0,sc.checkDataType)(f.type,i,c.strictNumbers)),Db(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,sc.reportTypeError)(t)),o.endIf()):Db(t,f),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function Db(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,UN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Af.shouldUseRule)(n,s)&&Wb(t,s.keyword,s.definition,e.type)})}function rD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(nD(t,e),t.opts.allowUnionTypes||oD(t,e),sD(t,t.dataTypes))}function nD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Zb(t.dataTypes,r)||$f(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),aD(t,e)}}function oD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&$f(t,"use allowUnionTypes to allow union type keyword")}function sD(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Af.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>iD(e,i))&&$f(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function iD(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Zb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function aD(t,e){let r=[];for(let n of t.dataTypes)Zb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function $f(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ur.checkStrictMode)(t,e,t.opts.strictTypes)}var ic=class{constructor(e,r,n){if((0,Bs.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,ur.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",Bb(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Bs.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?Ws.reportExtraError:Ws.reportError)(this,this.def.error,r)}$dataError(){(0,Ws.reportError)(this,this.def.$dataError||Ws.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ws.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,sc.checkDataTypes)(c,r,s.opts.strictNumbers,sc.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,Tf.getSubschema)(this.it,e);(0,Tf.extendSubschemaData)(n,this.it,e),(0,Tf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return VN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ur.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ur.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}};jr.KeywordCxt=ic;function Wb(t,e,r,n){let o=new ic(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Bs.funcKeywordCode)(o,r):"macro"in r?(0,Bs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Bs.funcKeywordCode)(o,r)}var cD=/^\/(?:[^~]|~0|~1)*$/,uD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Bb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!cD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=uD.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,ur.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}jr.getData=Bb});var ac=R(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var Mf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};If.default=Mf});var Ks=R(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var Of=Zs(),zf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Of.resolveUrl)(e,r,n),this.missingSchema=(0,Of.normalizeId)((0,Of.getFullPath)(e,this.missingRef))}};Nf.default=zf});var uc=R(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;var Tt=D(),dD=ac(),_n=cr(),At=Zs(),Vb=H(),lD=Vs(),_o=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,At.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_t.SchemaEnv=_o;function Lf(t){let e=Kb.call(this,t);if(e)return e;let r=(0,At.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Tt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:dD.default,code:(0,Tt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:_n.default.data,parentData:_n.default.parentData,parentDataProperty:_n.default.parentDataProperty,dataNames:[_n.default.data],dataPathArr:[Tt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Tt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Tt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,lD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(_n.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${_n.default.self}`,`${_n.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;p.evaluated={props:h instanceof Tt.Name?void 0:h,items:m instanceof Tt.Name?void 0:m,dynamicProps:h instanceof Tt.Name,dynamicItems:m instanceof Tt.Name},p.source&&(p.source.evaluated=(0,Tt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}_t.compileSchema=Lf;function fD(t,e,r){var n;r=(0,At.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=mD.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 _o({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=pD.call(this,s)}_t.resolveRef=fD;function pD(t){return(0,At.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Lf.call(this,t)}function Kb(t){for(let e of this._compilations)if(hD(e,t))return e}_t.getCompilingSchema=Kb;function hD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function mD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||cc.call(this,t,e)}function cc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,At._getFullPath)(this.opts.uriResolver,r),o=(0,At.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Df.call(this,r,t);let s=(0,At.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=cc.call(this,t,i);return typeof a?.schema!="object"?void 0:Df.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Lf.call(this,i),s===(0,At.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,At.resolveUrl)(this.opts.uriResolver,o,u)),new _o({schema:a,schemaId:c,root:t,baseId:o})}return Df.call(this,r,i)}}_t.resolveSchema=cc;var gD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Df(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,Vb.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!gD.has(a)&&u&&(e=(0,At.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Vb.schemaHasRulesButRef)(r,this.RULES)){let a=(0,At.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=cc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new _o({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Jb=R((IJ,yD)=>{yD.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 Uf=R((OJ,rR)=>{"use strict";var vD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xb=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),jf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Qb=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),_D=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ff(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 SD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Yb(t){return t.length=0,!0}function wD(t,e,r){if(t.length){let n=Ff(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function bD(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=wD;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=Yb}else{o.push(u);continue}}return o.length&&(a===Yb?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ff(o))),r.address=n.join(""),r}function eR(t){if(RD(t,":")<2)return{host:t,isIPV6:!1};let e=bD(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 RD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function PD(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 CD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},xD=/[@/?#:]/g,kD=/[@/?#]/g;function tR(t,e){let r=e?kD:xD;return r.lastIndex=0,t.replace(r,n=>CD[n])}function ED(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(jf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Qb(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function TD(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(jf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Qb(s)?e+=s:e+="%"+o,r+=2;continue}}_D(t[r])?e+=t[r]:e+=escape(t[r])}return e}function AD(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(jf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function $D(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Xb(r)){let n=eR(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=tR(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}rR.exports={nonSimpleDomain:SD,recomposeAuthority:$D,reescapeHostDelimiters:tR,normalizePercentEncoding:ED,normalizePathEncoding:TD,escapePreservingEscapes:AD,removeDotSegments:PD,isIPv4:Xb,isUUID:vD,normalizeIPv6:eR,stringArrayToHexStripped:Ff}});var aR=R((zJ,iR)=>{"use strict";var{isUUID:MD}=Uf(),ID=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,OD=["http","https","ws","wss","urn","urn:uuid"];function zD(t){return OD.indexOf(t)!==-1}function qf(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 nR(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function oR(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 ND(t){return t.secure=qf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function DD(t){if((t.port===(qf(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=Hf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function jD(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=Hf(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||!MD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function UD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var sR={scheme:"http",domainHost:!0,parse:nR,serialize:oR},qD={scheme:"https",domainHost:sR.domainHost,parse:nR,serialize:oR},dc={scheme:"ws",domainHost:!0,parse:ND,serialize:DD},HD={scheme:"wss",domainHost:dc.domainHost,parse:dc.parse,serialize:dc.serialize},GD={scheme:"urn",parse:LD,serialize:jD,skipNormalize:!0},ZD={scheme:"urn:uuid",parse:FD,serialize:UD,skipNormalize:!0},lc={http:sR,https:qD,ws:dc,wss:HD,urn:GD,"urn:uuid":ZD};Object.setPrototypeOf(lc,null);function Hf(t){return t&&(lc[t]||lc[t.toLowerCase()])||void 0}iR.exports={wsIsSecure:qf,SCHEMES:lc,isValidSchemeName:zD,getSchemeHandler:Hf}});var fR=R((NJ,hc)=>{"use strict";var{normalizeIPv6:WD,removeDotSegments:Js,recomposeAuthority:BD,normalizePercentEncoding:VD,normalizePathEncoding:KD,escapePreservingEscapes:JD,reescapeHostDelimiters:YD,isIPv4:XD,nonSimpleDomain:QD}=Uf(),{SCHEMES:eL,getSchemeHandler:uR}=aR();function tL(t,e){return typeof t=="string"?t=cL(t,e):typeof t=="object"&&(t=pc(Sn(t,e),e)),t}function rL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=fc(t,n),{parsed:i,malformedAuthorityOrPort:a}=fc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=dR(o,i,n,!0);return n.skipEscape=!0,Sn(c,n)}function dR(t,e,r,n){let o={};return n||(t=pc(Sn(t,r),r),e=pc(Sn(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 nL(t,e,r){let n=cR(t,r),o=cR(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Sn(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=uR(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=VD(r.path):(r.path=JD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=BD(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 oL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,iL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function aL(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 fc(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(sL);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(iL);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(oL);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=aL(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(XD(n.host)===!1){let f=WD(n.host);n.host=f.host.toLowerCase(),s=f.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=uR(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&QD(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=YD(unescape(n.host),s))),n.path&&(n.path=KD(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 pc(t,e){return fc(t,e).parsed}function cL(t,e){return lR(t,e).normalized}function lR(t,e){let{parsed:r,malformedAuthorityOrPort:n}=fc(t,e);return{normalized:n?t:Sn(r,e),malformedAuthorityOrPort:n}}function cR(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=lR(t,e);return n?void 0:r}if(typeof t=="object")return Sn(t,e)}var Gf={SCHEMES:eL,normalize:tL,resolve:rL,resolveComponent:dR,equal:nL,serialize:Sn,parse:pc};hc.exports=Gf;hc.exports.default=Gf;hc.exports.fastUri=Gf});var hR=R(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var pR=fR();pR.code='require("ajv/dist/runtime/uri").default';Zf.default=pR});var bR=R(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var uL=Vs();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return uL.KeywordCxt}});var So=D();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return So._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return So.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return So.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return So.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return So.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return So.CodeGen}});var dL=ac(),_R=Ks(),lL=_f(),Ys=uc(),fL=D(),Xs=Zs(),mc=Gs(),Bf=H(),mR=Jb(),pL=hR(),SR=(t,e)=>new RegExp(t,e);SR.code="new RegExp";var hL=["removeAdditional","useDefaults","coerceTypes"],mL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),gL={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."},yL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},gR=200;function vL(t){var e,r,n,o,s,i,a,c,u,d,l,f,p,h,m,y,v,b,w,x,S,P,I,ne,fe;let Re=t.strict,Wr=(e=t.code)===null||e===void 0?void 0:e.optimize,Br=Wr===!0||Wr===void 0?1:Wr||0,ut=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:SR,hr=(o=t.uriResolver)!==null&&o!==void 0?o:pL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:Re)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Br,regExp:ut}:{optimize:Br,regExp:ut},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:gR,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:gR,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(ne=t.unicodeRegExp)!==null&&ne!==void 0?ne:!0,int32range:(fe=t.int32range)!==null&&fe!==void 0?fe:!0,uriResolver:hr}}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,...vL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new fL.ValueScope({scope:{},prefixes:mL,es5:r,lines:n}),this.logger=PL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,lL.getRules)(),yR.call(this,gL,e,"NOT SUPPORTED"),yR.call(this,yL,e,"DEPRECATED","warn"),this._metaOpts=bL.call(this),e.formats&&SL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&wL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),_L.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=mR;n==="id"&&(o={...mR},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 f=this._addSchema(d,l);return f.validate||i.call(this,f)}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 _R.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,Xs.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=vR.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ys.SchemaEnv({schema:{},schemaId:n});if(r=Ys.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=vR.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,Xs.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(xL.call(this,n,r),!r)return(0,Bf.eachItem)(n,s=>Wf.call(this,s)),this;EL.call(this,r);let o={...r,type:(0,mc.getJSONTypes)(r.type),schemaType:(0,mc.getJSONTypes)(r.schemaType)};return(0,Bf.eachItem)(n,o.type.length===0?s=>Wf.call(this,s,o):s=>o.type.forEach(i=>Wf.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]=wR(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,Xs.normalizeId)(i||n);let u=Xs.getSchemaRefs.call(this,e,n);return c=new Ys.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):Ys.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{Ys.compileSchema.call(this,e)}finally{this.opts=r}}};Qs.ValidationError=dL.default;Qs.MissingRefError=_R.default;Ie.default=Qs;function yR(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 vR(t){return t=(0,Xs.normalizeId)(t),this.schemas[t]||this.refs[t]}function _L(){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 SL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function wL(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 bL(){let t={...this.opts};for(let e of hL)delete t[e];return t}var RL={log(){},warn(){},error(){}};function PL(t){if(t===!1)return RL;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 CL=/^[a-z_$][a-z0-9_$:-]*$/i;function xL(t,e){let{RULES:r}=this;if((0,Bf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!CL.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 Wf(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,mc.getJSONTypes)(e.type),schemaType:(0,mc.getJSONTypes)(e.schemaType)}};e.before?kL.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 kL(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 EL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=wR(e)),t.validateSchema=this.compile(e,!0))}var TL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function wR(t){return{anyOf:[t,TL]}}});var RR=R(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var AL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Vf.default=AL});var kR=R(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.callRef=wn.getValidate=void 0;var $L=Ks(),PR=vt(),et=D(),wo=cr(),CR=uc(),gc=H(),ML={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=CR.resolveRef.call(c,u,o,r);if(d===void 0)throw new $L.default(n.opts.uriResolver,o,r);if(d instanceof CR.SchemaEnv)return f(d);return p(d);function l(){if(s===u)return yc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return yc(t,(0,et._)`${h}.validate`,u,u.$async)}function f(h){let m=xR(t,h);yc(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,et.stringify)(h)}:{ref:h}),y=e.name("valid"),v=t.subschema({schema:h,dataTypes:[],schemaPath:et.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function xR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}wn.getValidate=xR;function yc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?wo.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,PR.callValidateCode)(t,e,u)}`),p(e),i||o.assign(h,!0)},m=>{o.if((0,et._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,PR.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let m=(0,et._)`${h}.errors`;o.assign(wo.default.vErrors,(0,et._)`${wo.default.vErrors} === null ? ${m} : ${wo.default.vErrors}.concat(${m})`),o.assign(wo.default.errors,(0,et._)`${wo.default.vErrors}.length`)}function p(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=gc.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,et._)`${h}.evaluated.props`);s.props=gc.mergeEvaluated.props(o,v,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=gc.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,et._)`${h}.evaluated.items`);s.items=gc.mergeEvaluated.items(o,v,s.items,et.Name)}}}wn.callRef=yc;wn.default=ML});var ER=R(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var IL=RR(),OL=kR(),zL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",IL.default,OL.default];Kf.default=zL});var TR=R(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var vc=D(),Fr=vc.operators,_c={maximum:{okStr:"<=",ok:Fr.LTE,fail:Fr.GT},minimum:{okStr:">=",ok:Fr.GTE,fail:Fr.LT},exclusiveMaximum:{okStr:"<",ok:Fr.LT,fail:Fr.GTE},exclusiveMinimum:{okStr:">",ok:Fr.GT,fail:Fr.LTE}},NL={message:({keyword:t,schemaCode:e})=>(0,vc.str)`must be ${_c[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vc._)`{comparison: ${_c[t].okStr}, limit: ${e}}`},DL={keyword:Object.keys(_c),type:"number",schemaType:"number",$data:!0,error:NL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,vc._)`${r} ${_c[e].fail} ${n} || isNaN(${r})`)}};Jf.default=DL});var AR=R(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var ei=D(),LL={message:({schemaCode:t})=>(0,ei.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ei._)`{multipleOf: ${t}}`},jL={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,ei._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ei._)`${i} !== parseInt(${i})`;t.fail$data((0,ei._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Yf.default=jL});var MR=R(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});function $R(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}Xf.default=$R;$R.code='require("ajv/dist/runtime/ucs2length").default'});var IR=R(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var bn=D(),FL=H(),UL=MR(),qL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,bn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,bn._)`{limit: ${t}}`},HL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?bn.operators.GT:bn.operators.LT,i=o.opts.unicode===!1?(0,bn._)`${r}.length`:(0,bn._)`${(0,FL.useFunc)(t.gen,UL.default)}(${r})`;t.fail$data((0,bn._)`${i} ${s} ${n}`)}};Qf.default=HL});var OR=R(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var GL=vt(),ZL=H(),bo=D(),WL={message:({schemaCode:t})=>(0,bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,bo._)`{pattern: ${t}}`},BL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:WL,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,bo._)`new RegExp`:(0,ZL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,bo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,bo._)`!${d}`)}else{let c=(0,GL.usePattern)(t,o);t.fail$data((0,bo._)`!${c}.test(${r})`)}}};ep.default=BL});var zR=R(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ti=D(),VL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ti.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ti._)`{limit: ${t}}`},KL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ti.operators.GT:ti.operators.LT;t.fail$data((0,ti._)`Object.keys(${r}).length ${o} ${n}`)}};tp.default=KL});var NR=R(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var ri=vt(),ni=D(),JL=H(),YL={message:({params:{missingProperty:t}})=>(0,ni.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ni._)`{missingProperty: ${t}}`},XL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:YL,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 p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,JL.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ni.nil,l);else for(let p of r)(0,ri.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,ri.checkMissingProp)(t,r,p)),(0,ri.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,ri.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,ri.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ni.not)(h),()=>{t.error(),e.break()})},ni.nil)}}};rp.default=XL});var DR=R(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var oi=D(),QL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,oi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,oi._)`{limit: ${t}}`},ej={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:QL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?oi.operators.GT:oi.operators.LT;t.fail$data((0,oi._)`${r}.length ${o} ${n}`)}};np.default=ej});var Sc=R(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var LR=kf();LR.code='require("ajv/dist/runtime/equal").default';op.default=LR});var jR=R(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var sp=Gs(),Oe=D(),tj=H(),rj=Sc(),nj={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},oj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:nj,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,sp.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Oe._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Oe._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Oe._)`${h} > 1`,()=>(l()?f:p)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),v=(0,sp.checkDataTypes)(u,y,a.opts.strictNumbers,sp.DataType.Wrong),b=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${h}--;`,()=>{e.let(y,(0,Oe._)`${r}[${h}]`),e.if(v,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${y} == "string"`,(0,Oe._)`${y} += "_"`),e.if((0,Oe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,Oe._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,tj.useFunc)(e,rj.default),v=e.name("outer");e.label(v).for((0,Oe._)`;${h}--;`,()=>e.for((0,Oe._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Oe._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};ip.default=oj});var FR=R(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var ap=D(),sj=H(),ij=Sc(),aj={message:"must be equal to constant",params:({schemaCode:t})=>(0,ap._)`{allowedValue: ${t}}`},cj={keyword:"const",$data:!0,error:aj,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,ap._)`!${(0,sj.useFunc)(e,ij.default)}(${r}, ${o})`):t.fail((0,ap._)`${s} !== ${r}`)}};cp.default=cj});var UR=R(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var si=D(),uj=H(),dj=Sc(),lj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,si._)`{allowedValues: ${t}}`},fj={keyword:"enum",schemaType:"array",$data:!0,error:lj,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,uj.useFunc)(e,dj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,si.or)(...o.map((h,m)=>f(p,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,si._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=o[h];return typeof m=="object"&&m!==null?(0,si._)`${u()}(${r}, ${p}[${h}])`:(0,si._)`${r} === ${m}`}}};up.default=fj});var qR=R(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var pj=TR(),hj=AR(),mj=IR(),gj=OR(),yj=zR(),vj=NR(),_j=DR(),Sj=jR(),wj=FR(),bj=UR(),Rj=[pj.default,hj.default,mj.default,gj.default,yj.default,vj.default,_j.default,Sj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wj.default,bj.default];dp.default=Rj});var fp=R(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.validateAdditionalItems=void 0;var Rn=D(),lp=H(),Pj={message:({params:{len:t}})=>(0,Rn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rn._)`{limit: ${t}}`},Cj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Pj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,lp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}HR(t,n)}};function HR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Rn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Rn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,lp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Rn._)`${a} <= ${e.length}`);r.if((0,Rn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:lp.Type.Num},u),i.allErrors||r.if((0,Rn.not)(u),()=>r.break())})}}ii.validateAdditionalItems=HR;ii.default=Cj});var pp=R(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.validateTuple=void 0;var GR=D(),wc=H(),xj=vt(),kj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ZR(t,"additionalItems",e);r.items=!0,!(0,wc.alwaysValidSchema)(r,e)&&t.ok((0,xj.validateArray)(t))}};function ZR(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=wc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,GR._)`${s}.length`);r.forEach((l,f)=>{(0,wc.alwaysValidSchema)(a,l)||(n.if((0,GR._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,wc.checkStrictMode)(a,y,f.strictTuples)}}}ai.validateTuple=ZR;ai.default=kj});var WR=R(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Ej=pp(),Tj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Ej.validateTuple)(t,"items")};hp.default=Tj});var VR=R(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var BR=D(),Aj=H(),$j=vt(),Mj=fp(),Ij={message:({params:{len:t}})=>(0,BR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,BR._)`{limit: ${t}}`},Oj={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,Aj.alwaysValidSchema)(n,e)&&(o?(0,Mj.validateAdditionalItems)(t,o):t.ok((0,$j.validateArray)(t)))}};mp.default=Oj});var KR=R(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var St=D(),bc=H(),zj={message:({params:{min:t,max:e}})=>e===void 0?(0,St.str)`must contain at least ${t} valid item(s)`:(0,St.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,St._)`{minContains: ${t}}`:(0,St._)`{minContains: ${t}, maxContains: ${e}}`},Nj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:zj,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,St._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,bc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,bc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,bc.alwaysValidSchema)(s,r)){let m=(0,St._)`${d} >= ${i}`;a!==void 0&&(m=(0,St._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?p(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,St._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:bc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,St._)`${m}++`),a===void 0?e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,St._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};gp.default=Nj});var XR=R(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.validateSchemaDeps=Bt.validatePropertyDeps=Bt.error=void 0;var yp=D(),Dj=H(),ci=vt();Bt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,yp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,yp._)`{property: ${t},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${e},
8
- deps: ${r}}`};var Tj={keyword:"dependencies",type:"object",schemaType:"object",error:Bt.error,code(t){let[e,r]=Aj(t);jR(t,e),FR(t,r)}};function Aj({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 jR(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,ti.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,ti.checkReportMissingProp)(t,u)}):(r.if((0,ap._)`${c} && (${(0,ti.checkMissingProp)(t,a,s)})`),(0,ti.reportMissingProp)(t,s),r.else())}}Bt.validatePropertyDeps=jR;function FR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Ej.alwaysValidSchema)(s,e[a])||(r.if((0,ti.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))}Bt.validateSchemaDeps=FR;Bt.default=Tj});var HR=R(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var qR=D(),$j=H(),Mj={message:"property name must be valid",params:({params:t})=>(0,qR._)`{propertyName: ${t.propertyName}}`},Ij={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Mj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,$j.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,qR.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};cp.default=Ij});var dp=R(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var yc=vt(),$t=D(),Oj=ar(),vc=H(),zj={message:"must NOT have additional properties",params:({params:t})=>(0,$t._)`{additionalProperty: ${t.additionalProperty}}`},Nj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:zj,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,vc.alwaysValidSchema)(i,r))return;let u=(0,yc.allSchemaProperties)(n.properties),d=(0,yc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,$t._)`${s} === ${Oj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let _;if(u.length>8){let b=(0,vc.schemaRefOrVal)(i,n.properties,"properties");_=(0,yc.isOwnProperty)(e,b,y)}else u.length?_=(0,$t.or)(...u.map(b=>(0,$t._)`${y} === ${b}`)):_=$t.nil;return d.length&&(_=(0,$t.or)(_,...d.map(b=>(0,$t._)`${(0,yc.usePattern)(t,b)}.test(${y})`))),(0,$t.not)(_)}function p(y){e.code((0,$t._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,vc.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(m(y,_,!1),e.if((0,$t.not)(_),()=>{t.reset(),p(y)})):(m(y,_),a||e.if((0,$t.not)(_),()=>e.break()))}}function m(y,_,b){let w={keyword:"additionalProperties",dataProp:y,dataPropType:vc.Type.Str};b===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,_)}}};up.default=Nj});var BR=R(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var Dj=Us(),GR=vt(),lp=H(),ZR=dp(),Lj={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&&ZR.default.code(new Dj.KeywordCxt(s,ZR.default,"additionalProperties"));let i=(0,GR.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=lp.mergeEvaluated.props(e,(0,lp.toHash)(i),s.props));let a=i.filter(l=>!(0,lp.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,GR.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)}}};fp.default=Lj});var JR=R(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var VR=vt(),_c=D(),WR=H(),KR=H(),jj={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,VR.allSchemaProperties)(r),c=a.filter(m=>(0,WR.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 _c.Name)&&(s.props=(0,KR.evaluatedPropsToName)(e,s.props));let{props:l}=s;f();function f(){for(let m of a)u&&p(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in u)new RegExp(m).test(y)&&(0,WR.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,_c._)`${(0,VR.usePattern)(t,m)}.test(${y})`,()=>{let _=c.includes(m);_||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:KR.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,_c._)`${l}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,_c.not)(d),()=>e.break())})})}}};pp.default=jj});var YR=R(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Fj=H(),Uj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Fj.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"}};hp.default=Uj});var XR=R(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var qj=vt(),Hj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:qj.validateUnion,error:{message:"must match a schema in anyOf"}};mp.default=Hj});var QR=R(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var Sc=D(),Gj=H(),Zj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Sc._)`{passingSchemas: ${t.passing}}`},Bj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Zj,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 f;(0,Gj.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Sc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Sc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),f&&t.mergeEvaluated(f,Sc.Name)})})}}};gp.default=Bj});var eP=R(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var Vj=H(),Wj={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,Vj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};yp.default=Wj});var nP=R(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var wc=D(),rP=H(),Kj={message:({params:t})=>(0,wc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,wc._)`{failingKeyword: ${t.ifClause}}`},Jj={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,rP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=tP(n,"then"),s=tP(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,wc.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 f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),l?e.assign(l,(0,wc._)`${d}`):t.setParams({ifClause:d})}}}};function tP(t,e){let r=t.schema[e];return r!==void 0&&!(0,rP.alwaysValidSchema)(t,r)}vp.default=Jj});var oP=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var Yj=H(),Xj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Yj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};_p.default=Xj});var sP=R(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});var Qj=rp(),e1=zR(),t1=np(),r1=DR(),n1=LR(),o1=UR(),s1=HR(),i1=dp(),a1=BR(),c1=JR(),u1=YR(),d1=XR(),l1=QR(),f1=eP(),p1=nP(),h1=oP();function m1(t=!1){let e=[u1.default,d1.default,l1.default,f1.default,p1.default,h1.default,s1.default,i1.default,o1.default,a1.default,c1.default];return t?e.push(e1.default,r1.default):e.push(Qj.default,t1.default),e.push(n1.default),e}Sp.default=m1});var iP=R(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});var _e=D(),g1={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},y1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:g1,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?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(_,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(_,m)),t.fail$data((0,_e.or)(b(),w()));function b(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${_}`}function w(){let k=d.$async?(0,_e._)`(${m}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,_e._)`${_}(${n})`,S=(0,_e._)`(typeof ${_} == "function" ? ${k} : ${_}.test(${n}))`;return(0,_e._)`${_} && ${_} !== true && ${y} === ${e} && !${S}`}}function p(){let h=l.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,_]=w(h);m===e&&t.pass(k());function b(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(S){let P=S instanceof RegExp?(0,_e.regexpCode)(S):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,I=r.scopeValue("formats",{key:s,ref:S,code:P});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,_e._)`${I}.validate`]:["string",S,I]}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 ${_}(${n})`}return typeof y=="function"?(0,_e._)`${_}(${n})`:(0,_e._)`${_}.test(${n})`}}}};wp.default=y1});var aP=R(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var v1=iP(),_1=[v1.default];bp.default=_1});var cP=R(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.contentVocabulary=yo.metadataVocabulary=void 0;yo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];yo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var dP=R(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var S1=yR(),w1=$R(),b1=sP(),R1=aP(),uP=cP(),P1=[S1.default,w1.default,(0,b1.default)(),R1.default,uP.metadataVocabulary,uP.contentVocabulary];Rp.default=P1});var fP=R(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.DiscrError=void 0;var lP;(function(t){t.Tag="tag",t.Mapping="mapping"})(lP||(bc.DiscrError=lP={}))});var hP=R(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var vo=D(),Pp=fP(),pP=nc(),C1=qs(),x1=H(),k1={message:({params:{discrError:t,tagName:e}})=>t===Pp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,vo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},E1={keyword:"discriminator",type:"object",schemaType:"object",error:k1,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,vo._)`${r}${(0,vo.getProperty)(a)}`);e.if((0,vo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Pp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,vo._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:Pp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,vo.Name),h}function f(){var p;let h={},m=_(o),y=!0;for(let k=0;k<i.length;k++){let S=i[k];if(S?.$ref&&!(0,x1.schemaHasRulesButRef)(S,s.self.RULES)){let I=S.$ref;if(S=pP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,I),S instanceof pP.SchemaEnv&&(S=S.schema),S===void 0)throw new C1.default(s.opts.uriResolver,s.baseId,I)}let P=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||_(S)),b(P,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function _({required:k}){return Array.isArray(k)&&k.includes(a)}function b(k,S){if(k.const)w(k.const,S);else if(k.enum)for(let P of k.enum)w(P,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(k,S){if(typeof k!="string"||k in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[k]=S}}}};Cp.default=E1});var mP=R((f5,T1)=>{T1.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 kp=R((le,xp)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var A1=lR(),$1=dP(),M1=hP(),gP=mP(),I1=["/properties"],Rc="http://json-schema.org/draft-07/schema",_o=class extends A1.default{_addVocabularies(){super._addVocabularies(),$1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(M1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(gP,I1):gP;this.addMetaSchema(e,Rc,!1),this.refs["http://json-schema.org/schema"]=Rc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Rc)?Rc:void 0)}};le.Ajv=_o;xp.exports=le=_o;xp.exports.Ajv=_o;Object.defineProperty(le,"__esModule",{value:!0});le.default=_o;var O1=Us();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return O1.KeywordCxt}});var So=D();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return So._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return So.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return So.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return So.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return So.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return So.CodeGen}});var z1=tc();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return z1.default}});var N1=qs();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return N1.default}})});var PP=R(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.formatNames=Wt.fastFormats=Wt.fullFormats=void 0;function Vt(t,e){return{validate:t,compare:e}}Wt.fullFormats={date:Vt(SP,$p),time:Vt(Tp(!0),Mp),"date-time":Vt(yP(!0),bP),"iso-time":Vt(Tp(),wP),"iso-date-time":Vt(yP(),RP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:q1,"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:H1,int32:{type:"number",validate:B1},int64:{type:"number",validate:V1},float:{type:"number",validate:_P},double:{type:"number",validate:_P},password:!0,binary:!0};Wt.fastFormats={...Wt.fullFormats,date:Vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,$p),time:Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Mp),"date-time":Vt(/^\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,bP),"iso-time":Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,wP),"iso-date-time":Vt(/^\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,RP),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};Wt.formatNames=Object.keys(Wt.fullFormats);function D1(t){return t%4===0&&(t%100!==0||t%400===0)}var L1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,j1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function SP(t){let e=L1.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&&D1(r)?29:j1[n])}function $p(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ep=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Tp(t){return function(r){let n=Ep.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,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&i<61}}function Mp(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 wP(t,e){if(!(t&&e))return;let r=Ep.exec(t),n=Ep.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 Ap=/t|\s/i;function yP(t){let e=Tp(t);return function(n){let o=n.split(Ap);return o.length===2&&SP(o[0])&&e(o[1])}}function bP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function RP(t,e){if(!(t&&e))return;let[r,n]=t.split(Ap),[o,s]=e.split(Ap),i=$p(r,o);if(i!==void 0)return i||Mp(n,s)}var F1=/\/|:/,U1=/^(?:[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 q1(t){return F1.test(t)&&U1.test(t)}var vP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function H1(t){return vP.lastIndex=0,vP.test(t)}var G1=-(2**31),Z1=2**31-1;function B1(t){return Number.isInteger(t)&&t<=Z1&&t>=G1}function V1(t){return Number.isInteger(t)}function _P(){return!0}var W1=/[^\\]\\Z/;function K1(t){if(W1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var CP=R(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.formatLimitDefinition=void 0;var J1=kp(),Mt=D(),Lr=Mt.operators,Pc={formatMaximum:{okStr:"<=",ok:Lr.LTE,fail:Lr.GT},formatMinimum:{okStr:">=",ok:Lr.GTE,fail:Lr.LT},formatExclusiveMaximum:{okStr:"<",ok:Lr.LT,fail:Lr.GTE},formatExclusiveMinimum:{okStr:">",ok:Lr.GT,fail:Lr.LTE}},Y1={message:({keyword:t,schemaCode:e})=>(0,Mt.str)`should be ${Pc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Mt._)`{comparison: ${Pc[t].okStr}, limit: ${e}}`};wo.formatLimitDefinition={keyword:Object.keys(Pc),type:"string",schemaType:"string",$data:!0,error:Y1,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 J1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Mt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Mt.or)((0,Mt._)`typeof ${p} != "object"`,(0,Mt._)`${p} instanceof RegExp`,(0,Mt._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:i.code.formats?(0,Mt._)`${i.code.formats}${(0,Mt.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,Mt._)`${f}.compare(${r}, ${n}) ${Pc[o].fail} 0`}},dependencies:["format"]};var X1=t=>(t.addKeyword(wo.formatLimitDefinition),t);wo.default=X1});var TP=R((ri,EP)=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var bo=PP(),Q1=CP(),Ip=D(),xP=new Ip.Name("fullFormats"),eF=new Ip.Name("fastFormats"),Op=(t,e={keywords:!0})=>{if(Array.isArray(e))return kP(t,e,bo.fullFormats,xP),t;let[r,n]=e.mode==="fast"?[bo.fastFormats,eF]:[bo.fullFormats,xP],o=e.formats||bo.formatNames;return kP(t,o,r,n),e.keywords&&(0,Q1.default)(t),t};Op.get=(t,e="full")=>{let n=(e==="fast"?bo.fastFormats:bo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function kP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ip._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}EP.exports=ri=Op;Object.defineProperty(ri,"__esModule",{value:!0});ri.default=Op});var oC=R((W5,nC)=>{nC.exports=rC;rC.sync=MF;var eC=pr("fs");function $F(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 tC(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:$F(e,r)}function rC(t,e,r){eC.stat(t,function(n,o){r(n,n?!1:tC(o,t,e))})}function MF(t,e){return tC(eC.statSync(t),t,e)}});var uC=R((K5,cC)=>{cC.exports=iC;iC.sync=IF;var sC=pr("fs");function iC(t,e,r){sC.stat(t,function(n,o){r(n,n?!1:aC(o,e))})}function IF(t,e){return aC(sC.statSync(t),e)}function aC(t,e){return t.isFile()&&OF(t,e)}function OF(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 lC=R((Y5,dC)=>{var J5=pr("fs"),zc;process.platform==="win32"||global.TESTING_WINDOWS?zc=oC():zc=uC();dC.exports=Qp;Qp.sync=zF;function Qp(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){Qp(t,e||{},function(s,i){s?o(s):n(i)})})}zc(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function zF(t,e){try{return zc.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var vC=R((X5,yC)=>{var Ao=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",fC=pr("path"),NF=Ao?";":":",pC=lC(),hC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),mC=(t,e)=>{let r=e.colon||NF,n=t.match(/\//)||Ao&&t.match(/\\/)?[""]:[...Ao?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Ao?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Ao?o.split(r):[""];return Ao&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},gC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=mC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(hC(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=fC.join(p,t),m=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];pC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},DF=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=mC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=fC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if(pC.sync(f,{pathExt:o}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw hC(t)};yC.exports=gC;gC.sync=DF});var SC=R((Q5,eh)=>{"use strict";var _C=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};eh.exports=_C;eh.exports.default=_C});var PC=R((e3,RC)=>{"use strict";var wC=pr("path"),LF=vC(),jF=SC();function bC(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=LF.sync(t.command,{path:r[jF({env:r})],pathExt:e?wC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=wC.resolve(o?t.options.cwd:"",i)),i}function FF(t){return bC(t)||bC(t,!0)}RC.exports=FF});var CC=R((t3,rh)=>{"use strict";var th=/([()\][%!^"`<>&|;, *?])/g;function UF(t){return t=t.replace(th,"^$1"),t}function qF(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(th,"^$1"),e&&(t=t.replace(th,"^$1")),t}rh.exports.command=UF;rh.exports.argument=qF});var kC=R((r3,xC)=>{"use strict";xC.exports=/^#!(.*)/});var TC=R((n3,EC)=>{"use strict";var HF=kC();EC.exports=(t="")=>{let e=t.match(HF);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((o3,AC)=>{"use strict";var nh=pr("fs"),GF=TC();function ZF(t){let r=Buffer.alloc(150),n;try{n=nh.openSync(t,"r"),nh.readSync(n,r,0,150,0),nh.closeSync(n)}catch{}return GF(r.toString())}AC.exports=ZF});var zC=R((s3,OC)=>{"use strict";var BF=pr("path"),MC=PC(),IC=CC(),VF=$C(),WF=process.platform==="win32",KF=/\.(?:com|exe)$/i,JF=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function YF(t){t.file=MC(t);let e=t.file&&VF(t.file);return e?(t.args.unshift(t.file),t.command=e,MC(t)):t.file}function XF(t){if(!WF)return t;let e=YF(t),r=!KF.test(e);if(t.options.forceShell||r){let n=JF.test(e);t.command=BF.normalize(t.command),t.command=IC.command(t.command),t.args=t.args.map(s=>IC.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 QF(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:XF(n)}OC.exports=QF});var LC=R((i3,DC)=>{"use strict";var oh=process.platform==="win32";function sh(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 eU(t,e){if(!oh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=NC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function NC(t,e){return oh&&t===1&&!e.file?sh(e.original,"spawn"):null}function tU(t,e){return oh&&t===1&&!e.file?sh(e.original,"spawnSync"):null}DC.exports={hookChildProcess:eU,verifyENOENT:NC,verifyENOENTSync:tU,notFoundError:sh}});var UC=R((a3,$o)=>{"use strict";var jC=pr("child_process"),ih=zC(),ah=LC();function FC(t,e,r){let n=ih(t,e,r),o=jC.spawn(n.command,n.args,n.options);return ah.hookChildProcess(o,n),o}function rU(t,e,r){let n=ih(t,e,r),o=jC.spawnSync(n.command,n.args,n.options);return o.error=o.error||ah.verifyENOENTSync(o.status,n),o}$o.exports=FC;$o.exports.spawn=FC;$o.exports.sync=rU;$o.exports._parse=ih;$o.exports._enoent=ah});var VC=R(uh=>{"use strict";var GC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,aU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,ZC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,cU=/\\([\u000b\u0020-\u00ff])/g,uU=/([\\"])/g,BC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;uh.format=dU;uh.parse=lU;function dU(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!BC.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],!ZC.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+pU(e[o])}return n}function lU(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?fU(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(!BC.test(n))throw new TypeError("invalid media type");var o=new hU(n.toLowerCase());if(r!==-1){var s,i,a;for(GC.lastIndex=r;i=GC.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(cU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function fU(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 pU(t){var e=String(t);if(ZC.test(e))return e;if(e.length>0&&!aU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(uU,"\\$1")+'"'}function hU(t){this.parameters=Object.create(null),this.type=t}});import{logger as TZ}from"@hermes/logger";import{logger as Oq}from"@hermes/logger";var bE="mcp-auth";function Ne(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(bE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as uq}from"@augmentcode/auggie-v2";import{logger as dq}from"@hermes/logger";import{logger as VE}from"@hermes/logger";import{logger as PE}from"@hermes/logger";function RE(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 hr(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":RE(t,e,r)?"plugin":"local"}function CE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var Qh=PE.child({prefix:"pi-mcp"}),xE="augment:mcp-status-report";function Yt(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 No(t,e,r,n){let o=Yt(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=Yt(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 kE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=Yt(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 EE(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 em="authentication required",TE="Authentication refresh is pending in the backend; retry shortly.",AE="timed out connecting after 30s",$E="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",ME="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",IE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",OE="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",zE="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function NE(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),s=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),i=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=i(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?ME:$E,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=i(a);s.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...DE({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}}function DE(t){let{state:e,id:r,name:n,reportedNames:o}=t;return e.authFallbackDisplacedConfigIds.has(r)?{errorMessage:zE,failureCategory:"auth_terminal"}:{errorMessage:o.has(n)?OE:IE,failureCategory:"configuration"}}function LE(t,e){return e!==void 0?e.isAuthError?em:e.error:t.status==="initializing"?AE:t.lastError??(t.status==="auth_required"?em:void 0)}function jE(t,e){let r=EE(t);if(r===void 0)return;let n=kE(e,t.name),o=r==="connected"?CE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:hr(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"?TE:LE(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 FE(t){let e=[];for(let r of t.servers.values()){let n=jE(r,t);n!==void 0&&e.push(n)}return NE(t,e),e}function J(t,e){try{let r=FE(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(xE,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 $i={local:4,registry:3,plugin:2,vfs:1};function Dt(t){return t.hostLeases??=new Map,t.hostLeases}function UE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Do(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Lo(t,e){return t.kind===e.kind&&t.identity===e.identity}function tm(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 lu(t,e){let r=UE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Mi(t,e,r){if(r.kind==="registry"){Do(t).set(e,{kind:"domain",domain:r.identity});return}Do(t).set(e,{kind:"blocked"})}function fu(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 In(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=Dt(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?In(i,s):{kind:s??"local",identity:e},c={owner:a,revision:lu(t,e),host:r};return n.set(e,c),Mi(t,e,a),c}function rm(t){let{state:e,name:r,host:n}=t,o=Dt(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:lu(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 jo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Dt(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=$i[n.kind]>$i[a.owner.kind],f=$i[n.kind]===$i[a.owner.kind],p=o===a.revision&&(s===void 0||s===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?tm(a):void 0;fu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:lu(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 pu(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=Dt(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Do(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=Dt(e).get(r);return!i||i.revision!==o||!Lo(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 Rt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Dt(e).get(r);if(!i||i.revision!==o||!Lo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=tm(i);if(a)return fu(e,r,s),i.host=void 0,i.retirement=a,a}function nm(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Dt(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Lo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Lo(i.owner,n)||i.revision!==o.incumbent.revision?(Mi(e,r,i.owner),!0):(s.delete(r),Do(e).set(r,{kind:"blocked"}),!0))}function Pe(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Dt(e),a=i.get(r);return!a||a.revision!==o||!Lo(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(fu(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),Do(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return Dt(t).get(e)}function om(t,e,r){return Dt(t).get(e)?.host===r}function Fo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function mr(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 hu(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function qE(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 HE(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 sm(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!hu(e,r):n!==void 0&&e!==n}function im(t,e,r){return r&&e!==void 0&&t!==void 0&&hu(t,e)}function GE(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!hu(s,n))}function am(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(HE({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||sm({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&sm({identity:i.domain,...l})?!0:GE({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function ZE(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return mr(r);if(n!==void 0)return{id:n,name:e}}function BE(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!mr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function cm(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=qE({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}`,f=am({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}),p=im(s,u,d),h=im(i,u,d),m=!f,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,b=f&&!(m||p||h||y);if(o==="durable"){let P=ZE({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:b})}let w=am({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&&!w,S=!1;return t.equalRevisionRebindDomains?.delete(e),(k||p)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),S=!0),(k||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),S=!0),k&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),BE({state:t,name:e,mode:o,stillOwnsNameScopedRevision:k,retiredConfig:c}),S&&(Fo(t,e),ot(t,e),t.authRefreshNeededReportKeys?.delete(e)),k}function dt(t,e,r,n){return cm(t,e,r,n,"durable")}function Uo(t,e,r,n){return cm(t,e,r,n,"session")}function um(t){let e=t.credential_owner_domain??t.credentialOwnerDomain;return typeof e=="string"&&/^user:.+/.test(e)?e:void 0}function gr(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 dm="augment:mcp-oauth-credentials",lm=300*1e3,WE=256,mu=VE.child({prefix:"pi-mcp"}),Pt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function st(t){return`user:${t}`}function Gr(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||gr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function On(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 Zr(t){return t.ownerDomain??On(t.domain)}function fm(t,e,r){let n=st(e);return r!==void 0?r===n:it(t)||On(t)===n}function KE(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function JE(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 YE(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function XE(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&KE(t.credentialRevisions.get(e),r.credentialRevision)&&YE(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function QE(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 eT(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 Br(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 yr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function pm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=lm&&yr(t,n)}function tT(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&yr(t,e)}function hm(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Br(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();pm(e,a);let c=Zr(n),u=it(c)?`${c}\0${r}`:c,d=i.get(u),l=d?.credential.credential_revision??d?.credential.credentialRevision;if(typeof l=="string"&&gr(n.revision,l)<=0)return;!d&&i.size>=WE&&tT(e),yr(e,u);let f={serverName:r,credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(u,f),f.expiryTimer=setTimeout(()=>{i.get(u)===f&&yr(e,u)},lm),f.expiryTimer.unref?.(),mu.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function rT(t,e){Br(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;Br(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||yr(e,r)}}function Oi(t){let{state:e,domain:r,forceNew:n=!1}=t;Br(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:rT(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 mm(t,e){Br(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)&&yr(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);Oi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function nT(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;Br(e);let n=st(r.id),o=QE(r),s=eT({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),oT({state:e,config:r,domain:n}),{domain:n,...i}}function gm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Br(e);let s=Zr(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:gr(r.revision,a),f=l===0;l!==void 0&&l<0||f&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&gr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:f})}function oT(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)&&On(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 sT(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(dm,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function iT(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();pm(e,o);let s=e.bootOAuthCredentialBuffer?.get(r);if(s)return yr(e,r),s;for(let[i,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&it(i.split("\0",1)[0]))return yr(e,i),a}function aT(t){let{config:e,pi:r,buffered:n}=t;mu.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),mu.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(dm,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function cT(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(Be(n,r)){if(n.name===r.name)return;await Uo(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 dt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function uT(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=XE(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 Pt(a)}async function dT(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 cT({state:e,config:r,previousConfig:s})}catch(h){throw uT({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 f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),sT({state:e,config:r,pi:n,intent:o});let p=iT({state:e,domain:o.domain,serverName:r.name});return Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&aT({config:r,pi:n,buffered:p}),!0}function vr(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=nT({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=JE(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 dT({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 ym}from"node:os";import{sep as lT}from"node:path";var gu=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},fT=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,pT=/\\\$\{/g,hT=new Set(["workspaceFolder","augmentToken"]),vm="${workspaceFolder}";function _m(t,e){return t.includes(vm)?t.split(vm).join(e):t}function Sm(t,e){return t.includes("${")?t.replace(fT,(n,o,s)=>{if(hT.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new gu(o)}).replace(pT,"${"):t}function mT(t){return t.startsWith("~")?t==="~"?ym():t.startsWith("~/")||t.startsWith(`~${lT}`)?ym()+t.slice(1):t:t}function yu(t,e,r){return mT(Sm(_m(t,e),r))}function zi(t,e,r){return Sm(_m(t,e),r)}function wm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=zi(s,e,r);return n}var gT="$augment-";function yT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(gT)?s:zi(s,e,r);return n}function Lt(t,e){let r=process.env;return{...t,url:zi(t.url,e,r),headers:yT(t.headers,e,r)}}function jt(t,e){let r=process.env;return{...t,command:yu(t.command,e,r),args:t.args,env:t.env?wm(t.env,e,r):void 0,cwd:t.cwd?yu(t.cwd,e,r):e}}import{readFileSync as wT}from"node:fs";import{logger as vT}from"@hermes/logger";var _T=vT.child({prefix:"pi-mcp"}),Ct=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function zn(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 ST(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 Nn(t,e){let r=zn(e);if(!r)throw new Ct(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Ct(`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 Ct(`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&&_T.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:ST(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var Pm=t=>wT(t,"utf8");function Ni(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bm(t){return Ni(t)&&("command"in t||"url"in t)}function _u(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function Rm(t,e){return _u(t.name)??e}function vu(t,e){let r=zn(t);if(r==="http"||r==="sse")return _u(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return _u(t.name,t.title,n)??e}function bT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[vu(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[vu(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[Rm(i,o),i]})}if(bm(t)){let r=t;return[[vu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(bm))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[Rm(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 Su(t){return t instanceof Error?t.message:String(t)}function RT(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}": ${Su(s)}`});return}}function PT(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=RT(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}: ${Su(c)}`}),[]}try{return bT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${Su(c)}`}),[]}}function wu(t,e=Pm){let r={},n=[];for(let o of t)for(let[s,i]of PT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function bu(t,e=Pm){return!t||t.length===0?new Set:new Set(Object.keys(wu(t,e).servers))}var xT=["global","project","local","managed"];function kT(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 ET(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 TT(t,e,r){let n=wu(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 AT(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 ET(xT.map(o=>kT(n,o)))}function Dn(t,e,r,n){let o=[],s=r&&r.length>0?TT(r,n,o):AT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Nn(a,c);i.push(u.type==="stdio"?jt(u,t):Lt(u,t))}catch(u){let d=u instanceof Ct?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 qT}from"@hermes/logger";import{Type as HT}from"@sinclair/typebox";var Ln=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 $T(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 IT(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&$T(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 OT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.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&&IT(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 qo(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 zT(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 Cm(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()?zT({state:e,configId:r,generation:n}):Cm({state:e,configId:r,generation:n}),i),i=>{throw Cm({state:e,configId:r,generation:n}),i})}function ee(){let t=globalThis;if(t[Di])return OT(t[Di]),t[Di];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Ln,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,authFallbackDisplacedConfigIds: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 xm=Symbol.for("__hermes_mcp_tool_registry__"),NT=Symbol.for("__hermes_mcp_extension_factory__");function km(){let t=globalThis;return t[xm]??=new Map,t[xm]}function _r(t){km().set(t.name,t)}function Em(t,e){let r=km();(e===void 0||r.get(t)===e)&&r.delete(t)}function Tm(t){Reflect.set(t,NT,!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 DT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function LT(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 jT(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
- `).trim()}function Ru(t,e,r){if(t.isError){let o=jT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=LT(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 Am(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=DT(t.params),o=await e.callTool(r,n,t.signal);return Ru(o,t.serverName,r)}var FT=/[^a-zA-Z0-9_-]/g;function Pu(t){return t.replace(FT,"_")}function UT(t,e){let r=Pu(e),n=Pu(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var Sr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=UT(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=`_${Pu(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Cu=qT.child({prefix:"pi-mcp"});function Ui(){return ee().toolRegistrationsByPi}function Mm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=HT.Unsafe(n.inputSchema??{})}catch(c){Cu.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>ee().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,f)=>Am({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(p=>p.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function xu(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),Em(n,s),r.definitionsByName?.delete(n),GT(t,e,n,r,o)}function GT(t,e,r,n,o){let s=ee();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 Sr(i);for(let d of c.listTools()){let{namespaced:l,collision:f}=u.put(d.name);if(f||l!==r)continue;let p=Mm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!p)return;$m(r,"mcp"),t.registerTool(p),_r(p),a.definitionsByName??=new Map,a.definitionsByName.set(r,p),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function ZT(t,e){let r=Ui(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=ee().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)xu(t,n,s,a);let i={generation:o,host:e,map:new Sr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function ku(t,e){let{registration:r,replaced:n}=ZT(t,e),o=new Set(r.registeredNames),s=new Sr(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:f}=s.put(d.name);if(f){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=ee();y.diagnostics.some(b=>b.server===i&&b.message.includes(`both map to "${l}"`))||(Cu.warn(m),y.diagnostics.push({server:i,message:m}));continue}let p=Mm({pi:t,serverName:i,tool:d,map:s,namespaced:l});p&&($m(l,"mcp"),t.registerTool(p),_r(p),r.definitionsByName??=new Map,r.definitionsByName.set(l,p),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&&xu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Cu.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Eu(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)xu(t,n,o,s);return n.byServer.delete(e.name),!0}function Im(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&ku(t,r)}import{getToolSource as rA}from"@augmentcode/auggie-v2";import{Type as BT}from"@sinclair/typebox";var VT="cliMcpToolSearchAutoEnable",WT="cliMcpToolSearchTokenThreshold",KT=!1,Om=2e4;function JT(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function YT(t){let e=0;for(let r of t.servers.values())e+=XT(r);return e}function XT(t){if(t.status!=="success")return 0;let e=new Sr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||QT(n.inputSchema)&&(r+=JT(n))}return r}function QT(t){try{return BT.Unsafe(t??{}),!0}catch{return!1}}function eA(t){let r=t.featureFlags?.flags?.[VT];return typeof r=="boolean"?r:KT}function tA(t){let r=t.featureFlags?.flags?.[WT];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:Om}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:Om}function zm(t){return eA(t)?YT(t)>=tA(t):!1}var nA="AUGGIE_ENABLE_TOOL_SEARCH",oA=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Ho(){return process.env[nA]==="1"}function jn(t){return Ho()||t.toolSearchLatched?!0:zm(t)?(t.toolSearchLatched=!0,!0):!1}function qi(t){let e=t.getActiveTools(),r=e.filter(n=>!sA(n)||oA.has(n));r.length!==e.length&&t.setActiveTools(r)}function sA(t){return rA(t)==="mcp"}import{setToolSource as Hm}from"@augmentcode/auggie-v2";import{logger as CA}from"@hermes/logger";import{Type as Gm}from"@sinclair/typebox";import{logger as iA}from"@hermes/logger";var Go={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Vr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Nm=iA.child({prefix:"pi-mcp"}),aA=5e3,cA=1,uA=2,dA=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),lA=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function fA(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 pA(t){return t===cA||typeof t=="string"&&dA.has(t)?"available":t===uA||typeof t=="string"&&lA.has(t)?"opt_in_required":"unknown"}function hA(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:fA(t.auth_type),state:pA(t.state)}}function Tu(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 Wr(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Tu(t,r))}async function Dm(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:Vr.UNSPECIFIED}),signal:AbortSignal.timeout(r??aA)});if(!s.ok)return Nm.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=hA(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Nm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var mA="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",gA=`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:Bt.error,code(t){let[e,r]=jj(t);JR(t,e),YR(t,r)}};function jj({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 JR(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,ci.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,ci.checkReportMissingProp)(t,u)}):(r.if((0,yp._)`${c} && (${(0,ci.checkMissingProp)(t,a,s)})`),(0,ci.reportMissingProp)(t,s),r.else())}}Bt.validatePropertyDeps=JR;function YR(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,ci.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))}Bt.validateSchemaDeps=YR;Bt.default=Lj});var eP=R(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var QR=D(),Fj=H(),Uj={message:"property name must be valid",params:({params:t})=>(0,QR._)`{propertyName: ${t.propertyName}}`},qj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Uj,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,QR.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};vp.default=qj});var Sp=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var Rc=vt(),$t=D(),Hj=cr(),Pc=H(),Gj={message:"must NOT have additional properties",params:({params:t})=>(0,$t._)`{additionalProperty: ${t.additionalProperty}}`},Zj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Gj,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,Pc.alwaysValidSchema)(i,r))return;let u=(0,Rc.allSchemaProperties)(n.properties),d=(0,Rc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,$t._)`${s} === ${Hj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(u.length>8){let b=(0,Pc.schemaRefOrVal)(i,n.properties,"properties");v=(0,Rc.isOwnProperty)(e,b,y)}else u.length?v=(0,$t.or)(...u.map(b=>(0,$t._)`${y} === ${b}`)):v=$t.nil;return d.length&&(v=(0,$t.or)(v,...d.map(b=>(0,$t._)`${(0,Rc.usePattern)(t,b)}.test(${y})`))),(0,$t.not)(v)}function p(y){e.code((0,$t._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Pc.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,$t.not)(v),()=>{t.reset(),p(y)})):(m(y,v),a||e.if((0,$t.not)(v),()=>e.break()))}}function m(y,v,b){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Pc.Type.Str};b===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,v)}}};_p.default=Zj});var nP=R(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var Wj=Vs(),tP=vt(),wp=H(),rP=Sp(),Bj={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&&rP.default.code(new Wj.KeywordCxt(s,rP.default,"additionalProperties"));let i=(0,tP.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=wp.mergeEvaluated.props(e,(0,wp.toHash)(i),s.props));let a=i.filter(l=>!(0,wp.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,tP.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)}}};bp.default=Bj});var aP=R(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var oP=vt(),Cc=D(),sP=H(),iP=H(),Vj={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,oP.allSchemaProperties)(r),c=a.filter(m=>(0,sP.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 Cc.Name)&&(s.props=(0,iP.evaluatedPropsToName)(e,s.props));let{props:l}=s;f();function f(){for(let m of a)u&&p(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in u)new RegExp(m).test(y)&&(0,sP.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,Cc._)`${(0,oP.usePattern)(t,m)}.test(${y})`,()=>{let v=c.includes(m);v||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:iP.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,Cc._)`${l}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Cc.not)(d),()=>e.break())})})}}};Rp.default=Vj});var cP=R(Pp=>{"use strict";Object.defineProperty(Pp,"__esModule",{value:!0});var Kj=H(),Jj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Kj.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"}};Pp.default=Jj});var uP=R(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});var Yj=vt(),Xj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Yj.validateUnion,error:{message:"must match a schema in anyOf"}};Cp.default=Xj});var dP=R(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var xc=D(),Qj=H(),e1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,xc._)`{passingSchemas: ${t.passing}}`},t1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:e1,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 f;(0,Qj.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,xc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,xc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),f&&t.mergeEvaluated(f,xc.Name)})})}}};xp.default=t1});var lP=R(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var r1=H(),n1={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,r1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};kp.default=n1});var hP=R(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var kc=D(),pP=H(),o1={message:({params:t})=>(0,kc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,kc._)`{failingKeyword: ${t.ifClause}}`},s1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:o1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,pP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=fP(n,"then"),s=fP(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,kc.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 f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),l?e.assign(l,(0,kc._)`${d}`):t.setParams({ifClause:d})}}}};function fP(t,e){let r=t.schema[e];return r!==void 0&&!(0,pP.alwaysValidSchema)(t,r)}Ep.default=s1});var mP=R(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var i1=H(),a1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,i1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Tp.default=a1});var gP=R(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var c1=fp(),u1=WR(),d1=pp(),l1=VR(),f1=KR(),p1=XR(),h1=eP(),m1=Sp(),g1=nP(),y1=aP(),v1=cP(),_1=uP(),S1=dP(),w1=lP(),b1=hP(),R1=mP();function P1(t=!1){let e=[v1.default,_1.default,S1.default,w1.default,b1.default,R1.default,h1.default,m1.default,p1.default,g1.default,y1.default];return t?e.push(u1.default,l1.default):e.push(c1.default,d1.default),e.push(f1.default),e}Ap.default=P1});var yP=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var _e=D(),C1={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},x1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:C1,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?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(v,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(v,m)),t.fail$data((0,_e.or)(b(),w()));function b(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${v}`}function w(){let x=d.$async?(0,_e._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,_e._)`${v}(${n})`,S=(0,_e._)`(typeof ${v} == "function" ? ${x} : ${v}.test(${n}))`;return(0,_e._)`${v} && ${v} !== true && ${y} === ${e} && !${S}`}}function p(){let h=l.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,v]=w(h);m===e&&t.pass(x());function b(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(S){let P=S instanceof RegExp?(0,_e.regexpCode)(S):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,I=r.scopeValue("formats",{key:s,ref:S,code:P});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,_e._)`${I}.validate`]:["string",S,I]}function x(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${v}(${n})`}return typeof y=="function"?(0,_e._)`${v}(${n})`:(0,_e._)`${v}.test(${n})`}}}};$p.default=x1});var vP=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var k1=yP(),E1=[k1.default];Mp.default=E1});var _P=R(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.contentVocabulary=Ro.metadataVocabulary=void 0;Ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var wP=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var T1=ER(),A1=qR(),$1=gP(),M1=vP(),SP=_P(),I1=[T1.default,A1.default,(0,$1.default)(),M1.default,SP.metadataVocabulary,SP.contentVocabulary];Ip.default=I1});var RP=R(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.DiscrError=void 0;var bP;(function(t){t.Tag="tag",t.Mapping="mapping"})(bP||(Ec.DiscrError=bP={}))});var CP=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var Po=D(),Op=RP(),PP=uc(),O1=Ks(),z1=H(),N1={message:({params:{discrError:t,tagName:e}})=>t===Op.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}}`},D1={keyword:"discriminator",type:"object",schemaType:"object",error:N1,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:Op.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Po._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:Op.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,Po.Name),h}function f(){var p;let h={},m=v(o),y=!0;for(let x=0;x<i.length;x++){let S=i[x];if(S?.$ref&&!(0,z1.schemaHasRulesButRef)(S,s.self.RULES)){let I=S.$ref;if(S=PP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,I),S instanceof PP.SchemaEnv&&(S=S.schema),S===void 0)throw new O1.default(s.opts.uriResolver,s.baseId,I)}let P=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||v(S)),b(P,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:x}){return Array.isArray(x)&&x.includes(a)}function b(x,S){if(x.const)w(x.const,S);else if(x.enum)for(let P of x.enum)w(P,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(x,S){if(typeof x!="string"||x in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[x]=S}}}};zp.default=D1});var xP=R((P5,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 Dp=R((le,Np)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var j1=bR(),F1=wP(),U1=CP(),kP=xP(),q1=["/properties"],Tc="http://json-schema.org/draft-07/schema",Co=class extends j1.default{_addVocabularies(){super._addVocabularies(),F1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(U1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kP,q1):kP;this.addMetaSchema(e,Tc,!1),this.refs["http://json-schema.org/schema"]=Tc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Tc)?Tc:void 0)}};le.Ajv=Co;Np.exports=le=Co;Np.exports.Ajv=Co;Object.defineProperty(le,"__esModule",{value:!0});le.default=Co;var H1=Vs();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return H1.KeywordCxt}});var xo=D();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return xo._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return xo.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return xo.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return xo.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return xo.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return xo.CodeGen}});var G1=ac();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return G1.default}});var Z1=Ks();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Z1.default}})});var zP=R(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.formatNames=Kt.fastFormats=Kt.fullFormats=void 0;function Vt(t,e){return{validate:t,compare:e}}Kt.fullFormats={date:Vt($P,Up),time:Vt(jp(!0),qp),"date-time":Vt(EP(!0),IP),"iso-time":Vt(jp(),MP),"iso-date-time":Vt(EP(),OP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Y1,"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:oF,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:X1,int32:{type:"number",validate:tF},int64:{type:"number",validate:rF},float:{type:"number",validate:AP},double:{type:"number",validate:AP},password:!0,binary:!0};Kt.fastFormats={...Kt.fullFormats,date:Vt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Up),time:Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,qp),"date-time":Vt(/^\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,IP),"iso-time":Vt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,MP),"iso-date-time":Vt(/^\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,OP),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};Kt.formatNames=Object.keys(Kt.fullFormats);function W1(t){return t%4===0&&(t%100!==0||t%400===0)}var B1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,V1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function $P(t){let e=B1.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&&W1(r)?29:V1[n])}function Up(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Lp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function jp(t){return function(r){let n=Lp.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,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&i<61}}function qp(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 MP(t,e){if(!(t&&e))return;let r=Lp.exec(t),n=Lp.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 Fp=/t|\s/i;function EP(t){let e=jp(t);return function(n){let o=n.split(Fp);return o.length===2&&$P(o[0])&&e(o[1])}}function IP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function OP(t,e){if(!(t&&e))return;let[r,n]=t.split(Fp),[o,s]=e.split(Fp),i=Up(r,o);if(i!==void 0)return i||qp(n,s)}var K1=/\/|:/,J1=/^(?:[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 Y1(t){return K1.test(t)&&J1.test(t)}var TP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function X1(t){return TP.lastIndex=0,TP.test(t)}var Q1=-(2**31),eF=2**31-1;function tF(t){return Number.isInteger(t)&&t<=eF&&t>=Q1}function rF(t){return Number.isInteger(t)}function AP(){return!0}var nF=/[^\\]\\Z/;function oF(t){if(nF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var NP=R(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.formatLimitDefinition=void 0;var sF=Dp(),Mt=D(),Ur=Mt.operators,Ac={formatMaximum:{okStr:"<=",ok:Ur.LTE,fail:Ur.GT},formatMinimum:{okStr:">=",ok:Ur.GTE,fail:Ur.LT},formatExclusiveMaximum:{okStr:"<",ok:Ur.LT,fail:Ur.GTE},formatExclusiveMinimum:{okStr:">",ok:Ur.GT,fail:Ur.LTE}},iF={message:({keyword:t,schemaCode:e})=>(0,Mt.str)`should be ${Ac[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Mt._)`{comparison: ${Ac[t].okStr}, limit: ${e}}`};ko.formatLimitDefinition={keyword:Object.keys(Ac),type:"string",schemaType:"string",$data:!0,error:iF,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 sF.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,Mt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Mt.or)((0,Mt._)`typeof ${p} != "object"`,(0,Mt._)`${p} instanceof RegExp`,(0,Mt._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:i.code.formats?(0,Mt._)`${i.code.formats}${(0,Mt.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,Mt._)`${f}.compare(${r}, ${n}) ${Ac[o].fail} 0`}},dependencies:["format"]};var aF=t=>(t.addKeyword(ko.formatLimitDefinition),t);ko.default=aF});var FP=R((ui,jP)=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});var Eo=zP(),cF=NP(),Hp=D(),DP=new Hp.Name("fullFormats"),uF=new Hp.Name("fastFormats"),Gp=(t,e={keywords:!0})=>{if(Array.isArray(e))return LP(t,e,Eo.fullFormats,DP),t;let[r,n]=e.mode==="fast"?[Eo.fastFormats,uF]:[Eo.fullFormats,DP],o=e.formats||Eo.formatNames;return LP(t,o,r,n),e.keywords&&(0,cF.default)(t),t};Gp.get=(t,e="full")=>{let n=(e==="fast"?Eo.fastFormats:Eo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function LP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Hp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}jP.exports=ui=Gp;Object.defineProperty(ui,"__esModule",{value:!0});ui.default=Gp});var mC=R((i3,hC)=>{hC.exports=pC;pC.sync=UF;var lC=mr("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 fC(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:FF(e,r)}function pC(t,e,r){lC.stat(t,function(n,o){r(n,n?!1:fC(o,t,e))})}function UF(t,e){return fC(lC.statSync(t),t,e)}});var SC=R((a3,_C)=>{_C.exports=yC;yC.sync=qF;var gC=mr("fs");function yC(t,e,r){gC.stat(t,function(n,o){r(n,n?!1:vC(o,e))})}function qF(t,e){return vC(gC.statSync(t),e)}function vC(t,e){return t.isFile()&&HF(t,e)}function HF(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 bC=R((u3,wC)=>{var c3=mr("fs"),Uc;process.platform==="win32"||global.TESTING_WINDOWS?Uc=mC():Uc=SC();wC.exports=uh;uh.sync=GF;function uh(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){uh(t,e||{},function(s,i){s?o(s):n(i)})})}Uc(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function GF(t,e){try{return Uc.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var TC=R((d3,EC)=>{var No=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",RC=mr("path"),ZF=No?";":":",PC=bC(),CC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),xC=(t,e)=>{let r=e.colon||ZF,n=t.match(/\//)||No&&t.match(/\\/)?[""]:[...No?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=No?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=No?o.split(r):[""];return No&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},kC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=xC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(CC(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=RC.join(p,t),m=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];PC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},WF=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=xC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=RC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if(PC.sync(f,{pathExt:o}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw CC(t)};EC.exports=kC;kC.sync=WF});var $C=R((l3,dh)=>{"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"};dh.exports=AC;dh.exports.default=AC});var zC=R((f3,OC)=>{"use strict";var MC=mr("path"),BF=TC(),VF=$C();function IC(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=BF.sync(t.command,{path:r[VF({env:r})],pathExt:e?MC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=MC.resolve(o?t.options.cwd:"",i)),i}function KF(t){return IC(t)||IC(t,!0)}OC.exports=KF});var NC=R((p3,fh)=>{"use strict";var lh=/([()\][%!^"`<>&|;, *?])/g;function JF(t){return t=t.replace(lh,"^$1"),t}function YF(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(lh,"^$1"),e&&(t=t.replace(lh,"^$1")),t}fh.exports.command=JF;fh.exports.argument=YF});var LC=R((h3,DC)=>{"use strict";DC.exports=/^#!(.*)/});var FC=R((m3,jC)=>{"use strict";var XF=LC();jC.exports=(t="")=>{let e=t.match(XF);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var qC=R((g3,UC)=>{"use strict";var ph=mr("fs"),QF=FC();function eU(t){let r=Buffer.alloc(150),n;try{n=ph.openSync(t,"r"),ph.readSync(n,r,0,150,0),ph.closeSync(n)}catch{}return QF(r.toString())}UC.exports=eU});var WC=R((y3,ZC)=>{"use strict";var tU=mr("path"),HC=zC(),GC=NC(),rU=qC(),nU=process.platform==="win32",oU=/\.(?:com|exe)$/i,sU=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function iU(t){t.file=HC(t);let e=t.file&&rU(t.file);return e?(t.args.unshift(t.file),t.command=e,HC(t)):t.file}function aU(t){if(!nU)return t;let e=iU(t),r=!oU.test(e);if(t.options.forceShell||r){let n=sU.test(e);t.command=tU.normalize(t.command),t.command=GC.command(t.command),t.args=t.args.map(s=>GC.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 cU(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:aU(n)}ZC.exports=cU});var KC=R((v3,VC)=>{"use strict";var hh=process.platform==="win32";function mh(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 uU(t,e){if(!hh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=BC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function BC(t,e){return hh&&t===1&&!e.file?mh(e.original,"spawn"):null}function dU(t,e){return hh&&t===1&&!e.file?mh(e.original,"spawnSync"):null}VC.exports={hookChildProcess:uU,verifyENOENT:BC,verifyENOENTSync:dU,notFoundError:mh}});var XC=R((_3,Do)=>{"use strict";var JC=mr("child_process"),gh=WC(),yh=KC();function YC(t,e,r){let n=gh(t,e,r),o=JC.spawn(n.command,n.args,n.options);return yh.hookChildProcess(o,n),o}function lU(t,e,r){let n=gh(t,e,r),o=JC.spawnSync(n.command,n.args,n.options);return o.error=o.error||yh.verifyENOENTSync(o.status,n),o}Do.exports=YC;Do.exports.spawn=YC;Do.exports.sync=lU;Do.exports._parse=gh;Do.exports._enoent=yh});var ox=R(_h=>{"use strict";var tx=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,gU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,rx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,yU=/\\([\u000b\u0020-\u00ff])/g,vU=/([\\"])/g,nx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;_h.format=_U;_h.parse=SU;function _U(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!nx.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],!rx.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+bU(e[o])}return n}function SU(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?wU(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(!nx.test(n))throw new TypeError("invalid media type");var o=new RU(n.toLowerCase());if(r!==-1){var s,i,a;for(tx.lastIndex=r;i=tx.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(yU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function wU(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 bU(t){var e=String(t);if(rx.test(e))return e;if(e.length>0&&!gU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(vU,"\\$1")+'"'}function RU(t){this.parameters=Object.create(null),this.type=t}});import{logger as UZ}from"@hermes/logger";import{logger as Hq}from"@hermes/logger";var $E="mcp-auth";function Ne(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus($E,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as vq}from"@augmentcode/auggie-v2";import{logger as _q}from"@hermes/logger";import{logger as rT}from"@hermes/logger";import{logger as IE}from"@hermes/logger";function ME(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 gr(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":ME(t,e,r)?"plugin":"local"}function OE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var dm=IE.child({prefix:"pi-mcp"}),zE="augment:mcp-status-report";function Xt(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 Go(t,e,r,n){let o=Xt(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=Xt(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 NE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=Xt(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 Ni=3e4;function DE(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>=Ni?"failed":void 0}default:return}}var lm="authentication required",LE="Authentication refresh is pending in the backend; retry shortly.",jE="timed out connecting after 30s",FE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",UE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",qE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",HE="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",GE="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function ZE(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),s=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),i=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=i(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?UE:FE,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=i(a);s.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...WE({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}}function WE(t){let{state:e,id:r,name:n,reportedNames:o}=t;return e.authFallbackDisplacedConfigIds.has(r)?{errorMessage:GE,failureCategory:"auth_terminal"}:{errorMessage:o.has(n)?HE:qE,failureCategory:"configuration"}}function BE(t,e){return e!==void 0?e.isAuthError?lm:e.error:t.status==="initializing"?jE:t.lastError??(t.status==="auth_required"?lm:void 0)}function VE(t,e){let r=DE(t);if(r===void 0)return;let n=NE(e,t.name),o=r==="connected"?OE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:gr(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"?LE:BE(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=VE(r,t);n!==void 0&&e.push(n)}return ZE(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(zE,o),dm.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){dm.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Di={local:4,registry:3,plugin:2,vfs:1};function Lt(t){return t.hostLeases??=new Map,t.hostLeases}function JE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Zo(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Wo(t,e){return t.kind===e.kind&&t.identity===e.identity}function fm(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 wu(t,e){let r=JE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Li(t,e,r){if(r.kind==="registry"){Zo(t).set(e,{kind:"domain",domain:r.identity});return}Zo(t).set(e,{kind:"blocked"})}function bu(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 Ln(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=Lt(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?Ln(i,s):{kind:s??"local",identity:e},c={owner:a,revision:wu(t,e),host:r};return n.set(e,c),Li(t,e,a),c}function pm(t){let{state:e,name:r,host:n}=t,o=Lt(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:wu(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),Li(e,r,i.owner),i}function Bo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Lt(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Di[n.kind]>Di[a.owner.kind],f=Di[n.kind]===Di[a.owner.kind],p=o===a.revision&&(s===void 0||s===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?fm(a):void 0;bu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:wu(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),Li(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function Ru(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=Lt(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Zo(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function ji(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Lt(e).get(r);return!i||i.revision!==o||!Wo(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 Rt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Lt(e).get(r);if(!i||i.revision!==o||!Wo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=fm(i);if(a)return bu(e,r,s),i.host=void 0,i.retirement=a,a}function hm(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Lt(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Wo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Wo(i.owner,n)||i.revision!==o.incumbent.revision?(Li(e,r,i.owner),!0):(s.delete(r),Zo(e).set(r,{kind:"blocked"}),!0))}function Pe(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Lt(e),a=i.get(r);return!a||a.revision!==o||!Wo(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(bu(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),Zo(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return Lt(t).get(e)}function mm(t,e,r){return Lt(t).get(e)?.host===r}function Vo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function yr(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 We(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 YE(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?!We(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function gm(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!Pu(e,r):n!==void 0&&e!==n}function ym(t,e,r){return r&&e!==void 0&&t!==void 0&&Pu(t,e)}function QE(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 vm(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"||gm({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&gm({identity:i.domain,...l})?!0:QE({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function eT(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return yr(r);if(n!==void 0)return{id:n,name:e}}function tT(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!yr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function _m(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=YE({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}`,f=vm({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}),p=ym(s,u,d),h=ym(i,u,d),m=!f,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,b=f&&!(m||p||h||y);if(o==="durable"){let P=eT({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:b})}let w=vm({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}),x=m&&!w,S=!1;return t.equalRevisionRebindDomains?.delete(e),(x||p)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),S=!0),(x||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),S=!0),x&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),tT({state:t,name:e,mode:o,stillOwnsNameScopedRevision:x,retiredConfig:c}),S&&(Vo(t,e),ot(t,e),t.authRefreshNeededReportKeys?.delete(e)),x}function dt(t,e,r,n){return _m(t,e,r,n,"durable")}function Ko(t,e,r,n){return _m(t,e,r,n,"session")}function Sm(t){let e=t.credential_owner_domain??t.credentialOwnerDomain;return typeof e=="string"&&/^user:.+/.test(e)?e:void 0}function vr(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 wm="augment:mcp-oauth-credentials",bm=300*1e3,nT=256,Cu=rT.child({prefix:"pi-mcp"}),Pt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function st(t){return`user:${t}`}function Vr(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||vr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function jn(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 Kr(t){return t.ownerDomain??jn(t.domain)}function Rm(t,e,r){let n=st(e);return r!==void 0?r===n:it(t)||jn(t)===n}function oT(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function sT(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 iT(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function aT(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&oT(t.credentialRevisions.get(e),r.credentialRevision)&&iT(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function cT(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 uT(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??"")||!We(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Jr(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 _r(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function Pm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=bm&&_r(t,n)}function dT(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&_r(t,e)}function Cm(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Jr(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();Pm(e,a);let c=Kr(n),u=it(c)?`${c}\0${r}`:c,d=i.get(u),l=d?.credential.credential_revision??d?.credential.credentialRevision;if(typeof l=="string"&&vr(n.revision,l)<=0)return;!d&&i.size>=nT&&dT(e),_r(e,u);let f={serverName:r,credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(u,f),f.expiryTimer=setTimeout(()=>{i.get(u)===f&&_r(e,u)},bm),f.expiryTimer.unref?.(),Cu.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function lT(t,e){Jr(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function Be(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:s=!1}=t;Jr(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||_r(e,r)}}function Fi(t){let{state:e,domain:r,forceNew:n=!1}=t;Jr(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&&Be({state:e,domain:r,epoch:o.epoch});let i={epoch:lT(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 xm(t,e){Jr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Be({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)&&_r(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);Fi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function fT(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;Jr(e);let n=st(r.id),o=cT(r),s=uT({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?(Be({state:e,domain:n,epoch:i.epoch}),i=void 0):i&&(i.allowEqualRevisionRebind=s);if(!i){let a=Fi({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),pT({state:e,config:r,domain:n}),{domain:n,...i}}function km(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Jr(e);let s=Kr(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:vr(r.revision,a),f=l===0;l!==void 0&&l<0||f&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&vr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:f})}function pT(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)&&jn(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 hT(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),Be({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let i={[r.name]:s.credential};n.events.emit(wm,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function mT(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();Pm(e,o);let s=e.bootOAuthCredentialBuffer?.get(r);if(s)return _r(e,r),s;for(let[i,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&it(i.split("\0",1)[0]))return _r(e,i),a}function gT(t){let{config:e,pi:r,buffered:n}=t;Cu.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),Cu.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(wm,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function yT(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(We(n,r)){if(n.name===r.name)return;await Ko(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 dt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function vT(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=aT(e,r.name,o);Be({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 Pt(a)}async function _T(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 yT({state:e,config:r,previousConfig:s})}catch(h){throw vT({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 Be({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),hT({state:e,config:r,pi:n,intent:o});let p=mT({state:e,domain:o.domain,serverName:r.name});return Be({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&gT({config:r,pi:n,buffered:p}),!0}function Sr(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=fT({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=sT(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 _T({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 OT}from"@augmentcode/auggie-v2";import{homedir as Em}from"node:os";import{sep as ST}from"node:path";var xu=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},wT=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,bT=/\\\$\{/g,RT=new Set(["workspaceFolder","augmentToken"]),Tm="${workspaceFolder}";function Am(t,e){return t.includes(Tm)?t.split(Tm).join(e):t}function $m(t,e){return t.includes("${")?t.replace(wT,(n,o,s)=>{if(RT.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new xu(o)}).replace(bT,"${"):t}function PT(t){return t.startsWith("~")?t==="~"?Em():t.startsWith("~/")||t.startsWith(`~${ST}`)?Em()+t.slice(1):t:t}function ku(t,e,r){return PT($m(Am(t,e),r))}function Ui(t,e,r){return $m(Am(t,e),r)}function Mm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Ui(s,e,r);return n}var CT="$augment-";function xT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(CT)?s:Ui(s,e,r);return n}function jt(t,e){let r=process.env;return{...t,url:Ui(t.url,e,r),headers:xT(t.headers,e,r)}}function Ft(t,e){let r=process.env;return{...t,command:ku(t.command,e,r),args:t.args,env:t.env?Mm(t.env,e,r):void 0,cwd:t.cwd?ku(t.cwd,e,r):e}}import{readFileSync as AT}from"node:fs";import{logger as kT}from"@hermes/logger";var ET=kT.child({prefix:"pi-mcp"}),Ct=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function Fn(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 TT(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 Un(t,e){let r=Fn(e);if(!r)throw new Ct(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Ct(`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 Ct(`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&&ET.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:TT(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var zm=t=>AT(t,"utf8");function qi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Im(t){return qi(t)&&("command"in t||"url"in t)}function Tu(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function Om(t,e){return Tu(t.name)??e}function Eu(t,e){let r=Fn(t);if(r==="http"||r==="sse")return Tu(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return Tu(t.name,t.title,n)??e}function $T(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[Eu(n,String(r)),n]});if(qi(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[Eu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(qi(n))return Object.entries(n).map(([o,s])=>{let i=s;return[Om(i,o),i]})}if(Im(t)){let r=t;return[[Eu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(Im))return Object.entries(t).map(([r,n])=>{if(!qi(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[Om(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 Au(t){return t instanceof Error?t.message:String(t)}function MT(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}": ${Au(s)}`});return}}function IT(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=MT(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}: ${Au(c)}`}),[]}try{return $T(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${Au(c)}`}),[]}}function $u(t,e=zm){let r={},n=[];for(let o of t)for(let[s,i]of IT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function Mu(t,e=zm){return!t||t.length===0?new Set:new Set(Object.keys($u(t,e).servers))}var zT=["global","project","local","managed"];function NT(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 DT(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 LT(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 jT(t,e,r){let n=OT.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 DT(zT.map(o=>NT(n,o)))}function qn(t,e,r,n){let o=[],s=r&&r.length>0?LT(r,n,o):jT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Un(a,c);i.push(u.type==="stdio"?Ft(u,t):jt(u,t))}catch(u){let d=u instanceof Ct?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 qm}from"@augmentcode/auggie-v2";import{logger as YT}from"@hermes/logger";import{Type as XT}from"@sinclair/typebox";var Hn=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 Hi=Symbol.for("__pi_mcp_state__");function FT(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 UT(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function qT(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&FT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&UT(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 HT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.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&&qT(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 Gi(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 GT(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 Nm(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Zi(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()?GT({state:e,configId:r,generation:n}):Nm({state:e,configId:r,generation:n}),i),i=>{throw Nm({state:e,configId:r,generation:n}),i})}function ee(){let t=globalThis;if(t[Hi])return HT(t[Hi]),t[Hi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Hn,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,authFallbackDisplacedConfigIds: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[Hi]=e,e}var Dm=Symbol.for("__hermes_mcp_tool_registry__"),ZT=Symbol.for("__hermes_mcp_extension_factory__");function Lm(){let t=globalThis;return t[Dm]??=new Map,t[Dm]}function wr(t){Lm().set(t.name,t)}function jm(t,e){let r=Lm();(e===void 0||r.get(t)===e)&&r.delete(t)}function Fm(t){Reflect.set(t,ZT,!0)}function Wi(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 WT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function BT(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 VT(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
+ `).trim()}function Iu(t,e,r){if(t.isError){let o=VT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=BT(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 Um(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Wi(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=WT(t.params),o=await e.callTool(r,n,t.signal);return Iu(o,t.serverName,r)}var KT=/[^a-zA-Z0-9_-]/g;function Ou(t){return t.replace(KT,"_")}function JT(t,e){let r=Ou(e),n=Ou(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var br=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=JT(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=`_${Ou(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var zu=YT.child({prefix:"pi-mcp"});function Bi(){return ee().toolRegistrationsByPi}function Hm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=XT.Unsafe(n.inputSchema??{})}catch(c){zu.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>ee().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,f)=>Um({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(p=>p.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function Nu(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),jm(n,s),r.definitionsByName?.delete(n),QT(t,e,n,r,o)}function QT(t,e,r,n,o){let s=ee();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 br(i);for(let d of c.listTools()){let{namespaced:l,collision:f}=u.put(d.name);if(f||l!==r)continue;let p=Hm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!p)return;qm(r,"mcp"),t.registerTool(p),wr(p),a.definitionsByName??=new Map,a.definitionsByName.set(r,p),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function eA(t,e){let r=Bi(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=ee().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)Nu(t,n,s,a);let i={generation:o,host:e,map:new br(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function Du(t,e){let{registration:r,replaced:n}=eA(t,e),o=new Set(r.registeredNames),s=new br(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:f}=s.put(d.name);if(f){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=ee();y.diagnostics.some(b=>b.server===i&&b.message.includes(`both map to "${l}"`))||(zu.warn(m),y.diagnostics.push({server:i,message:m}));continue}let p=Hm({pi:t,serverName:i,tool:d,map:s,namespaced:l});p&&(qm(l,"mcp"),t.registerTool(p),wr(p),r.definitionsByName??=new Map,r.definitionsByName.set(l,p),Bi().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Bi().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&Nu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&zu.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Lu(t,e,r){let n=Bi().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)Nu(t,n,o,s);return n.byServer.delete(e.name),!0}function Gm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&Du(t,r)}import{getToolSource as lA}from"@augmentcode/auggie-v2";import{Type as tA}from"@sinclair/typebox";var rA="cliMcpToolSearchAutoEnable",nA="cliMcpToolSearchTokenThreshold",oA=!1,Zm=2e4;function sA(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function iA(t){let e=0;for(let r of t.servers.values())e+=aA(r);return e}function aA(t){if(t.status!=="success")return 0;let e=new br(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||cA(n.inputSchema)&&(r+=sA(n))}return r}function cA(t){try{return tA.Unsafe(t??{}),!0}catch{return!1}}function uA(t){let r=t.featureFlags?.flags?.[rA];return typeof r=="boolean"?r:oA}function dA(t){let r=t.featureFlags?.flags?.[nA];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:Zm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:Zm}function Wm(t){return uA(t)?iA(t)>=dA(t):!1}var fA="AUGGIE_ENABLE_TOOL_SEARCH",pA=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Yo(){return process.env[fA]==="1"}function Gn(t){return Yo()||t.toolSearchLatched?!0:Wm(t)?(t.toolSearchLatched=!0,!0):!1}function Vi(t){let e=t.getActiveTools(),r=e.filter(n=>!hA(n)||pA.has(n));r.length!==e.length&&t.setActiveTools(r)}function hA(t){return lA(t)==="mcp"}import{setToolSource as eg}from"@augmentcode/auggie-v2";import{logger as OA}from"@hermes/logger";import{Type as tg}from"@sinclair/typebox";import{logger as mA}from"@hermes/logger";var Xo={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Yr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Bm=mA.child({prefix:"pi-mcp"}),gA=5e3,yA=1,vA=2,_A=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),SA=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function wA(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 bA(t){return t===yA||typeof t=="string"&&_A.has(t)?"available":t===vA||typeof t=="string"&&SA.has(t)?"opt_in_required":"unknown"}function RA(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:wA(t.auth_type),state:bA(t.state)}}function ju(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 Xr(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!ju(t,r))}async function Vm(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:Yr.UNSPECIFIED}),signal:AbortSignal.timeout(r??gA)});if(!s.ok)return Bm.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=RA(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Bm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var PA="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",CA=`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).`,yA=/[\n\r]/g,vA=/</g,_A=/>/g;function Kr(t){return t.replace(yA," ").replace(vA,"\u2039").replace(_A,"\u203A").trim()}function SA(){let t=process.env[mA];return t?.trim()?t:gA}var wA=/\{\{(query|server_name|tool_list)\}\}/g;function Lm(t,e,r){let n={"{{query}}":Kr(t),"{{server_name}}":Kr(e),"{{tool_list}}":r};return SA().replace(wA,o=>n[o]??o)}function be(t){return{content:[{type:"text",text:t}],details:void 0}}function jm(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Au(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Hi(t,e,r){let n={mcp_server:t,tools:jm(e).map(Au),note:r};return be(JSON.stringify(n,null,2))}function Fm(t){return jm(t).map(e=>{let r=Kr(e.name),n=Kr(e.description??"");return`- ${r}: ${n}`}).join(`
17
- `)}function Um(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 bA}from"@earendil-works/pi-ai";var RA="augment:tool-search-usage";function PA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function qm(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 bA(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(RA,a),PA(i)}var Bm=CA.child({prefix:"pi-mcp"}),Zo="find-tool",Jr="execute-tool",xA=10,Zm=15,kA=20,EA={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"]},TA={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 $u(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ").trim().replace(/\s+/g," ")}function AA(t){let e=[...ee().servers.values()].filter(c=>c.status==="success"),r=e.find(c=>c.name===t);if(r)return{server:r,name:r.name};let n=$u(t),o=e.filter(c=>n.length>0&&$u(c.name)===n);if(o.length===1){let[c]=o;return{server:c,name:c.name}}let s=n.split(" ").filter(Boolean),i=e.filter(c=>{let u=new Set($u(c.name).split(" "));return n.length>0&&s.every(d=>u.has(d))});if(i.length===1){let[c]=i;return{server:c,name:c.name}}let a=[...o,...i].map(c=>c.name).filter((c,u,d)=>d.indexOf(c)===u).sort();if(a.length>1){let c=e.map(u=>u.name).sort();throw new Error(`MCP server name "${t}" is ambiguous. Matching servers: ${a.join(", ")}. Use an exact server name. Available servers: ${c.join(", ")}.`)}}function Vm(t,e){let r=ee(),n=t.getAllTools().map(u=>u.name);if(!n.includes(e)){let u=e.trim().toLowerCase(),d=Wr(r).find(l=>l.id===e.trim()||l.name.toLowerCase()===u);if(d)throw new Error(`MCP server "${d.name}" is available but not attached. Call attach-mcp-server now with config_id "${d.id}"; it attaches directly without requiring user approval.`)}let o=n.includes(e)?void 0:AA(e);if(o)return o;let s=t.getActiveTools(),i=r.servers.get(e),a=[...r.servers.values()].filter(u=>u.status==="success").map(u=>u.name).sort(),c=Fi(e,i?.status,n,s);throw new Error(`${c} Available servers: ${a.join(", ")||"none"}.`)}function $A(t){if(t==null)throw new Error(`${Jr} 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(`${Jr} "arguments" must be an object, not ${e}.`)}return t}async function MA(t,e,r,n,o){let s=Lm(r,n,Fm(o)),i=await qm(t,e,s);if(!i)return;let a=Um(i);return o.find(c=>c.name===a)}async function IA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Zo} requires string "query" and "mcp_server" parameters.`);let s=Vm(t,o),i=s.server.listTools();if(i.length===0)throw new Error(`No tools available on MCP server "${s.name}".`);if(i.length<=xA)return Hi(s.name,i,"All tools on this server.");try{let a=await MA(t,e,n,s.name,i);return a?be(JSON.stringify(Au(a),null,2)):Hi(s.name,i,"No single best match; all tools listed.")}catch(a){return Bm.warn(`${Zo} LLM match failed: ${a instanceof Error?a.message:String(a)}`),Hi(s.name,i,"Search failed; all tools listed.")}}async function OA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Jr} requires string "mcp_server" and "tool_name" parameters.`);let i=$A(s),a=Vm(t,n),c=await a.server.callTool(o,i,r);return Ru(c,a.name,o)}function zA(){let t=ee(),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 ${Jr}.`,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,Zm).join(", "),u=a.length>Zm?", \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).`,xA=/[\n\r]/g,kA=/</g,EA=/>/g;function Qr(t){return t.replace(xA," ").replace(kA,"\u2039").replace(EA,"\u203A").trim()}function TA(){let t=process.env[PA];return t?.trim()?t:CA}var AA=/\{\{(query|server_name|tool_list)\}\}/g;function Km(t,e,r){let n={"{{query}}":Qr(t),"{{server_name}}":Qr(e),"{{tool_list}}":r};return TA().replace(AA,o=>n[o]??o)}function be(t){return{content:[{type:"text",text:t}],details:void 0}}function Jm(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Fu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Ki(t,e,r){let n={mcp_server:t,tools:Jm(e).map(Fu),note:r};return be(JSON.stringify(n,null,2))}function Ym(t){return Jm(t).map(e=>{let r=Qr(e.name),n=Qr(e.description??"");return`- ${r}: ${n}`}).join(`
17
+ `)}function Xm(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 $A}from"@earendil-works/pi-ai";var MA="augment:tool-search-usage";function IA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Qm(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 $A(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(MA,a),IA(i)}var ng=OA.child({prefix:"pi-mcp"}),Zn="find-tool",Rr="execute-tool",zA=10,rg=15,NA=20,DA={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"]},LA={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 Uu(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ").trim().replace(/\s+/g," ")}function jA(t){let e=[...ee().servers.values()].filter(c=>c.status==="success"),r=e.find(c=>c.name===t);if(r)return{server:r,name:r.name};let n=Uu(t),o=e.filter(c=>n.length>0&&Uu(c.name)===n);if(o.length===1){let[c]=o;return{server:c,name:c.name}}let s=n.split(" ").filter(Boolean),i=e.filter(c=>{let u=new Set(Uu(c.name).split(" "));return n.length>0&&s.every(d=>u.has(d))});if(i.length===1){let[c]=i;return{server:c,name:c.name}}let a=[...o,...i].map(c=>c.name).filter((c,u,d)=>d.indexOf(c)===u).sort();if(a.length>1){let c=e.map(u=>u.name).sort();throw new Error(`MCP server name "${t}" is ambiguous. Matching servers: ${a.join(", ")}. Use an exact server name. Available servers: ${c.join(", ")}.`)}}function og(t,e){let r=ee(),n=t.getAllTools().map(u=>u.name);if(!n.includes(e)){let u=e.trim().toLowerCase(),d=Xr(r).find(l=>l.id===e.trim()||l.name.toLowerCase()===u);if(d)throw new Error(`MCP server "${d.name}" is available but not attached. Call attach-mcp-server now with config_id "${d.id}"; it attaches directly without requiring user approval.`)}let o=n.includes(e)?void 0:jA(e);if(o)return o;let s=t.getActiveTools(),i=r.servers.get(e),a=[...r.servers.values()].filter(u=>u.status==="success").map(u=>u.name).sort(),c=Wi(e,i?.status,n,s);throw new Error(`${c} Available servers: ${a.join(", ")||"none"}.`)}function FA(t){if(t==null)throw new Error(`${Rr} 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(`${Rr} "arguments" must be an object, not ${e}.`)}return t}async function UA(t,e,r,n,o){let s=Km(r,n,Ym(o)),i=await Qm(t,e,s);if(!i)return;let a=Xm(i);return o.find(c=>c.name===a)}async function qA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Zn} requires string "query" and "mcp_server" parameters.`);let s=og(t,o),i=s.server.listTools();if(i.length===0)throw new Error(`No tools available on MCP server "${s.name}".`);if(i.length<=zA)return Ki(s.name,i,"All tools on this server.");try{let a=await UA(t,e,n,s.name,i);return a?be(JSON.stringify(Fu(a),null,2)):Ki(s.name,i,"No single best match; all tools listed.")}catch(a){return ng.warn(`${Zn} LLM match failed: ${a instanceof Error?a.message:String(a)}`),Ki(s.name,i,"Search failed; all tools listed.")}}async function HA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Rr} requires string "mcp_server" and "tool_name" parameters.`);let i=FA(s),a=og(t,n),c=await a.server.callTool(o,i,r);return Iu(c,a.name,o)}function GA(){let t=ee(),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 ${Rr}. When this gateway is present, MCP tools may intentionally be absent as top-level tools. Before reporting an expected MCP capability unavailable, search its attached server with ${Zn}, then invoke it with ${Rr}.`,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,rg).join(", "),u=a.length>rg?", \u2026":"";return`- ${i.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
18
18
  ${s.join(`
19
- `)}`)}let o=Wr(t).slice(0,kA);if(o.length>0){let s=o.map(i=>{let a=Kr(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=Xr(t).slice(0,NA);if(o.length>0){let s=o.map(i=>{let a=Qr(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 Yr(t){let e={name:Zo,label:Zo,description:zA(),parameters:Gm.Unsafe(EA),execute:(n,o,s,i,a)=>IA(t,a,o)},r={name:Jr,label:Jr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:Gm.Unsafe(TA),execute:(n,o,s)=>OA(t,o,s)};Hm(Zo,"mcp"),Hm(Jr,"mcp"),t.registerTool(e),t.registerTool(r),_r(e),_r(r),Bm.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as SU}from"@hermes/logger";import{logger as HA}from"@hermes/logger";import{logger as NA}from"@hermes/logger";function Xr(t){return new Promise(e=>setTimeout(e,t))}var Wm=NA.child({prefix:"pi-mcp"}),Bo={maxTries:3,initialMs:500,mult:2,maxMs:2e3},Mu=3e4,Xt=200,lt=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 Iu(t){return t instanceof lt?t.statusCode>=500:!0}async function Qr(t){let e;for(let r=0;r<Bo.maxTries;r++)try{return await t()}catch(n){if(e=n,!Iu(n))throw n;if(r<Bo.maxTries-1){let o=Math.min(Bo.initialMs*Bo.mult**r,Bo.maxMs);await Xr(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??Mu}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>Xt?`${s.slice(0,Xt)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return Qr(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return Qr(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function Km(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)}`;Wm.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)}`;Wm.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function DA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var Jm=32;function LA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>Jm&&(e=e.slice(0,Jm)),e=e.replace(/_+$/,""),e}function Ym(t,e){let r=e?LA(e):"",n=DA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function Xm(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var jA=1e12,FA=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function UA(t){let e=FA.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=Number(e[4]),i=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||s>23||i>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function qA(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<jA?t*1e3:t;if(typeof t=="string")return UA(t)}function Qm(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:qA(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Ft=HA.child({prefix:"pi-mcp"}),B=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},Un=class extends Error{},tg=[100,500],GA=tg.length+1,ZA=t=>new Promise(e=>{setTimeout(e,t)});function eg(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var zu="augment.mcp-access-token.",BA=JSON.stringify({retired:!0}),Zi=3;function Ut(t){return`${zu}${t}`}function Bi(t){return`legacy:${t}`}function Qt(t){return t?.id?Ym(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 wr(t){let e=Vi(t);return e?JSON.stringify(e):void 0}function VA(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 Nu(t){if(typeof t=="string")try{return Nu(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 WA(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function Fn(t){try{let e=JSON.parse(t);return{credentialIdentity:Nu(e.credentialIdentity),state:WA(e)}}catch{return{}}}function Vo(t,e){let r={...t,type:"oauth",credentialIdentity:Vi(e)};return JSON.stringify(r)}function en(t,e){let r=Xm({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 KA(t){return JSON.stringify({credentialIdentity:Vi(t),credentialState:"retired",retired:!0})}function JA(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=VA(e),s=Nu(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 Ou(t){try{let e=Qm(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||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 Wo=class{_memory=new Ln;_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=ZA){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(()=>{Ft.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(()=>{Ft.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=wr(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=Qt(e),n=wr(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=Fn(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=Ou(i.value);if(!c)throw new B;try{await r.upsertUserSecret(n,en(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Qt(e),n=wr(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=Fn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Ou(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=Qt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,en(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=Qt(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(Ut(e),()=>this._restoreLegacyCredential({client:i,key:Ut(e),persistedToken:r,currentToken:n,registry:o}))}catch{Ft.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(Ut(e),()=>this._restoreLegacyCredentialExact({client:i,key:Ut(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!==Vo(s,a)))try{return{revision:await r.upsertUserSecret(n,Vo(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!==en(o,i)))try{return{revision:await r.upsertUserSecret(n,en(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!==Vo(o,i)))try{await r.upsertUserSecret(n,Vo(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{Ft.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=wr(o);if(!s)throw new B;for(let i=0;i<Zi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?Fn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new B;try{return await this._upsertUserSecretOnce(e,r,en(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new B}async _retireRegistryCredential(e,r,n){let o=wr(n);if(!o)throw new B;for(let s=0;s<Zi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?Fn(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 lt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=Qt(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=eg(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?GA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new Un;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 Un}_persistenceRetryDelay(e,r,n){let o=n?tg[r]:void 0,s=!(e instanceof B)&&Iu(e);if(o===void 0||!s){n&&Ft.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(Ut(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,Ut(e),Vo(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 Un||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=wr(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=Qt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new B));let l=this._shouldPersist()&&!i,f;return l&&(c?f=this._enqueueWrite(Ut(e),async()=>{let p=await c.upsertUserSecret(Ut(e),BA)}):f=Promise.reject(new B)),this._awaitRetirements(e,d,f).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"&&Ft.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Ft.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=Ut(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 Un&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Qt(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(()=>{Ft.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(eg(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=Qt(r),o=wr(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=Fn(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=Ou(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,en(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=Qt(n),i=wr(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=Fn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,en(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(Ut(r));return o?JA(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){Ft.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),Ft.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var rg="Augment Code",ng="https://augmentcode.com",og="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var XA=1e3,QA=500;function Lu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Ko(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Du=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function sg(t){return new URLSearchParams({k:t}).toString().slice(2)}function e0(t,e){let r=`${sg(t)}:${sg(e)}`;return`Basic ${btoa(r)}`}function ug(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function t0(t){return t.client.token_endpoint_auth_method==="none"||!ug(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function r0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function n0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var o0=401,dg=500;function ju(t,...e){return t.status<dg&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function ig(t){return ju(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===o0}async function ag(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=ug(t);e==="basic"&&s?n.Authorization=e0(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=n0(c),d=c.slice(0,QA);throw new tn(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Du;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*XA:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function cg(t,e){try{return await ag(t,e,t.resource)}catch(r){if(r instanceof tn&&t.resource&&ju(r,"invalid_target"))return await ag(t,e,void 0);throw r}}var tn=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 Fu(t){return!(t instanceof tn)||t.status>=dg?!1:ju(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Uu(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=t0(t);try{return await cg(e,r)}catch(n){let o=r0(r);if(!(n instanceof tn)||!o||!ig(n))throw n;try{return await cg(e,o)}catch(s){throw s instanceof tn&&ig(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as X0}from"@hermes/logger";var Gu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Gu="oauth4webapi/v3.8.6");function Zn(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 qt="ERR_INVALID_ARG_VALUE",We="ERR_INVALID_ARG_TYPE";function pe(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var Ku=Symbol(),s0=Symbol(),i0=Symbol(),nn=Symbol();var lg=Symbol();var a0=new TextEncoder,c0=new TextDecoder;function Zu(t){return typeof t=="string"?a0.encode(t):c0.decode(t)}var Bu;Uint8Array.prototype.toBase64?Bu=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Bu=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 Vu;Uint8Array.fromBase64?Vu=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw pe("The input to be decoded is not correctly encoded.",qt,e)}}:Vu=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 pe("The input to be decoded is not correctly encoded.",qt,e)}};function Ki(t){return typeof t=="string"?Vu(t):Bu(t)}var Hn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=F0,Error.captureStackTrace?.(this,this.constructor)}},Jo=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new Jo(t,{code:e,cause:r})}function Ji(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Ju(t){Zn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Gu&&!e.has("user-agent")&&e.set("user-agent",Gu),e.has("authorization"))throw pe('"options.headers" must not include the "authorization" header name',qt);return e}function Yu(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw pe('"options.signal" must return or be an instance of AbortSignal',We);return e}}function u0(t){return t.includes("//")?t.replace("//","/"):t}function d0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=u0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function l0(t,e,r,n){if(!(t instanceof URL))throw pe(`"${e}" must be an instance of URL`,We);bg(t,n?.[Ku]!==!0);let o=r(new URL(t.href)),s=Ju(n?.headers);return s.set("accept","application/json"),(n?.[nn]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:Yu(o,n?.signal)})}function qn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw pe(`${r} must be a number`,We,o);if(t>0)return;if(e){if(t!==0)throw pe(`${r} must be a non-negative number`,qt,o);return}throw pe(`${r} must be a positive number`,qt,o)}catch(s){throw n?O(s.message,n,o):s}}function Te(t,e,r,n){try{if(typeof t!="string")throw pe(`${e} must be a string`,We,n);if(t.length===0)throw pe(`${e} must not be empty`,qt,n)}catch(o){throw r?O(o.message,r,n):o}}async function hg(t,e){let r=t;if(!(r instanceof URL)&&r!==Qi)throw pe('"expectedIssuerIdentifier" must be an instance of URL',We);if(!Zn(e,Response))throw pe('"response" must be an instance of Response',We);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',sd,e);Qo(e);let n=await na(e);if(Te(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==Qi&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',ta,{expected:r.href,body:n,attribute:"issuer"});return n}function mg(t){p0(t,"application/json")}function f0(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,q0,t)}function p0(t,e){if(C0(t)!==e)throw f0(t,e)}function Xu(){return Ki(crypto.getRandomValues(new Uint8Array(32)))}function gg(){return Xu()}function yg(){return Xu()}function vg(){return Xu()}async function _g(t){return Te(t,"codeVerifier"),Ki(await crypto.subtle.digest("SHA-256",Zu(t)))}function Qu(t){let e=t?.[s0];return typeof e=="number"&&Number.isFinite(e)?e:0}function ed(t){let e=t?.[i0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function td(){return Math.floor(Date.now()/1e3)}function ea(t){if(typeof t!="object"||t===null)throw pe('"as" must be an object',We);Te(t.issuer,'"as.issuer"')}function rd(t){if(typeof t!="object"||t===null)throw pe('"client" must be an object',We);Te(t.client_id,'"client.client_id"')}function fg(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 nd(t){return Te(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function Sg(t){return Te(t,'"clientSecret"'),(e,r,n,o)=>{let s=fg(r.client_id),i=fg(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function wg(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var h0=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function bg(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",H0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",G0,t)}function pg(t,e,r,n){let o;if(typeof t!="string"||!(o=h0(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?Z0:B0,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return bg(o,n),o}function Rg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?pg(t.mtls_endpoint_aliases[e],e,r,n):pg(t[e],e,r,n)}var Gn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=j0,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)}},Yo=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=U0,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)}},Xo=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=L0,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!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",m0="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",g0='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',y0="("+Yi+")\\s*=\\s*"+g0,v0="("+Yi+")\\s*=\\s*("+Yi+")",_0=new RegExp("^[,\\s]*("+Yi+")"),S0=new RegExp("^[,\\s]*"+y0+"[,\\s]*(.*)"),w0=new RegExp("^[,\\s]*"+v0+"[,\\s]*(.*)"),b0=new RegExp("^("+m0+")(?:$|[,\\s])(.*)");function R0(t){if(!Zn(t,Response))throw pe('"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(_0),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 f,p;if(o=n.match(S0)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(w0)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match(b0)){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 P0(t){if(t.status>399&&t.status<500){Qo(t),mg(t);try{let e=await t.clone().json();if(Ji(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Pg(t,e,r){if(t.status!==e){T0(t);let n;throw(n=await P0(t))?(await t.body?.cancel(),new Gn("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,sd,t)}}function Cg(t){if(!od.has(t))throw pe('"options.DPoP" is not a valid DPoPHandle',qt)}function C0(t){return t.headers.get("content-type")?.split(";")[0]}async function x0(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?.[nn]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Yu(n,i?.signal)})}async function k0(t,e,r,n,o,s){let i=Rg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[Ku]!==!0);o.set("grant_type",n);let a=Ju(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(Cg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await x0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var xg=new WeakMap,E0=new WeakMap;function kg(t){if(!t.id_token)return;let e=xg.get(t);if(!e)throw pe('"ref" was already garbage collected or did not resolve from the proper sources',qt);return e}async function Eg(t,e,r,n,o,s){if(ea(t),rd(e),!Zn(r,Response))throw pe('"response" must be an instance of Response',We);await Pg(r,200,"Token Endpoint"),Qo(r);let i=await na(r);if(Te(i.access_token,'"response" body "access_token" property',V,{body:i}),Te(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;qn(a,!0,'"response" body "expires_in" property',V,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Te(i.refresh_token,'"response" body "refresh_token" property',V,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw O('"response" body "scope" property must be a string',V,{body:i});if(i.id_token!==void 0){Te(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&&(qn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await V0(i.id_token,W0.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Qu(e),ed(e),o).then(z0.bind(void 0,a)).then($0.bind(void 0,t)).then(A0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',br,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',br,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&qn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),E0.set(r,u),xg.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 Hn("unsupported `token_type` value",{cause:{body:i}});return i}function T0(t){let e;if(e=R0(t))throw new Xo("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function A0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',br,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',br,{expected:t,claims:e.claims,claim:"aud"});return e}function $0(t,e){let r=t[Y0]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',br,{expected:r,claims:e.claims,claim:"iss"});return e}var od=new WeakSet;function M0(t){return od.add(t),t}var I0=Symbol();async function Tg(t,e,r,n,o,s,i){if(ea(t),rd(e),!od.has(n))throw pe('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',qt);Te(o,'"redirectUri"');let a=rn(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==I0&&(Te(s,'"codeVerifier"'),c.set("code_verifier",s)),k0(t,e,r,"authorization_code",c,i)}var O0={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 z0(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${O0[r]}) claim missing`,V,{claims:e.claims});return e}var qu=Symbol(),Hu=Symbol();async function Ag(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?N0(t,e,r,n.expectedNonce,n.maxAge,n[lg],n.recognizedTokenTypes):D0(t,e,r,n?.[lg],n?.recognizedTokenTypes)}async function N0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=qu;break;case qu:break;default:Te(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Hu;break;case Hu:break;default:qn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await Eg(t,e,r,a,s,i);Te(c.id_token,'"response" body "id_token" property',V,{body:c});let u=kg(c);if(o!==Hu){let d=td()+Qu(e),l=ed(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",Xi,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===qu){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',br,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',br,{expected:n,claims:u,claim:"nonce"});return c}async function D0(t,e,r,n,o){let s=await Eg(t,e,r,void 0,n,o),i=kg(s);if(i){if(e.default_max_age!==void 0){qn(e.default_max_age,!0,'"client.default_max_age"');let a=td()+Qu(e),c=ed(e);if(i.auth_time+e.default_max_age<a-c)throw O("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 O('unexpected ID Token "nonce" claim value',br,{expected:void 0,claims:i,claim:"nonce"})}return s}var L0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",j0="OAUTH_RESPONSE_BODY_ERROR",F0="OAUTH_UNSUPPORTED_OPERATION",U0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Wu="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var q0="OAUTH_RESPONSE_IS_NOT_JSON",sd="OAUTH_RESPONSE_IS_NOT_CONFORM",H0="OAUTH_HTTP_REQUEST_FORBIDDEN",G0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Xi="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",br="OAUTH_JWT_CLAIM_COMPARISON_FAILED",ta="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Z0="OAUTH_MISSING_SERVER_METADATA",B0="OAUTH_INVALID_SERVER_METADATA";function Qo(t){if(t.bodyUsed)throw pe('"response" body has been used already',qt)}async function V0(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 Hn("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",V,t);let c;try{c=JSON.parse(Zu(Ki(s)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",Wu,l)}if(!Ji(c))throw O("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new Hn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Zu(Ki(i)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",Wu,l)}if(!Ji(u))throw O("JWT Payload must be a top level object",V,t);let d=td()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Xi,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',Xi,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function W0(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function rn(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,V);return r}var K0=Symbol(),J0=Symbol();function $g(t,e,r,n){if(ea(t),rd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw pe('"parameters" must be an instance of URLSearchParams, or URL',We);if(rn(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=rn(r,"iss"),s=rn(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case J0:if(s!==void 0)throw O('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case K0:break;default:if(Te(n,'"expectedState" argument'),s!==n)throw O(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(rn(r,"error"))throw new Yo("authorization response from the server is an error",{cause:r});let a=rn(r,"id_token"),c=rn(r,"token");if(a!==void 0||c!==void 0)throw new Hn("implicit and hybrid flows are not supported");return M0(new URLSearchParams(r))}async function Mg(t,e,r){ea(t);let n=Rg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[Ku]!==!0),o=Ju(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(Cg(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?.[nn]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:Yu(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Ig(t){if(!Zn(t,Response))throw pe('"response" must be an instance of Response',We);await Pg(t,201,"Dynamic Client Registration Endpoint"),Qo(t);let e=await na(t);return Te(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&Te(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&qn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function Og(t,e){return l0(t,"resourceIdentifier",r=>(d0(r,".well-known/oauth-protected-resource",!0),r),e)}async function ra(t,e){let r=t;if(!(r instanceof URL)&&r!==Qi)throw pe('"expectedResourceIdentifier" must be an instance of URL',We);if(!Zn(e,Response))throw pe('"response" must be an instance of Response',We);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',sd,e);Qo(e);let n=await na(e);if(Te(n.resource,'"response" body "resource" property',V,{body:n}),r!==Qi&&new URL(n.resource).href!==r.href)throw O('"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=mg){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',Wu,n)}if(!Ji(r))throw O('"response" body must be a top level object',V,{body:r});return r}var Qi=Symbol(),Y0=Symbol();var Dg=X0.child({prefix:"pi-mcp"}),es=1e4,Q0=1e3,e$=401,zg=200,t$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,r$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Lg;function Bn(){return Lg??globalThis.fetch}function jg(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Fg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function ad(t){let e=Fg(t);try{let r=await n$(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await c$(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ia(r)}throw new Error("Failed to discover metadata URL")}async function n$(t){try{let e=await Og(t,{signal:AbortSignal.timeout(es),[nn]:Lg??void 0});return e.ok?await ra(t,e):(e.body?.cancel().catch(()=>{}),await Ug(t,e.headers.get("www-authenticate"))??await Ng(t))}catch{return await Ng(t)}}async function Ng(t){for(let e of["HEAD","GET"])try{let r=await Bn()(t,{method:e,signal:AbortSignal.timeout(es)});r.body?.cancel().catch(()=>{});let n=await Ug(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Ug(t,e){let r=a$(e);if(r)try{let n=await Bn()(r,{signal:AbortSignal.timeout(es)});return await o$(t,n)}catch{return}}async function o$(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 Jo)||o.code!==ta)throw o;let s=s$(r);if(!s||!i$(s,t))throw o;return await ra(s,new Response(r,n))}}function s$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function i$(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 a$(t){if(!t)return;let e=t.match(t$),r=t.match(r$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function c$(t){for(let e of u$(t))try{let r=new URL(e,t),n=await Bn()(r,{signal:AbortSignal.timeout(es)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function u$(t){let e=t.pathname.startsWith("/")?t.pathname.slice(1):t.pathname;return[...e.length>0?[new URL(`/.well-known/oauth-authorization-server/${e}`,t),new URL(`/.well-known/openid-configuration/${e}`,t),new URL(`/${e}/.well-known/openid-configuration`,t)]:[],new URL("/.well-known/oauth-authorization-server",t),new URL("/.well-known/openid-configuration",t)]}async function cd(t){try{let e=await Bn()(t,{signal:AbortSignal.timeout(es)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await d$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await hg(o,new Response(r,n))}catch(e){throw ia(e)}}async function d$(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 id=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 l$(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 ud({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return l$({...t,clientId:n});if(!e.registration_endpoint)throw new id(e.issuer);return await f$(e,r)}async function f$(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Mg(t,{client_name:rg,client_uri:ng,logo_uri:og,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[nn]:p$});return n.ok||Dg.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Ig(n)}catch(r){throw ia(r)}}async function p$(t,e){let r=await Bn()(t,jg(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Dg.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${m$(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 h$(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}),Bn()(t,jg(o))}function m$(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>zg?`${t.slice(0,zg)}\u2026`:t}}async function oa(t,e,r,n,o,s,i){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=gg(),c=await _g(a),u=yg(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!i?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=Fg(s??t).toString(),m=new URL(r.authorization_endpoint);return m.searchParams.set("response_type","code"),m.searchParams.set("client_id",e.client_id),m.searchParams.set("code_challenge",c),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("redirect_uri",n),m.searchParams.set("resource",h),m.searchParams.set("state",u),p&&m.searchParams.set("scope",p),l?.includes("offline_access")&&m.searchParams.set("prompt","consent"),r.code_challenge_methods_supported?.includes("S256")||(d=vg(),m.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:m}}function sa(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function dd(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await oa(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function g$(t,e,r){let n=await Tg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[nn]:h$,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Ag(t.serverMetadata,t.client,await y$(n))}async function ld(t,e){try{let r=$g(e.serverMetadata,e.client,t,e.state),n=await _$(e.client,o=>g$(e,r,o));return b$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ia(r)}}async function y$(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 qg(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function v$(t){let e=qg(t);return e===void 0?wg():t.token_endpoint_auth_method==="client_secret_basic"?Sg(e):nd(e)}async function _$(t,e){try{return await e(v$(t))}catch(r){let n=S$(t);if(n&&w$(r))return await e(n);throw r}}function S$(t){let e=qg(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return nd(e)}function w$(t){return t instanceof Gn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof Xo?t.status===e$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function b$(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*Q0:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ia(t){if(t instanceof Gn||t instanceof Yo){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 R$=/(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,Hg=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,Gg=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,Zg=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,ts="[redacted]";function P$(t){return Hg.test(t)||Gg.test(t)||Zg.test(t)}var C$=new RegExp(Hg.source,"g"),x$=new RegExp(Gg.source,"gi"),k$=new RegExp(Zg.source,"g");function Bg(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function pd(t){return t&&Bg(t,8192).replace(C$,ts).replace(x$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${ts}`).replace(k$,ts)}function fd(t,e,r){if(e)return ts;if(typeof t=="string")return P$(t)?ts:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>fd(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=fd(s,R$.test(o),r+1);return n}function Vg(t,e=500){if(t==null)return;let r=fd(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return Bg(n,e)}var Kg={reportError:()=>{}},Wg=Symbol.for("__pi_mcp_error_reporter_slot__");function Jg(){let t=globalThis,e=t[Wg];return e||(e={reporter:null},t[Wg]=e),e}function Yg(t){let e=Jg(),r=e.reporter??Kg;return e.reporter=t,r}function E$(){return Jg().reporter??Kg}function hd(t,e){try{E$().reportError(t,e)}catch{}}import{logger as T$}from"@hermes/logger";var md=T$.child({prefix:"pi-mcp"});function Xg(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++):md.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];md.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function Qg(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(zu)){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 ey(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,md.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function ty(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as A$}from"@hermes/logger";var rs=A$.child({prefix:"pi-mcp"}),$$="$augment-",ns=/\$augment-[a-zA-Z0-9_.-]+/g,M$=new RegExp(ns.source);function aa(t){return M$.test(t)}function ca(t){return t.slice($$.length)}function gd(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(ns))e.add(ca(n[0]));return[...e].sort()}var I$=["permission_denied","missing","transient"];function ry(t){let e=new Set(t);return I$.find(r=>e.has(r))??"missing"}var ft=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 ny(t,e,r,n,o,s,i){let a=[...t.matchAll(ns)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=ca(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),s.set(f,p===void 0?"missing":p.reason),rs.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),rs.warn(`Secret "${f}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),rs.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),s.set(f,"transient"),rs.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function oy({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(!aa(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){rs.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await ny(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 O$=/["$`\\]/g;function z$(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 N$(t,e){let r=z$(e);if(r==="double")return t.replace(O$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function sy(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await ny(t,"command",e,r,n,o,N$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as gU}from"node:async_hooks";var iy,yd=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 f=d[l];f in a||(a[f]=u[f].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 Ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vn=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(iy=globalThis).__zod_globalConfig??(iy.__zod_globalConfig={});var Wn=globalThis.__zod_globalConfig;function Ke(t){return t&&Object.assign(Wn,t),Wn}var U={};du(U,{BIGINT_FORMAT_RANGES:()=>dy,Class:()=>_d,NUMBER_FORMAT_RANGES:()=>Cd,aborted:()=>Cr,allowsEval:()=>bd,assert:()=>U$,assertEqual:()=>D$,assertIs:()=>j$,assertNever:()=>F$,assertNotEqual:()=>L$,assignProp:()=>Rr,base64ToUint8Array:()=>fy,base64urlToUint8Array:()=>oM,cached:()=>Jn,captureStackTrace:()=>la,cleanEnum:()=>nM,cleanRegex:()=>as,clone:()=>pt,cloneDef:()=>H$,createTransparentProxy:()=>K$,defineLazy:()=>Y,esc:()=>da,escapeRegex:()=>tr,explicitlyAborted:()=>xd,extend:()=>X$,finalizeIssue:()=>ht,floatSafeRemainder:()=>Sd,getElementAtPath:()=>G$,getEnumValues:()=>ss,getLengthableOrigin:()=>cs,getParsedType:()=>W$,getSizableOrigin:()=>ly,hexToUint8Array:()=>iM,isObject:()=>on,isPlainObject:()=>Pr,issue:()=>Yn,joinValues:()=>ua,jsonStringifyReplacer:()=>Kn,merge:()=>eM,mergeDefs:()=>er,normalizeParams:()=>A,nullish:()=>is,numKeys:()=>V$,objectClone:()=>q$,omit:()=>Y$,optionalKeys:()=>Pd,parsedType:()=>kd,partial:()=>tM,pick:()=>J$,prefixIssues:()=>rr,primitiveTypes:()=>uy,promiseAllObject:()=>Z$,propertyKeyTypes:()=>Rd,randomString:()=>B$,required:()=>rM,safeExtend:()=>Q$,shallowClone:()=>cy,slugify:()=>wd,stringifyPrimitive:()=>fa,uint8ArrayToBase64:()=>py,uint8ArrayToBase64url:()=>sM,uint8ArrayToHex:()=>aM,unwrapMessage:()=>os});function D$(t){return t}function L$(t){return t}function j$(t){}function F$(t){throw new Error("Unexpected value in exhaustive check")}function U$(t){}function ss(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 ua(t,e="|"){return t.map(r=>fa(r)).join(e)}function Kn(t,e){return typeof e=="bigint"?e.toString():e}function Jn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function is(t){return t==null}function as(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Sd(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 ay=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==ay)return n===void 0&&(n=ay,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function q$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Rr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function er(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function H$(t){return er(t._zod.def)}function G$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Z$(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 B$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function da(t){return JSON.stringify(t)}function wd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var la="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function on(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var bd=Jn(()=>{if(Wn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Pr(t){if(on(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(on(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function cy(t){return Pr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function V$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var W$=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}`)}},Rd=new Set(["string","number","symbol"]),uy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function tr(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 fa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Pd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Cd={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]},dy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function J$(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=er(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 Rr(this,"shape",i),i},checks:[]});return pt(t,s)}function Y$(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=er(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 Rr(this,"shape",i),i},checks:[]});return pt(t,s)}function X$(t,e){if(!Pr(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=er(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Rr(this,"shape",s),s}});return pt(t,o)}function Q$(t,e){if(!Pr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=er(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Rr(this,"shape",n),n}});return pt(t,r)}function eM(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=er(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Rr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function tM(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=er(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 Rr(this,"shape",c),c},checks:[]});return pt(e,i)}function rM(t,e,r){let n=er(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 Rr(this,"shape",s),s}});return pt(e,n)}function Cr(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 xd(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 rr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function os(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n=t.message?t.message:os(t.inst?._zod.def?.error?.(t))??os(e?.error?.(t))??os(r.customError?.(t))??os(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 ly(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function cs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function kd(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 Yn(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function nM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function fy(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 py(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function oM(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return fy(e+r)}function sM(t){return py(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function iM(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 aM(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var _d=class{constructor(...e){}};var hy=(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,Kn,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},pa=v("$ZodError",hy),Ed=v("$ZodError",hy,{Parent:Error});function Td(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 Ad(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 ha=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 Ht;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ke())));throw la(a,o?.callee),a}return i.value};var ma=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=>ht(c,s,Ke())));throw la(a,o?.callee),a}return i.value};var us=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 Ht;return s.issues.length?{success:!1,error:new(t??pa)(s.issues.map(i=>ht(i,o,Ke())))}:{success:!0,data:s.value}},ds=us(Ed),ls=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=>ht(i,o,Ke())))}:{success:!0,data:s.value}},ga=ls(Ed),my=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ha(t)(e,r,o)};var gy=t=>(e,r,n)=>ha(t)(e,r,n);var yy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ma(t)(e,r,o)};var vy=t=>async(e,r,n)=>ma(t)(e,r,n);var _y=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return us(t)(e,r,o)};var Sy=t=>(e,r,n)=>us(t)(e,r,n);var wy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ls(t)(e,r,o)};var by=t=>async(e,r,n)=>ls(t)(e,r,n);var Ry=/^[cC][0-9a-z]{6,}$/,Py=/^[0-9a-z]+$/,Cy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xy=/^[0-9a-vA-V]{20}$/,ky=/^[A-Za-z0-9]{27}$/,Ey=/^[a-zA-Z0-9_-]{21}$/,Ty=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Ay=/^([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})$/,$d=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 uM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function My(){return new RegExp(uM,"u")}var Iy=/^(?:(?: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])$/,Oy=/^(([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 zy=/^((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])$/,Ny=/^(([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])$/,Dy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Md=/^[A-Za-z0-9_-]*$/;var Ly=/^https?$/,jy=/^\+[1-9]\d{6,14}$/,Fy="(?:(?:\\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])))",Uy=new RegExp(`^${Fy}$`);function qy(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 Hy(t){return new RegExp(`^${qy(t)}$`)}function Gy(t){let e=qy({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(`^${Fy}T(?:${n})$`)}var Zy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},By=/^-?\d+n?$/,Vy=/^-?\d+$/,Id=/^-?\d+(?:\.\d+)?$/,Wy=/^(?:true|false)$/i,Ky=/^null$/i;var Jy=/^[^A-Z]*$/,Yy=/^[^a-z]*$/;var Ae=v("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Xy={number:"number",bigint:"bigint",object:"date"},Od=v("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);let r=Xy[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})}}),zd=v("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);let r=Xy[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})}}),Qy=v("$ZodCheckMultipleOf",(t,e)=>{Ae.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):Sd(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})}}),ev=v("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Cd[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=Vy)}),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 tv=v("$ZodCheckMaxLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!is(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=cs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),rv=v("$ZodCheckMinLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!is(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=cs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),nv=v("$ZodCheckLengthEquals",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!is(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=cs(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})}}),ps=v("$ZodCheckStringFormat",(t,e)=>{var r,n;Ae.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=()=>{})}),ov=v("$ZodCheckRegex",(t,e)=>{ps.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})}}),sv=v("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Jy),ps.init(t,e)}),iv=v("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Yy),ps.init(t,e)}),av=v("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);let r=tr(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})}}),cv=v("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`^${tr(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})}}),uv=v("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`.*${tr(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 dv=v("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ya=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 en(t){let e={name:Zn,label:Zn,description:GA(),parameters:tg.Unsafe(DA),execute:(n,o,s,i,a)=>qA(t,a,o)},r={name:Rr,label:Rr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:tg.Unsafe(LA),execute:(n,o,s)=>HA(t,o,s)};eg(Zn,"mcp"),eg(Rr,"mcp"),t.registerTool(e),t.registerTool(r),wr(e),wr(r),ng.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as TU}from"@hermes/logger";import{logger as XA}from"@hermes/logger";import{logger as ZA}from"@hermes/logger";function tn(t){return new Promise(e=>setTimeout(e,t))}var sg=ZA.child({prefix:"pi-mcp"}),Qo={maxTries:3,initialMs:500,mult:2,maxMs:2e3},qu=3e4,Qt=200,lt=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 Hu(t){return t instanceof lt?t.statusCode>=500:!0}async function rn(t){let e;for(let r=0;r<Qo.maxTries;r++)try{return await t()}catch(n){if(e=n,!Hu(n))throw n;if(r<Qo.maxTries-1){let o=Math.min(Qo.initialMs*Qo.mult**r,Qo.maxMs);await tn(o)}}throw e}var Ji=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??qu}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>Qt?`${s.slice(0,Qt)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return rn(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return rn(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function ig(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)}`;sg.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)}`;sg.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function WA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var ag=32;function BA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>ag&&(e=e.slice(0,ag)),e=e.replace(/_+$/,""),e}function cg(t,e){let r=e?BA(e):"",n=WA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function ug(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var VA=1e12,KA=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function JA(t){let e=KA.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=Number(e[4]),i=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||s>23||i>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function YA(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<VA?t*1e3:t;if(typeof t=="string")return JA(t)}function dg(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:YA(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Ut=XA.child({prefix:"pi-mcp"}),W=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},Bn=class extends Error{},fg=[100,500],QA=fg.length+1,e0=t=>new Promise(e=>{setTimeout(e,t)});function lg(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Zu="augment.mcp-access-token.",t0=JSON.stringify({retired:!0}),Yi=3;function qt(t){return`${Zu}${t}`}function Xi(t){return`legacy:${t}`}function er(t){return t?.id?cg(t.id,t.name):void 0}function Qi(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 Pr(t){let e=Qi(t);return e?JSON.stringify(e):void 0}function r0(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 Wu(t){if(typeof t=="string")try{return Wu(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 n0(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function Wn(t){try{let e=JSON.parse(t);return{credentialIdentity:Wu(e.credentialIdentity),state:n0(e)}}catch{return{}}}function es(t,e){let r={...t,type:"oauth",credentialIdentity:Qi(e)};return JSON.stringify(r)}function nn(t,e){let r=ug({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:Qi(e),credentialState:"active"})}function o0(t){return JSON.stringify({credentialIdentity:Qi(t),credentialState:"retired",retired:!0})}function s0(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=r0(e),s=Wu(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 Gu(t){try{let e=dg(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||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 ts=class{_memory=new Hn;_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=e0){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(()=>{Ut.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(()=>{Ut.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=Pr(r);if(!n)throw new W;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=er(e),n=Pr(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 W}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<Yi;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new W}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=Wn(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new W;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=Gu(i.value);if(!c)throw new W;try{await r.upsertUserSecret(n,nn(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=er(e),n=Pr(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new W;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new W;let i=Wn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Gu(s.value))throw new W;return s.version})}catch{throw new W}}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=er(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,nn(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 W;if(c)return{revision:await this._asPersistenceResult(c()),domain:Xi(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=er(o),c;if(a&&o){if(!i||s?.domain!==`private:${o.id}`)throw new W;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 W;if(a&&o){try{await this._enqueueWrite(qt(e),()=>this._restoreLegacyCredential({client:i,key:qt(e),persistedToken:r,currentToken:n,registry:o}))}catch{Ut.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return c}if(s?.domain!==Xi(e))throw new W;try{return await this._enqueueWrite(qt(e),()=>this._restoreLegacyCredentialExact({client:i,key:qt(e),serverName:e,persistedToken:r,currentToken:n,registry:o,persistedRevision:s}))}catch{throw new W}}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!==es(s,a)))try{return{revision:await r.upsertUserSecret(n,es(i,a),c.revision),domain:Xi(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!==nn(o,i)))try{return{revision:await r.upsertUserSecret(n,nn(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!==es(o,i)))try{await r.upsertUserSecret(n,es(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 W}if(o?.(),s?.id&&!i)throw new W;try{await n?.()}catch{Ut.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=Pr(o);if(!s)throw new W;for(let i=0;i<Yi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?Wn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new W;try{return await this._upsertUserSecretOnce(e,r,nn(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new W}async _retireRegistryCredential(e,r,n){let o=Pr(n);if(!o)throw new W;for(let s=0;s<Yi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?Wn(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new W;try{await this._upsertUserSecretOnce(e,r,o0(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new W}_isVersionConflict(e){return e instanceof lt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=er(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 W;if(u)return{revision:await this._asPersistenceResult(u()),domain:Xi(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new W}}_enqueueWrite(e,r,n){let o=lg(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?QA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new Bn;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 W}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new Bn}_persistenceRetryDelay(e,r,n){let o=n?fg[r]:void 0,s=!(e instanceof W)&&Hu(e);if(o===void 0||!s){n&&Ut.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(qt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,qt(e),es(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 Bn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=Pr(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=er(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new W));let l=this._shouldPersist()&&!i,f;return l&&(c?f=this._enqueueWrite(qt(e),async()=>{let p=await c.upsertUserSecret(qt(e),t0)}):f=Promise.reject(new W)),this._awaitRetirements(e,d,f).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"&&Ut.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Ut.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=qt(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 Bn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=er(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(()=>{Ut.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(lg(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=er(r),o=Pr(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<Yi;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=Wn(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=Gu(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,nn(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=er(n),i=Pr(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=Wn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,nn(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(qt(r));return o?s0(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){Ut.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),Ut.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var pg="Augment Code",hg="https://augmentcode.com",mg="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var a0=1e3,c0=500;function Vu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function rs(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Bu=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function gg(t){return new URLSearchParams({k:t}).toString().slice(2)}function u0(t,e){let r=`${gg(t)}:${gg(e)}`;return`Basic ${btoa(r)}`}function Sg(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function d0(t){return t.client.token_endpoint_auth_method==="none"||!Sg(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function l0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function f0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var p0=401,wg=500;function Ku(t,...e){return t.status<wg&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function yg(t){return Ku(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===p0}async function vg(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=Sg(t);e==="basic"&&s?n.Authorization=u0(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=f0(c),d=c.slice(0,c0);throw new on(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Bu;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*a0:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function _g(t,e){try{return await vg(t,e,t.resource)}catch(r){if(r instanceof on&&t.resource&&Ku(r,"invalid_target"))return await vg(t,e,void 0);throw r}}var on=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 Ju(t){return!(t instanceof on)||t.status>=wg?!1:Ku(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Yu(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=d0(t);try{return await _g(e,r)}catch(n){let o=l0(r);if(!(n instanceof on)||!o||!yg(n))throw n;try{return await _g(e,o)}catch(s){throw s instanceof on&&yg(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as a$}from"@hermes/logger";var ed;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ed="oauth4webapi/v3.8.6");function Yn(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 Ht="ERR_INVALID_ARG_VALUE",Ve="ERR_INVALID_ARG_TYPE";function pe(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var sd=Symbol(),h0=Symbol(),m0=Symbol(),an=Symbol();var bg=Symbol();var g0=new TextEncoder,y0=new TextDecoder;function td(t){return typeof t=="string"?g0.encode(t):y0.decode(t)}var rd;Uint8Array.prototype.toBase64?rd=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):rd=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 nd;Uint8Array.fromBase64?nd=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw pe("The input to be decoded is not correctly encoded.",Ht,e)}}:nd=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 pe("The input to be decoded is not correctly encoded.",Ht,e)}};function ta(t){return typeof t=="string"?nd(t):rd(t)}var Kn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=K0,Error.captureStackTrace?.(this,this.constructor)}},ns=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new ns(t,{code:e,cause:r})}function ra(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function id(t){Yn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(ed&&!e.has("user-agent")&&e.set("user-agent",ed),e.has("authorization"))throw pe('"options.headers" must not include the "authorization" header name',Ht);return e}function ad(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw pe('"options.signal" must return or be an instance of AbortSignal',Ve);return e}}function v0(t){return t.includes("//")?t.replace("//","/"):t}function _0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=v0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function S0(t,e,r,n){if(!(t instanceof URL))throw pe(`"${e}" must be an instance of URL`,Ve);Ig(t,n?.[sd]!==!0);let o=r(new URL(t.href)),s=id(n?.headers);return s.set("accept","application/json"),(n?.[an]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ad(o,n?.signal)})}function Vn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw pe(`${r} must be a number`,Ve,o);if(t>0)return;if(e){if(t!==0)throw pe(`${r} must be a non-negative number`,Ht,o);return}throw pe(`${r} must be a positive number`,Ht,o)}catch(s){throw n?O(s.message,n,o):s}}function Te(t,e,r,n){try{if(typeof t!="string")throw pe(`${e} must be a string`,Ve,n);if(t.length===0)throw pe(`${e} must not be empty`,Ht,n)}catch(o){throw r?O(o.message,r,n):o}}async function Cg(t,e){let r=t;if(!(r instanceof URL)&&r!==sa)throw pe('"expectedIssuerIdentifier" must be an instance of URL',Ve);if(!Yn(e,Response))throw pe('"response" must be an instance of Response',Ve);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',md,e);is(e);let n=await ua(e);if(Te(n.issuer,'"response" body "issuer" property',B,{body:n}),r!==sa&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',aa,{expected:r.href,body:n,attribute:"issuer"});return n}function xg(t){b0(t,"application/json")}function w0(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,Y0,t)}function b0(t,e){if(O0(t)!==e)throw w0(t,e)}function cd(){return ta(crypto.getRandomValues(new Uint8Array(32)))}function kg(){return cd()}function Eg(){return cd()}function Tg(){return cd()}async function Ag(t){return Te(t,"codeVerifier"),ta(await crypto.subtle.digest("SHA-256",td(t)))}function ud(t){let e=t?.[h0];return typeof e=="number"&&Number.isFinite(e)?e:0}function dd(t){let e=t?.[m0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function ld(){return Math.floor(Date.now()/1e3)}function ia(t){if(typeof t!="object"||t===null)throw pe('"as" must be an object',Ve);Te(t.issuer,'"as.issuer"')}function fd(t){if(typeof t!="object"||t===null)throw pe('"client" must be an object',Ve);Te(t.client_id,'"client.client_id"')}function Rg(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 pd(t){return Te(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function $g(t){return Te(t,'"clientSecret"'),(e,r,n,o)=>{let s=Rg(r.client_id),i=Rg(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function Mg(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var R0=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function Ig(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",X0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",Q0,t)}function Pg(t,e,r,n){let o;if(typeof t!="string"||!(o=R0(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?e$:t$,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return Ig(o,n),o}function Og(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Pg(t.mtls_endpoint_aliases[e],e,r,n):Pg(t[e],e,r,n)}var Jn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=V0,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)}},os=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=J0,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)}},ss=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=B0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},na="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",P0="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",C0='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',x0="("+na+")\\s*=\\s*"+C0,k0="("+na+")\\s*=\\s*("+na+")",E0=new RegExp("^[,\\s]*("+na+")"),T0=new RegExp("^[,\\s]*"+x0+"[,\\s]*(.*)"),A0=new RegExp("^[,\\s]*"+k0+"[,\\s]*(.*)"),$0=new RegExp("^("+P0+")(?:$|[,\\s])(.*)");function M0(t){if(!Yn(t,Response))throw pe('"response" must be an instance of Response',Ve);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(E0),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 f,p;if(o=n.match(T0)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(A0)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match($0)){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){is(t),xg(t);try{let e=await t.clone().json();if(ra(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function zg(t,e,r){if(t.status!==e){L0(t);let n;throw(n=await I0(t))?(await t.body?.cancel(),new Jn("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,md,t)}}function Ng(t){if(!hd.has(t))throw pe('"options.DPoP" is not a valid DPoPHandle',Ht)}function O0(t){return t.headers.get("content-type")?.split(";")[0]}async function z0(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?.[an]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ad(n,i?.signal)})}async function N0(t,e,r,n,o,s){let i=Og(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[sd]!==!0);o.set("grant_type",n);let a=id(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(Ng(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await z0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var Dg=new WeakMap,D0=new WeakMap;function Lg(t){if(!t.id_token)return;let e=Dg.get(t);if(!e)throw pe('"ref" was already garbage collected or did not resolve from the proper sources',Ht);return e}async function jg(t,e,r,n,o,s){if(ia(t),fd(e),!Yn(r,Response))throw pe('"response" must be an instance of Response',Ve);await zg(r,200,"Token Endpoint"),is(r);let i=await ua(r);if(Te(i.access_token,'"response" body "access_token" property',B,{body:i}),Te(i.token_type,'"response" body "token_type" property',B,{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;Vn(a,!0,'"response" body "expires_in" property',B,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Te(i.refresh_token,'"response" body "refresh_token" property',B,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw O('"response" body "scope" property must be a string',B,{body:i});if(i.id_token!==void 0){Te(i.id_token,'"response" body "id_token" property',B,{body:i});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Vn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await r$(i.id_token,n$.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),ud(e),dd(e),o).then(G0.bind(void 0,a)).then(F0.bind(void 0,t)).then(j0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',Cr,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',Cr,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Vn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',B,{claims:c}),D0.set(r,u),Dg.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 Kn("unsupported `token_type` value",{cause:{body:i}});return i}function L0(t){let e;if(e=M0(t))throw new ss("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function j0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',Cr,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',Cr,{expected:t,claims:e.claims,claim:"aud"});return e}function F0(t,e){let r=t[i$]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',Cr,{expected:r,claims:e.claims,claim:"iss"});return e}var hd=new WeakSet;function U0(t){return hd.add(t),t}var q0=Symbol();async function Fg(t,e,r,n,o,s,i){if(ia(t),fd(e),!hd.has(n))throw pe('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ht);Te(o,'"redirectUri"');let a=sn(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',B);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==q0&&(Te(s,'"codeVerifier"'),c.set("code_verifier",s)),N0(t,e,r,"authorization_code",c,i)}var H0={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 G0(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${H0[r]}) claim missing`,B,{claims:e.claims});return e}var Xu=Symbol(),Qu=Symbol();async function Ug(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?Z0(t,e,r,n.expectedNonce,n.maxAge,n[bg],n.recognizedTokenTypes):W0(t,e,r,n?.[bg],n?.recognizedTokenTypes)}async function Z0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=Xu;break;case Xu:break;default:Te(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Qu;break;case Qu:break;default:Vn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await jg(t,e,r,a,s,i);Te(c.id_token,'"response" body "id_token" property',B,{body:c});let u=Lg(c);if(o!==Qu){let d=ld()+ud(e),l=dd(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",oa,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===Xu){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Cr,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',Cr,{expected:n,claims:u,claim:"nonce"});return c}async function W0(t,e,r,n,o){let s=await jg(t,e,r,void 0,n,o),i=Lg(s);if(i){if(e.default_max_age!==void 0){Vn(e.default_max_age,!0,'"client.default_max_age"');let a=ld()+ud(e),c=dd(e);if(i.auth_time+e.default_max_age<a-c)throw O("too much time has elapsed since the last End-User authentication",oa,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Cr,{expected:void 0,claims:i,claim:"nonce"})}return s}var B0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",V0="OAUTH_RESPONSE_BODY_ERROR",K0="OAUTH_UNSUPPORTED_OPERATION",J0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var od="OAUTH_PARSE_ERROR",B="OAUTH_INVALID_RESPONSE";var Y0="OAUTH_RESPONSE_IS_NOT_JSON",md="OAUTH_RESPONSE_IS_NOT_CONFORM",X0="OAUTH_HTTP_REQUEST_FORBIDDEN",Q0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",oa="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Cr="OAUTH_JWT_CLAIM_COMPARISON_FAILED",aa="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var e$="OAUTH_MISSING_SERVER_METADATA",t$="OAUTH_INVALID_SERVER_METADATA";function is(t){if(t.bodyUsed)throw pe('"response" body has been used already',Ht)}async function r$(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 Kn("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",B,t);let c;try{c=JSON.parse(td(ta(s)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",od,l)}if(!ra(c))throw O("JWT Header must be a top level object",B,t);if(e(c),c.crit!==void 0)throw new Kn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(td(ta(i)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",od,l)}if(!ra(u))throw O("JWT Payload must be a top level object",B,t);let d=ld()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',B,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',oa,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',B,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',B,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',B,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',oa,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',B,{claims:u});return{header:c,claims:u,jwt:t}}function n$(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function sn(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,B);return r}var o$=Symbol(),s$=Symbol();function qg(t,e,r,n){if(ia(t),fd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw pe('"parameters" must be an instance of URLSearchParams, or URL',Ve);if(sn(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',B,{parameters:r});let o=sn(r,"iss"),s=sn(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',B,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',B,{expected:t.issuer,parameters:r});switch(n){case void 0:case s$:if(s!==void 0)throw O('unexpected "state" response parameter encountered',B,{expected:void 0,parameters:r});break;case o$:break;default:if(Te(n,'"expectedState" argument'),s!==n)throw O(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',B,{expected:n,parameters:r})}if(sn(r,"error"))throw new os("authorization response from the server is an error",{cause:r});let a=sn(r,"id_token"),c=sn(r,"token");if(a!==void 0||c!==void 0)throw new Kn("implicit and hybrid flows are not supported");return U0(new URLSearchParams(r))}async function Hg(t,e,r){ia(t);let n=Og(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[sd]!==!0),o=id(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(Ng(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?.[an]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:ad(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Gg(t){if(!Yn(t,Response))throw pe('"response" must be an instance of Response',Ve);await zg(t,201,"Dynamic Client Registration Endpoint"),is(t);let e=await ua(t);return Te(e.client_id,'"response" body "client_id" property',B,{body:e}),e.client_secret!==void 0&&Te(e.client_secret,'"response" body "client_secret" property',B,{body:e}),e.client_secret&&Vn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',B,{body:e}),e}async function Zg(t,e){return S0(t,"resourceIdentifier",r=>(_0(r,".well-known/oauth-protected-resource",!0),r),e)}async function ca(t,e){let r=t;if(!(r instanceof URL)&&r!==sa)throw pe('"expectedResourceIdentifier" must be an instance of URL',Ve);if(!Yn(e,Response))throw pe('"response" must be an instance of Response',Ve);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',md,e);is(e);let n=await ua(e);if(Te(n.resource,'"response" body "resource" property',B,{body:n}),r!==sa&&new URL(n.resource).href!==r.href)throw O('"response" body "resource" property does not match the expected value',aa,{expected:r.href,body:n,attribute:"resource"});return n}async function ua(t,e=xg){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',od,n)}if(!ra(r))throw O('"response" body must be a top level object',B,{body:r});return r}var sa=Symbol(),i$=Symbol();var Vg=a$.child({prefix:"pi-mcp"}),as=1e4,c$=1e3,u$=401,Wg=200,d$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,l$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Kg;function Xn(){return Kg??globalThis.fetch}function Jg(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function Yg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function yd(t){let e=Yg(t);try{let r=await f$(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await y$(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw fa(r)}throw new Error("Failed to discover metadata URL")}async function f$(t){try{let e=await Zg(t,{signal:AbortSignal.timeout(as),[an]:Kg??void 0});return e.ok?await ca(t,e):(e.body?.cancel().catch(()=>{}),await Xg(t,e.headers.get("www-authenticate"))??await Bg(t))}catch{return await Bg(t)}}async function Bg(t){for(let e of["HEAD","GET"])try{let r=await Xn()(t,{method:e,signal:AbortSignal.timeout(as)});r.body?.cancel().catch(()=>{});let n=await Xg(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Xg(t,e){let r=g$(e);if(r)try{let n=await Xn()(r,{signal:AbortSignal.timeout(as)});return await p$(t,n)}catch{return}}async function p$(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await ca(t,new Response(r,n))}catch(o){if(!(o instanceof ns)||o.code!==aa)throw o;let s=h$(r);if(!s||!m$(s,t))throw o;return await ca(s,new Response(r,n))}}function h$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function m$(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 g$(t){if(!t)return;let e=t.match(d$),r=t.match(l$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function y$(t){for(let e of v$(t))try{let r=new URL(e,t),n=await Xn()(r,{signal:AbortSignal.timeout(as)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function v$(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 vd(t){try{let e=await Xn()(t,{signal:AbortSignal.timeout(as)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await _$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await Cg(o,new Response(r,n))}catch(e){throw fa(e)}}async function _$(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 gd=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 S$(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 _d({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return S$({...t,clientId:n});if(!e.registration_endpoint)throw new gd(e.issuer);return await w$(e,r)}async function w$(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Hg(t,{client_name:pg,client_uri:hg,logo_uri:mg,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[an]:b$});return n.ok||Vg.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Gg(n)}catch(r){throw fa(r)}}async function b$(t,e){let r=await Xn()(t,Jg(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Vg.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${P$(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 R$(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}),Xn()(t,Jg(o))}function P$(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>Wg?`${t.slice(0,Wg)}\u2026`:t}}async function da(t,e,r,n,o,s,i){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=kg(),c=await Ag(a),u=Eg(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!i?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=Yg(s??t).toString(),m=new URL(r.authorization_endpoint);return m.searchParams.set("response_type","code"),m.searchParams.set("client_id",e.client_id),m.searchParams.set("code_challenge",c),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("redirect_uri",n),m.searchParams.set("resource",h),m.searchParams.set("state",u),p&&m.searchParams.set("scope",p),l?.includes("offline_access")&&m.searchParams.set("prompt","consent"),r.code_challenge_methods_supported?.includes("S256")||(d=Tg(),m.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:m}}function la(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function Sd(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await da(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function C$(t,e,r){let n=await Fg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[an]:R$,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Ug(t.serverMetadata,t.client,await x$(n))}async function wd(t,e){try{let r=qg(e.serverMetadata,e.client,t,e.state),n=await E$(e.client,o=>C$(e,r,o));return $$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw fa(r)}}async function x$(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 Qg(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function k$(t){let e=Qg(t);return e===void 0?Mg():t.token_endpoint_auth_method==="client_secret_basic"?$g(e):pd(e)}async function E$(t,e){try{return await e(k$(t))}catch(r){let n=T$(t);if(n&&A$(r))return await e(n);throw r}}function T$(t){let e=Qg(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return pd(e)}function A$(t){return t instanceof Jn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof ss?t.status===u$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function $$(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*c$:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function fa(t){if(t instanceof Jn||t instanceof os){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 M$=/(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,ey=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,ty=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,ry=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,cs="[redacted]";function I$(t){return ey.test(t)||ty.test(t)||ry.test(t)}var O$=new RegExp(ey.source,"g"),z$=new RegExp(ty.source,"gi"),N$=new RegExp(ry.source,"g");function ny(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function Rd(t){return t&&ny(t,8192).replace(O$,cs).replace(z$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${cs}`).replace(N$,cs)}function bd(t,e,r){if(e)return cs;if(typeof t=="string")return I$(t)?cs:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>bd(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=bd(s,M$.test(o),r+1);return n}function oy(t,e=500){if(t==null)return;let r=bd(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return ny(n,e)}var iy={reportError:()=>{}},sy=Symbol.for("__pi_mcp_error_reporter_slot__");function ay(){let t=globalThis,e=t[sy];return e||(e={reporter:null},t[sy]=e),e}function cy(t){let e=ay(),r=e.reporter??iy;return e.reporter=t,r}function D$(){return ay().reporter??iy}function Pd(t,e){try{D$().reportError(t,e)}catch{}}import{logger as L$}from"@hermes/logger";var Cd=L$.child({prefix:"pi-mcp"});function uy(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++):Cd.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];Cd.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function dy(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Zu)){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 ly(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,Cd.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function fy(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as j$}from"@hermes/logger";var us=j$.child({prefix:"pi-mcp"}),F$="$augment-",ds=/\$augment-[a-zA-Z0-9_.-]+/g,U$=new RegExp(ds.source);function pa(t){return U$.test(t)}function ha(t){return t.slice(F$.length)}function xd(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(ds))e.add(ha(n[0]));return[...e].sort()}var q$=["permission_denied","missing","transient"];function py(t){let e=new Set(t);return q$.find(r=>e.has(r))??"missing"}var ft=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 hy(t,e,r,n,o,s,i){let a=[...t.matchAll(ds)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=ha(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),s.set(f,p===void 0?"missing":p.reason),us.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),us.warn(`Secret "${f}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),us.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),s.set(f,"transient"),us.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function my({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(!pa(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){us.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await hy(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 H$=/["$`\\]/g;function G$(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 Z$(t,e){let r=G$(e);if(r==="double")return t.replace(H$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function gy(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await hy(t,"command",e,r,n,o,Z$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as CU}from"node:async_hooks";var yy,kd=Object.freeze({status:"aborted"});function _(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 f=d[l];f in a||(a[f]=u[f].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 Gt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Qn=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(yy=globalThis).__zod_globalConfig??(yy.__zod_globalConfig={});var eo=globalThis.__zod_globalConfig;function Ke(t){return t&&Object.assign(eo,t),eo}var U={};Su(U,{BIGINT_FORMAT_RANGES:()=>wy,Class:()=>Td,NUMBER_FORMAT_RANGES:()=>zd,aborted:()=>Er,allowsEval:()=>Md,assert:()=>J$,assertEqual:()=>W$,assertIs:()=>V$,assertNever:()=>K$,assertNotEqual:()=>B$,assignProp:()=>xr,base64ToUint8Array:()=>Ry,base64urlToUint8Array:()=>pM,cached:()=>ro,captureStackTrace:()=>ya,cleanEnum:()=>fM,cleanRegex:()=>hs,clone:()=>pt,cloneDef:()=>X$,createTransparentProxy:()=>oM,defineLazy:()=>Y,esc:()=>ga,escapeRegex:()=>rr,explicitlyAborted:()=>Nd,extend:()=>aM,finalizeIssue:()=>ht,floatSafeRemainder:()=>Ad,getElementAtPath:()=>Q$,getEnumValues:()=>fs,getLengthableOrigin:()=>ms,getParsedType:()=>nM,getSizableOrigin:()=>by,hexToUint8Array:()=>mM,isObject:()=>cn,isPlainObject:()=>kr,issue:()=>no,joinValues:()=>ma,jsonStringifyReplacer:()=>to,merge:()=>uM,mergeDefs:()=>tr,normalizeParams:()=>A,nullish:()=>ps,numKeys:()=>rM,objectClone:()=>Y$,omit:()=>iM,optionalKeys:()=>Od,parsedType:()=>Dd,partial:()=>dM,pick:()=>sM,prefixIssues:()=>nr,primitiveTypes:()=>Sy,promiseAllObject:()=>eM,propertyKeyTypes:()=>Id,randomString:()=>tM,required:()=>lM,safeExtend:()=>cM,shallowClone:()=>_y,slugify:()=>$d,stringifyPrimitive:()=>va,uint8ArrayToBase64:()=>Py,uint8ArrayToBase64url:()=>hM,uint8ArrayToHex:()=>gM,unwrapMessage:()=>ls});function W$(t){return t}function B$(t){return t}function V$(t){}function K$(t){throw new Error("Unexpected value in exhaustive check")}function J$(t){}function fs(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 ma(t,e="|"){return t.map(r=>va(r)).join(e)}function to(t,e){return typeof e=="bigint"?e.toString():e}function ro(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ps(t){return t==null}function hs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ad(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 vy=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==vy)return n===void 0&&(n=vy,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Y$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function xr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function tr(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function X$(t){return tr(t._zod.def)}function Q$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function eM(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 tM(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ga(t){return JSON.stringify(t)}function $d(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ya="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function cn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Md=ro(()=>{if(eo.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function kr(t){if(cn(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(cn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function _y(t){return kr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function rM(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var nM=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}`)}},Id=new Set(["string","number","symbol"]),Sy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function rr(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 oM(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 va(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Od(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var zd={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]},wy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function sM(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=tr(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 xr(this,"shape",i),i},checks:[]});return pt(t,s)}function iM(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=tr(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 xr(this,"shape",i),i},checks:[]});return pt(t,s)}function aM(t,e){if(!kr(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=tr(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return xr(this,"shape",s),s}});return pt(t,o)}function cM(t,e){if(!kr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=tr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return xr(this,"shape",n),n}});return pt(t,r)}function uM(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=tr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return xr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function dM(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=tr(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 xr(this,"shape",c),c},checks:[]});return pt(e,i)}function lM(t,e,r){let n=tr(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 xr(this,"shape",s),s}});return pt(e,n)}function Er(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 Nd(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 nr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ls(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n=t.message?t.message:ls(t.inst?._zod.def?.error?.(t))??ls(e?.error?.(t))??ls(r.customError?.(t))??ls(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 by(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ms(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Dd(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 no(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function fM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Ry(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 Py(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function pM(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Ry(e+r)}function hM(t){return Py(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function mM(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 gM(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Td=class{constructor(...e){}};var Cy=(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,to,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},_a=_("$ZodError",Cy),Ld=_("$ZodError",Cy,{Parent:Error});function jd(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 Fd(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 Sa=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 Gt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ke())));throw ya(a,o?.callee),a}return i.value};var wa=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=>ht(c,s,Ke())));throw ya(a,o?.callee),a}return i.value};var gs=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 Gt;return s.issues.length?{success:!1,error:new(t??_a)(s.issues.map(i=>ht(i,o,Ke())))}:{success:!0,data:s.value}},ys=gs(Ld),vs=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=>ht(i,o,Ke())))}:{success:!0,data:s.value}},ba=vs(Ld),xy=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Sa(t)(e,r,o)};var ky=t=>(e,r,n)=>Sa(t)(e,r,n);var Ey=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return wa(t)(e,r,o)};var Ty=t=>async(e,r,n)=>wa(t)(e,r,n);var Ay=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return gs(t)(e,r,o)};var $y=t=>(e,r,n)=>gs(t)(e,r,n);var My=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return vs(t)(e,r,o)};var Iy=t=>async(e,r,n)=>vs(t)(e,r,n);var Oy=/^[cC][0-9a-z]{6,}$/,zy=/^[0-9a-z]+$/,Ny=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dy=/^[0-9a-vA-V]{20}$/,Ly=/^[A-Za-z0-9]{27}$/,jy=/^[a-zA-Z0-9_-]{21}$/,Fy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Uy=/^([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})$/,Ud=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 qy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var vM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Hy(){return new RegExp(vM,"u")}var Gy=/^(?:(?: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])$/,Zy=/^(([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 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])\/([0-9]|[1-2][0-9]|3[0-2])$/,By=/^(([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])$/,Vy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qd=/^[A-Za-z0-9_-]*$/;var Ky=/^https?$/,Jy=/^\+[1-9]\d{6,14}$/,Yy="(?:(?:\\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])))",Xy=new RegExp(`^${Yy}$`);function Qy(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 ev(t){return new RegExp(`^${Qy(t)}$`)}function tv(t){let e=Qy({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(`^${Yy}T(?:${n})$`)}var rv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},nv=/^-?\d+n?$/,ov=/^-?\d+$/,Hd=/^-?\d+(?:\.\d+)?$/,sv=/^(?:true|false)$/i,iv=/^null$/i;var av=/^[^A-Z]*$/,cv=/^[^a-z]*$/;var Ae=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),uv={number:"number",bigint:"bigint",object:"date"},Gd=_("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);let r=uv[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})}}),Zd=_("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);let r=uv[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})}}),dv=_("$ZodCheckMultipleOf",(t,e)=>{Ae.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):Ad(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})}}),lv=_("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=zd[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=ov)}),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 fv=_("$ZodCheckMaxLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ps(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=ms(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),pv=_("$ZodCheckMinLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ps(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=ms(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),hv=_("$ZodCheckLengthEquals",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ps(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=ms(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})}}),Ss=_("$ZodCheckStringFormat",(t,e)=>{var r,n;Ae.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=()=>{})}),mv=_("$ZodCheckRegex",(t,e)=>{Ss.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})}}),gv=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=av),Ss.init(t,e)}),yv=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=cv),Ss.init(t,e)}),vv=_("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);let r=rr(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})}}),_v=_("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`^${rr(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})}}),Sv=_("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);let r=new RegExp(`.*${rr(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 wv=_("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ra=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 fv={major:4,minor:4,patch:3};var te=v("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=fv;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=Cr(i),d;for(let l of a){if(l._zod.def.when){if(xd(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Ht;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=Cr(i,f)))});else{if(i.issues.length===f)continue;u||(u=Cr(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(Cr(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ht;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 Ht;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=ds(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ga(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Sa=v("$ZodString",(t,e)=>{te.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Zy(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=v("$ZodStringFormat",(t,e)=>{ps.init(t,e),Sa.init(t,e)}),wv=v("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Ay),ce.init(t,e)}),bv=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=$d(n))}else e.pattern??(e.pattern=$d());ce.init(t,e)}),Rv=v("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=$y),ce.init(t,e)}),Pv=v("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Ly.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})}}}),Cv=v("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=My()),ce.init(t,e)}),xv=v("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ey),ce.init(t,e)}),kv=v("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ry),ce.init(t,e)}),Ev=v("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Py),ce.init(t,e)}),Tv=v("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Cy),ce.init(t,e)}),Av=v("$ZodXID",(t,e)=>{e.pattern??(e.pattern=xy),ce.init(t,e)}),$v=v("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ky),ce.init(t,e)}),Mv=v("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Gy(e)),ce.init(t,e)}),Iv=v("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Uy),ce.init(t,e)}),Ov=v("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Hy(e)),ce.init(t,e)}),zv=v("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ty),ce.init(t,e)}),Nv=v("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Iy),ce.init(t,e),t._zod.bag.format="ipv4"}),Dv=v("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Oy),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var Lv=v("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=zy),ce.init(t,e)}),jv=v("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ny),ce.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 Fv(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Uv=v("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Dy),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Fv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function fM(t){if(!Md.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Fv(r)}var qv=v("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Md),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{fM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Hv=v("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jy),ce.init(t,e)});function pM(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 Gv=v("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{pM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Dd=v("$ZodNumber",(t,e)=>{te.init(t,e),t._zod.pattern=t._zod.bag.pattern??Id,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}}),Zv=v("$ZodNumberFormat",(t,e)=>{ev.init(t,e),Dd.init(t,e)}),Bv=v("$ZodBoolean",(t,e)=>{te.init(t,e),t._zod.pattern=Wy,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}}),Vv=v("$ZodBigInt",(t,e)=>{te.init(t,e),t._zod.pattern=By,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 Wv=v("$ZodNull",(t,e)=>{te.init(t,e),t._zod.pattern=Ky,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}}),Kv=v("$ZodAny",(t,e)=>{te.init(t,e),t._zod.parse=r=>r}),Jv=v("$ZodUnknown",(t,e)=>{te.init(t,e),t._zod.parse=r=>r}),Yv=v("$ZodNever",(t,e)=>{te.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Xv=v("$ZodDate",(t,e)=>{te.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 pv(t,e,r){t.issues.length&&e.issues.push(...rr(r,t.issues)),e.value[r]=t.value}var Qv=v("$ZodArray",(t,e)=>{te.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=>pv(u,r,i))):pv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function _a(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...rr(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 e_(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=Pd(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function t_(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 f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>_a(h,r,f,e,d,l))):_a(p,r,f,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 hM=v("$ZodObject",(t,e)=>{if(te.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=Jn(()=>e_(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=on,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 f of i.keys){let p=l[f],h=p._zod.optin==="optional",m=p._zod.optout==="optional",y=p._zod.run({value:u[f],issues:[]},c);y instanceof Promise?d.push(y.then(_=>_a(_,a,f,u,h,m))):_a(y,a,f,u,h,m)}return s?t_(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),r_=v("$ZodObjectJIT",(t,e)=>{hM.init(t,e);let r=t._zod.parse,n=Jn(()=>e_(e)),o=f=>{let p=new ya(["shape","payload","ctx"]),h=n.value,m=w=>{let k=da(w);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),_=0;for(let w of h.keys)y[w]=`key_${_++}`;p.write("const newResult = {};");for(let w of h.keys){let k=y[w],S=da(w),P=f[w],I=P?._zod?.optin==="optional",ne=P?._zod?.optout==="optional";p.write(`const ${k} = ${m(w)};`),I&&ne?p.write(`
27
- if (${k}.issues.length) {
26
+ `))}};var Rv={major:4,minor:4,patch:3};var te=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Rv;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=Er(i),d;for(let l of a){if(l._zod.def.when){if(Nd(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Gt;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=Er(i,f)))});else{if(i.issues.length===f)continue;u||(u=Er(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(Er(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Gt;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 Gt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=ys(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ba(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),xa=_("$ZodString",(t,e)=>{te.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??rv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=_("$ZodStringFormat",(t,e)=>{Ss.init(t,e),xa.init(t,e)}),Mv=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Uy),ce.init(t,e)}),Iv=_("$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=Ud(n))}else e.pattern??(e.pattern=Ud());ce.init(t,e)}),Ov=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=qy),ce.init(t,e)}),zv=_("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Ky.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})}}}),Nv=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Hy()),ce.init(t,e)}),Dv=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=jy),ce.init(t,e)}),Lv=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Oy),ce.init(t,e)}),jv=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=zy),ce.init(t,e)}),Fv=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ny),ce.init(t,e)}),Uv=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Dy),ce.init(t,e)}),qv=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ly),ce.init(t,e)}),Hv=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=tv(e)),ce.init(t,e)}),Gv=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Xy),ce.init(t,e)}),Zv=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=ev(e)),ce.init(t,e)}),Wv=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Fy),ce.init(t,e)}),Bv=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Gy),ce.init(t,e),t._zod.bag.format="ipv4"}),Vv=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Zy),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var Kv=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Wy),ce.init(t,e)}),Jv=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=By),ce.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 Yv(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Xv=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Vy),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{Yv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function wM(t){if(!qd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Yv(r)}var Qv=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=qd),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{wM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),e_=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Jy),ce.init(t,e)});function bM(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 t_=_("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{bM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Bd=_("$ZodNumber",(t,e)=>{te.init(t,e),t._zod.pattern=t._zod.bag.pattern??Hd,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}}),r_=_("$ZodNumberFormat",(t,e)=>{lv.init(t,e),Bd.init(t,e)}),n_=_("$ZodBoolean",(t,e)=>{te.init(t,e),t._zod.pattern=sv,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}}),o_=_("$ZodBigInt",(t,e)=>{te.init(t,e),t._zod.pattern=nv,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 s_=_("$ZodNull",(t,e)=>{te.init(t,e),t._zod.pattern=iv,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}}),i_=_("$ZodAny",(t,e)=>{te.init(t,e),t._zod.parse=r=>r}),a_=_("$ZodUnknown",(t,e)=>{te.init(t,e),t._zod.parse=r=>r}),c_=_("$ZodNever",(t,e)=>{te.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var u_=_("$ZodDate",(t,e)=>{te.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 Pv(t,e,r){t.issues.length&&e.issues.push(...nr(r,t.issues)),e.value[r]=t.value}var d_=_("$ZodArray",(t,e)=>{te.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=>Pv(u,r,i))):Pv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Ca(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...nr(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 l_(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=Od(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function f_(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 f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>Ca(h,r,f,e,d,l))):Ca(p,r,f,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 RM=_("$ZodObject",(t,e)=>{if(te.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=ro(()=>l_(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=cn,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 f of i.keys){let p=l[f],h=p._zod.optin==="optional",m=p._zod.optout==="optional",y=p._zod.run({value:u[f],issues:[]},c);y instanceof Promise?d.push(y.then(v=>Ca(v,a,f,u,h,m))):Ca(y,a,f,u,h,m)}return s?f_(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),p_=_("$ZodObjectJIT",(t,e)=>{RM.init(t,e);let r=t._zod.parse,n=ro(()=>l_(e)),o=f=>{let p=new Ra(["shape","payload","ctx"]),h=n.value,m=w=>{let x=ga(w);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),v=0;for(let w of h.keys)y[w]=`key_${v++}`;p.write("const newResult = {};");for(let w of h.keys){let x=y[w],S=ga(w),P=f[w],I=P?._zod?.optin==="optional",ne=P?._zod?.optout==="optional";p.write(`const ${x} = ${m(w)};`),I&&ne?p.write(`
27
+ if (${x}.issues.length) {
28
28
  if (${S} in input) {
29
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
29
+ payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
30
30
  ...iss,
31
31
  path: iss.path ? [${S}, ...iss.path] : [${S}]
32
32
  })));
33
33
  }
34
34
  }
35
35
 
36
- if (${k}.value === undefined) {
36
+ if (${x}.value === undefined) {
37
37
  if (${S} in input) {
38
38
  newResult[${S}] = undefined;
39
39
  }
40
40
  } else {
41
- newResult[${S}] = ${k}.value;
41
+ newResult[${S}] = ${x}.value;
42
42
  }
43
43
 
44
44
  `):I?p.write(`
45
- if (${k}.issues.length) {
46
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
45
+ if (${x}.issues.length) {
46
+ payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
47
47
  ...iss,
48
48
  path: iss.path ? [${S}, ...iss.path] : [${S}]
49
49
  })));
50
50
  }
51
51
 
52
- if (${k}.value === undefined) {
52
+ if (${x}.value === undefined) {
53
53
  if (${S} in input) {
54
54
  newResult[${S}] = undefined;
55
55
  }
56
56
  } else {
57
- newResult[${S}] = ${k}.value;
57
+ newResult[${S}] = ${x}.value;
58
58
  }
59
59
 
60
60
  `):p.write(`
61
- const ${k}_present = ${S} in input;
62
- if (${k}.issues.length) {
63
- payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
61
+ const ${x}_present = ${S} in input;
62
+ if (${x}.issues.length) {
63
+ payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
64
64
  ...iss,
65
65
  path: iss.path ? [${S}, ...iss.path] : [${S}]
66
66
  })));
67
67
  }
68
- if (!${k}_present && !${k}.issues.length) {
68
+ if (!${x}_present && !${x}.issues.length) {
69
69
  payload.issues.push({
70
70
  code: "invalid_type",
71
71
  expected: "nonoptional",
@@ -74,31 +74,31 @@ When the user's request requires one of these servers, call attach-mcp-server im
74
74
  });
75
75
  }
76
76
 
77
- if (${k}_present) {
78
- if (${k}.value === undefined) {
77
+ if (${x}_present) {
78
+ if (${x}.value === undefined) {
79
79
  newResult[${S}] = undefined;
80
80
  } else {
81
- newResult[${S}] = ${k}.value;
81
+ newResult[${S}] = ${x}.value;
82
82
  }
83
83
  }
84
84
 
85
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(w,k)=>b(f,w,k)},s,i=on,a=!Wn.jitless,u=a&&bd.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return i(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?t_([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function hv(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=>!Cr(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=>ht(i,n,Ke())))}),e)}var Ld=v("$ZodUnion",(t,e)=>{te.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=>as(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=>hv(a,n,t,o)):hv(i,n,t,o)}});var n_=v("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ld.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=Jn(()=>{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(!on(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)}}),o_=v("$ZodIntersection",(t,e)=>{te.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])=>mv(r,c,u)):mv(r,s,i)}});function Nd(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(Pr(t)&&Pr(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=Nd(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=Nd(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 mv(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}),Cr(t))return t;let i=Nd(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 s_=v("$ZodRecord",(t,e)=>{te.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Pr(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(p=>ht(p,n,Ke())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...rr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...rr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Id.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=>ht(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(...rr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...rr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var i_=v("$ZodEnum",(t,e)=>{te.init(t,e);let r=ss(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>Rd.has(typeof o)).map(o=>typeof o=="string"?tr(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}}),a_=v("$ZodLiteral",(t,e)=>{if(te.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"?tr(n):n?tr(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 c_=v("$ZodTransform",(t,e)=>{te.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Vn(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 Ht;return r.value=o,r.fallback=!0,r}});function gv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var jd=v("$ZodOptional",(t,e)=>{te.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(`^(${as(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=>gv(i,o)):gv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),u_=v("$ZodExactOptional",(t,e)=>{jd.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)}),d_=v("$ZodNullable",(t,e)=>{te.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(`^(${as(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)}),l_=v("$ZodDefault",(t,e)=>{te.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=>yv(s,e)):yv(o,e)}});function yv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var f_=v("$ZodPrefault",(t,e)=>{te.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))}),p_=v("$ZodNonOptional",(t,e)=>{te.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=>vv(s,t)):vv(o,t)}});function vv(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 h_=v("$ZodCatch",(t,e)=>{te.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=>ht(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=>ht(s,n,Ke()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Fd=v("$ZodPipe",(t,e)=>{te.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=>va(i,e.in,n)):va(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>va(s,e.out,n)):va(o,e.out,n)}});function va(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 m_=v("$ZodPreprocess",(t,e)=>{Fd.init(t,e)}),g_=v("$ZodReadonly",(t,e)=>{te.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(_v):_v(o)}});function _v(t){return t.value=Object.freeze(t.value),t}var y_=v("$ZodCustom",(t,e)=>{Ae.init(t,e),te.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=>Sv(s,r,n,t));Sv(o,r,n,t)}});function Sv(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(Yn(o))}}var mM=()=>{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=kd(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${fa(o.values[0])}`:`Invalid option: expected one of ${ua(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":""}: ${ua(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 v_(){return{localeError:mM()}}var __;var Ud=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 S_(){return new Ud}(__=globalThis).__zod_globalRegistry??(__.__zod_globalRegistry=S_());var xr=globalThis.__zod_globalRegistry;function w_(t,e){return new t({type:"string",...A(e)})}function b_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function R_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function qd(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 C_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function x_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function k_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Hd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function E_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function T_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function A_(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 M_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function I_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function O_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function z_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function N_(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function D_(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function L_(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function j_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function F_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function U_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function q_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function H_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function G_(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function Z_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function B_(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function V_(t,e){return new t({type:"number",checks:[],...A(e)})}function W_(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function K_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function J_(t,e){return new t({type:"boolean",...A(e)})}function Y_(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function X_(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function Q_(t,e){return new t({type:"null",...A(e)})}function eS(t){return new t({type:"any"})}function tS(t){return new t({type:"unknown"})}function rS(t,e){return new t({type:"never",...A(e)})}function nS(t,e){return new t({type:"date",coerce:!0,...A(e)})}function Xn(t,e){return new Od({check:"less_than",...A(e),value:t,inclusive:!1})}function nr(t,e){return new Od({check:"less_than",...A(e),value:t,inclusive:!0})}function Qn(t,e){return new zd({check:"greater_than",...A(e),value:t,inclusive:!1})}function xt(t,e){return new zd({check:"greater_than",...A(e),value:t,inclusive:!0})}function hs(t,e){return new Qy({check:"multiple_of",...A(e),value:t})}function wa(t,e){return new tv({check:"max_length",...A(e),maximum:t})}function eo(t,e){return new rv({check:"min_length",...A(e),minimum:t})}function ba(t,e){return new nv({check:"length_equals",...A(e),length:t})}function Gd(t,e){return new ov({check:"string_format",format:"regex",...A(e),pattern:t})}function Zd(t){return new sv({check:"string_format",format:"lowercase",...A(t)})}function Bd(t){return new iv({check:"string_format",format:"uppercase",...A(t)})}function Vd(t,e){return new av({check:"string_format",format:"includes",...A(e),includes:t})}function Wd(t,e){return new cv({check:"string_format",format:"starts_with",...A(e),prefix:t})}function Kd(t,e){return new uv({check:"string_format",format:"ends_with",...A(e),suffix:t})}function kr(t){return new dv({check:"overwrite",tx:t})}function Jd(t){return kr(e=>e.normalize(t))}function Yd(){return kr(t=>t.trim())}function Xd(){return kr(t=>t.toLowerCase())}function Qd(){return kr(t=>t.toUpperCase())}function el(){return kr(t=>wd(t))}function oS(t,e,r){return new t({type:"array",element:e,...A(r)})}function sS(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function iS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function aS(t,e){let r=gM(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Yn(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(Yn(s))}},t(n.value,n)),e);return r}function gM(t,e){let r=new Ae({check:"custom",...A(e)});return r._zod.check=t,r}function tl(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??xr,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 f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(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"&&Fe(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 rl(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,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}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
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(w,x)=>b(f,w,x)},s,i=cn,a=!eo.jitless,u=a&&Md.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return i(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?f_([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function Cv(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=>!Er(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=>ht(i,n,Ke())))}),e)}var Vd=_("$ZodUnion",(t,e)=>{te.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=>hs(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=>Cv(a,n,t,o)):Cv(i,n,t,o)}});var h_=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Vd.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=ro(()=>{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(!cn(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)}}),m_=_("$ZodIntersection",(t,e)=>{te.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])=>xv(r,c,u)):xv(r,s,i)}});function Wd(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(kr(t)&&kr(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=Wd(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=Wd(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 xv(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}),Er(t))return t;let i=Wd(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 g_=_("$ZodRecord",(t,e)=>{te.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!kr(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(p=>ht(p,n,Ke())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...nr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...nr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Hd.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=>ht(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(...nr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...nr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var y_=_("$ZodEnum",(t,e)=>{te.init(t,e);let r=fs(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>Id.has(typeof o)).map(o=>typeof o=="string"?rr(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}}),v_=_("$ZodLiteral",(t,e)=>{if(te.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"?rr(n):n?rr(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 __=_("$ZodTransform",(t,e)=>{te.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qn(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 Gt;return r.value=o,r.fallback=!0,r}});function kv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Kd=_("$ZodOptional",(t,e)=>{te.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(`^(${hs(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=>kv(i,o)):kv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),S_=_("$ZodExactOptional",(t,e)=>{Kd.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)}),w_=_("$ZodNullable",(t,e)=>{te.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(`^(${hs(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)}),b_=_("$ZodDefault",(t,e)=>{te.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=>Ev(s,e)):Ev(o,e)}});function Ev(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var R_=_("$ZodPrefault",(t,e)=>{te.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))}),P_=_("$ZodNonOptional",(t,e)=>{te.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=>Tv(s,t)):Tv(o,t)}});function Tv(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 C_=_("$ZodCatch",(t,e)=>{te.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=>ht(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=>ht(s,n,Ke()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Jd=_("$ZodPipe",(t,e)=>{te.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=>Pa(i,e.in,n)):Pa(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Pa(s,e.out,n)):Pa(o,e.out,n)}});function Pa(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 x_=_("$ZodPreprocess",(t,e)=>{Jd.init(t,e)}),k_=_("$ZodReadonly",(t,e)=>{te.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 E_=_("$ZodCustom",(t,e)=>{Ae.init(t,e),te.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=>$v(s,r,n,t));$v(o,r,n,t)}});function $v(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(no(o))}}var PM=()=>{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=Dd(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${va(o.values[0])}`:`Invalid option: expected one of ${ma(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":""}: ${ma(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 T_(){return{localeError:PM()}}var A_;var Yd=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 $_(){return new Yd}(A_=globalThis).__zod_globalRegistry??(A_.__zod_globalRegistry=$_());var Tr=globalThis.__zod_globalRegistry;function M_(t,e){return new t({type:"string",...A(e)})}function I_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function O_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function Xd(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function z_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function N_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function D_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function L_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Qd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function j_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function F_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function U_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function q_(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function H_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function G_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function Z_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function W_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function B_(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function V_(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function K_(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function J_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function Y_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function X_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function Q_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function eS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function tS(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function rS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function nS(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function oS(t,e){return new t({type:"number",checks:[],...A(e)})}function sS(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function iS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function aS(t,e){return new t({type:"boolean",...A(e)})}function cS(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function uS(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function dS(t,e){return new t({type:"null",...A(e)})}function lS(t){return new t({type:"any"})}function fS(t){return new t({type:"unknown"})}function pS(t,e){return new t({type:"never",...A(e)})}function hS(t,e){return new t({type:"date",coerce:!0,...A(e)})}function oo(t,e){return new Gd({check:"less_than",...A(e),value:t,inclusive:!1})}function or(t,e){return new Gd({check:"less_than",...A(e),value:t,inclusive:!0})}function so(t,e){return new Zd({check:"greater_than",...A(e),value:t,inclusive:!1})}function xt(t,e){return new Zd({check:"greater_than",...A(e),value:t,inclusive:!0})}function ws(t,e){return new dv({check:"multiple_of",...A(e),value:t})}function ka(t,e){return new fv({check:"max_length",...A(e),maximum:t})}function io(t,e){return new pv({check:"min_length",...A(e),minimum:t})}function Ea(t,e){return new hv({check:"length_equals",...A(e),length:t})}function el(t,e){return new mv({check:"string_format",format:"regex",...A(e),pattern:t})}function tl(t){return new gv({check:"string_format",format:"lowercase",...A(t)})}function rl(t){return new yv({check:"string_format",format:"uppercase",...A(t)})}function nl(t,e){return new vv({check:"string_format",format:"includes",...A(e),includes:t})}function ol(t,e){return new _v({check:"string_format",format:"starts_with",...A(e),prefix:t})}function sl(t,e){return new Sv({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Ar(t){return new wv({check:"overwrite",tx:t})}function il(t){return Ar(e=>e.normalize(t))}function al(){return Ar(t=>t.trim())}function cl(){return Ar(t=>t.toLowerCase())}function ul(){return Ar(t=>t.toUpperCase())}function dl(){return Ar(t=>$d(t))}function mS(t,e,r){return new t({type:"array",element:e,...A(r)})}function gS(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function yS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function vS(t,e){let r=CM(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(no(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(no(s))}},t(n.value,n)),e);return r}function CM(t,e){let r=new Ae({check:"custom",...A(e)});return r._zod.check=t,r}function ll(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??Tr,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 f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(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"&&Fe(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 fl(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,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}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 nl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let 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:ms(e,"input",t.processors),output:ms(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fe(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 Fe(n.element,r);if(n.type==="set")return Fe(n.valueType,r);if(n.type==="lazy")return Fe(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 Fe(n.innerType,r);if(n.type==="intersection")return Fe(n.left,r)||Fe(n.right,r);if(n.type==="record"||n.type==="map")return Fe(n.keyType,r)||Fe(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Fe(n.in,r)||Fe(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Fe(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Fe(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Fe(o,r))return!0;return!!(n.rest&&Fe(n.rest,r))}return!1}var cS=(t,e={})=>r=>{let n=tl({...r,processors:e});return ve(t,n),rl(n,t),nl(n,t)},ms=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=tl({...o??{},target:s,io:e,processors:r});return ve(t,i),rl(i,t),nl(i,t)};var yM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},uS=(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=yM[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}))])}},dS=(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),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},lS=(t,e,r,n)=>{r.type="boolean"},fS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var pS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var hS=(t,e,r,n)=>{r.not={}},mS=(t,e,r,n)=>{},gS=(t,e,r,n)=>{},yS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},vS=(t,e,r,n)=>{let o=t._zod.def,s=ss(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},_S=(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 SS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var wS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var bS=(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"]})},RS=(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},CS=(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 xS=(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)}},kS=(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"}]},ES=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},TS=(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))},AS=(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},MS=(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},IS=(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 ol=(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 Ra(t){return!!t._zod}function kt(t,e){return Ra(t)?ds(t,e):t.safeParse(e)}function Pa(t){if(!t)return;let e;if(Ra(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ca(t){if(Ra(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 gs={};du(gs,{ZodISODate:()=>zS,ZodISODateTime:()=>OS,ZodISODuration:()=>DS,ZodISOTime:()=>NS,date:()=>il,datetime:()=>sl,duration:()=>cl,time:()=>al});var OS=v("ZodISODateTime",(t,e)=>{Mv.init(t,e),he.init(t,e)});function sl(t){return H_(OS,t)}var zS=v("ZodISODate",(t,e)=>{Iv.init(t,e),he.init(t,e)});function il(t){return G_(zS,t)}var NS=v("ZodISOTime",(t,e)=>{Ov.init(t,e),he.init(t,e)});function al(t){return Z_(NS,t)}var DS=v("ZodISODuration",(t,e)=>{zv.init(t,e),he.init(t,e)});function cl(t){return B_(DS,t)}var CM=(t,e)=>{pa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ad(t,r)},flatten:{value:r=>Td(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Kn,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Kn,2)}},isEmpty:{get(){return t.issues.length===0}}})};var at=v("ZodError",CM,{Parent:Error});var jS=ha(at),FS=ma(at),US=us(at),qS=ls(at),HS=my(at),GS=gy(at),ZS=yy(at),BS=vy(at),VS=_y(at),WS=Sy(at),KS=wy(at),JS=by(at);var YS=new WeakMap;function ys(t,e,r){let n=Object.getPrototypeOf(t),o=YS.get(n);if(o||(o=new Set,YS.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 oe=v("ZodType",(t,e)=>(te.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:ms(t,"input"),output:ms(t,"output")}}),t.toJSONSchema=cS(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>jS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>US(t,r,n),t.parseAsync=async(r,n)=>FS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>qS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>HS(t,r,n),t.decode=(r,n)=>GS(t,r,n),t.encodeAsync=async(r,n)=>ZS(t,r,n),t.decodeAsync=async(r,n)=>BS(t,r,n),t.safeEncode=(r,n)=>VS(t,r,n),t.safeDecode=(r,n)=>WS(t,r,n),t.safeEncodeAsync=async(r,n)=>KS(t,r,n),t.safeDecodeAsync=async(r,n)=>JS(t,r,n),ys(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(pI(r,n))},superRefine(r,n){return this.check(hI(r,n))},overwrite(r){return this.check(kr(r))},optional(){return ge(this)},exactOptional(){return tI(this)},nullable(){return tw(this)},nullish(){return ge(tw(this))},nonoptional(r){return aI(this,r)},array(){return C(this)},or(r){return ue([this,r])},and(r){return Ea(this,r)},transform(r){return rw(this,fw(r))},default(r){return oI(this,r)},prefault(r){return iI(this,r)},catch(r){return uI(this,r)},pipe(r){return rw(this,r)},readonly(){return fI(this)},describe(r){let n=this.clone();return xr.add(n,{description:r}),n},meta(...r){if(r.length===0)return xr.get(this);let n=this.clone();return xr.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 xr.get(t)?.description},configurable:!0}),t)),nw=v("_ZodString",(t,e)=>{Sa.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>uS(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,ys(t,"_ZodString",{regex(...n){return this.check(Gd(...n))},includes(...n){return this.check(Vd(...n))},startsWith(...n){return this.check(Wd(...n))},endsWith(...n){return this.check(Kd(...n))},min(...n){return this.check(eo(...n))},max(...n){return this.check(wa(...n))},length(...n){return this.check(ba(...n))},nonempty(...n){return this.check(eo(1,...n))},lowercase(n){return this.check(Zd(n))},uppercase(n){return this.check(Bd(n))},trim(){return this.check(Yd())},normalize(...n){return this.check(Jd(...n))},toLowerCase(){return this.check(Xd())},toUpperCase(){return this.check(Qd())},slugify(){return this.check(el())}})}),dl=v("ZodString",(t,e)=>{Sa.init(t,e),nw.init(t,e),t.email=r=>t.check(R_(kM,r)),t.url=r=>t.check(Hd(ow,r)),t.jwt=r=>t.check(q_(qM,r)),t.emoji=r=>t.check(E_(EM,r)),t.guid=r=>t.check(qd(XS,r)),t.uuid=r=>t.check(P_(xa,r)),t.uuidv4=r=>t.check(C_(xa,r)),t.uuidv6=r=>t.check(x_(xa,r)),t.uuidv7=r=>t.check(k_(xa,r)),t.nanoid=r=>t.check(T_(TM,r)),t.guid=r=>t.check(qd(XS,r)),t.cuid=r=>t.check(A_(AM,r)),t.cuid2=r=>t.check($_($M,r)),t.ulid=r=>t.check(M_(MM,r)),t.base64=r=>t.check(j_(jM,r)),t.base64url=r=>t.check(F_(FM,r)),t.xid=r=>t.check(I_(IM,r)),t.ksuid=r=>t.check(O_(OM,r)),t.ipv4=r=>t.check(z_(zM,r)),t.ipv6=r=>t.check(N_(NM,r)),t.cidrv4=r=>t.check(D_(DM,r)),t.cidrv6=r=>t.check(L_(LM,r)),t.e164=r=>t.check(U_(UM,r)),t.datetime=r=>t.check(sl(r)),t.date=r=>t.check(il(r)),t.time=r=>t.check(al(r)),t.duration=r=>t.check(cl(r))});function g(t){return w_(dl,t)}var he=v("ZodStringFormat",(t,e)=>{ce.init(t,e),nw.init(t,e)}),kM=v("ZodEmail",(t,e)=>{Rv.init(t,e),he.init(t,e)});var XS=v("ZodGUID",(t,e)=>{wv.init(t,e),he.init(t,e)});var xa=v("ZodUUID",(t,e)=>{bv.init(t,e),he.init(t,e)});var ow=v("ZodURL",(t,e)=>{Pv.init(t,e),he.init(t,e)});function sw(t){return Hd(ow,t)}var EM=v("ZodEmoji",(t,e)=>{Cv.init(t,e),he.init(t,e)});var TM=v("ZodNanoID",(t,e)=>{xv.init(t,e),he.init(t,e)});var AM=v("ZodCUID",(t,e)=>{kv.init(t,e),he.init(t,e)});var $M=v("ZodCUID2",(t,e)=>{Ev.init(t,e),he.init(t,e)});var MM=v("ZodULID",(t,e)=>{Tv.init(t,e),he.init(t,e)});var IM=v("ZodXID",(t,e)=>{Av.init(t,e),he.init(t,e)});var OM=v("ZodKSUID",(t,e)=>{$v.init(t,e),he.init(t,e)});var zM=v("ZodIPv4",(t,e)=>{Nv.init(t,e),he.init(t,e)});var NM=v("ZodIPv6",(t,e)=>{Dv.init(t,e),he.init(t,e)});var DM=v("ZodCIDRv4",(t,e)=>{Lv.init(t,e),he.init(t,e)});var LM=v("ZodCIDRv6",(t,e)=>{jv.init(t,e),he.init(t,e)});var jM=v("ZodBase64",(t,e)=>{Uv.init(t,e),he.init(t,e)});var FM=v("ZodBase64URL",(t,e)=>{qv.init(t,e),he.init(t,e)});var UM=v("ZodE164",(t,e)=>{Hv.init(t,e),he.init(t,e)});var qM=v("ZodJWT",(t,e)=>{Gv.init(t,e),he.init(t,e)});var ka=v("ZodNumber",(t,e)=>{Dd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>dS(t,n,o,s),ys(t,"ZodNumber",{gt(n,o){return this.check(Qn(n,o))},gte(n,o){return this.check(xt(n,o))},min(n,o){return this.check(xt(n,o))},lt(n,o){return this.check(Xn(n,o))},lte(n,o){return this.check(nr(n,o))},max(n,o){return this.check(nr(n,o))},int(n){return this.check(QS(n))},safe(n){return this.check(QS(n))},positive(n){return this.check(Qn(0,n))},nonnegative(n){return this.check(xt(0,n))},negative(n){return this.check(Xn(0,n))},nonpositive(n){return this.check(nr(0,n))},multipleOf(n,o){return this.check(hs(n,o))},step(n,o){return this.check(hs(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 V_(ka,t)}var HM=v("ZodNumberFormat",(t,e)=>{Zv.init(t,e),ka.init(t,e)});function QS(t){return K_(HM,t)}var ll=v("ZodBoolean",(t,e)=>{Bv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o)});function se(t){return J_(ll,t)}var iw=v("ZodBigInt",(t,e)=>{Vv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>fS(t,n,o,s),t.gte=(n,o)=>t.check(xt(n,o)),t.min=(n,o)=>t.check(xt(n,o)),t.gt=(n,o)=>t.check(Qn(n,o)),t.gte=(n,o)=>t.check(xt(n,o)),t.min=(n,o)=>t.check(xt(n,o)),t.lt=(n,o)=>t.check(Xn(n,o)),t.lte=(n,o)=>t.check(nr(n,o)),t.max=(n,o)=>t.check(nr(n,o)),t.positive=n=>t.check(Qn(BigInt(0),n)),t.negative=n=>t.check(Xn(BigInt(0),n)),t.nonpositive=n=>t.check(nr(BigInt(0),n)),t.nonnegative=n=>t.check(xt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(hs(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var GM=v("ZodNull",(t,e)=>{Wv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o)});function aw(t){return Q_(GM,t)}var ZM=v("ZodAny",(t,e)=>{Kv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o)});function cw(){return eS(ZM)}var BM=v("ZodUnknown",(t,e)=>{Jv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gS(t,r,n,o)});function me(){return tS(BM)}var VM=v("ZodNever",(t,e)=>{Yv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(t,r,n,o)});function WM(t){return rS(VM,t)}var uw=v("ZodDate",(t,e)=>{Xv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>yS(t,n,o,s),t.min=(n,o)=>t.check(xt(n,o)),t.max=(n,o)=>t.check(nr(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)=>{Qv.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bS(t,r,n,o),t.element=e.element,ys(t,"ZodArray",{min(r,n){return this.check(eo(r,n))},nonempty(r){return this.check(eo(1,r))},max(r,n){return this.check(wa(r,n))},length(r,n){return this.check(ba(r,n))},unwrap(){return this.element}})});function C(t,e){return oS(KM,t,e)}var dw=v("ZodObject",(t,e)=>{r_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>RS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),ys(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:me()})},loose(){return this.clone({...this._zod.def,catchall:me()})},strict(){return this.clone({...this._zod.def,catchall:WM()})},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(pw,this,r[0])},required(...r){return U.required(hw,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new dw(r)}function Ce(t,e){return new dw({type:"object",shape:t,catchall:me(),...U.normalizeParams(e)})}var lw=v("ZodUnion",(t,e)=>{Ld.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>PS(t,r,n,o),t.options=e.options});function ue(t,e){return new lw({type:"union",options:t,...U.normalizeParams(e)})}var JM=v("ZodDiscriminatedUnion",(t,e)=>{lw.init(t,e),n_.init(t,e)});function fl(t,e,r){return new JM({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var YM=v("ZodIntersection",(t,e)=>{o_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>CS(t,r,n,o)});function Ea(t,e){return new YM({type:"intersection",left:t,right:e})}var ew=v("ZodRecord",(t,e)=>{s_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>xS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new ew({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new ew({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var ul=v("ZodEnum",(t,e)=>{i_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>vS(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 ul({...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 ul({...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 ul({type:"enum",entries:r,...U.normalizeParams(e)})}var XM=v("ZodLiteral",(t,e)=>{a_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(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 XM({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var QM=v("ZodTransform",(t,e)=>{c_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>wS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Vn(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 fw(t){return new QM({type:"transform",transform:t})}var pw=v("ZodOptional",(t,e)=>{jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ol(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ge(t){return new pw({type:"optional",innerType:t})}var eI=v("ZodExactOptional",(t,e)=>{u_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ol(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function tI(t){return new eI({type:"optional",innerType:t})}var rI=v("ZodNullable",(t,e)=>{d_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function tw(t){return new rI({type:"nullable",innerType:t})}var nI=v("ZodDefault",(t,e)=>{l_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>TS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function oI(t,e){return new nI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var sI=v("ZodPrefault",(t,e)=>{f_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>AS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function iI(t,e){return new sI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var hw=v("ZodNonOptional",(t,e)=>{p_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ES(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function aI(t,e){return new hw({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var cI=v("ZodCatch",(t,e)=>{h_.init(t,e),oe.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 uI(t,e){return new cI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var mw=v("ZodPipe",(t,e)=>{Fd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>MS(t,r,n,o),t.in=e.in,t.out=e.out});function rw(t,e){return new mw({type:"pipe",in:t,out:e})}var dI=v("ZodPreprocess",(t,e)=>{mw.init(t,e),m_.init(t,e)}),lI=v("ZodReadonly",(t,e)=>{g_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function fI(t){return new lI({type:"readonly",innerType:t})}var gw=v("ZodCustom",(t,e)=>{y_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>SS(t,r,n,o)});function yw(t,e){return sS(gw,t??(()=>!0),e)}function pI(t,e={}){return iS(gw,t,e)}function hI(t,e){return aS(t,e)}function pl(t,e){return new dI({type:"pipe",in:fw(t),out:e})}var _w={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 vw;vw||(vw={});var Ta={};du(Ta,{bigint:()=>vI,boolean:()=>yI,date:()=>_I,number:()=>gI,string:()=>mI});function mI(t){return b_(dl,t)}function gI(t){return W_(ka,t)}function yI(t){return Y_(ll,t)}function vI(t){return X_(iw,t)}function _I(t){return nS(uw,t)}Ke(v_());var no="2025-11-25";var Sw=[no,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Er="io.modelcontextprotocol/related-task",$a="2.0",xe=yw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),ww=ue([g(),W().int()]),bw=g(),pV=Ce({ttl:W().optional(),pollInterval:W().optional()}),wI=x({ttl:W().optional()}),bI=x({taskId:g()}),ml=Ce({progressToken:ww.optional(),[Er]:bI.optional()}),ct=x({_meta:ml.optional()}),vs=ct.extend({task:wI.optional()}),Rw=t=>vs.safeParse(t).success,$e=x({method:g(),params:ct.loose().optional()}),mt=x({_meta:ml.optional()}),gt=x({method:g(),params:mt.loose().optional()}),ke=Ce({_meta:ml.optional()}),Ma=ue([g(),W().int()]),Pw=x({jsonrpc:E($a),id:Ma,...$e.shape}).strict(),_s=t=>Pw.safeParse(t).success,Cw=x({jsonrpc:E($a),...gt.shape}).strict(),xw=t=>Cw.safeParse(t).success,gl=x({jsonrpc:E($a),id:Ma,result:ke}).strict(),sn=t=>gl.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 yl=x({jsonrpc:E($a),id:Ma.optional(),error:x({code:W().int(),message:g(),data:me().optional()})}).strict();var kw=t=>yl.safeParse(t).success;var Tr=ue([Pw,Cw,gl,yl]),hV=ue([gl,yl]),an=ke.strict(),RI=mt.extend({requestId:Ma.optional(),reason:g().optional()}),Ia=gt.extend({method:E("notifications/cancelled"),params:RI}),PI=x({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Je(["light","dark"]).optional()}),Ss=x({icons:C(PI).optional()}),ro=x({name:g(),title:g().optional()}),Ew=ro.extend({...ro.shape,...Ss.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),CI=Ea(x({applyDefaults:se().optional()}),ae(g(),me())),xI=pl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ea(x({form:CI.optional(),url:xe.optional()}),ae(g(),me()).optional())),kI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({sampling:Ce({createMessage:xe.optional()}).optional(),elicitation:Ce({create:xe.optional()}).optional()}).optional()}),EI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({tools:Ce({call:xe.optional()}).optional()}).optional()}),TI=x({experimental:ae(g(),xe).optional(),sampling:x({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:xI.optional(),roots:x({listChanged:se().optional()}).optional(),tasks:kI.optional(),extensions:ae(g(),xe).optional()}),AI=ct.extend({protocolVersion:g(),capabilities:TI,clientInfo:Ew}),$I=$e.extend({method:E("initialize"),params:AI});var MI=x({experimental:ae(g(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:x({listChanged:se().optional()}).optional(),resources:x({subscribe:se().optional(),listChanged:se().optional()}).optional(),tools:x({listChanged:se().optional()}).optional(),tasks:EI.optional(),extensions:ae(g(),xe).optional()}),vl=ke.extend({protocolVersion:g(),capabilities:MI,serverInfo:Ew,instructions:g().optional()}),Tw=gt.extend({method:E("notifications/initialized"),params:mt.optional()}),Aw=t=>Tw.safeParse(t).success,Oa=$e.extend({method:E("ping"),params:ct.optional()}),II=x({progress:W(),total:ge(W()),message:ge(g())}),OI=x({...mt.shape,...II.shape,progressToken:ww}),za=gt.extend({method:E("notifications/progress"),params:OI}),zI=ct.extend({cursor:bw.optional()}),ws=$e.extend({params:zI.optional()}),bs=ke.extend({nextCursor:bw.optional()}),NI=Je(["working","input_required","completed","failed","cancelled"]),Rs=x({taskId:g(),status:NI,ttl:ue([W(),aw()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ge(W()),statusMessage:ge(g())}),cn=ke.extend({task:Rs}),DI=mt.merge(Rs),Ps=gt.extend({method:E("notifications/tasks/status"),params:DI}),Na=$e.extend({method:E("tasks/get"),params:ct.extend({taskId:g()})}),Da=ke.merge(Rs),La=$e.extend({method:E("tasks/result"),params:ct.extend({taskId:g()})}),mV=ke.loose(),ja=ws.extend({method:E("tasks/list")}),Fa=bs.extend({tasks:C(Rs)}),Ua=$e.extend({method:E("tasks/cancel"),params:ct.extend({taskId:g()})}),$w=ke.merge(Rs),Mw=x({uri:g(),mimeType:ge(g()),_meta:ae(g(),me()).optional()}),Iw=Mw.extend({text:g()}),_l=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ow=Mw.extend({blob:_l}),Cs=Je(["user","assistant"]),oo=x({audience:C(Cs).optional(),priority:W().min(0).max(1).optional(),lastModified:gs.datetime({offset:!0}).optional()}),zw=x({...ro.shape,...Ss.shape,uri:g(),description:ge(g()),mimeType:ge(g()),size:ge(W()),annotations:oo.optional(),_meta:ge(Ce({}))}),LI=x({...ro.shape,...Ss.shape,uriTemplate:g(),description:ge(g()),mimeType:ge(g()),annotations:oo.optional(),_meta:ge(Ce({}))}),jI=ws.extend({method:E("resources/list")}),Sl=bs.extend({resources:C(zw)}),FI=ws.extend({method:E("resources/templates/list")}),wl=bs.extend({resourceTemplates:C(LI)}),bl=ct.extend({uri:g()}),UI=bl,qI=$e.extend({method:E("resources/read"),params:UI}),Rl=ke.extend({contents:C(ue([Iw,Ow]))}),Pl=gt.extend({method:E("notifications/resources/list_changed"),params:mt.optional()}),HI=bl,GI=$e.extend({method:E("resources/subscribe"),params:HI}),ZI=bl,BI=$e.extend({method:E("resources/unsubscribe"),params:ZI}),VI=mt.extend({uri:g()}),WI=gt.extend({method:E("notifications/resources/updated"),params:VI}),KI=x({name:g(),description:ge(g()),required:ge(se())}),JI=x({...ro.shape,...Ss.shape,description:ge(g()),arguments:ge(C(KI)),_meta:ge(Ce({}))}),YI=ws.extend({method:E("prompts/list")}),Cl=bs.extend({prompts:C(JI)}),XI=ct.extend({name:g(),arguments:ae(g(),g()).optional()}),QI=$e.extend({method:E("prompts/get"),params:XI}),xl=x({type:E("text"),text:g(),annotations:oo.optional(),_meta:ae(g(),me()).optional()}),kl=x({type:E("image"),data:_l,mimeType:g(),annotations:oo.optional(),_meta:ae(g(),me()).optional()}),El=x({type:E("audio"),data:_l,mimeType:g(),annotations:oo.optional(),_meta:ae(g(),me()).optional()}),eO=x({type:E("tool_use"),name:g(),id:g(),input:ae(g(),me()),_meta:ae(g(),me()).optional()}),tO=x({type:E("resource"),resource:ue([Iw,Ow]),annotations:oo.optional(),_meta:ae(g(),me()).optional()}),rO=zw.extend({type:E("resource_link")}),Tl=ue([xl,kl,El,rO,tO]),nO=x({role:Cs,content:Tl}),Al=ke.extend({description:g().optional(),messages:C(nO)}),$l=gt.extend({method:E("notifications/prompts/list_changed"),params:mt.optional()}),oO=x({title:g().optional(),readOnlyHint:se().optional(),destructiveHint:se().optional(),idempotentHint:se().optional(),openWorldHint:se().optional()}),sO=x({taskSupport:Je(["required","optional","forbidden"]).optional()}),Nw=x({...ro.shape,...Ss.shape,description:g().optional(),inputSchema:x({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()),outputSchema:x({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()).optional(),annotations:oO.optional(),execution:sO.optional(),_meta:ae(g(),me()).optional()}),iO=ws.extend({method:E("tools/list")}),Ml=bs.extend({tools:C(Nw)}),un=ke.extend({content:C(Tl).default([]),structuredContent:ae(g(),me()).optional(),isError:se().optional()}),gV=un.or(ke.extend({toolResult:me()})),aO=vs.extend({name:g(),arguments:ae(g(),me()).optional()}),cO=$e.extend({method:E("tools/call"),params:aO}),xs=gt.extend({method:E("notifications/tools/list_changed"),params:mt.optional()}),Dw=x({autoRefresh:se().default(!0),debounceMs:W().int().nonnegative().default(300)}),Lw=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),uO=ct.extend({level:Lw}),dO=$e.extend({method:E("logging/setLevel"),params:uO}),lO=mt.extend({level:Lw,logger:g().optional(),data:me()}),fO=gt.extend({method:E("notifications/message"),params:lO}),pO=x({name:g().optional()}),hO=x({hints:C(pO).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),mO=x({mode:Je(["auto","required","none"]).optional()}),gO=x({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(Tl).default([]),structuredContent:x({}).loose().optional(),isError:se().optional(),_meta:ae(g(),me()).optional()}),yO=fl("type",[xl,kl,El]),Aa=fl("type",[xl,kl,El,eO,gO]),vO=x({role:Cs,content:ue([Aa,C(Aa)]),_meta:ae(g(),me()).optional()}),_O=vs.extend({messages:C(vO),modelPreferences:hO.optional(),systemPrompt:g().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:C(g()).optional(),metadata:xe.optional(),tools:C(Nw).optional(),toolChoice:mO.optional()}),Il=$e.extend({method:E("sampling/createMessage"),params:_O}),Ol=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens"]).or(g())),role:Cs,content:yO}),zl=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Cs,content:ue([Aa,C(Aa)])}),SO=x({type:E("boolean"),title:g().optional(),description:g().optional(),default:se().optional()}),wO=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()}),bO=x({type:Je(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),RO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),PO=x({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(x({const:g(),title:g()})),default:g().optional()}),CO=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),xO=ue([RO,PO]),kO=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()}),EO=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()}),TO=ue([kO,EO]),AO=ue([CO,xO,TO]),$O=ue([AO,SO,wO,bO]),MO=vs.extend({mode:E("form").optional(),message:g(),requestedSchema:x({type:E("object"),properties:ae(g(),$O),required:C(g()).optional()})}),IO=vs.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),OO=ue([MO,IO]),Nl=$e.extend({method:E("elicitation/create"),params:OO}),zO=mt.extend({elicitationId:g()}),NO=gt.extend({method:E("notifications/elicitation/complete"),params:zO}),Dl=ke.extend({action:Je(["accept","decline","cancel"]),content:pl(t=>t===null?void 0:t,ae(g(),ue([g(),W(),se(),C(g())])).optional())}),DO=x({type:E("ref/resource"),uri:g()});var LO=x({type:E("ref/prompt"),name:g()}),jO=ct.extend({ref:ue([LO,DO]),argument:x({name:g(),value:g()}),context:x({arguments:ae(g(),g()).optional()}).optional()}),FO=$e.extend({method:E("completion/complete"),params:jO});var Ll=ke.extend({completion:Ce({values:C(g()).max(100),total:ge(W().int()),hasMore:ge(se())})}),UO=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ae(g(),me()).optional()}),qO=$e.extend({method:E("roots/list"),params:ct.optional()}),HO=ke.extend({roots:C(UO)}),GO=gt.extend({method:E("notifications/roots/list_changed"),params:mt.optional()}),yV=ue([Oa,$I,FO,dO,QI,YI,jI,FI,qI,GI,BI,cO,iO,Na,La,ja,Ua]),vV=ue([Ia,za,Tw,GO,Ps]),_V=ue([an,Ol,zl,Dl,HO,Da,Fa,cn]),SV=ue([Oa,Il,Nl,qO,Na,La,ja,Ua]),wV=ue([Ia,za,fO,WI,Pl,xs,$l,Ps,NO]),bV=ue([an,vl,Ll,Al,Cl,Sl,wl,Rl,un,Ml,Da,Fa,cn]),$=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 hl(o.elicitations,r)}return new t(e,r,n)}},hl=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 Ar(t){return t==="completed"||t==="failed"||t==="cancelled"}var tW=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function jl(t){let r=Pa(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ca(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Fl(t,e){let r=kt(t,e);if(!r.success)throw r.error;return r.data}var JO=6e4,qa=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(Ia,r=>{this._oncancel(r)}),this.setNotificationHandler(za,r=>{this._onprogress(r)}),this.setRequestHandler(Oa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Na,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(La,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,f=new $(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!Ar(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ar(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Er]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ja,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(Ua,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(Ar(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),sn(s)||kw(s)?this._onresponse(s):_s(s)?this._onrequest(s,i):xw(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?.[Er]?.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=Rw(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,f)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});let h=p.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId: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),sn(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(sn(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),sn(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,cn,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},Ar(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=b=>{d(b)};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(b){l(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Er]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let w=b instanceof $?b:new $(M.RequestTimeout,String(b));d(w)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let w=kt(r,b.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??JO,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let b=w=>{let k=this._responseHandlers.get(f);k?k(w):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(f),d(w)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Da,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},Fa,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||{},[Er]: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||{},[Er]: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||{},[Er]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=jl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Fl(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=jl(e);this._notificationHandlers.set(n,o=>{let s=Fl(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"&&_s(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=Ps.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ar(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(Ar(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=Ps.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ar(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function jw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Fw(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];jw(i)&&jw(s)?r[o]={...i,...s}:r[o]=s}return r}var AP=Ti(kp(),1),$P=Ti(TP(),1);function tF(){let t=new AP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$P.default)(t),t}var Cc=class{constructor(e){this._ajv=e??tF()}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 xc=class{constructor(e){this._client=e}async*callToolStream(e,r=un,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 MP(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 IP(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 kc(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&&kc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&kc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&kc(r,e)}}function rF(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 Ec=class extends qa{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 Cc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",xs,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",$l,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Pl,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new xc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fw(this._capabilities,e)}setRequestHandler(e,r){let o=Pa(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ca(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=kt(Nl,c);if(!d.success){let b=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=rF(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let b=kt(cn,h);if(!b.success){let w=b.error instanceof Error?b.error.message:String(b.error);throw new $(M.InvalidParams,`Invalid task creation result: ${w}`)}return b.data}let m=kt(Dl,h);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${b}`)}let y=m.data,_=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&_&&this._capabilities.elicitation?.form?.applyDefaults)try{kc(_,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=kt(Il,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,f=await Promise.resolve(r(c,u));if(l.task){let y=kt(cn,f);if(!y.success){let _=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${_}`)}return y.data}let h=l.tools||l.toolChoice?zl:Ol,m=kt(h,f);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:no,capabilities:this._capabilities,clientInfo:this._clientInfo}},vl,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Sw.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){MP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&IP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},an,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ll,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},an,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Al,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Cl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Sl,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},wl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Rl,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},an,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},an,r)}async callTool(e,r=un,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},Ml,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Dw.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 f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var ni=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}},OP=10,nF=13,wn=32;function zp(t){}function Tc(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=zp,onError:r=zp,onRetry:n=zp,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let ne=y(S);ne!==""&&(i.push(ne),a=ne.length),m();return}if(S.indexOf(`
88
- `)===-1&&S.indexOf("\r")===-1){i.push(S),a+=S.length,m();return}i.push(S);let P=i.join("");i.length=0,a=0;let I=y(P);I!==""&&(i.push(I),a=I.length),m()}function m(){s!==void 0&&(a+d.length<=s||(p=!0,i.length=0,a=0,u=void 0,d="",l=0,f=void 0,r(new ni(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(S){let P=0;if(S.indexOf("\r")===-1){let I=S.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 pl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let 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:bs(e,"input",t.processors),output:bs(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fe(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 Fe(n.element,r);if(n.type==="set")return Fe(n.valueType,r);if(n.type==="lazy")return Fe(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 Fe(n.innerType,r);if(n.type==="intersection")return Fe(n.left,r)||Fe(n.right,r);if(n.type==="record"||n.type==="map")return Fe(n.keyType,r)||Fe(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Fe(n.in,r)||Fe(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Fe(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Fe(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Fe(o,r))return!0;return!!(n.rest&&Fe(n.rest,r))}return!1}var _S=(t,e={})=>r=>{let n=ll({...r,processors:e});return ve(t,n),fl(n,t),pl(n,t)},bs=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ll({...o??{},target:s,io:e,processors:r});return ve(t,i),fl(i,t),pl(i,t)};var xM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},SS=(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=xM[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}))])}},wS=(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),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},bS=(t,e,r,n)=>{r.type="boolean"},RS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var PS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var CS=(t,e,r,n)=>{r.not={}},xS=(t,e,r,n)=>{},kS=(t,e,r,n)=>{},ES=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},TS=(t,e,r,n)=>{let o=t._zod.def,s=fs(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 $S=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var MS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var IS=(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"]})},OS=(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)},zS=(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},NS=(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 DS=(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)}},LS=(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"}]},jS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},FS=(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))},US=(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)))},qS=(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},HS=(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},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,r.readOnly=!0};var hl=(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 Ta(t){return!!t._zod}function kt(t,e){return Ta(t)?ys(t,e):t.safeParse(e)}function Aa(t){if(!t)return;let e;if(Ta(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $a(t){if(Ta(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 Rs={};Su(Rs,{ZodISODate:()=>WS,ZodISODateTime:()=>ZS,ZodISODuration:()=>VS,ZodISOTime:()=>BS,date:()=>gl,datetime:()=>ml,duration:()=>vl,time:()=>yl});var ZS=_("ZodISODateTime",(t,e)=>{Hv.init(t,e),he.init(t,e)});function ml(t){return eS(ZS,t)}var WS=_("ZodISODate",(t,e)=>{Gv.init(t,e),he.init(t,e)});function gl(t){return tS(WS,t)}var BS=_("ZodISOTime",(t,e)=>{Zv.init(t,e),he.init(t,e)});function yl(t){return rS(BS,t)}var VS=_("ZodISODuration",(t,e)=>{Wv.init(t,e),he.init(t,e)});function vl(t){return nS(VS,t)}var OM=(t,e)=>{_a.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Fd(t,r)},flatten:{value:r=>jd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,to,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,to,2)}},isEmpty:{get(){return t.issues.length===0}}})};var at=_("ZodError",OM,{Parent:Error});var JS=Sa(at),YS=wa(at),XS=gs(at),QS=vs(at),ew=xy(at),tw=ky(at),rw=Ey(at),nw=Ty(at),ow=Ay(at),sw=$y(at),iw=My(at),aw=Iy(at);var cw=new WeakMap;function Ps(t,e,r){let n=Object.getPrototypeOf(t),o=cw.get(n);if(o||(o=new Set,cw.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 oe=_("ZodType",(t,e)=>(te.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:bs(t,"input"),output:bs(t,"output")}}),t.toJSONSchema=_S(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>JS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>XS(t,r,n),t.parseAsync=async(r,n)=>YS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>QS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>ew(t,r,n),t.decode=(r,n)=>tw(t,r,n),t.encodeAsync=async(r,n)=>rw(t,r,n),t.decodeAsync=async(r,n)=>nw(t,r,n),t.safeEncode=(r,n)=>ow(t,r,n),t.safeDecode=(r,n)=>sw(t,r,n),t.safeEncodeAsync=async(r,n)=>iw(t,r,n),t.safeDecodeAsync=async(r,n)=>aw(t,r,n),Ps(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(bI(r,n))},superRefine(r,n){return this.check(RI(r,n))},overwrite(r){return this.check(Ar(r))},optional(){return ge(this)},exactOptional(){return dI(this)},nullable(){return fw(this)},nullish(){return ge(fw(this))},nonoptional(r){return gI(this,r)},array(){return C(this)},or(r){return ue([this,r])},and(r){return Oa(this,r)},transform(r){return pw(this,Rw(r))},default(r){return pI(this,r)},prefault(r){return mI(this,r)},catch(r){return vI(this,r)},pipe(r){return pw(this,r)},readonly(){return wI(this)},describe(r){let n=this.clone();return Tr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Tr.get(this);let n=this.clone();return Tr.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 Tr.get(t)?.description},configurable:!0}),t)),hw=_("_ZodString",(t,e)=>{xa.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>SS(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Ps(t,"_ZodString",{regex(...n){return this.check(el(...n))},includes(...n){return this.check(nl(...n))},startsWith(...n){return this.check(ol(...n))},endsWith(...n){return this.check(sl(...n))},min(...n){return this.check(io(...n))},max(...n){return this.check(ka(...n))},length(...n){return this.check(Ea(...n))},nonempty(...n){return this.check(io(1,...n))},lowercase(n){return this.check(tl(n))},uppercase(n){return this.check(rl(n))},trim(){return this.check(al())},normalize(...n){return this.check(il(...n))},toLowerCase(){return this.check(cl())},toUpperCase(){return this.check(ul())},slugify(){return this.check(dl())}})}),Sl=_("ZodString",(t,e)=>{xa.init(t,e),hw.init(t,e),t.email=r=>t.check(O_(NM,r)),t.url=r=>t.check(Qd(mw,r)),t.jwt=r=>t.check(Q_(YM,r)),t.emoji=r=>t.check(j_(DM,r)),t.guid=r=>t.check(Xd(uw,r)),t.uuid=r=>t.check(z_(Ma,r)),t.uuidv4=r=>t.check(N_(Ma,r)),t.uuidv6=r=>t.check(D_(Ma,r)),t.uuidv7=r=>t.check(L_(Ma,r)),t.nanoid=r=>t.check(F_(LM,r)),t.guid=r=>t.check(Xd(uw,r)),t.cuid=r=>t.check(U_(jM,r)),t.cuid2=r=>t.check(q_(FM,r)),t.ulid=r=>t.check(H_(UM,r)),t.base64=r=>t.check(J_(VM,r)),t.base64url=r=>t.check(Y_(KM,r)),t.xid=r=>t.check(G_(qM,r)),t.ksuid=r=>t.check(Z_(HM,r)),t.ipv4=r=>t.check(W_(GM,r)),t.ipv6=r=>t.check(B_(ZM,r)),t.cidrv4=r=>t.check(V_(WM,r)),t.cidrv6=r=>t.check(K_(BM,r)),t.e164=r=>t.check(X_(JM,r)),t.datetime=r=>t.check(ml(r)),t.date=r=>t.check(gl(r)),t.time=r=>t.check(yl(r)),t.duration=r=>t.check(vl(r))});function g(t){return M_(Sl,t)}var he=_("ZodStringFormat",(t,e)=>{ce.init(t,e),hw.init(t,e)}),NM=_("ZodEmail",(t,e)=>{Ov.init(t,e),he.init(t,e)});var uw=_("ZodGUID",(t,e)=>{Mv.init(t,e),he.init(t,e)});var Ma=_("ZodUUID",(t,e)=>{Iv.init(t,e),he.init(t,e)});var mw=_("ZodURL",(t,e)=>{zv.init(t,e),he.init(t,e)});function gw(t){return Qd(mw,t)}var DM=_("ZodEmoji",(t,e)=>{Nv.init(t,e),he.init(t,e)});var LM=_("ZodNanoID",(t,e)=>{Dv.init(t,e),he.init(t,e)});var jM=_("ZodCUID",(t,e)=>{Lv.init(t,e),he.init(t,e)});var FM=_("ZodCUID2",(t,e)=>{jv.init(t,e),he.init(t,e)});var UM=_("ZodULID",(t,e)=>{Fv.init(t,e),he.init(t,e)});var qM=_("ZodXID",(t,e)=>{Uv.init(t,e),he.init(t,e)});var HM=_("ZodKSUID",(t,e)=>{qv.init(t,e),he.init(t,e)});var GM=_("ZodIPv4",(t,e)=>{Bv.init(t,e),he.init(t,e)});var ZM=_("ZodIPv6",(t,e)=>{Vv.init(t,e),he.init(t,e)});var WM=_("ZodCIDRv4",(t,e)=>{Kv.init(t,e),he.init(t,e)});var BM=_("ZodCIDRv6",(t,e)=>{Jv.init(t,e),he.init(t,e)});var VM=_("ZodBase64",(t,e)=>{Xv.init(t,e),he.init(t,e)});var KM=_("ZodBase64URL",(t,e)=>{Qv.init(t,e),he.init(t,e)});var JM=_("ZodE164",(t,e)=>{e_.init(t,e),he.init(t,e)});var YM=_("ZodJWT",(t,e)=>{t_.init(t,e),he.init(t,e)});var Ia=_("ZodNumber",(t,e)=>{Bd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>wS(t,n,o,s),Ps(t,"ZodNumber",{gt(n,o){return this.check(so(n,o))},gte(n,o){return this.check(xt(n,o))},min(n,o){return this.check(xt(n,o))},lt(n,o){return this.check(oo(n,o))},lte(n,o){return this.check(or(n,o))},max(n,o){return this.check(or(n,o))},int(n){return this.check(dw(n))},safe(n){return this.check(dw(n))},positive(n){return this.check(so(0,n))},nonnegative(n){return this.check(xt(0,n))},negative(n){return this.check(oo(0,n))},nonpositive(n){return this.check(or(0,n))},multipleOf(n,o){return this.check(ws(n,o))},step(n,o){return this.check(ws(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 V(t){return oS(Ia,t)}var XM=_("ZodNumberFormat",(t,e)=>{r_.init(t,e),Ia.init(t,e)});function dw(t){return iS(XM,t)}var wl=_("ZodBoolean",(t,e)=>{n_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bS(t,r,n,o)});function se(t){return aS(wl,t)}var yw=_("ZodBigInt",(t,e)=>{o_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>RS(t,n,o,s),t.gte=(n,o)=>t.check(xt(n,o)),t.min=(n,o)=>t.check(xt(n,o)),t.gt=(n,o)=>t.check(so(n,o)),t.gte=(n,o)=>t.check(xt(n,o)),t.min=(n,o)=>t.check(xt(n,o)),t.lt=(n,o)=>t.check(oo(n,o)),t.lte=(n,o)=>t.check(or(n,o)),t.max=(n,o)=>t.check(or(n,o)),t.positive=n=>t.check(so(BigInt(0),n)),t.negative=n=>t.check(oo(BigInt(0),n)),t.nonpositive=n=>t.check(or(BigInt(0),n)),t.nonnegative=n=>t.check(xt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(ws(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var QM=_("ZodNull",(t,e)=>{s_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>PS(t,r,n,o)});function vw(t){return dS(QM,t)}var eI=_("ZodAny",(t,e)=>{i_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>xS(t,r,n,o)});function _w(){return lS(eI)}var tI=_("ZodUnknown",(t,e)=>{a_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kS(t,r,n,o)});function me(){return fS(tI)}var rI=_("ZodNever",(t,e)=>{c_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>CS(t,r,n,o)});function nI(t){return pS(rI,t)}var Sw=_("ZodDate",(t,e)=>{u_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>ES(t,n,o,s),t.min=(n,o)=>t.check(xt(n,o)),t.max=(n,o)=>t.check(or(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 oI=_("ZodArray",(t,e)=>{d_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o),t.element=e.element,Ps(t,"ZodArray",{min(r,n){return this.check(io(r,n))},nonempty(r){return this.check(io(1,r))},max(r,n){return this.check(ka(r,n))},length(r,n){return this.check(Ea(r,n))},unwrap(){return this.element}})});function C(t,e){return mS(oI,t,e)}var ww=_("ZodObject",(t,e)=>{p_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>OS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),Ps(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:me()})},loose(){return this.clone({...this._zod.def,catchall:me()})},strict(){return this.clone({...this._zod.def,catchall:nI()})},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(Pw,this,r[0])},required(...r){return U.required(Cw,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new ww(r)}function Ce(t,e){return new ww({type:"object",shape:t,catchall:me(),...U.normalizeParams(e)})}var bw=_("ZodUnion",(t,e)=>{Vd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>zS(t,r,n,o),t.options=e.options});function ue(t,e){return new bw({type:"union",options:t,...U.normalizeParams(e)})}var sI=_("ZodDiscriminatedUnion",(t,e)=>{bw.init(t,e),h_.init(t,e)});function bl(t,e,r){return new sI({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var iI=_("ZodIntersection",(t,e)=>{m_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>NS(t,r,n,o)});function Oa(t,e){return new iI({type:"intersection",left:t,right:e})}var lw=_("ZodRecord",(t,e)=>{g_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>DS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new lw({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new lw({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var _l=_("ZodEnum",(t,e)=>{y_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(n,o,s)=>TS(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 _l({...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 _l({...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 _l({type:"enum",entries:r,...U.normalizeParams(e)})}var aI=_("ZodLiteral",(t,e)=>{v_.init(t,e),oe.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 aI({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var cI=_("ZodTransform",(t,e)=>{__.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>MS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Qn(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 Rw(t){return new cI({type:"transform",transform:t})}var Pw=_("ZodOptional",(t,e)=>{Kd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ge(t){return new Pw({type:"optional",innerType:t})}var uI=_("ZodExactOptional",(t,e)=>{S_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function dI(t){return new uI({type:"optional",innerType:t})}var lI=_("ZodNullable",(t,e)=>{w_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>LS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function fw(t){return new lI({type:"nullable",innerType:t})}var fI=_("ZodDefault",(t,e)=>{b_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>FS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function pI(t,e){return new fI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var hI=_("ZodPrefault",(t,e)=>{R_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>US(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function mI(t,e){return new hI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var Cw=_("ZodNonOptional",(t,e)=>{P_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function gI(t,e){return new Cw({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var yI=_("ZodCatch",(t,e)=>{C_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function vI(t,e){return new yI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var xw=_("ZodPipe",(t,e)=>{Jd.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>HS(t,r,n,o),t.in=e.in,t.out=e.out});function pw(t,e){return new xw({type:"pipe",in:t,out:e})}var _I=_("ZodPreprocess",(t,e)=>{xw.init(t,e),x_.init(t,e)}),SI=_("ZodReadonly",(t,e)=>{k_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>GS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function wI(t){return new SI({type:"readonly",innerType:t})}var kw=_("ZodCustom",(t,e)=>{E_.init(t,e),oe.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$S(t,r,n,o)});function Ew(t,e){return gS(kw,t??(()=>!0),e)}function bI(t,e={}){return yS(kw,t,e)}function RI(t,e){return vS(t,e)}function Rl(t,e){return new _I({type:"pipe",in:Rw(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 Tw;Tw||(Tw={});var za={};Su(za,{bigint:()=>kI,boolean:()=>xI,date:()=>EI,number:()=>CI,string:()=>PI});function PI(t){return I_(Sl,t)}function CI(t){return sS(Ia,t)}function xI(t){return cS(wl,t)}function kI(t){return uS(yw,t)}function EI(t){return hS(Sw,t)}Ke(T_());var uo="2025-11-25";var $w=[uo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],$r="io.modelcontextprotocol/related-task",Da="2.0",xe=Ew(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Mw=ue([g(),V().int()]),Iw=g(),CB=Ce({ttl:V().optional(),pollInterval:V().optional()}),AI=k({ttl:V().optional()}),$I=k({taskId:g()}),Cl=Ce({progressToken:Mw.optional(),[$r]:$I.optional()}),ct=k({_meta:Cl.optional()}),Cs=ct.extend({task:AI.optional()}),Ow=t=>Cs.safeParse(t).success,$e=k({method:g(),params:ct.loose().optional()}),mt=k({_meta:Cl.optional()}),gt=k({method:g(),params:mt.loose().optional()}),ke=Ce({_meta:Cl.optional()}),La=ue([g(),V().int()]),zw=k({jsonrpc:E(Da),id:La,...$e.shape}).strict(),xs=t=>zw.safeParse(t).success,Nw=k({jsonrpc:E(Da),...gt.shape}).strict(),Dw=t=>Nw.safeParse(t).success,xl=k({jsonrpc:E(Da),id:La,result:ke}).strict(),un=t=>xl.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 kl=k({jsonrpc:E(Da),id:La.optional(),error:k({code:V().int(),message:g(),data:me().optional()})}).strict();var Lw=t=>kl.safeParse(t).success;var Mr=ue([zw,Nw,xl,kl]),xB=ue([xl,kl]),dn=ke.strict(),MI=mt.extend({requestId:La.optional(),reason:g().optional()}),ja=gt.extend({method:E("notifications/cancelled"),params:MI}),II=k({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Je(["light","dark"]).optional()}),ks=k({icons:C(II).optional()}),co=k({name:g(),title:g().optional()}),jw=co.extend({...co.shape,...ks.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),OI=Oa(k({applyDefaults:se().optional()}),ae(g(),me())),zI=Rl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Oa(k({form:OI.optional(),url:xe.optional()}),ae(g(),me()).optional())),NI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({sampling:Ce({createMessage:xe.optional()}).optional(),elicitation:Ce({create:xe.optional()}).optional()}).optional()}),DI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({tools:Ce({call:xe.optional()}).optional()}).optional()}),LI=k({experimental:ae(g(),xe).optional(),sampling:k({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:zI.optional(),roots:k({listChanged:se().optional()}).optional(),tasks:NI.optional(),extensions:ae(g(),xe).optional()}),jI=ct.extend({protocolVersion:g(),capabilities:LI,clientInfo:jw}),FI=$e.extend({method:E("initialize"),params:jI});var UI=k({experimental:ae(g(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:k({listChanged:se().optional()}).optional(),resources:k({subscribe:se().optional(),listChanged:se().optional()}).optional(),tools:k({listChanged:se().optional()}).optional(),tasks:DI.optional(),extensions:ae(g(),xe).optional()}),El=ke.extend({protocolVersion:g(),capabilities:UI,serverInfo:jw,instructions:g().optional()}),Fw=gt.extend({method:E("notifications/initialized"),params:mt.optional()}),Uw=t=>Fw.safeParse(t).success,Fa=$e.extend({method:E("ping"),params:ct.optional()}),qI=k({progress:V(),total:ge(V()),message:ge(g())}),HI=k({...mt.shape,...qI.shape,progressToken:Mw}),Ua=gt.extend({method:E("notifications/progress"),params:HI}),GI=ct.extend({cursor:Iw.optional()}),Es=$e.extend({params:GI.optional()}),Ts=ke.extend({nextCursor:Iw.optional()}),ZI=Je(["working","input_required","completed","failed","cancelled"]),As=k({taskId:g(),status:ZI,ttl:ue([V(),vw()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ge(V()),statusMessage:ge(g())}),ln=ke.extend({task:As}),WI=mt.merge(As),$s=gt.extend({method:E("notifications/tasks/status"),params:WI}),qa=$e.extend({method:E("tasks/get"),params:ct.extend({taskId:g()})}),Ha=ke.merge(As),Ga=$e.extend({method:E("tasks/result"),params:ct.extend({taskId:g()})}),kB=ke.loose(),Za=Es.extend({method:E("tasks/list")}),Wa=Ts.extend({tasks:C(As)}),Ba=$e.extend({method:E("tasks/cancel"),params:ct.extend({taskId:g()})}),qw=ke.merge(As),Hw=k({uri:g(),mimeType:ge(g()),_meta:ae(g(),me()).optional()}),Gw=Hw.extend({text:g()}),Tl=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zw=Hw.extend({blob:Tl}),Ms=Je(["user","assistant"]),lo=k({audience:C(Ms).optional(),priority:V().min(0).max(1).optional(),lastModified:Rs.datetime({offset:!0}).optional()}),Ww=k({...co.shape,...ks.shape,uri:g(),description:ge(g()),mimeType:ge(g()),size:ge(V()),annotations:lo.optional(),_meta:ge(Ce({}))}),BI=k({...co.shape,...ks.shape,uriTemplate:g(),description:ge(g()),mimeType:ge(g()),annotations:lo.optional(),_meta:ge(Ce({}))}),VI=Es.extend({method:E("resources/list")}),Al=Ts.extend({resources:C(Ww)}),KI=Es.extend({method:E("resources/templates/list")}),$l=Ts.extend({resourceTemplates:C(BI)}),Ml=ct.extend({uri:g()}),JI=Ml,YI=$e.extend({method:E("resources/read"),params:JI}),Il=ke.extend({contents:C(ue([Gw,Zw]))}),Ol=gt.extend({method:E("notifications/resources/list_changed"),params:mt.optional()}),XI=Ml,QI=$e.extend({method:E("resources/subscribe"),params:XI}),eO=Ml,tO=$e.extend({method:E("resources/unsubscribe"),params:eO}),rO=mt.extend({uri:g()}),nO=gt.extend({method:E("notifications/resources/updated"),params:rO}),oO=k({name:g(),description:ge(g()),required:ge(se())}),sO=k({...co.shape,...ks.shape,description:ge(g()),arguments:ge(C(oO)),_meta:ge(Ce({}))}),iO=Es.extend({method:E("prompts/list")}),zl=Ts.extend({prompts:C(sO)}),aO=ct.extend({name:g(),arguments:ae(g(),g()).optional()}),cO=$e.extend({method:E("prompts/get"),params:aO}),Nl=k({type:E("text"),text:g(),annotations:lo.optional(),_meta:ae(g(),me()).optional()}),Dl=k({type:E("image"),data:Tl,mimeType:g(),annotations:lo.optional(),_meta:ae(g(),me()).optional()}),Ll=k({type:E("audio"),data:Tl,mimeType:g(),annotations:lo.optional(),_meta:ae(g(),me()).optional()}),uO=k({type:E("tool_use"),name:g(),id:g(),input:ae(g(),me()),_meta:ae(g(),me()).optional()}),dO=k({type:E("resource"),resource:ue([Gw,Zw]),annotations:lo.optional(),_meta:ae(g(),me()).optional()}),lO=Ww.extend({type:E("resource_link")}),jl=ue([Nl,Dl,Ll,lO,dO]),fO=k({role:Ms,content:jl}),Fl=ke.extend({description:g().optional(),messages:C(fO)}),Ul=gt.extend({method:E("notifications/prompts/list_changed"),params:mt.optional()}),pO=k({title:g().optional(),readOnlyHint:se().optional(),destructiveHint:se().optional(),idempotentHint:se().optional(),openWorldHint:se().optional()}),hO=k({taskSupport:Je(["required","optional","forbidden"]).optional()}),Bw=k({...co.shape,...ks.shape,description:g().optional(),inputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()),outputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()).optional(),annotations:pO.optional(),execution:hO.optional(),_meta:ae(g(),me()).optional()}),mO=Es.extend({method:E("tools/list")}),ql=Ts.extend({tools:C(Bw)}),fn=ke.extend({content:C(jl).default([]),structuredContent:ae(g(),me()).optional(),isError:se().optional()}),EB=fn.or(ke.extend({toolResult:me()})),gO=Cs.extend({name:g(),arguments:ae(g(),me()).optional()}),yO=$e.extend({method:E("tools/call"),params:gO}),Is=gt.extend({method:E("notifications/tools/list_changed"),params:mt.optional()}),Vw=k({autoRefresh:se().default(!0),debounceMs:V().int().nonnegative().default(300)}),Kw=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),vO=ct.extend({level:Kw}),_O=$e.extend({method:E("logging/setLevel"),params:vO}),SO=mt.extend({level:Kw,logger:g().optional(),data:me()}),wO=gt.extend({method:E("notifications/message"),params:SO}),bO=k({name:g().optional()}),RO=k({hints:C(bO).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),PO=k({mode:Je(["auto","required","none"]).optional()}),CO=k({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(jl).default([]),structuredContent:k({}).loose().optional(),isError:se().optional(),_meta:ae(g(),me()).optional()}),xO=bl("type",[Nl,Dl,Ll]),Na=bl("type",[Nl,Dl,Ll,uO,CO]),kO=k({role:Ms,content:ue([Na,C(Na)]),_meta:ae(g(),me()).optional()}),EO=Cs.extend({messages:C(kO),modelPreferences:RO.optional(),systemPrompt:g().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:C(g()).optional(),metadata:xe.optional(),tools:C(Bw).optional(),toolChoice:PO.optional()}),Hl=$e.extend({method:E("sampling/createMessage"),params:EO}),Gl=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens"]).or(g())),role:Ms,content:xO}),Zl=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Ms,content:ue([Na,C(Na)])}),TO=k({type:E("boolean"),title:g().optional(),description:g().optional(),default:se().optional()}),AO=k({type:E("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:g().optional()}),$O=k({type:Je(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),MO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),IO=k({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(k({const:g(),title:g()})),default:g().optional()}),OO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),zO=ue([MO,IO]),NO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({type:E("string"),enum:C(g())}),default:C(g()).optional()}),DO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({anyOf:C(k({const:g(),title:g()}))}),default:C(g()).optional()}),LO=ue([NO,DO]),jO=ue([OO,zO,LO]),FO=ue([jO,TO,AO,$O]),UO=Cs.extend({mode:E("form").optional(),message:g(),requestedSchema:k({type:E("object"),properties:ae(g(),FO),required:C(g()).optional()})}),qO=Cs.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),HO=ue([UO,qO]),Wl=$e.extend({method:E("elicitation/create"),params:HO}),GO=mt.extend({elicitationId:g()}),ZO=gt.extend({method:E("notifications/elicitation/complete"),params:GO}),Bl=ke.extend({action:Je(["accept","decline","cancel"]),content:Rl(t=>t===null?void 0:t,ae(g(),ue([g(),V(),se(),C(g())])).optional())}),WO=k({type:E("ref/resource"),uri:g()});var BO=k({type:E("ref/prompt"),name:g()}),VO=ct.extend({ref:ue([BO,WO]),argument:k({name:g(),value:g()}),context:k({arguments:ae(g(),g()).optional()}).optional()}),KO=$e.extend({method:E("completion/complete"),params:VO});var Vl=ke.extend({completion:Ce({values:C(g()).max(100),total:ge(V().int()),hasMore:ge(se())})}),JO=k({uri:g().startsWith("file://"),name:g().optional(),_meta:ae(g(),me()).optional()}),YO=$e.extend({method:E("roots/list"),params:ct.optional()}),XO=ke.extend({roots:C(JO)}),QO=gt.extend({method:E("notifications/roots/list_changed"),params:mt.optional()}),TB=ue([Fa,FI,KO,_O,cO,iO,VI,KI,YI,QI,tO,yO,mO,qa,Ga,Za,Ba]),AB=ue([ja,Ua,Fw,QO,$s]),$B=ue([dn,Gl,Zl,Bl,XO,Ha,Wa,ln]),MB=ue([Fa,Hl,Wl,YO,qa,Ga,Za,Ba]),IB=ue([ja,Ua,wO,nO,Ol,Is,Ul,$s,ZO]),OB=ue([dn,El,Vl,Fl,zl,Al,$l,Il,fn,ql,Ha,Wa,ln]),$=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 Pl(o.elicitations,r)}return new t(e,r,n)}},Pl=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 Ir(t){return t==="completed"||t==="failed"||t==="cancelled"}var pV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kl(t){let r=Aa(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$a(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Jl(t,e){let r=kt(t,e);if(!r.success)throw r.error;return r.data}var sz=6e4,Va=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(ja,r=>{this._oncancel(r)}),this.setNotificationHandler(Ua,r=>{this._onprogress(r)}),this.setRequestHandler(Fa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qa,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(Ga,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,f=new $(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!Ir(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ir(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[$r]:{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(Ba,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(Ir(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),un(s)||Lw(s)?this._onresponse(s):xs(s)?this._onrequest(s,i):Dw(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?.[$r]?.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=Ow(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,f)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});let h=p.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId: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),un(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(un(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),un(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,ln,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},Ir(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=b=>{d(b)};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(b){l(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[$r]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let w=b instanceof $?b:new $(M.RequestTimeout,String(b));d(w)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let w=kt(r,b.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??sz,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=w=>{let x=this._responseHandlers.get(f);x?x(w):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(f),d(w)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ha,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},Wa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},qw,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||{},[$r]: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||{},[$r]: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||{},[$r]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Kl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Jl(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=Kl(e);this._notificationHandlers.set(n,o=>{let s=Jl(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"&&xs(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=$s.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ir(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(Ir(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=$s.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Ir(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Jw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Yw(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];Jw(i)&&Jw(s)?r[o]={...i,...s}:r[o]=s}return r}var UP=zi(Dp(),1),qP=zi(FP(),1);function dF(){let t=new UP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qP.default)(t),t}var $c=class{constructor(e){this._ajv=e??dF()}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 Mc=class{constructor(e){this._client=e}async*callToolStream(e,r=fn,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 HP(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 GP(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 Ic(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&&Ic(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ic(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ic(r,e)}}function lF(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 Oc=class extends Va{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 $c,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Is,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Ul,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ol,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Mc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Yw(this._capabilities,e)}setRequestHandler(e,r){let o=Aa(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=$a(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=kt(Wl,c);if(!d.success){let b=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=lF(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let b=kt(ln,h);if(!b.success){let w=b.error instanceof Error?b.error.message:String(b.error);throw new $(M.InvalidParams,`Invalid task creation result: ${w}`)}return b.data}let m=kt(Bl,h);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${b}`)}let y=m.data,v=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Ic(v,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=kt(Hl,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,f=await Promise.resolve(r(c,u));if(l.task){let y=kt(ln,f);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let h=l.tools||l.toolChoice?Zl:Gl,m=kt(h,f);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:uo,capabilities:this._capabilities,clientInfo:this._clientInfo}},El,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!$w.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){HP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&GP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},dn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Vl,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},dn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Fl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},zl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Al,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},$l,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Il,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},dn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},dn,r)}async callTool(e,r=fn,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},ql,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Vw.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 f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var di=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}},ZP=10,fF=13,Pn=32;function Zp(t){}function zc(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=Zp,onError:r=Zp,onRetry:n=Zp,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let ne=y(S);ne!==""&&(i.push(ne),a=ne.length),m();return}if(S.indexOf(`
88
+ `)===-1&&S.indexOf("\r")===-1){i.push(S),a+=S.length,m();return}i.push(S);let P=i.join("");i.length=0,a=0;let I=y(P);I!==""&&(i.push(I),a=I.length),m()}function m(){s!==void 0&&(a+d.length<=s||(p=!0,i.length=0,a=0,u=void 0,d="",l=0,f=void 0,r(new di(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(S){let P=0;if(S.indexOf("\r")===-1){let I=S.indexOf(`
89
89
  `,P);for(;I!==-1;){if(P===I){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0,P=I+1,I=S.indexOf(`
90
- `,P);continue}let ne=S.charCodeAt(P);if(zP(S,P,ne)){let fe=S.charCodeAt(P+5)===wn?P+6:P+5,Re=S.slice(fe,I);if(l===0&&S.charCodeAt(I+1)===OP){e({id:u,event:f,data:Re}),u=void 0,d="",f=void 0,P=I+2,I=S.indexOf(`
90
+ `,P);continue}let ne=S.charCodeAt(P);if(WP(S,P,ne)){let fe=S.charCodeAt(P+5)===Pn?P+6:P+5,Re=S.slice(fe,I);if(l===0&&S.charCodeAt(I+1)===ZP){e({id:u,event:f,data:Re}),u=void 0,d="",f=void 0,P=I+2,I=S.indexOf(`
91
91
  `,P);continue}d=l===0?Re:`${d}
92
- ${Re}`,l++}else NP(S,P,ne)?f=S.slice(S.charCodeAt(P+6)===wn?P+7:P+6,I)||void 0:_(S,P,I);P=I+1,I=S.indexOf(`
92
+ ${Re}`,l++}else BP(S,P,ne)?f=S.slice(S.charCodeAt(P+6)===Pn?P+7:P+6,I)||void 0:v(S,P,I);P=I+1,I=S.indexOf(`
93
93
  `,P)}return S.slice(P)}for(;P<S.length;){let I=S.indexOf("\r",P),ne=S.indexOf(`
94
- `,P),fe=-1;if(I!==-1&&ne!==-1?fe=I<ne?I:ne:I!==-1?I===S.length-1?fe=-1:fe=I:ne!==-1&&(fe=ne),fe===-1)break;_(S,P,fe),P=fe+1,S.charCodeAt(P-1)===nF&&S.charCodeAt(P)===OP&&P++}return S.slice(P)}function _(S,P,I){if(P===I){w();return}let ne=S.charCodeAt(P);if(zP(S,P,ne)){let fr=S.charCodeAt(P+5)===wn?P+6:P+5,Xh=S.slice(fr,I);d=l===0?Xh:`${d}
95
- ${Xh}`,l++;return}if(NP(S,P,ne)){f=S.slice(S.charCodeAt(P+6)===wn?P+7:P+6,I)||void 0;return}if(ne===105&&S.charCodeAt(P+1)===100&&S.charCodeAt(P+2)===58){let fr=S.slice(S.charCodeAt(P+3)===wn?P+4:P+3,I);u=fr.includes("\0")?void 0:fr;return}if(ne===58){if(o){let fr=S.slice(P,I);o(fr.slice(S.charCodeAt(P+1)===wn?2:1))}return}let fe=S.slice(P,I),Re=fe.indexOf(":");if(Re===-1){b(fe,"",fe);return}let qr=fe.slice(0,Re),Hr=fe.charCodeAt(Re+1)===wn?2:1,ut=fe.slice(Re+Hr);b(qr,ut,fe)}function b(S,P,I){switch(S){case"event":f=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 ni(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:I}));break;default:r(new ni(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:P,line:I}));break}}function w(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function k(S={}){if(S.consume&&i.length>0){let P=i.join("");_(P,0,P.length)}c=!0,u=void 0,d="",l=0,f=void 0,i.length=0,a=0,p=!1}return{feed:h,reset:k}}function zP(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 NP(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 $c=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(DP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(DP(this),r)}};function oF(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Np(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Np).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Np(t.cause)}`:t.message:`${t}`}function DP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var jP=t=>{throw TypeError(t)},Gp=(t,e,r)=>e.has(t)||jP("Cannot "+r),F=(t,e,r)=>(Gp(t,e,"read from private field"),r?r.call(t):e.get(t)),Ee=(t,e,r)=>e.has(t)?jP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ye=(t,e,r,n)=>(Gp(t,e,"write to private field"),e.set(t,r),r),ur=(t,e,r)=>(Gp(t,e,"access private method"),r),tt,bn,Ro,Ac,Mc,ii,xo,ai,jr,Po,ko,Co,oi,It,Dp,Lp,jp,LP,Fp,Up,si,qp,Hp,Rn=class extends EventTarget{constructor(e,r){var n,o;super(),Ee(this,It),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ee(this,tt),Ee(this,bn),Ee(this,Ro),Ee(this,Ac),Ee(this,Mc),Ee(this,ii),Ee(this,xo),Ee(this,ai,null),Ee(this,jr),Ee(this,Po),Ee(this,ko,null),Ee(this,Co,null),Ee(this,oi,null),Ee(this,Lp,async s=>{var i;F(this,Po).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){ur(this,It,si).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ye(this,Ro,new URL(s.url)):ye(this,Ro,void 0),u!==200){ur(this,It,si).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ur(this,It,si).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.OPEN);let l=new Event("open");if((i=F(this,oi))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){ur(this,It,si).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:m,value:y}=await p.read();y&&F(this,Po).feed(f.decode(y,{stream:!m})),m&&(h=!1,F(this,Po).reset(),ur(this,It,qp).call(this))}while(h)}),Ee(this,jp,s=>{ye(this,jr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&ur(this,It,qp).call(this,Np(s))}),Ee(this,Fp,s=>{typeof s.id=="string"&&ye(this,ai,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,Ro)?F(this,Ro).origin:F(this,bn).origin,lastEventId:s.id||""});F(this,Co)&&(!s.event||s.event==="message")&&F(this,Co).call(this,i),this.dispatchEvent(i)}),Ee(this,Up,s=>{ye(this,ii,s)}),Ee(this,Hp,()=>{ye(this,xo,void 0),F(this,tt)===this.CONNECTING&&ur(this,It,Dp).call(this)});try{if(e instanceof URL)ye(this,bn,e);else if(typeof e=="string")ye(this,bn,new URL(e,sF()));else throw new Error("Invalid URL")}catch{throw oF("An invalid or illegal string was specified")}ye(this,Po,Tc({onEvent:F(this,Fp),onRetry:F(this,Up)})),ye(this,tt,this.CONNECTING),ye(this,ii,3e3),ye(this,Mc,(n=r?.fetch)!=null?n:globalThis.fetch),ye(this,Ac,(o=r?.withCredentials)!=null?o:!1),ur(this,It,Dp).call(this)}get readyState(){return F(this,tt)}get url(){return F(this,bn).href}get withCredentials(){return F(this,Ac)}get onerror(){return F(this,ko)}set onerror(e){ye(this,ko,e)}get onmessage(){return F(this,Co)}set onmessage(e){ye(this,Co,e)}get onopen(){return F(this,oi)}set onopen(e){ye(this,oi,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,xo)&&clearTimeout(F(this,xo)),F(this,tt)!==this.CLOSED&&(F(this,jr)&&F(this,jr).abort(),ye(this,tt,this.CLOSED),ye(this,jr,void 0))}};tt=new WeakMap,bn=new WeakMap,Ro=new WeakMap,Ac=new WeakMap,Mc=new WeakMap,ii=new WeakMap,xo=new WeakMap,ai=new WeakMap,jr=new WeakMap,Po=new WeakMap,ko=new WeakMap,Co=new WeakMap,oi=new WeakMap,It=new WeakSet,Dp=function(){ye(this,tt,this.CONNECTING),ye(this,jr,new AbortController),F(this,Mc)(F(this,bn),ur(this,It,LP).call(this)).then(F(this,Lp)).catch(F(this,jp))},Lp=new WeakMap,jp=new WeakMap,LP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,ai)?{"Last-Event-ID":F(this,ai)}:void 0},cache:"no-store",signal:(t=F(this,jr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Fp=new WeakMap,Up=new WeakMap,si=function(t,e){var r;F(this,tt)!==this.CLOSED&&ye(this,tt,this.CLOSED);let n=new $c("error",{code:e,message:t});(r=F(this,ko))==null||r.call(this,n),this.dispatchEvent(n)},qp=function(t,e){var r;if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.CONNECTING);let n=new $c("error",{code:e,message:t});(r=F(this,ko))==null||r.call(this,n),this.dispatchEvent(n),ye(this,xo,setTimeout(F(this,Hp),F(this,ii)))},Hp=new WeakMap,Rn.CONNECTING=0,Rn.OPEN=1,Rn.CLOSED=2;function sF(){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 Eo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Ic(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Eo(e.headers),...Eo(n.headers)}:e.headers};return t(r,o)}:t}var Zp;Zp=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function iF(t){return(await Zp).getRandomValues(new Uint8Array(t))}async function aF(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await iF(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function cF(t){return await aF(t)}async function uF(t){let e=await(await Zp).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Bp(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await cF(t),r=await uF(e);return{code_verifier:e,code_challenge:r}}var ze=sw().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:_w.custom,message:"URL must be parseable",fatal:!0}),yd}).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"}),UP=Ce({resource:g().url(),authorization_servers:C(ze).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:se().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:se().optional()}),Vp=Ce({issuer:g(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.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:ze.optional(),revocation_endpoint:ze.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:se().optional()}),dF=Ce({issuer:g(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.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:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:se().optional()}),qP=x({...dF.shape,...Vp.pick({code_challenge_methods_supported:!0}).shape}),HP=x({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:Ta.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),GP=x({error:g(),error_description:g().optional(),error_uri:g().optional()}),FP=ze.optional().or(E("").transform(()=>{})),lF=x({redirect_uris:C(ze),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:ze.optional(),logo_uri:FP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:FP,policy_uri:g().optional(),jwks_uri:ze.optional(),jwks:cw().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),fF=x({client_id:g(),client_secret:g().optional(),client_id_issued_at:W().optional(),client_secret_expires_at:W().optional()}).strip(),ZP=lF.merge(fF),$5=x({error:g(),error_description:g().optional()}).strip(),M5=x({token:g(),token_type_hint:g().optional()}).strip();function BP(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function VP({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}},ci=class extends Se{};ci.errorCode="invalid_request";var Pn=class extends Se{};Pn.errorCode="invalid_client";var Cn=class extends Se{};Cn.errorCode="invalid_grant";var xn=class extends Se{};xn.errorCode="unauthorized_client";var ui=class extends Se{};ui.errorCode="unsupported_grant_type";var di=class extends Se{};di.errorCode="invalid_scope";var li=class extends Se{};li.errorCode="access_denied";var dr=class extends Se{};dr.errorCode="server_error";var fi=class extends Se{};fi.errorCode="temporarily_unavailable";var pi=class extends Se{};pi.errorCode="unsupported_response_type";var hi=class extends Se{};hi.errorCode="unsupported_token_type";var mi=class extends Se{};mi.errorCode="invalid_token";var gi=class extends Se{};gi.errorCode="method_not_allowed";var yi=class extends Se{};yi.errorCode="too_many_requests";var kn=class extends Se{};kn.errorCode="invalid_client_metadata";var vi=class extends Se{};vi.errorCode="insufficient_scope";var _i=class extends Se{};_i.errorCode="invalid_target";var WP={[ci.errorCode]:ci,[Pn.errorCode]:Pn,[Cn.errorCode]:Cn,[xn.errorCode]:xn,[ui.errorCode]:ui,[di.errorCode]:di,[li.errorCode]:li,[dr.errorCode]:dr,[fi.errorCode]:fi,[pi.errorCode]:pi,[hi.errorCode]:hi,[mi.errorCode]:mi,[gi.errorCode]:gi,[yi.errorCode]:yi,[kn.errorCode]:kn,[vi.errorCode]:vi,[_i.errorCode]:_i};var He=class extends Error{constructor(e){super(e??"Unauthorized")}};function pF(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Wp="code",Kp="S256";function hF(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&pF(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 mF(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":gF(o,s,r);return;case"client_secret_post":yF(o,s,n);return;case"none":vF(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function gF(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 yF(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function vF(t,e){e.set("client_id",t)}async function JP(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=GP.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=WP[o]||dr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new dr(o)}}async function lr(t,e){try{return await Jp(t,e)}catch(r){if(r instanceof Pn||r instanceof xn)return await t.invalidateCredentials?.("all"),await Jp(t,e);if(r instanceof Cn)return await t.invalidateCredentials?.("tokens"),await Jp(t,e);throw r}}async function Jp(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 XP(c,{fetchFn:s}),!a)try{a=await YP(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 w=await CF(e,{resourceMetadataUrl:d,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await SF(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,k=t.clientMetadataUrl;if(k&&!_F(k))throw new kn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(w&&k)p={client_id:k},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await AF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:s});await t.saveClientInformation(P),p=P}}let h=!t.redirectUrl;if(r!==void 0||h){let w=await TF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let w=await EF(c,{metadata:u,clientInformation:p,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Se)||w instanceof dr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:_,codeVerifier:b}=await xF(c,{metadata:u,clientInformation:p,state:y,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(b),await t.redirectToAuthorization(_),"REDIRECT"}function _F(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function SF(t,e,r){let n=BP(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!VP({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 To(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Yp(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Yp(t,"scope")||void 0,a=Yp(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Yp(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 YP(t,e,r=fetch){let n=await RF(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 UP.parse(await n.json())}async function Xp(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Xp(t,void 0,r):void 0;throw n}}function wF(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function KP(t,e,r=fetch){return await Xp(t,{"MCP-Protocol-Version":e},r)}function bF(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function RF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??no,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=wF(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await KP(i,s,r);if(!n?.metadataUrl&&bF(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await KP(c,s,r)}return a}function PF(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 XP(t,{fetchFn:e=fetch,protocolVersion:r=no}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=PF(t);for(let{url:s,type:i}of o){let a=await Xp(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"?Vp.parse(await a.json()):qP.parse(await a.json())}}}async function CF(t,e){let r,n;try{r=await YP(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 XP(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function xF(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(Wp))throw new Error(`Incompatible auth server: does not support response type ${Wp}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Kp))throw new Error(`Incompatible auth server: does not support code challenge method ${Kp}`)}else a=new URL("/authorize",t);let c=await Bp(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Wp),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Kp),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 kF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function QP(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=hF(n,d);mF(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await JP(u);return HP.parse(await u.json())}async function EF(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 QP(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function TF(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=kF(o,u,t.redirectUrl)}let c=await t.clientInformation();return QP(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function AF(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 JP(i);return ZP.parse(await i.json())}var Si=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Oc=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=Ic(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await lr(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 He;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=Eo(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 Rn(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}=To(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 Si(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=Tr.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 He("No auth provider");if(await lr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("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}=To(o);if(this._resourceMetadataUrl=i,this._scope=a,await lr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;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 HC=Ti(UC(),1);import ch from"node:process";import{PassThrough as sU}from"node:stream";var nU=10*1024*1024,Nc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??nU}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),oU(r)}clear(){this._buffer=void 0}};function oU(t){return Tr.parse(JSON.parse(t))}function qC(t){return JSON.stringify(t)+`
98
- `}var iU=ch.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Lc(){let t={};for(let e of iU){let r=ch.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Dc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Nc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new sU)}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,HC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Lc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:ch.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=qC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var WC=Ti(VC(),1);function KC(t){if(t)try{return WC.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var jc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Tc({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 mU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ot=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Fc=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=Ic(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??mU}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await lr(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 He;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=Eo(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 Ot(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 jc({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(i=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Tr.parse(JSON.parse(p.data));sn(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(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new He("No auth provider");if(await lr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("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:_s(e)?e.id:void 0}).catch(p=>this.onerror?.(p));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 p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ot(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=To(a);if(this._resourceMetadataUrl=h,this._scope=m,await lr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=To(a);if(y==="insufficient_scope"){let _=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new Ot(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=_??void 0,await lr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new He;return this.send(e)}}throw new Ot(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Aw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=KC(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(m=>Tr.parse(m)):[Tr.parse(p)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ot(-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 Ot(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 JC(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 yU={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 YC(t){return{...Lc(),...yU,...t??{}}}function XC(){return Lc()}var dh=class t extends Dc{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),fe=-1;if(I!==-1&&ne!==-1?fe=I<ne?I:ne:I!==-1?I===S.length-1?fe=-1:fe=I:ne!==-1&&(fe=ne),fe===-1)break;v(S,P,fe),P=fe+1,S.charCodeAt(P-1)===fF&&S.charCodeAt(P)===ZP&&P++}return S.slice(P)}function v(S,P,I){if(P===I){w();return}let ne=S.charCodeAt(P);if(WP(S,P,ne)){let hr=S.charCodeAt(P+5)===Pn?P+6:P+5,um=S.slice(hr,I);d=l===0?um:`${d}
95
+ ${um}`,l++;return}if(BP(S,P,ne)){f=S.slice(S.charCodeAt(P+6)===Pn?P+7:P+6,I)||void 0;return}if(ne===105&&S.charCodeAt(P+1)===100&&S.charCodeAt(P+2)===58){let hr=S.slice(S.charCodeAt(P+3)===Pn?P+4:P+3,I);u=hr.includes("\0")?void 0:hr;return}if(ne===58){if(o){let hr=S.slice(P,I);o(hr.slice(S.charCodeAt(P+1)===Pn?2:1))}return}let fe=S.slice(P,I),Re=fe.indexOf(":");if(Re===-1){b(fe,"",fe);return}let Wr=fe.slice(0,Re),Br=fe.charCodeAt(Re+1)===Pn?2:1,ut=fe.slice(Re+Br);b(Wr,ut,fe)}function b(S,P,I){switch(S){case"event":f=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 di(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:I}));break;default:r(new di(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:P,line:I}));break}}function w(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function x(S={}){if(S.consume&&i.length>0){let P=i.join("");v(P,0,P.length)}c=!0,u=void 0,d="",l=0,f=void 0,i.length=0,a=0,p=!1}return{feed:h,reset:x}}function WP(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 BP(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 Dc=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(VP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(VP(this),r)}};function pF(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Wp(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Wp).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Wp(t.cause)}`:t.message:`${t}`}function VP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var JP=t=>{throw TypeError(t)},eh=(t,e,r)=>e.has(t)||JP("Cannot "+r),F=(t,e,r)=>(eh(t,e,"read from private field"),r?r.call(t):e.get(t)),Ee=(t,e,r)=>e.has(t)?JP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ye=(t,e,r,n)=>(eh(t,e,"write to private field"),e.set(t,r),r),dr=(t,e,r)=>(eh(t,e,"access private method"),r),tt,Cn,To,Nc,Lc,pi,Mo,hi,qr,Ao,Io,$o,li,It,Bp,Vp,Kp,KP,Jp,Yp,fi,Xp,Qp,xn=class extends EventTarget{constructor(e,r){var n,o;super(),Ee(this,It),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ee(this,tt),Ee(this,Cn),Ee(this,To),Ee(this,Nc),Ee(this,Lc),Ee(this,pi),Ee(this,Mo),Ee(this,hi,null),Ee(this,qr),Ee(this,Ao),Ee(this,Io,null),Ee(this,$o,null),Ee(this,li,null),Ee(this,Vp,async s=>{var i;F(this,Ao).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){dr(this,It,fi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ye(this,To,new URL(s.url)):ye(this,To,void 0),u!==200){dr(this,It,fi).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){dr(this,It,fi).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.OPEN);let l=new Event("open");if((i=F(this,li))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){dr(this,It,fi).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:m,value:y}=await p.read();y&&F(this,Ao).feed(f.decode(y,{stream:!m})),m&&(h=!1,F(this,Ao).reset(),dr(this,It,Xp).call(this))}while(h)}),Ee(this,Kp,s=>{ye(this,qr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&dr(this,It,Xp).call(this,Wp(s))}),Ee(this,Jp,s=>{typeof s.id=="string"&&ye(this,hi,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,To)?F(this,To).origin:F(this,Cn).origin,lastEventId:s.id||""});F(this,$o)&&(!s.event||s.event==="message")&&F(this,$o).call(this,i),this.dispatchEvent(i)}),Ee(this,Yp,s=>{ye(this,pi,s)}),Ee(this,Qp,()=>{ye(this,Mo,void 0),F(this,tt)===this.CONNECTING&&dr(this,It,Bp).call(this)});try{if(e instanceof URL)ye(this,Cn,e);else if(typeof e=="string")ye(this,Cn,new URL(e,hF()));else throw new Error("Invalid URL")}catch{throw pF("An invalid or illegal string was specified")}ye(this,Ao,zc({onEvent:F(this,Jp),onRetry:F(this,Yp)})),ye(this,tt,this.CONNECTING),ye(this,pi,3e3),ye(this,Lc,(n=r?.fetch)!=null?n:globalThis.fetch),ye(this,Nc,(o=r?.withCredentials)!=null?o:!1),dr(this,It,Bp).call(this)}get readyState(){return F(this,tt)}get url(){return F(this,Cn).href}get withCredentials(){return F(this,Nc)}get onerror(){return F(this,Io)}set onerror(e){ye(this,Io,e)}get onmessage(){return F(this,$o)}set onmessage(e){ye(this,$o,e)}get onopen(){return F(this,li)}set onopen(e){ye(this,li,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,Mo)&&clearTimeout(F(this,Mo)),F(this,tt)!==this.CLOSED&&(F(this,qr)&&F(this,qr).abort(),ye(this,tt,this.CLOSED),ye(this,qr,void 0))}};tt=new WeakMap,Cn=new WeakMap,To=new WeakMap,Nc=new WeakMap,Lc=new WeakMap,pi=new WeakMap,Mo=new WeakMap,hi=new WeakMap,qr=new WeakMap,Ao=new WeakMap,Io=new WeakMap,$o=new WeakMap,li=new WeakMap,It=new WeakSet,Bp=function(){ye(this,tt,this.CONNECTING),ye(this,qr,new AbortController),F(this,Lc)(F(this,Cn),dr(this,It,KP).call(this)).then(F(this,Vp)).catch(F(this,Kp))},Vp=new WeakMap,Kp=new WeakMap,KP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,hi)?{"Last-Event-ID":F(this,hi)}:void 0},cache:"no-store",signal:(t=F(this,qr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Jp=new WeakMap,Yp=new WeakMap,fi=function(t,e){var r;F(this,tt)!==this.CLOSED&&ye(this,tt,this.CLOSED);let n=new Dc("error",{code:e,message:t});(r=F(this,Io))==null||r.call(this,n),this.dispatchEvent(n)},Xp=function(t,e){var r;if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.CONNECTING);let n=new Dc("error",{code:e,message:t});(r=F(this,Io))==null||r.call(this,n),this.dispatchEvent(n),ye(this,Mo,setTimeout(F(this,Qp),F(this,pi)))},Qp=new WeakMap,xn.CONNECTING=0,xn.OPEN=1,xn.CLOSED=2;function hF(){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 Oo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function jc(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Oo(e.headers),...Oo(n.headers)}:e.headers};return t(r,o)}:t}var th;th=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function mF(t){return(await th).getRandomValues(new Uint8Array(t))}async function gF(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await mF(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function yF(t){return await gF(t)}async function vF(t){let e=await(await th).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function rh(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await yF(t),r=await vF(e);return{code_verifier:e,code_challenge:r}}var ze=gw().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Aw.custom,message:"URL must be parseable",fatal:!0}),kd}).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"}),XP=Ce({resource:g().url(),authorization_servers:C(ze).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:se().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:se().optional()}),nh=Ce({issuer:g(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.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:ze.optional(),revocation_endpoint:ze.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:se().optional()}),_F=Ce({issuer:g(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.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:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:se().optional()}),QP=k({..._F.shape,...nh.pick({code_challenge_methods_supported:!0}).shape}),eC=k({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:za.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),tC=k({error:g(),error_description:g().optional(),error_uri:g().optional()}),YP=ze.optional().or(E("").transform(()=>{})),SF=k({redirect_uris:C(ze),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:ze.optional(),logo_uri:YP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:YP,policy_uri:g().optional(),jwks_uri:ze.optional(),jwks:_w().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),wF=k({client_id:g(),client_secret:g().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),rC=SF.merge(wF),H5=k({error:g(),error_description:g().optional()}).strip(),G5=k({token:g(),token_type_hint:g().optional()}).strip();function nC(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function oC({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}},mi=class extends Se{};mi.errorCode="invalid_request";var kn=class extends Se{};kn.errorCode="invalid_client";var En=class extends Se{};En.errorCode="invalid_grant";var Tn=class extends Se{};Tn.errorCode="unauthorized_client";var gi=class extends Se{};gi.errorCode="unsupported_grant_type";var yi=class extends Se{};yi.errorCode="invalid_scope";var vi=class extends Se{};vi.errorCode="access_denied";var lr=class extends Se{};lr.errorCode="server_error";var _i=class extends Se{};_i.errorCode="temporarily_unavailable";var Si=class extends Se{};Si.errorCode="unsupported_response_type";var wi=class extends Se{};wi.errorCode="unsupported_token_type";var bi=class extends Se{};bi.errorCode="invalid_token";var Ri=class extends Se{};Ri.errorCode="method_not_allowed";var Pi=class extends Se{};Pi.errorCode="too_many_requests";var An=class extends Se{};An.errorCode="invalid_client_metadata";var Ci=class extends Se{};Ci.errorCode="insufficient_scope";var xi=class extends Se{};xi.errorCode="invalid_target";var sC={[mi.errorCode]:mi,[kn.errorCode]:kn,[En.errorCode]:En,[Tn.errorCode]:Tn,[gi.errorCode]:gi,[yi.errorCode]:yi,[vi.errorCode]:vi,[lr.errorCode]:lr,[_i.errorCode]:_i,[Si.errorCode]:Si,[wi.errorCode]:wi,[bi.errorCode]:bi,[Ri.errorCode]:Ri,[Pi.errorCode]:Pi,[An.errorCode]:An,[Ci.errorCode]:Ci,[xi.errorCode]:xi};var He=class extends Error{constructor(e){super(e??"Unauthorized")}};function bF(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var oh="code",sh="S256";function RF(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&bF(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 PF(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":CF(o,s,r);return;case"client_secret_post":xF(o,s,n);return;case"none":kF(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function CF(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 xF(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function kF(t,e){e.set("client_id",t)}async function aC(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=tC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=sC[o]||lr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new lr(o)}}async function fr(t,e){try{return await ih(t,e)}catch(r){if(r instanceof kn||r instanceof Tn)return await t.invalidateCredentials?.("all"),await ih(t,e);if(r instanceof En)return await t.invalidateCredentials?.("tokens"),await ih(t,e);throw r}}async function ih(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 uC(c,{fetchFn:s}),!a)try{a=await cC(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 w=await OF(e,{resourceMetadataUrl:d,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await TF(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,x=t.clientMetadataUrl;if(x&&!EF(x))throw new An(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${x}`);if(w&&x)p={client_id:x},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await jF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:s});await t.saveClientInformation(P),p=P}}let h=!t.redirectUrl;if(r!==void 0||h){let w=await LF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let w=await DF(c,{metadata:u,clientInformation:p,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Se)||w instanceof lr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:b}=await zF(c,{metadata:u,clientInformation:p,state:y,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(b),await t.redirectToAuthorization(v),"REDIRECT"}function EF(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function TF(t,e,r){let n=nC(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!oC({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 zo(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=ah(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=ah(t,"scope")||void 0,a=ah(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function ah(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 cC(t,e,r=fetch){let n=await MF(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 XP.parse(await n.json())}async function ch(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?ch(t,void 0,r):void 0;throw n}}function AF(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function iC(t,e,r=fetch){return await ch(t,{"MCP-Protocol-Version":e},r)}function $F(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function MF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??uo,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=AF(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await iC(i,s,r);if(!n?.metadataUrl&&$F(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await iC(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 uC(t,{fetchFn:e=fetch,protocolVersion:r=uo}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=IF(t);for(let{url:s,type:i}of o){let a=await ch(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"?nh.parse(await a.json()):QP.parse(await a.json())}}}async function OF(t,e){let r,n;try{r=await cC(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 uC(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function zF(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(oh))throw new Error(`Incompatible auth server: does not support response type ${oh}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(sh))throw new Error(`Incompatible auth server: does not support code challenge method ${sh}`)}else a=new URL("/authorize",t);let c=await rh(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",oh),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",sh),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 NF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function dC(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=RF(n,d);PF(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await aC(u);return eC.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 dC(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=NF(o,u,t.redirectUrl)}let c=await t.clientInformation();return dC(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function jF(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 aC(i);return rC.parse(await i.json())}var ki=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Fc=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=jc(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await fr(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 He;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=Oo(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 xn(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}=zo(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 ki(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=Mr.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 He("No auth provider");if(await fr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("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}=zo(o);if(this._resourceMetadataUrl=i,this._scope=a,await fr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;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 ex=zi(XC(),1);import vh from"node:process";import{PassThrough as hU}from"node:stream";var fU=10*1024*1024,qc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??fU}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),pU(r)}clear(){this._buffer=void 0}};function pU(t){return Mr.parse(JSON.parse(t))}function QC(t){return JSON.stringify(t)+`
98
+ `}var mU=vh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Gc(){let t={};for(let e of mU){let r=vh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Hc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new qc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new hU)}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,ex.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Gc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:vh.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=QC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var sx=zi(ox(),1);function ix(t){if(t)try{return sx.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=zc({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 PU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Ot=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Wc=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=jc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??PU}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await fr(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 He;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=Oo(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 Ot(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:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(i=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=Mr.parse(JSON.parse(p.data));un(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(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new He("No auth provider");if(await fr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("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:xs(e)?e.id:void 0}).catch(p=>this.onerror?.(p));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 p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Ot(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=zo(a);if(this._resourceMetadataUrl=h,this._scope=m,await fr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=zo(a);if(y==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Ot(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=v??void 0,await fr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new He;return this.send(e)}}throw new Ot(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Uw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=ix(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(m=>Mr.parse(m)):[Mr.parse(p)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new Ot(-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 Ot(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 ax(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 xU={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 cx(t){return{...Gc(),...xU,...t??{}}}function ux(){return Gc()}var Sh=class t extends Hc{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 QC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new dh(e)}var En=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}},lh=new gU;function fh(t,e){return lh.run(t,e)}function vU(t){lh.getStore()?.onFailure?.(t)}function ex({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=lh.getStore(),c=new En({status:i.status,transport:e,operation:a?.operation??"transport"});throw vU(c),c}}function tx(t,e){let r=ex({getHeaders:e.getHeaders,transport:"http"});return new Fc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function rx(t,e){let r=ex({getHeaders:e.getHeaders,transport:"sse"});return new Oc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function nx(){return new Ec({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var ox=xs,sx=ke;function wt(t){return t instanceof En&&t.status===401||(t instanceof Ot||t instanceof Si)&&t.code===401}function ix(t){return t instanceof $&&t.code===M.MethodNotFound}function ph(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var _U=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function ax(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return _U.some(r=>e.includes(r))}function cx(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function hh(t){return t instanceof En&&t.transport==="http"&&t.status===404||t instanceof Ot&&t.code===404}var X=SU.child({prefix:"pi-mcp"});function wU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function bU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&wU(r,o)})}var RU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),PU=/^Node\.js v\d/,CU=/^[\w$.]*error[\w$]*:/i,ux=400,xU=63e3,dx=3,kU=/[\\/]lib[\\/]cli\.js/,EU="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.",gx=Symbol("mcpReinitReported");function TU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,gx,{value:!0,enumerable:!1,configurable:!0})}function AU(t){return typeof t=="object"&&t!==null&&t[gx]===!0}function $U(t){let e=t.filter(a=>!PU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>kU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return EU;let o=r.findIndex(a=>CU.test(a)),i=(o===-1?r.slice(-dx):r.slice(o,o+dx)).join(" / ");return i.length>ux?`${i.slice(0,ux)}\u2026`:i}function MU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(RU,"").split(`
101
- `).map(s=>s.trim()).filter(s=>s.length>0),o=$U(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var IU=6e5,OU=18e5,lx=2147483647,zU=3e4,fx=1e4,yx=[250,1e3,2e3],Tn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},wi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},NU=250,px=3,DU=[200,500];function LU(t){for(let e of Object.values(t))if(aa(e))return!0;return!1}function vx(t){let e=new Set;for(let r of t.matchAll(ns))e.add(ca(r[0]));return[...e].sort()}function yh(t){return[...new Set(t)].sort()}function hx(t,e){return ry(e.map(r=>t?.[r]??"missing"))}function jU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return yh([...e&&t?gd(t):[],...n&&r?vx(r):[]])}var Uc="${augmentToken}";function FU(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 UU(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var _x="(unknown uri)",vh="unknown",mx=/=+$/,qU=/\s+/g,HU=/[-_]/g,GU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function An(t,e){return typeof t=="string"?t:e}function Sx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function ZU(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function BU(t){let e=t.replace(qU,"").replace(HU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(mx,"");if(r.toString("base64").replace(mx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function wx(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function VU(t){let e=wx(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=An(e.uri,_x),n=An(e.mimeType,vh);if(typeof e.blob=="string"&&ZU(n)){let s=BU(e.blob);if(s!==void 0)return s}let o=Sx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function WU(t){let e=An(t.type,"unknown");if(e==="resource")return VU(t);if(e==="audio"){let r=An(t.mimeType,vh),n=Sx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=An(t.uri,_x),n=An(t.name,""),o=An(t.mimeType,vh);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=wx(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&GU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function JU(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:WU(t)}}function YU(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(JU(n))}return e}function XU(t){return Vg(t,xU)}function QU(t,e){let r=YU(t);if(r.length===0){let o=XU(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 bx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),eq=new Set([502,503,504]),bi=yx.length+1,tq=2;function rq(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 nq(t){if(wt(t)||hh(t)||t instanceof ft)return;let e=t?.cause?.code;if(typeof e=="string")return bx.has(e)?{totalAttempts:bi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:tq}:eq.has(r)?{totalAttempts:bi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:bi}:void 0}var oq=80,sq=10,iq=/[^a-zA-Z0-9_.()-]/g,aq=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function qc(t){return t.replace(iq,"_").slice(0,oq)||"unknown"}function cq(t){let e=rq(t);if(e!==void 0&&(/^\d{3}$/.test(e)||bx.has(e)))return e}function Ge(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=aq.has(e)?e:"Error",n=cq(t);return n===void 0?r:`${r}(${n})`}function mh(t,e,r){return t instanceof ft?new ft(qc(t.serverName),t.missingKeys.slice(0,sq).map(qc),void 0,t.reason).message:t instanceof En?t.message:`MCP ${r} ${e} failed (${Ge(t)})`}function gh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:qc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Hc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Gc=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=>pd(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 (${Ge(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=mh(r,"connect",this._config.type),o=this._config.type==="stdio"&&!wt(r)?pd(MU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ge(r))}}async _connectWithRetries(){let e=bi,r={available:!0};for(let n=1;n<=bi;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=nq(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=(yx[r-1]??0)+Math.floor(Math.random()*(NU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ge(e)}; retrying in ${s}ms`),await Xr(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 wt(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!ee().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 Tn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=nx();this._client=s;let i;try{if(await fh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(ox,()=>{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=ee();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 (${Ge(n)})`)}}}_recordConnectFailure(e,r,n=mh(e,r,this._config.type)){if(e instanceof ft){this._status="failed";let o=ee();No(o,this.name,e.reason,Yt(o,this.name,this._config.id))}else if(e instanceof wi||e instanceof Tn)this._status="failed";else if(wt(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(wt(e)){this._status="auth_required";let o=ee(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=mh(e,r,this._config.type);hd(gh(o,Ge(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=JC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=YC(this._resolvedEnv??e.env);return QC({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 rx(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=tx(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?LU(r):!1,o=e.type==="stdio"&&aa(e.command);if(!(n||o))return;let s=ee();if(!ty(s)){let a=jU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new ft(this.name,a)}let i=Qg(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 oy({configEnv:e,localEnv:n?XC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${Ge(i)})`),new ft(this.name,gd(e),i,"transient")}let s=yh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new ft(this.name,s,void 0,hx(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await sy(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${Ge(s)})`),new ft(this.name,vx(e),s,"transient")}let o=yh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new ft(this.name,o,void 0,hx(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(Uc)))return;let o;if(FU(e.url)){let i=ee().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Uc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Uc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${UU(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(Uc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=ee();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=ee(),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?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=ee().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,mr(r));let o=this._usableToken();o&&(o.accessToken&&!Lu(o)||ee().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Ko(o)&&ee().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=ee(),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:Yt(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),Gr({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;Gr({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)&&Fu(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&No(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"}, ${Ge(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),No(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=mr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Uu(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),Gr({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:hh(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 (${Ge(s)})`),TU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Tn}async _withAuthRetry(e,r,n){let o=this._config,s=ee(),i=Yt(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),fh({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||!wt(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new wi;if(this._hostedCredentialProvenance!==void 0)throw new Tn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let f=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw wt(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=ee();No(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ge(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 Hc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Hc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},zU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=ee(),r=Yt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=px&&n.outcome==="transient";i++)await Xr(DU[i-2]??0),n=await this._runProbe();let o=Yt(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 ${px} 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:fx})},"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 (${Ge(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":ix(e)||ph(e)?"alive":wt(e)?"authFailure":ax(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:fx})}catch(r){if(this._reinitializingPromise||this._disposed||ph(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 wt(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&&!wt(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=!bU(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 (${Ge(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ge(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>lx)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${lx}.`);let s={timeout:this._config.timeoutMs??IU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??OU,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??{}},sx,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=QU(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 Tn||e instanceof wi)throw e;if(wt(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=qc(r),s=Ge(e),i=cx(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw AU(e)||hd(gh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),gh(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 Rx=dq.child({prefix:"pi-mcp"}),lq=3,fq=6e4;function pq(t,e){let r=Date.now(),n=r-fq,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=lq?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function Px(t){Yr(t),qi(t)}async function hq(t,e,r){if(!pq(e,t)){Rx.warn(`MCP server "${t}" automatic restart rate-limited`);return}Rx.warn(`MCP server "${t}" wedged; recycling transport`),await Fr(t,e,r)}function Zc(t,e,r){if(mq(e)){Px(t);return}ku(t,r),jn(e)&&Px(t)}function mq(t){return Ho()||t.toolSearchLatched}function Kt(t,e,r){return om(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function _h(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 gq(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&&fm(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 Sh(t){let{state:e,config:r,generation:n}=t;return new Gc(r,gq({state:e,config:r,hostGeneration:n}))}function Ze(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 wh(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 bh(t,e,r){return t.configDesiredRevisions.get(e)===r}function Cx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function Rh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Kt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(uq,c)},t.onWedged=()=>{if(!Kt(t,e,r))return;let i=r.currentLoad?.latestPi??n;hq(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(!Kt(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(!Kt(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=()=>{Kt(t,e,r)&&t.status==="success"&&Zc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Eu(i,t,e),i!==n&&Eu(n,t,e)}}async function xx(t,e,r,n){let o=setTimeout(()=>{Kt(t,e,r)&&J(n(),r)},Ai);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Kt(t,e,r)&&J(n(),r)}}async function kx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function Bc(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 yq(t){let{state:e,config:r,displaced:n,retirement:o}=t;wh(e,n.config),Fo(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():dt(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 vq(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=Rt({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"}}),Pe({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 _q(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Kt(r,o,e)?a?.(n)===!1?(await vq({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Zc(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 Sq(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(!bh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=_h(e,r.name),l=Sh({state:e,config:r,generation:d});return Rh(l,d,e,o),Ii({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:_q({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function wq(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!bh(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=In(a,s),f=jo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>Sq({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:i}),m=async()=>(f.displacedHost&&f.retirement?await yq({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await pu(f.retirement),h());return f.retirement?m():h()}async function bt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ze(e,d.name)})).map(async d=>{try{let l=await wq({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 bq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!Cx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);wh(e,s),Fo(e,t);let a=Rt({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||!Cx(e,t,n))return Pe({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=_h(e,t),u=Sh({state:e,config:s,generation:c});if(Rh(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 xx(u,c,e,d),Kt(u,c,e)&&u.status==="success"&&Zc(d(),e,u),!0}function Fr(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 bq({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 Rq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;wh(e,n.config),Fo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():dt(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 Ex(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=Dn(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ze(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},f=jo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await Rq({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await pu(f.retirement),Z(e,t)?.revision!==f.lease.revision||!bh(e,t,c)){Pe({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){Pe({state:e,name:t,owner:l,revision:f.lease.revision}),J(s(),e);return}let p=_h(e,t),h=Sh({state:e,config:a,generation:p});Rh(h,p,e,r),Ii({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await xx(h,p,e,s),Kt(h,p,e)&&h.status==="success"&&Zc(s(),e,h))}async function Ri(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Fr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as Pq}from"@hermes/logger";var Ph=Pq.child({prefix:"pi-mcp"}),Cq=1e6,xq=1e3,kq=/^\d+$/;function Tx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function $n(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"||!kq.test(e)||typeof r!="string"||r.length===0)return;let n=um(t);return{revision:e.replace(/^0+(?=\d)/,""),domain:Tx(r),...n===void 0?{}:{ownerDomain:n}}}function Eq(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:gr(o,n)>0?o:n}function Tq(t,e,r){if(t===void 0)return!0;let n=Tx(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain?!0:r?.kind==="domain"&&!it(n)&&it(e.domain)&&On(n)===r.domain}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 Ph.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=On(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(!Tq(c,r,i))return"reject";let u=Eq(n?.acceptedRevisions,r.domain,s);if(u===void 0)return"apply";let d=gr(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 $q(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 Mq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function Iq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*xq+Math.floor(t.access_token_expires_at.nanos/Cq):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 Vc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!Mq(s)){Ph.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=$n(s),a=Aq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=Iq(s);if($q(t,o,c,i)){Ph.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 zq=Oq.child({prefix:"pi-mcp"});function Nq(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 Dq(t,e,r){let n=Object.entries(t).filter(([o,s])=>{let i=$n(s);if(i===void 0)return!1;let a=Zr(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 Ax(t){let{pi:e,state:r,update:n}=t,o=Nq(r,n.configId),s=o?Dq(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=Vc(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 f=$n(s);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,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??Fr,l=t.report??J;await d(o.name,r,u).catch(f=>{zq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${f instanceof Error?f.name:"non-Error"}`)}),l(u,r),Ne(r)}import{logger as Jq}from"@hermes/logger";import{execFile as Ch}from"node:child_process";import{win32 as xh}from"node:path";import{logger as Lq}from"@hermes/logger";var jq=5e3,Fq=/^[a-z]:[\\/]/i,Uq=/[<>:"|?*]/;function qq(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!Fq.test(t)||!xh.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||Uq.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:xh.join(xh.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function Hq(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function Gq(t,e){switch(process.platform){case"darwin":return Ch("open",[t],e);case"win32":{let r=qq();return r?Ch(r,["-NoProfile","-NonInteractive","-EncodedCommand",Hq(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return Ch("xdg-open",[t],e)}}function $x(t,e=jq){let r=Lq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let s=!1,i=null,a=setTimeout(()=>{if(!s){s=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{i?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);i=Gq(o,c=>{s||(s=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as Zq}from"node:http";function Wc(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Mx(t){let e=Wc(t.title),r=Wc(t.heading),n=Wc(t.message),o=t.details?Wc(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 dx(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new Sh(e)}var $n=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}},wh=new CU;function bh(t,e){return wh.run(t,e)}function kU(t){wh.getStore()?.onFailure?.(t)}function lx({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=wh.getStore(),c=new $n({status:i.status,transport:e,operation:a?.operation??"transport"});throw kU(c),c}}function fx(t,e){let r=lx({getHeaders:e.getHeaders,transport:"http"});return new Wc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function px(t,e){let r=lx({getHeaders:e.getHeaders,transport:"sse"});return new Fc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function hx(){return new Oc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var mx=Is,gx=ke;function wt(t){return t instanceof $n&&t.status===401||(t instanceof Ot||t instanceof ki)&&t.code===401}function yx(t){return t instanceof $&&t.code===M.MethodNotFound}function Rh(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var EU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function vx(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return EU.some(r=>e.includes(r))}function _x(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function Ph(t){return t instanceof $n&&t.transport==="http"&&t.status===404||t instanceof Ot&&t.code===404}var X=TU.child({prefix:"pi-mcp"});function AU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function $U(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&AU(r,o)})}var MU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),IU=/^Node\.js v\d/,OU=/^[\w$.]*error[\w$]*:/i,Sx=400,zU=63e3,wx=3,NU=/[\\/]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.",kx=Symbol("mcpReinitReported");function LU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,kx,{value:!0,enumerable:!1,configurable:!0})}function jU(t){return typeof t=="object"&&t!==null&&t[kx]===!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=>NU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return DU;let o=r.findIndex(a=>OU.test(a)),i=(o===-1?r.slice(-wx):r.slice(o,o+wx)).join(" / ");return i.length>Sx?`${i.slice(0,Sx)}\u2026`:i}function UU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(MU,"").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 qU=6e5,HU=18e5,bx=2147483647,GU=3e4,Rx=1e4,Ex=[250,1e3,2e3],Mn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},Ei=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},ZU=250,Px=3,WU=[200,500];function BU(t){for(let e of Object.values(t))if(pa(e))return!0;return!1}function Tx(t){let e=new Set;for(let r of t.matchAll(ds))e.add(ha(r[0]));return[...e].sort()}function kh(t){return[...new Set(t)].sort()}function Cx(t,e){return py(e.map(r=>t?.[r]??"missing"))}function VU({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return kh([...e&&t?xd(t):[],...n&&r?Tx(r):[]])}var Bc="${augmentToken}";function KU(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 JU(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var Ax="(unknown uri)",Eh="unknown",xx=/=+$/,YU=/\s+/g,XU=/[-_]/g,QU=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function In(t,e){return typeof t=="string"?t:e}function $x(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function eq(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function tq(t){let e=t.replace(YU,"").replace(XU,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(xx,"");if(r.toString("base64").replace(xx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function Mx(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function rq(t){let e=Mx(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=In(e.uri,Ax),n=In(e.mimeType,Eh);if(typeof e.blob=="string"&&eq(n)){let s=tq(e.blob);if(s!==void 0)return s}let o=$x(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function nq(t){let e=In(t.type,"unknown");if(e==="resource")return rq(t);if(e==="audio"){let r=In(t.mimeType,Eh),n=$x(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=In(t.uri,Ax),n=In(t.name,""),o=In(t.mimeType,Eh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function oq(t){if(t.type!=="resource")return;let e=Mx(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&QU.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function sq(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=oq(t);return e||{type:"text",text:nq(t)}}function iq(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(sq(n))}return e}function aq(t){return oy(t,zU)}function cq(t,e){let r=iq(t);if(r.length===0){let o=aq(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 Ix=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),uq=new Set([502,503,504]),Ti=Ex.length+1,dq=2;function lq(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 fq(t){if(wt(t)||Ph(t)||t instanceof ft)return;let e=t?.cause?.code;if(typeof e=="string")return Ix.has(e)?{totalAttempts:Ti}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:dq}:uq.has(r)?{totalAttempts:Ti}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Ti}:void 0}var pq=80,hq=10,mq=/[^a-zA-Z0-9_.()-]/g,gq=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Vc(t){return t.replace(mq,"_").slice(0,pq)||"unknown"}function yq(t){let e=lq(t);if(e!==void 0&&(/^\d{3}$/.test(e)||Ix.has(e)))return e}function Ge(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=gq.has(e)?e:"Error",n=yq(t);return n===void 0?r:`${r}(${n})`}function Ch(t,e,r){return t instanceof ft?new ft(Vc(t.serverName),t.missingKeys.slice(0,hq).map(Vc),void 0,t.reason).message:t instanceof $n?t.message:`MCP ${r} ${e} failed (${Ge(t)})`}function xh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Vc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Kc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Jc=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=>Rd(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 (${Ge(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=Ch(r,"connect",this._config.type),o=this._config.type==="stdio"&&!wt(r)?Rd(UU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ge(r))}}async _connectWithRetries(){let e=Ti,r={available:!0};for(let n=1;n<=Ti;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=fq(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=(Ex[r-1]??0)+Math.floor(Math.random()*(ZU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ge(e)}; retrying in ${s}ms`),await tn(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 wt(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!ee().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 Mn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=hx();this._client=s;let i;try{if(await bh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(mx,()=>{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=ee();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 (${Ge(n)})`)}}}_recordConnectFailure(e,r,n=Ch(e,r,this._config.type)){if(e instanceof ft){this._status="failed";let o=ee();Go(o,this.name,e.reason,Xt(o,this.name,this._config.id))}else if(e instanceof Ei||e instanceof Mn)this._status="failed";else if(wt(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(wt(e)){this._status="auth_required";let o=ee(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=Ch(e,r,this._config.type);Pd(xh(o,Ge(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=ax(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=cx(this._resolvedEnv??e.env);return dx({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 px(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=fx(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?BU(r):!1,o=e.type==="stdio"&&pa(e.command);if(!(n||o))return;let s=ee();if(!fy(s)){let a=VU({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new ft(this.name,a)}let i=dy(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 my({configEnv:e,localEnv:n?ux():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${Ge(i)})`),new ft(this.name,xd(e),i,"transient")}let s=kh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new ft(this.name,s,void 0,Cx(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await gy(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${Ge(s)})`),new ft(this.name,Tx(e),s,"transient")}let o=kh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new ft(this.name,o,void 0,Cx(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(Bc)))return;let o;if(KU(e.url)){let i=ee().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Bc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Bc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${JU(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(Bc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=ee();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=ee(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!We(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=ee().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,yr(r));let o=this._usableToken();o&&(o.accessToken&&!Vu(o)||ee().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():rs(o)&&ee().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=ee(),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:Xt(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||!We(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),Vr({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;Vr({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 W?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof W)&&Ju(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&Go(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"}, ${Ge(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),Go(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=yr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Yu(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),Vr({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:Ph(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 (${Ge(s)})`),LU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Mn}async _withAuthRetry(e,r,n){let o=this._config,s=ee(),i=Xt(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),bh({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||!wt(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new Ei;if(this._hostedCredentialProvenance!==void 0)throw new Mn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let f=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw wt(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=ee();Go(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ge(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 Kc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Kc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},GU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=ee(),r=Xt(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=Px&&n.outcome==="transient";i++)await tn(WU[i-2]??0),n=await this._runProbe();let o=Xt(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 ${Px} 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:Rx})},"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 (${Ge(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":yx(e)||Rh(e)?"alive":wt(e)?"authFailure":vx(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:Rx})}catch(r){if(this._reinitializingPromise||this._disposed||Rh(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 wt(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&&!wt(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=!$U(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 (${Ge(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ge(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>bx)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${bx}.`);let s={timeout:this._config.timeoutMs??qU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??HU,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??{}},gx,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=cq(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 Mn||e instanceof Ei)throw e;if(wt(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Vc(r),s=Ge(e),i=_x(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 jU(e)||Pd(xh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),xh(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 Ox=_q.child({prefix:"pi-mcp"}),Sq=3,wq=6e4;function bq(t,e){let r=Date.now(),n=r-wq,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=Sq?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function zx(t){en(t),Vi(t)}async function Rq(t,e,r){if(!bq(e,t)){Ox.warn(`MCP server "${t}" automatic restart rate-limited`);return}Ox.warn(`MCP server "${t}" wedged; recycling transport`),await Hr(t,e,r)}function Yc(t,e,r){if(Pq(e)){zx(t);return}Du(t,r),Gn(e)&&zx(t)}function Pq(t){return Yo()||t.toolSearchLatched}function Jt(t,e,r){return mm(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function Th(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 Cq(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&&Rm(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 Ah(t){let{state:e,config:r,generation:n}=t;return new Jc(r,Cq({state:e,config:r,hostGeneration:n}))}function Ze(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 $h(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 Mh(t,e,r){return t.configDesiredRevisions.get(e)===r}function Nx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function Ih(t,e,r,n){t.onStateChange=(i,a)=>{if(!Jt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(vq,c)},t.onWedged=()=>{if(!Jt(t,e,r))return;let i=r.currentLoad?.latestPi??n;Rq(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(!Jt(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(!Jt(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=()=>{Jt(t,e,r)&&t.status==="success"&&Yc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Lu(i,t,e),i!==n&&Lu(n,t,e)}}async function Dx(t,e,r,n){let o=setTimeout(()=>{Jt(t,e,r)&&J(n(),r)},Ni);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Jt(t,e,r)&&J(n(),r)}}async function Lx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function Xc(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 xq(t){let{state:e,config:r,displaced:n,retirement:o}=t;$h(e,n.config),Vo(e,r.name),n.beginDisposal?.();try{let s=We(n.config,r)?Promise.resolve():dt(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 kq(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=Rt({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"}}),Pe({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 Eq(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Jt(r,o,e)?a?.(n)===!1?(await kq({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Yc(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 Tq(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(!Mh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=Th(e,r.name),l=Ah({state:e,config:r,generation:d});return Ih(l,d,e,o),ji({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:Eq({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function Aq(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!Mh(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=Ln(a,s),f=Bo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>Tq({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:i}),m=async()=>(f.displacedHost&&f.retirement?await xq({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await Ru(f.retirement),h());return f.retirement?m():h()}async function bt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ze(e,d.name)})).map(async d=>{try{let l=await Aq({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)},Ni);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function $q({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!Nx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);$h(e,s),Vo(e,t);let a=Rt({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||!Nx(e,t,n))return Pe({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=Th(e,t),u=Ah({state:e,config:s,generation:c});if(Ih(u,c,e,r),!ji({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await Dx(u,c,e,d),Jt(u,c,e)&&u.status==="success"&&Yc(d(),e,u),!0}function Hr(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 $q({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 Mq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;$h(e,n.config),Vo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&We(n.config,o)?Promise.resolve():dt(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 jx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=qn(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ze(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},f=Bo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await Mq({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await Ru(f.retirement),Z(e,t)?.revision!==f.lease.revision||!Mh(e,t,c)){Pe({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){Pe({state:e,name:t,owner:l,revision:f.lease.revision}),J(s(),e);return}let p=Th(e,t),h=Ah({state:e,config:a,generation:p});Ih(h,p,e,r),ji({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await Dx(h,p,e,s),Jt(h,p,e)&&h.status==="success"&&Yc(s(),e,h))}async function Ai(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Hr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as Iq}from"@hermes/logger";var Oh=Iq.child({prefix:"pi-mcp"}),Oq=1e6,zq=1e3,Nq=/^\d+$/;function Fx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function On(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(typeof e!="string"||!Nq.test(e)||typeof r!="string"||r.length===0)return;let n=Sm(t);return{revision:e.replace(/^0+(?=\d)/,""),domain:Fx(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:vr(o,n)>0?o:n}function Lq(t,e,r){if(t===void 0)return!0;let n=Fx(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain?!0:r?.kind==="domain"&&!it(n)&&it(e.domain)&&jn(n)===r.domain}function jq(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 Oh.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=jn(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=vr(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 Uq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function qq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*zq+Math.floor(t.access_token_expires_at.nanos/Oq):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 Qc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!Uq(s)){Oh.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=On(s),a=jq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=qq(s);if(Fq(t,o,c,i)){Oh.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 Gq=Hq.child({prefix:"pi-mcp"});function Zq(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 Wq(t,e,r){let n=Object.entries(t).filter(([o,s])=>{let i=On(s);if(i===void 0)return!1;let a=Kr(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 Ux(t){let{pi:e,state:r,update:n}=t,o=Zq(r,n.configId),s=o?Wq(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=Qc(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 f=On(s);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,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??Hr,l=t.report??J;await d(o.name,r,u).catch(f=>{Gq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${f instanceof Error?f.name:"non-Error"}`)}),l(u,r),Ne(r)}import{logger as sH}from"@hermes/logger";import{execFile as zh}from"node:child_process";import{win32 as Nh}from"node:path";import{logger as Bq}from"@hermes/logger";var Vq=5e3,Kq=/^[a-z]:[\\/]/i,Jq=/[<>:"|?*]/;function Yq(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!Kq.test(t)||!Nh.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||Jq.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:Nh.join(Nh.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function Xq(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function Qq(t,e){switch(process.platform){case"darwin":return zh("open",[t],e);case"win32":{let r=Yq();return r?zh(r,["-NoProfile","-NonInteractive","-EncodedCommand",Xq(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return zh("xdg-open",[t],e)}}function qx(t,e=Vq){let r=Bq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let s=!1,i=null,a=setTimeout(()=>{if(!s){s=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{i?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);i=Qq(o,c=>{s||(s=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as eH}from"node:http";function eu(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Hx(t){let e=eu(t.title),r=eu(t.heading),n=eu(t.message),o=t.details?eu(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 Ix(t){return Mx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Kc(t,e){return Mx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var Bq="127.0.0.1",Nx="/callback",Ox=3e3,zx=3010,Vq="Authentication successful. You can close this window.",Jc={"Content-Type":"text/html; charset=utf-8"};function Dx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function Lx(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:{code:r,state:e}};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}let s=n.get("code");if(!s)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{kind:"success",result:{code:s,state:o??e}}}function kh(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function Wq(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==Nx){e.writeHead(404,Jc),e.end(Kc("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){let a=c=>{e.writeHead(400,Jc),e.end(Kc("Authentication did not complete.",`Error: ${i}`));let u=kh(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!s){e.writeHead(400,Jc),e.end(Kc("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Jc),e.end(Ix(Vq)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function Kq(t){for(let e=Ox;e<=zx;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,Bq)}))return e;throw new Error(`No free port in ${Ox}-${zx} for the OAuth callback server`)}async function jx(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,s=Zq((a,c)=>{Wq(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),i=await Kq(s);return{port:i,redirectUri:`http://localhost:${i}${Nx}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>s.close(),setErrorRetryHandler:a=>{o=a}}}var Eh=Jq.child({prefix:"pi-mcp"}),Yq=300*1e3,qx="MCP authentication was superseded";function Fx(){return Dx()?"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 Mn(t){if(t.aborted)throw new Error("Authentication cancelled")}function Hx(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&&Gx(t.credentialRevisions.get(e),r.credentialRevision)}function Gx(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Ux(t,e,r){if(!Hx(t,e,r))throw new Error(qx)}async function Xq(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=mr(d);try{let f=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(f===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!Gx(t.credentialRevisions.get(e),u))return;Gr({state:t,name:e,revision:f}),J(t.currentLoad?.latestPi??s,t)}catch{Eh.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function Qq(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 eH(t,e,r,n){return new Promise((o,s)=>{let i=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=m=>{i||(i=!0,c(),m())},d=()=>u(()=>s(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>s(new Error("Authentication timed out"))),Yq)},f=m=>{let y=m instanceof Error?m.message:String(m);u(()=>s(new Error(`Could not read the pasted authorization code (${y}). Restart sign-in and paste the full redirect URL.`)))},p=async(m,y)=>{let _=await n(m,l);if(!i){if(_){h(y);return}u(()=>s(kh(m)))}},h=(m=e.waitForManualCode())=>{m.then(async y=>{if(!(i||!y))try{let _=Lx(y,r());if(_.kind==="success"){u(()=>o(new URLSearchParams({code:_.result.code,state:_.result.state})));return}let b=e.waitForManualCode();await p(_.params,b)}catch(_){f(_)}}).catch(y=>u(()=>s(y instanceof Error?y:new Error(String(y)))))};if(t.setErrorRetryHandler(m=>n(m,l)),l(),e.signal.aborted){u(()=>s(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(m=>{m&&u(()=>o(new URLSearchParams({code:m.code,state:m.state})))}).catch(m=>u(()=>s(m instanceof Error?m:new Error(String(m))))),h()})}async function Zx(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=mr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Ux(r,e,c),Mn(o.signal),d=await jx(),Mn(o.signal);let f=new URL(i.url),p=await ad(f);Mn(o.signal);let h=await cd(p);Mn(o.signal);let m=await ud({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});Mn(o.signal);let y=await oa(f,m,h,d.redirectUri,p.resourceScopes?.join(" "),p.resourceIdentifier?new URL(p.resourceIdentifier):void 0);Mn(o.signal);let _=y,b=!1,w,k,S=(Re,qr)=>{if(b)return k&&w&&sa(Re,w)?k.then(ut=>ut.authUri.toString()):Promise.resolve(null);if(!sa(Re,_))return Promise.resolve(null);b=!0;let Hr=_;return w=Hr,qr(),Eh.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),k=dd(Hr).then(ut=>(_=ut,o.onAuthUrl({url:ut.authUri.toString(),instructions:Fx()}),ut)),k.then(ut=>ut.authUri.toString())};d.setErrorRetryHandler(Re=>S(Re,()=>{})),o.onAuthUrl({url:y.authUri.toString(),instructions:Fx()}),Mn(o.signal),await $x(y.authUri.toString());let P=await eH(d,o,()=>_.state,S),I=await ld(P,_);Ux(r,e,c);let ne=Qq(I),fe=await c.tokenStore.persistAuthenticated(e,ne,u,l);if(!Hx(r,e,c))throw await Xq(r,e,c,ne,fe,n),new Error(qx);c.tokenStore.commit(e,ne),r.preservedCredentialIdentities?.delete(e),Gr({state:r,name:e,revision:fe}),r.tokens.clearAuthRequired(e),ot(r,e),await Ri([e],r,n),J(r.currentLoad?.latestPi??n,r),Eh.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as gH}from"@augmentcode/auggie-v2";import{resolveTargetFiles as tH,SETTINGS_TARGET_ORDER as rH,SettingsManager as nH,scopeToSettingsTarget as oH,settingsTargetToScope as Th}from"@augmentcode/auggie-v2";var sH=rH.map(t=>Th(t)),Bx=(t,e)=>nH.create(t,e);function Vx(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 Wx(t,e,r){let n=Bx(e,r);return sH.filter(o=>Vx(n,o)?.[t])}function Kx(t){let e=t.map(n=>({target:oH(n),path:n,exists:!0})),r=tH({files:e});return"directTarget"in r?{scopes:t,direct:Th(r.directTarget)}:{scopes:r.files.map(n=>Th(n.target)),direct:null}}function iH(t,e,r){let{servers:n}=Dn(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Jx(t,e,r,n,o){try{let s=Bx(n,o);if(!Vx(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:iH(t,n,o)!==e}}function Ah(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function Yx(t,e,r){return Ah(t)}function Xx(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as aH}from"@hermes/logger";var Mh=aH.child({prefix:"pi-mcp"}),Qx="hermes:mcp:register-server-source";function cH(t,e){return t.type==="stdio"?jt(t,e):Lt(t,e)}function ek(t,e){return JSON.stringify(t)===JSON.stringify(e)}function uH(t,e){return{...t,disabled:e}}function dH(t){try{return t.getServers()}catch(e){return Mh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function lH(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function tk(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 fH(t,e,r,n){let o=new Map;if(!t)return o;for(let s of dH(t)){let i=e.servers.get(s.name),a=cH(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=uH(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),f=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,p=i!==void 0&&d===void 0&&n.has(s.name)&&ek(i.config,u);p&&(Q(e,s.name,i),rm({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(f||p||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),tk(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function pH(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){Pe({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=Rt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=dt(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"}}),Pe({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function rk(t,e){tk(t,e)}function hH(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"){rk(e,a);continue}u===o.get(a)&&n.has(a)&&ek(u.config,c)||(i.set(a,Ze(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function mH(t,e,r){let n=r?.connect??bt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&lH(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=fH(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 pH(a,u,e);let{reservedRevisions:d,toConnect:l}=hH({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Mh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),_=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return _||rk(e,h.name),_};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(f(),e),Ne(e)}}function $h(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>mH(t,e,r)).catch(s=>{Mh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function nk(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),$h(o.currentLoad?.latestPi??s,o,e))}function ok(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,$h(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,$h(e.currentLoad?.latestPi??t,e))})}}function yH(t,e){let n=gH.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function sk(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(yH(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:Ah(e)};if(bu(r.mcpConfigOverride).has(e))return{kind:"session"};if(hr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=Wx(e,n,o);if(i.length===0)return{kind:"blocked",message:Yx(e,n,o)};let{scopes:a,direct:c}=Kx(i);return{kind:"local",scopes:a,direct:c}}async function ik(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 nk({name:e,disabled:r,state:n,pi:o});return}bu(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 bt([a],n,o,void 0,void 0,i?.owner.kind),Ne(n)}async function ak(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=Jx(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await Ex(e,o,s,i,a),Ne(o),c.overridden?{notice:Xx(e)}:{}}import{Key as DH,matchesKey as LH,SpinnerTimer as jH,wrapTextWithAnsi as FH}from"@earendil-works/pi-tui";import{Key as PH,matchesKey as CH}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as vH,scopeToSettingsTarget as _H}from"@augmentcode/auggie-v2";import{truncateToWidth as SH,visibleWidth as ck}from"@earendil-works/pi-tui";var wH=15,bH=2;function uk(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 Ih(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function dk(t){return Math.max(Oh(t),wH)}function Oh(t){return t.reduce((r,n)=>Math.max(r,ck(n)),0)+bH}function Pi(t,e){let r=e-ck(t);return r>0?t+" ".repeat(r):t}function lk(t,e){return SH(t,Math.max(1,e),"\u2026")}function fk(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 RH(t,e){return Math.max(0,t-e)}function zh(t,e,r){return Math.max(0,Math.min(t,RH(e,r)))}function pk(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 hk(t,e){return String(t+1).padStart(String(e).length," ")}function mk(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function Nh(t){return vH(_H(t))}function Yc(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 gk(){return{step:"serverList",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var Mo=15;var xH="k",kH="j";function Io(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 yk(t,e){return e.matches(t,"tui.select.up")||t===xH?{kind:"up"}:e.matches(t,"tui.select.down")||t===kH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:CH(t,PH.backspace)?{kind:"back"}:{kind:"ignore"}}function EH(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=Io(rt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=Io(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 TH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Yc(n);switch(e.kind){case"up":return{state:{...t,actionIndex:Io(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:Io(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 AH(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 $H(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)]?.logLines().length??0;switch(e.kind){case"up":return{state:{...t,logScrollOffset:zh(t.logScrollOffset-1,n,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:zh(t.logScrollOffset+1,n,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function MH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Xc(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function IH(t,e){let r=t.targetScopes.length;if(r===0)return{state:Xc(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:Io(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:Io(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Xc(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Xc({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Xc(t,"serverActions")}}default:return{state:t}}}function vk(t,e,r){switch(t.step){case"serverList":return EH(t,e,r.snapshots);case"serverActions":return TH(t,e,r);case"viewTools":return AH(t,e,r);case"viewLogs":return $H(t,e,r);case"pasteAuthCode":return MH(t,e);case"selectTarget":return IH(t,e);default:return{state:t}}}var Dh="\u2192 ",Qc=" ";function OH(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 _k(t,e,r){if(e.length===0)return[r.fg("muted","No MCP servers available")];let n=dk(e.map(c=>c.name)),o=Oh(["Source",...e.map(Ih)]),s=rt(e,t.selectedServer),a=[Qc+Pi(r.bold(r.fg("accent","Name")),n)+Pi(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=uk(u),f=r.fg(l.color,l.label)+(l.hint?r.fg("muted",l.hint):"");a.push((d?Dh:Qc)+Pi(OH(u,d,r),n)+Pi(r.fg("muted",Ih(u)),o)+f)}return a}var zH={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 NH(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 zH[t]}function Sk(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",lk(s+o.connectionInfo,n))];o.source==="plugin"&&i.push(r.fg("muted","Source: plugin (toggles apply to this session only)")),i.push("");let a=Yc(o);for(let[c,u]of a.entries()){let d=c===t.actionIndex,l=NH(u,o),f=u==="authenticate"?mk(o.status):l.label,p=d?r.bold(r.fg("accent",f)):r.fg("text",f);i.push((d?Dh:Qc)+p+r.fg("muted",` - ${l.description}`))}return i}function wk(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}=fk(t.toolIndex,o,Mo),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",`${hk(c,o)} `)+l+(u.disabled?r.fg("muted"," (disabled)"):""))}return a}function bk(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=pk(t.logScrollOffset,s,Mo),a=[];s>Mo&&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 Rk(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",Nh(i))):r.fg("text",Nh(i));o.push((a?Dh:Qc)+c)}return o}function UH(t){return t.type==="stdio"?t.command:t.url}function qH(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
143
+ </html>`}function Gx(t){return Hx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function tu(t,e){return Hx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var tH="127.0.0.1",Bx="/callback",Zx=3e3,Wx=3010,rH="Authentication successful. You can close this window.",ru={"Content-Type":"text/html; charset=utf-8"};function Vx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function Kx(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:{code:r,state:e}};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}let s=n.get("code");if(!s)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{kind:"success",result:{code:s,state:o??e}}}function Dh(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function nH(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==Bx){e.writeHead(404,ru),e.end(tu("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){let a=c=>{e.writeHead(400,ru),e.end(tu("Authentication did not complete.",`Error: ${i}`));let u=Dh(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!s){e.writeHead(400,ru),e.end(tu("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,ru),e.end(Gx(rH)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function oH(t){for(let e=Zx;e<=Wx;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,tH)}))return e;throw new Error(`No free port in ${Zx}-${Wx} for the OAuth callback server`)}async function Jx(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,s=eH((a,c)=>{nH(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),i=await oH(s);return{port:i,redirectUri:`http://localhost:${i}${Bx}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>s.close(),setErrorRetryHandler:a=>{o=a}}}var Lh=sH.child({prefix:"pi-mcp"}),iH=300*1e3,Qx="MCP authentication was superseded";function Yx(){return Vx()?"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 zn(t){if(t.aborted)throw new Error("Authentication cancelled")}function ek(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&&tk(t.credentialRevisions.get(e),r.credentialRevision)}function tk(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Xx(t,e,r){if(!ek(t,e,r))throw new Error(Qx)}async function aH(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||!We(r.server.config,i.config))return;let d=i.config,l=yr(d);try{let f=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(f===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!tk(t.credentialRevisions.get(e),u))return;Vr({state:t,name:e,revision:f}),J(t.currentLoad?.latestPi??s,t)}catch{Lh.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function cH(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 uH(t,e,r,n){return new Promise((o,s)=>{let i=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=m=>{i||(i=!0,c(),m())},d=()=>u(()=>s(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>s(new Error("Authentication timed out"))),iH)},f=m=>{let y=m instanceof Error?m.message:String(m);u(()=>s(new Error(`Could not read the pasted authorization code (${y}). Restart sign-in and paste the full redirect URL.`)))},p=async(m,y)=>{let v=await n(m,l);if(!i){if(v){h(y);return}u(()=>s(Dh(m)))}},h=(m=e.waitForManualCode())=>{m.then(async y=>{if(!(i||!y))try{let v=Kx(y,r());if(v.kind==="success"){u(()=>o(new URLSearchParams({code:v.result.code,state:v.result.state})));return}let b=e.waitForManualCode();await p(v.params,b)}catch(v){f(v)}}).catch(y=>u(()=>s(y instanceof Error?y:new Error(String(y)))))};if(t.setErrorRetryHandler(m=>n(m,l)),l(),e.signal.aborted){u(()=>s(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(m=>{m&&u(()=>o(new URLSearchParams({code:m.code,state:m.state})))}).catch(m=>u(()=>s(m instanceof Error?m:new Error(String(m))))),h()})}async function rk(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=yr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Xx(r,e,c),zn(o.signal),d=await Jx(),zn(o.signal);let f=new URL(i.url),p=await yd(f);zn(o.signal);let h=await vd(p);zn(o.signal);let m=await _d({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});zn(o.signal);let y=await da(f,m,h,d.redirectUri,p.resourceScopes?.join(" "),p.resourceIdentifier?new URL(p.resourceIdentifier):void 0);zn(o.signal);let v=y,b=!1,w,x,S=(Re,Wr)=>{if(b)return x&&w&&la(Re,w)?x.then(ut=>ut.authUri.toString()):Promise.resolve(null);if(!la(Re,v))return Promise.resolve(null);b=!0;let Br=v;return w=Br,Wr(),Lh.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),x=Sd(Br).then(ut=>(v=ut,o.onAuthUrl({url:ut.authUri.toString(),instructions:Yx()}),ut)),x.then(ut=>ut.authUri.toString())};d.setErrorRetryHandler(Re=>S(Re,()=>{})),o.onAuthUrl({url:y.authUri.toString(),instructions:Yx()}),zn(o.signal),await qx(y.authUri.toString());let P=await uH(d,o,()=>v.state,S),I=await wd(P,v);Xx(r,e,c);let ne=cH(I),fe=await c.tokenStore.persistAuthenticated(e,ne,u,l);if(!ek(r,e,c))throw await aH(r,e,c,ne,fe,n),new Error(Qx);c.tokenStore.commit(e,ne),r.preservedCredentialIdentities?.delete(e),Vr({state:r,name:e,revision:fe}),r.tokens.clearAuthRequired(e),ot(r,e),await Ai([e],r,n),J(r.currentLoad?.latestPi??n,r),Lh.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as CH}from"@augmentcode/auggie-v2";import{resolveTargetFiles as dH,SETTINGS_TARGET_ORDER as lH,SettingsManager as fH,scopeToSettingsTarget as pH,settingsTargetToScope as jh}from"@augmentcode/auggie-v2";var hH=lH.map(t=>jh(t)),nk=(t,e)=>fH.create(t,e);function ok(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 sk(t,e,r){let n=nk(e,r);return hH.filter(o=>ok(n,o)?.[t])}function ik(t){let e=t.map(n=>({target:pH(n),path:n,exists:!0})),r=dH({files:e});return"directTarget"in r?{scopes:t,direct:jh(r.directTarget)}:{scopes:r.files.map(n=>jh(n.target)),direct:null}}function mH(t,e,r){let{servers:n}=qn(e,r);return n.find(o=>o.name===t)?.disabled===!0}function ak(t,e,r,n,o){try{let s=nk(n,o);if(!ok(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:mH(t,n,o)!==e}}function Fh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function ck(t,e,r){return Fh(t)}function uk(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as gH}from"@hermes/logger";var qh=gH.child({prefix:"pi-mcp"}),dk="hermes:mcp:register-server-source";function yH(t,e){return t.type==="stdio"?Ft(t,e):jt(t,e)}function lk(t,e){return JSON.stringify(t)===JSON.stringify(e)}function vH(t,e){return{...t,disabled:e}}function _H(t){try{return t.getServers()}catch(e){return qh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function SH(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function fk(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 wH(t,e,r,n){let o=new Map;if(!t)return o;for(let s of _H(t)){let i=e.servers.get(s.name),a=yH(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=vH(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),f=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,p=i!==void 0&&d===void 0&&n.has(s.name)&&lk(i.config,u);p&&(Q(e,s.name,i),pm({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(f||p||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),fk(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function bH(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){Pe({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=Rt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=dt(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"}}),Pe({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function pk(t,e){fk(t,e)}function RH(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"){pk(e,a);continue}u===o.get(a)&&n.has(a)&&lk(u.config,c)||(i.set(a,Ze(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function PH(t,e,r){let n=r?.connect??bt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&SH(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=wH(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 bH(a,u,e);let{reservedRevisions:d,toConnect:l}=RH({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;qh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),v=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return v||pk(e,h.name),v};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(f(),e),Ne(e)}}function Uh(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>PH(t,e,r)).catch(s=>{qh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function hk(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),Uh(o.currentLoad?.latestPi??s,o,e))}function mk(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Uh(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Uh(e.currentLoad?.latestPi??t,e))})}}function xH(t,e){let n=CH.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function gk(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(xH(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:Fh(e)};if(Mu(r.mcpConfigOverride).has(e))return{kind:"session"};if(gr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=sk(e,n,o);if(i.length===0)return{kind:"blocked",message:ck(e,n,o)};let{scopes:a,direct:c}=ik(i);return{kind:"local",scopes:a,direct:c}}async function yk(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 hk({name:e,disabled:r,state:n,pi:o});return}Mu(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 bt([a],n,o,void 0,void 0,i?.owner.kind),Ne(n)}async function vk(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=ak(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await jx(e,o,s,i,a),Ne(o),c.overridden?{notice:uk(e)}:{}}import{DynamicBorder as BH}from"@augmentcode/auggie-v2";import{Key as VH,matchesKey as KH,SearchableWindowedList as JH,SpinnerTimer as YH,truncateToWidth as uu,wrapTextWithAnsi as XH}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as kH,scopeToSettingsTarget as EH}from"@augmentcode/auggie-v2";import{truncateToWidth as TH,visibleWidth as Nn,wrapTextWithAnsi as AH}from"@earendil-works/pi-tui";var $H=2,MH=2,nu={name:"Name",source:"Source",status:"Status"};function Hh(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 Gh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Zh(t,e){let r=e-Nn(t);return r>0?t+" ".repeat(r):t}function ou(t){return t.reduce((e,r)=>Math.max(e,Nn(r)),0)}function Lo(t,e,r,n){let o=`${e}Width`,s=Math.min(Math.max(0,r-t[o]),n);return t[o]+=s,n-s}function _k(t,e){let r=Math.max(1,Math.floor(e)),n=Math.min($H,r),o=r-n,s=Math.min(3,o),i=s<2?0:Math.min(MH,Math.floor((o-s)/(s-1))),a=o-i*Math.max(0,s-1),c=["name","source","status"].slice(0,s),u={prefixWidth:n,gapWidth:i,nameWidth:0,sourceWidth:0,statusWidth:0};for(let y of c)a=Lo(u,y,1,a);for(let y=1;a>0;y++){let v=!1;for(let b of c)if(!(y>=Nn(nu[b]))&&(a=Lo(u,b,y+1,a),v=!0,a===0))break;if(!v)break}let d=t.map(y=>Gh(y)),l=t.map(y=>Hh(y)),f=Math.max(Nn(nu.source),ou(d)),p=Math.max(Nn(nu.status),ou(l.map(y=>y.label))),h=Math.max(Nn(nu.name),ou(t.map(y=>y.name))),m=Math.max(p,ou(l.map(y=>y.label+(y.hint??""))));return a=Lo(u,"source",f,a),a=Lo(u,"status",p,a),a=Lo(u,"name",h,a),Lo(u,"status",m,a),u}function Sk(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 jo(t,e){let r=Math.max(1,Math.floor(e));return t.flatMap(n=>AH(n,r).map(o=>Nn(o)<=r?o:TH(o,r,"")))}function IH(t,e){return Math.max(0,t-e)}function Fo(t,e,r){return Math.max(0,Math.min(t,IH(e,r)))}function wk(t,e,r){let n=Fo(t,e,r),o=Math.min(e,n+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Rows ${n+1}-${o} of ${e}`}}function bk(t,e){return String(t+1).padStart(String(e).length," ")}function Rk(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function Wh(t){return kH(EH(t))}import{Key as OH,matchesKey as zH}from"@earendil-works/pi-tui";function su(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 Pk(){return{step:"serverList",filterQuery:"",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var Ck=10,Dn=15;var NH="k",DH="j";function Uo(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 Bh(t,e,r=!0){return e.matches(t,"tui.select.up")||r&&t===NH?{kind:"up"}:e.matches(t,"tui.select.down")||r&&t===DH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:zH(t,OH.backspace)?{kind:"back"}:{kind:"ignore"}}function LH(t,e,r){if(e.kind==="filterChanged")return{state:{...t,filterQuery:e.query,selectedServer:r[0]?.name??null}};let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=Uo(rt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=Uo(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 jH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=su(n);switch(e.kind){case"up":return{state:{...t,actionIndex:Uo(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:Uo(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 FH(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 UH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)]?.logLines()??[],o=jo(n,r.logViewportWidth).length;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Fo(t.logScrollOffset-1,o,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Fo(t.logScrollOffset+1,o,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function qH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function iu(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function HH(t,e){let r=t.targetScopes.length;if(r===0)return{state:iu(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:Uo(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:Uo(t.targetIndex+1,r)}};case"cancel":case"back":return{state:iu(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:iu({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:iu(t,"serverActions")}}default:return{state:t}}}function xk(t,e,r){switch(t.step){case"serverList":return LH(t,e,r.snapshots);case"serverActions":return jH(t,e,r);case"viewTools":return FH(t,e,r);case"viewLogs":return UH(t,e,r);case"pasteAuthCode":return qH(t,e);case"selectTarget":return HH(t,e);default:return{state:t}}}import{truncateToWidth as zt,visibleWidth as GH,wrapTextWithAnsi as Gr}from"@earendil-works/pi-tui";var Vh="\u2192 ",au=" ";function kk(t,e,r){return e?r.bold(r.fg("accent",t)):r.fg("text",t)}function pr(t,e){return e>0?zt(t,e,"\u2026"):""}function Ek(t,e,r,n,o,s,i){let a=Math.max(1,i),c=_k(r,a),u=" ".repeat(c.gapWidth),d=(h,m,y,v)=>{let b=[c.nameWidth>0?Zh(m,c.nameWidth):"",c.sourceWidth>0?Zh(y,c.sourceWidth):"",c.statusWidth>0?v:""].filter(w=>w.length>0);return h+b.join(u)},l=pr(au,c.prefixWidth),p=[d(l,s.bold(s.fg("accent",pr("Name",c.nameWidth))),s.bold(s.fg("accent",pr("Source",c.sourceWidth))),s.bold(s.fg("accent",pr("Status",c.statusWidth))))];if(e.length===0)p.push(zt(s.fg("muted","No MCP servers available"),a,"\u2026"));else if(o.total===0)p.push(zt(s.fg("muted","No matching MCP servers"),a,"\u2026"));else for(let h of n){let m=h.name===t.selectedServer,y=Hh(h),v=pr(y.label,c.statusWidth),b=c.statusWidth-GH(v),w=y.hint?pr(y.hint,b):"",x=s.fg(y.color,v)+(w?s.fg("muted",w):""),S=pr(m?Vh:au,c.prefixWidth);p.push(d(m?s.fg("accent",S):S,kk(pr(h.name,c.nameWidth),m,s),kk(pr(Gh(h),c.sourceWidth),m,s),x))}return o.hasOverflow&&p.push(zt(s.fg("muted",` (${o.current}/${o.total})`),a,"\u2026")),p}var ZH={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 WH(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 ZH[t]}function Tk(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)];if(!s)return Gr(r.fg("muted","No MCP servers available"),o);let i=s.transport==="stdio"?"Command: ":"URL: ",a=Gr(r.fg("muted",i+s.connectionInfo),o);s.source==="plugin"&&a.push(...Gr(r.fg("muted","Source: plugin (toggles apply to this session only)"),o)),a.push("");let c=su(s);for(let[u,d]of c.entries()){let l=u===t.actionIndex,f=WH(d,s),p=d==="authenticate"?Rk(s.status):f.label,h=l?r.bold(r.fg("accent",p)):r.fg("text",p);a.push(zt((l?Vh:au)+h+r.fg("muted",` - ${f.description}`),o,"\u2026"))}return a}function Ak(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)];if(!s)return Gr(r.fg("muted","No tools available."),o);if(s.disabled)return Gr(r.fg("muted","Server is disabled; no tools are currently available."),o);if(s.tools.length===0)return Gr(r.fg("muted","No tools available."),o);let i=s.tools.length,{start:a,end:c}=Sk(t.toolIndex,i,Dn),u=[];for(let d=a;d<c;d++){let l=s.tools[d];if(!l)continue;let p=d===t.toolIndex?r.bold(r.fg("accent",l.name)):r.fg("text",l.name);u.push(zt(r.fg("muted",`${bk(d,i)} `)+p+(l.disabled?r.fg("muted"," (disabled)"):""),o,"\u2026"))}return u}function $k(t,e,r,n){let o=Math.max(1,n),i=e[rt(e,t.selectedServer)]?.logLines()??[];if(i.length===0)return Gr(r.fg("muted","No logs available yet."),o);let a=jo(i,o),c=a.length,u=wk(t.logScrollOffset,c,Dn),d=[];c>Dn&&d.push(zt(r.fg("muted",u.rangeLabel),o,"\u2026")),u.aboveCount>0&&d.push(zt(r.fg("dim",`\u2191 ${u.aboveCount} more rows`),o,"\u2026"));for(let l of a.slice(u.start,u.end))d.push(zt(r.fg("text",l),o,""));return u.belowCount>0&&d.push(zt(r.fg("dim",`\u2193 ${u.belowCount} more rows`),o,"\u2026")),d}function Mk(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)]?.name??"",i=[...Gr(r.fg("muted",`Save the toggle for "${s}" to which settings file?`),o),""];for(let[a,c]of t.targetScopes.entries()){let u=a===t.targetIndex,d=u?r.bold(r.fg("accent",Wh(c))):r.fg("text",Wh(c));i.push(zt((u?Vh:au)+d,o,"\u2026"))}return i}var cu=3;function QH(t){return t.type==="stdio"?t.command:t.url}function eG(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 HH(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:hr(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:UH(r.config),logLines:()=>qH(r)});return e.sort((r,n)=>Pk(r)-Pk(n)),e}function GH(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 ZH(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 BH(t,e,r,n){switch(t.step){case"serverActions":return Sk(t,e,r,n);case"viewTools":return wk(t,e,r);case"viewLogs":return bk(t,e,r);case"selectTarget":return Rk(t,e,r);default:return _k(t,e,r)}}function VH(t,e,r,n){let o=r.bold(r.fg("accent",GH(t,e))),s=BH(t,e,r,n);return[o,"",...s,"",r.fg("muted",ZH(t.step))]}function WH(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 KH(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function JH(t,e,r){let n=i=>i.flatMap(a=>FH(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 YH(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function Ck(t){return t?"Disabling":"Enabling"}function xk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Lh=class{state=gk();config;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;queuedManualCodes=[];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?WH(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme):this.authenticating?JH({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,e):VH(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=yk(e,this.config.keybindings),o=vk(this.state,n,{snapshots:r,windowSize:Mo});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,Ck(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(xk(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,Ck(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(xk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new jH(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=KH(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(LH(e,DH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&YH(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),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)}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?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function kk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new Lh({tui:s,theme:i,keybindings:a,snapshots:()=>HH(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Fh=["list"];function Ek(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 XH(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var QH="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function jh(t,e){return e.length>0?[t,...e]:null}function eG(t){let e=[],r=[];for(let o of t.servers.values())(hr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[jh("MCP Server Status:",e.map(Ek)),jh("Plugin MCP servers:",r.map(Ek)),jh("Diagnostics:",t.diagnostics.map(XH))];return t.servers.size===0&&n.unshift([QH]),n.filter(o=>o!==null).map(o=>o.join(`
145
+ `)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function Ik(t){return t.disabled?2:t.status==="auth_required"?0:1}function tG(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:gr(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:QH(r.config),logLines:()=>eG(r)});return e.sort((r,n)=>Ik(r)-Ik(n)),e}function rG(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 nG(t){switch(t){case"serverList":return"Type to filter \xB7 \u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function oG(t,e,r,n,o){switch(t.step){case"serverActions":return Tk(t,e,n,o);case"viewTools":return Ak(t,e,n,o);case"viewLogs":return $k(t,e,n,o);case"selectTarget":return Mk(t,e,n,o);default:return Ek(t,e,r.getMatchingItems(),r.getVisibleItems(),r.getMetadata(),n,o)}}function sG(t,e,r,n,o){let s=Math.max(1,o),i=uu(n.bold(n.fg("accent",rG(t,e))),s,"\u2026"),a=t.step==="serverList"&&s>=cu?[...r.renderInput(s),""]:[],c=oG(t,e,r,n,s);return[i,"",...a,...c,"",uu(n.fg("muted",nG(t.step)),s,"\u2026")]}function iG(t,e,r,n,o){let s=Math.max(1,o),i=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),a=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[uu(i,s,"\u2026"),"",uu(a,s,"\u2026")]}function aG(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function cG(t,e,r){let n=i=>i.flatMap(a=>XH(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 uG(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function Ok(t){return t?"Disabling":"Enabling"}function zk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Kh=class{state=Pk();config;border;serverList;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;queuedManualCodes=[];authInPaste=!1;authPasteBuffer="";authDone;currentWidth;_focused=!1;component=this;get focused(){return this._focused}set focused(e){this._focused=e,this.syncSearchFocus()}constructor(e){this.config=e,this.border=new BH(r=>e.theme.fg("border",r)),this.serverList=new JH({items:[],getIdentity:r=>r.name,getSearchText:r=>r.name,maxVisible:Ck})}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){let r=Math.max(1,e);this.currentWidth=r,this.syncSearchFocus();let n;if(this.busy)n=iG(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme,r);else if(this.authenticating)n=cG({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,r);else{let o=this.config.snapshots();this.syncServerList(o),this.clampLogScrollOffset(o,r),n=sG(this.state,o,this.serverList,this.config.theme,r)}return[...this.border.render(r),...n,...this.border.render(r)]}handleInput=e=>{this.dispatch(e)};invalidate(){}syncServerList(e){this.serverList.setItems(e);let r=this.state.selectedServer;r!==null&&this.serverList.selectIdentity(r)||(this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null})}isSearchAvailable(){return this.currentWidth===void 0||this.currentWidth>=cu}syncSearchFocus(){let e=this.currentWidth!==void 0&&this.currentWidth>=cu&&this.state.step==="serverList"&&this.busy===null&&this.authenticating===null;this.serverList.setInputFocused(this._focused&&e)}clampLogScrollOffset(e,r){if(this.state.step!=="viewLogs")return;let n=e[rt(e,this.state.selectedServer)],o=jo(n?.logLines()??[],r).length,s=Fo(this.state.logScrollOffset,o,Dn);s!==this.state.logScrollOffset&&(this.state={...this.state,logScrollOffset:s})}applyAction(e,r){let n=xk(this.state,e,{snapshots:r,windowSize:Dn,logViewportWidth:this.currentWidth??cu});this.state=n.state,n.effect&&this.runEffect(n.effect)}dispatchServerList(e,r){this.syncServerList(r);let n=this.isSearchAvailable(),o=Bh(e,this.config.keybindings,!n);if(o.kind==="up"||o.kind==="down"){o.kind==="up"?this.serverList.selectPrevious():this.serverList.selectNext(),this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null};return}if(o.kind==="confirm"||o.kind==="cancel"){this.applyAction(o,[...this.serverList.getMatchingItems()]);return}n&&this.serverList.handleInput(e)&&this.applyAction({kind:"filterChanged",query:this.serverList.getQuery()},[...this.serverList.getMatchingItems()])}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots();this.state.step==="serverList"?this.dispatchServerList(e,r):this.applyAction(Bh(e,this.config.keybindings),r),this.syncSearchFocus(),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,Ok(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(zk(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,Ok(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(zk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new YH(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=aG(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(KH(e,VH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&uG(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),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)}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?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function Nk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new Kh({tui:s,theme:i,keybindings:a,snapshots:()=>tG(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Yh=["list"];function Dk(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 dG(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var lG="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function Jh(t,e){return e.length>0?[t,...e]:null}function fG(t){let e=[],r=[];for(let o of t.servers.values())(gr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[Jh("MCP Server Status:",e.map(Dk)),Jh("Plugin MCP servers:",r.map(Dk)),Jh("Diagnostics:",t.diagnostics.map(dG))];return t.servers.size===0&&n.unshift([lG]),n.filter(o=>o!==null).map(o=>o.join(`
147
147
  `)).join(`
148
148
 
149
- `)}function tG(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Fh.includes(e))return e}async function rG(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=Ri([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function Tk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Fh.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 kk(n,e,i=>Ri([i],e,t),{classify:i=>sk({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>ik({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>ak({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)=>Zx({serverName:i,state:e,pi:t,controller:a}));return}let s=tG(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Fh.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(eG(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await rG(n,e,t)}})}import{logger as nG}from"@hermes/logger";var Ak=nG.child({prefix:"pi-mcp"}),Uh="augment:feature-flags";function oG(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(Uh,r=>{let n=oG(r);if(n===void 0){Ak.warn(`${Uh} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,Ak.debug(`Received feature-flag snapshot via ${Uh} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as sG}from"@hermes/logger";var eu=sG.child({prefix:"pi-mcp"}),qh="augment:mcp-attach-result";function Mk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(qh,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){eu.warn(`${qh} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){eu.debug(`${qh}: 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 tu(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 Dm(r);o.ok?(e.mcpCatalog=o.entries,eu.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,eu.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),jn(e)&&Yr(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as iG}from"@hermes/logger";var Ci=iG.child({prefix:"pi-mcp"}),Ik=300*1e3,Hh=600*1e3;function aG(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&&(Ko(o,e)||o.expiresAt>e+Hh||(Ci.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Hh}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&Ci.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{Ci.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function Ok(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{aG(t)},Ik);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,Ci.debug(`Started background MCP OAuth refresh loop (interval ${Ik}ms, buffer ${Hh}ms)`)}function zk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,Ci.debug("Stopped background MCP OAuth refresh loop"))}import{logger as wG}from"@hermes/logger";function cG(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Go.OAUTH:return"oauth";case Go.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 uG(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Vr.CLI:return"cli";case Vr.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 ru(t){if(t==null)return;if(t.length===0)return[];let e=t.map(uG).filter(r=>r!==void 0);return e.length===0?void 0:e}function nu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=cG(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=zn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Nn(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Ct?i.message:String(i)}}}function dG(t){let e=t.config?.auth_type;return e===Go.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function lG(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 Gh(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 fG(t,e,r){if(r!==void 0&&t.added_by===r)return ru(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?ru(n):[]}function pG(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let p=Gh(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let p=new Set(s),h=Gh(e,r,()=>!0),m=new Set(h.map(w=>w.id)),y=h.filter(w=>p.has(w.id)),_=h.filter(w=>!p.has(w.id)).map(w=>w.id),b=s.filter(w=>!m.has(w));return{selected:y,filteredOutIds:_,missingIds:b,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=Gh(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let m=!d.has(p.id)&&a.has(p.id)?fG(p,o,i):ru(p.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function hG(t){return t==null?Vr.CLOUD_AGENT:void 0}function mG(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 Nk(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?jt(t,n):Lt(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 gG(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=nu(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)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`}};let d=Nk(c,e.id,i,s);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=Nk(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 yG(t){let e=[],r=[],n=[];for(let o of t)dG(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 vG(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=lG(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}}function _G(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function ou(t){let e=t.client??new Gi(t.creds),{tenant:r,user:n,diagnostics:o}=await Km(e,hG(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=pG({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=yG(a),f=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...mG(u));let p=[],h=new Map,m=new Set(t.localServerNames),y=[...f.filter(w=>i.has(w.id)),...f.filter(w=>!i.has(w.id))];for(let w of y){let k=gG({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:m,workspaceRoot:t.workspaceRoot});_G(k,{servers:p,retainedNames:d,diagnostics:o,nameCollisionFallbacks:h})}let _=vG(p);d.push(..._.droppedNames),o.push(..._.diagnostics);let b=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&b.set(w.id,w.config.name);return{servers:_.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:b,nameCollisionFallbacks:h}}import{logger as SG}from"@hermes/logger";var Oo=SG.child({prefix:"pi-mcp"});function Dk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Oo.warn("Embedded MCP config is missing an id; ignoring");return}let n=nu(r,"tenant");if(!n.ok){Oo.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?jt(n.server,o):Lt(n.server,o)}catch(s){Oo.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function Lk(t,e){let r;try{r=JSON.parse(t)}catch(n){Oo.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return Dk(r,e)}function su(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Oo.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Oo.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=Dk(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 zt=wG.child({prefix:"pi-mcp"});function bG(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 Jt(t){Ve({state:t.state,domain:st(t.configId),epoch:t.intentEpoch})}function RG(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 jk(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function Fk(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),zt.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function xi(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Jt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(zt.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 PG(t,e){return e.flatMap(r=>Bc(t,r)?[r.config]:[])}function CG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function xG(t,e){let r=CG(e);if(r){if(xi(t,r.error),r.error instanceof Pt)throw r.error;return}let n=PG(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){bG(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 Uk(t,e){try{xG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function kG(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 zt.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 zt.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 EG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await qo(t.state,t.configId),t.superseded()){Jt(t);return}if(kG(t,e)){Jt(t);return}try{if(!await vr({state:t.state,config:e,pi:t.activePi})){Jt(t);return}}catch(r){throw xi(t,r),r}zt.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);Uk(t,r??[])}catch(r){if(xi(t,r),r instanceof Pt)throw r}}async function TG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Jt(t),zt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){Fk(r,e),zt.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),Jt(t);return}if(await qo(r,n),o()){Jt(t);return}try{if((await Promise.all(e.servers.map(c=>vr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Jt(t);return}}catch(a){throw xi(t,a),a}zt.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()){Jt(t);return}Fk(r,e),Uk(t,i??[])}function AG(t,e){if(typeof e=="string")return Lk(e,t.workspaceRoot??process.cwd())}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 zt.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();if(!Li({state:r,configId:i,generation:s?.attachmentGeneration}))return zt.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=RG(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 f=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,p={state:r,configId:i,activePi:u,connect:o?.connect??bt,report:o?.report??J,intentEpoch:a.epoch,superseded:f,sourceOwnership:()=>!f(),hasLiveHostForId:()=>jk(r,i)},h=AG(r,s?.embeddedConfig),m;if(h)m=EG(p,h);else{let y=r.credentials;y?m=(o?.discover??ou)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(b=>TG(p,b)).catch(b=>{if(!(b instanceof Pt)){xi(p,b);return}throw b}):(zt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Jt(p),m=Promise.resolve())}return ji({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>jk(r,i)})}import{logger as $G}from"@hermes/logger";var Nt=$G.child({prefix:"pi-mcp"});function Gk(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function Zk(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?Rt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ze(e,r),"retiring"):void 0:(Pe({state:e,name:r,owner:n.owner,revision:n.revision}),Ze(e,r),"released");let c=a.get(r),u=jo({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:Ze(e,r),leaseRevision:u.lease.revision}}function MG(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=Zk({state:e,name:r,lease:c,host:n,isDeselected:Gk({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"&&Pe({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function IG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=Zk({state:e,name:r,lease:n,isDeselected:Gk({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function OG(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=MG({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||IG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function Bk(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 f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=i.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){i.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&s.push(dt(t,l,f.id,f))}try{await Promise.all(s)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Pt(f)}let d=new Map;for(let[l,f]of i){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),Be(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function zG(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:f}]of t.allConfigsById)n&&!n.has(l)||u.has(f)||d.has(f)||(d.add(f),a.push(f));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function NG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return su(n,e.workspaceRoot??process.cwd())}async function DG(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(dt(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 Pt(c)}}function LG(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 jG(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function FG(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 UG(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 Bk(e,r.servers,n,s,o!==void 0)}async function Vk(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():qo(t,r.id)))}async function Hk(t){return await Vk(t.state,t.result),t.state.registryGeneration===t.generation&&await UG(t),t.result}function qG(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Nt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=zG(n,r,s);return Hk({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=>Hk({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function HG(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Nt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Nt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function GG(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 Wk(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&&Pe({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function ZG(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}),Nt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await Vk(e,r),e.registryGeneration!==o)return;let c=Wk({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>vr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;HG({state:e,result:r,selection:n}),Zh({state:e,result:r,selection:n,slotReservations:a});let l=GG({state:e,result:{...r,servers:u}});if(l.length===0)return;let f=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 Nt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let b=a.get(m.name)?.configRevision;if(b===void 0)return!0;let w=e.configDesiredRevisions.get(m.name);return w!==b?(Nt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${b} to ${w} by a concurrent operation`),!1):!0});if(f.length===0)return;Nt.info(`Registry discovery: connecting ${f.length} server(s)`);let h=(await s(f,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));await BG({state:e,pi:i,result:r,generation:o,connect:s})}async function BG(t){let{state:e,pi:r,result:n,generation:o,connect:s}=t,i=n.nameCollisionFallbacks;if(!(!i||i.size===0))for(let[a,c]of i)for(let u of c){let d=await VG({state:e,pi:r,generation:o,connect:s,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function VG(t){let{state:e,pi:r,generation:n,connect:o,name:s,candidate:i}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(s);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===i.id)return"settled";if(!await vr({state:e,config:i,pi:r})||e.registryGeneration!==n)return"abort";Nt.info(`MCP auth fallback: "${s}" (id=${c}) landed ${a.status}; connecting same-named config id=${i.id} in its place`),await o([i],e,e.currentLoad?.latestPi??r,Wk({state:e,generation:n}));let d=e.servers.get(s);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===i.id&&d.status==="success"?"settled":"next"}async function WG(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Nt.warn(i),e.registryGeneration===n&&(await Bk(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function KG(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 JG(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await ZG({...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 Pt)throw KG(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 WG({...t.resultArgs,error:r})}}function Kk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??ou,i=o?.connect??bt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Nt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&mm(r,new Set(a.configIds.map(st)));let c=NG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Nt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let _ of a.configIds??[])Ve({state:r,domain:st(_)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=DG({state:r,previousSelectedIds:d,configIds:a.configIds}),f=LG({parsedEmbedded:c,configIds:a.configIds}),p=++r.registryGeneration,h=Promise.all([OG(r,a.configIds,f),l]).then(([_])=>_);jG(r);let m=a.configIds?[...a.configIds]:void 0,y=qG({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:FG(r),previousSelectedIds:d,selection:m,generation:p,discover:s});return y?JG({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:p,connect:i,pi:e}}):Promise.resolve()}import{logger as YG}from"@hermes/logger";var Ur=YG.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 QG(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function Qk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function eZ(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function Jk(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&&(eZ({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 eE(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function Yk(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 tE(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function tZ(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?In(n):void 0;if(s===void 0){Ze(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?nm({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):Pe({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(tE(e,r),Ze(e,r))}async function Bh(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 b=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Ur.warn(b),e.diagnostics.push({message:b,origin:"registry"}),new Error(b)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=In(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,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ze(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,_=y?.result;if(d&&_?.status==="failed"&&_.transportDisposed!==!0){let b=_.error instanceof Error?_.error:new Error(String(_.error)),w=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Ur.warn(w),e.diagnostics.push({server:a,message:w}),b}try{await Uo(e,a,r,i)}catch(b){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let w=`Live MCP remove-server failed to detach ${a}: ${b instanceof Error?b.message:String(b)}`;throw Ur.warn(w),e.diagnostics.push({server:a,message:w}),b}Qk({state:e,configId:r,fence:s})&&(eE(e,r),tZ({state:e,name:a,config:i,retirement:y})),Ur.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 Xk(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)}`;Ur.warn(s),e.diagnostics.push({server:r,message:s})}async function rZ(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(Xk({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Uo(e,r,n,o.config)]);return Xk({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 nZ(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=Ze(e,n),f=Rt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),Ur.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await rZ({state:e,name:n,configId:r,server:a});if(h&&Qk({state:e,configId:r,fence:i})?eE(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:f,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&Pe({state:e,name:n,owner:c.owner,revision:c.revision})&&tE(e,n),s(p,e),!h)throw m}function rE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Ur.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Li({state:r,configId:i,generation:s?.attachmentGeneration}))return Ur.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=Yk(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(i),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(i);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(Jk({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>Bh({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=XG(r,i);if(u===void 0&&d===void 0)return a(Bh({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=QG({state:r,configId:i,liveEditGeneration:h});return a(Jk({state:r,configId:i,fence:m,operation:()=>{let y=Yk(r,i);return y===void 0?Bh({state:r,configId:i,pi:e,report:c,sourceFence:m}):nZ({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as oZ}from"@hermes/logger";var ki=oZ.child({prefix:"pi-mcp"}),nE=3,oE=6e4,sZ=1e3,iZ=8e3;function Vh(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Fr,i=o?.now??Date.now,a=o?.sleep??Xr,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return ki.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return ki.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),f=r.mcpRestartState.get(d),p=f&&l-f.lastRestart<oE?f.count+1:1,h=r.currentLoad?.latestPi??e;if(p>nE)return ki.warn(`augment:mcp-restart-server: ${d} exceeded ${nE} restarts within ${oE}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:p,lastRestart:l});let m=Math.min(sZ*2**(p-1),iZ);return(p>1?a(m):Promise.resolve()).then(()=>(ki.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(_=>{let b=`Live MCP restart-server failed for ${d}: ${_ instanceof Error?_.message:String(_)}`;ki.warn(b),r.diagnostics.push({server:d,message:b})}).then(()=>{c(h,r)})}import{logger as aZ}from"@hermes/logger";var Ei=aZ.child({prefix:"pi-mcp"}),cZ=/^\d+$/,Wh=1,sE="AUGMENT_ACTIVE_SPACE_ID",uZ="augment-mcp-access-token-";function iu(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function iE(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 au=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??Mu}lookupBody(e){let r={name:e};return!e.startsWith(uZ)&&Object.hasOwn(process.env,sE)&&(r.active_space_id=process.env[sE]??""),r}getSecret(e){let r=iu(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 Qr(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=iu(e),i=(await this._callUpsert({name:o,value:r,scope:Wh,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!cZ.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),Ei.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await Qr(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=iu(e);this.cache.delete(r),await this._callDelete({name:r,scope:Wh}),Ei.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>Xt?`${o.slice(0,Xt)}\u2026[truncated]`:o;throw new lt(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>Xt?`${o.slice(0,Xt)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=iu(e);try{let n=await Qr(()=>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===Wh||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:iE(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof lt&&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&&Ei.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await Qr(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:iE(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof lt&&o.statusCode===404)return Ei.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Ei.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>Xt?`${s.slice(0,Xt)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}};function Kh(t){return{latestPi:t}}import{randomUUID as dZ}from"node:crypto";import{setToolSource as lZ}from"@augmentcode/auggie-v2";import{logger as fZ}from"@hermes/logger";import{Type as pZ}from"@sinclair/typebox";var cE=fZ.child({prefix:"pi-mcp"}),cu="attach-mcp-server",hZ="augment:mcp-attach-request",mZ=15e3,gZ={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 yZ(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],s=o.find(l=>l.id===r);if(s)return{kind:"match",entry:s};let i=o.filter(l=>l.name.toLowerCase()===n),a=i.length===1?i[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(i.length===0)return{kind:"none"};let c=new Set(Wr(t).map(l=>l.id)),u=i.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:i}}function vZ(t,e){let r=e.name.toLowerCase();return Wr(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function Jh(t,e){let r=vZ(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function _Z(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},mZ);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function aE(t){let e=Wr(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function SZ(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return be(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${Jh(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return be(`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.${Jh(r,e)}`)}function wZ(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return be(`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,be("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 be(`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 be(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return be(`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 be(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return be(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${Jh(n,e)}`);case"NO_ACTIVE_VM":return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return be(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function bZ(t,e,r){if(e.mcpAttachDisabled)return be("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(`${cu} requires a string "config_id" parameter. ${aE(e)}`);let o=yZ(e,n);if(o.kind==="none")return be(`No MCP server matching "${n}" is available to attach. ${aE(e)}`);if(o.kind==="ambiguous"){let d=o.candidates.map(l=>`"${l.name}" (id: ${l.id})`).join(", ");return be(`Multiple MCP servers match the name "${n}": ${d}. Retry with the exact id of the intended server.`)}let s=o.entry,i=SZ({entry:s,state:e});if(i!==void 0)return i;if(Tu(e,s))return be(`MCP server "${s.name}" is already attached to this session. Use find-tool to discover its tools.`);if(s.state!=="available"&&s.state!=="opt_in_required")return be(`MCP server "${s.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=dZ();cE.info(`attach-mcp-server: requesting attach of "${s.name}" (config=${s.id} request=${a})`);let c=_Z(e,a);t.events.emit(hZ,{configId:s.id,requestId:a});let u=await c;return wZ({entry:s,result:u,state:e})}function Yh(t,e){let r={name:cu,label:cu,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:pZ.Unsafe(gZ),execute:(n,o)=>bZ(t,e,o)};lZ(cu,"mcp"),t.registerTool(r),_r(r),cE.debug("Registered attach-mcp-server tool")}import{logger as RZ}from"@hermes/logger";var zo=RZ.child({prefix:"pi-mcp"});async function PZ(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=Rt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ze(t,r);let i=dt(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"}}),Pe({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function CZ(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),zo.warn(r.message))}function xZ(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"}),zo.warn(a);return}try{let a=Nn(r,n);return{...a.type==="stdio"?jt(a,i):Lt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Ct?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"}),zo.warn(c);return}}function kZ(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=xZ({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function EZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function uE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??bt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return zo.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&&EZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=PZ(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;CZ(r,i.diagnostics);let{servers:l,blockedNames:f}=kZ(r,i);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(zo.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(p??[]).some(y=>y.config===m&&Bc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;zo.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var nt=TZ.child({prefix:"pi-mcp"}),hE="augment:mcp-oauth-credentials",dE="augment:mcp-header-secrets",lE="augment:mcp-header-secret-failures",fE="augment:credentials",AZ="augment:mcp-config-ids",pE="augment:mcp-configs",$Z="augment:mcp-vfs-servers",MZ="augment:mcp-add-server",IZ="augment:mcp-restart-server",OZ="augment:mcp-remove-server";function zZ(t){if(!t.secretsClient||t.tokens instanceof Wo)return;let e=t.tokens;t.tokens=new Wo(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),nt.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function NZ(t){if(!t||typeof t!="object"){nt.warn(`${hE} 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){Ax({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=GZ({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)){Vh({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 LZ(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(hE,r=>{let n=NZ(r);n&&DZ({pi:t,state:e,payload:n})}))}function jZ(t){let{state:e,name:r,revision:n}=t,o=Zr(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 FZ(t){let{state:e,revision:r}=t,n=Zr(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function UZ(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=$n(i);if(a===void 0){o[s]=i;continue}if(FZ({state:e,revision:a})){gm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(jZ({state:e,name:s,revision:a})){o[s]=i;continue}hm({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function qZ(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=$n(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 HZ(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"&&Fr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Ne(r)})}}function GZ(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=UZ({state:r,credentials:n,suppressReconnect:o}),i=Vc(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return qZ({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(nt.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),HZ({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function ZZ(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(dE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${dE} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);Xg(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(lE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${lE} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);ey(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}))}function BZ(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(fE,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){nt.warn(`${fE} 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 au(e.credentials),zZ(e)}),t.events.on(AZ,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,Yh(e.currentLoad?.latestPi??t,e)),Kk({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;Ne(e),tu(n,e)})}))}function VZ(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(pE,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){nt.warn(`${pE} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=su(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&vr({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 WZ(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on($Z,r=>{uE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Ne(e)})}))}function KZ(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(MZ,r=>{qk({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;Ne(e),tu(n,e)})}))}function JZ(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(IZ,r=>{Vh({pi:t,state:e,data:r}).then(()=>{Ne(e)})}))}function YZ(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(OZ,r=>{rE({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;Ne(e),tu(n,e)})}))}function PX(t){return Yg(t)}var mE=t=>{let e=ee();e.currentLoad=Kh(t);let r=!1;Tk(t,e),LZ(t,e),ZZ(t,e),BZ(t,e),VZ(t,e),WZ(t,e),KZ(t,e),JZ(t,e),YZ(t,e),$k(t,e),Mk(t,e),e.mcpAttachCloudSignaled&&Yh(t,e),t.on("session_start",(n,o)=>{e.currentLoad=Kh(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,Ok(e),e.connectStarted)jn(e)?(Yr(t),qi(t)):Im(t,e),Ne(e);else{e.connectStarted=!0,Ho()&&Yr(t);let{servers:i,diagnostics:a}=Dn(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),nt.warn(c.message);bt(i,e,t).then(()=>kx(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Ne(e)})}r||(r=!0,t.events.emit(Qx,ok(t,e)))}),t.on("session_shutdown",()=>{zk(e)})};Tm(mE);var CX=mE;export{CX as default,PX as setMcpErrorReporter};
149
+ `)}function pG(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Yh.includes(e))return e}async function hG(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=Ai([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function Lk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Yh.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 Nk(n,e,i=>Ai([i],e,t),{classify:i=>gk({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>yk({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>vk({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)=>rk({serverName:i,state:e,pi:t,controller:a}));return}let s=pG(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Yh.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(fG(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await hG(n,e,t)}})}import{logger as mG}from"@hermes/logger";var jk=mG.child({prefix:"pi-mcp"}),Xh="augment:feature-flags";function gG(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 Fk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Xh,r=>{let n=gG(r);if(n===void 0){jk.warn(`${Xh} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,jk.debug(`Received feature-flag snapshot via ${Xh} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as yG}from"@hermes/logger";var du=yG.child({prefix:"pi-mcp"}),Qh="augment:mcp-attach-result";function Uk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(Qh,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){du.warn(`${Qh} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){du.debug(`${Qh}: 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 lu(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 Vm(r);o.ok?(e.mcpCatalog=o.entries,du.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,du.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),Gn(e)&&en(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as vG}from"@hermes/logger";var $i=vG.child({prefix:"pi-mcp"}),qk=300*1e3,em=600*1e3;function _G(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&&(rs(o,e)||o.expiresAt>e+em||($i.debug(`Background refresh: token for MCP server "${r.name}" expires within ${em}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&$i.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{$i.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function Hk(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{_G(t)},qk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,$i.debug(`Started background MCP OAuth refresh loop (interval ${qk}ms, buffer ${em}ms)`)}function Gk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,$i.debug("Stopped background MCP OAuth refresh loop"))}import{logger as IG}from"@hermes/logger";function SG(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Xo.OAUTH:return"oauth";case Xo.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 wG(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Yr.CLI:return"cli";case Yr.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 fu(t){if(t==null)return;if(t.length===0)return[];let e=t.map(wG).filter(r=>r!==void 0);return e.length===0?void 0:e}function pu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=SG(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=Fn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Un(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Ct?i.message:String(i)}}}function bG(t){let e=t.config?.auth_type;return e===Xo.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function RG(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 tm(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 PG(t,e,r){if(r!==void 0&&t.added_by===r)return fu(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?fu(n):[]}function CG(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let p=tm(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let p=new Set(s),h=tm(e,r,()=>!0),m=new Set(h.map(w=>w.id)),y=h.filter(w=>p.has(w.id)),v=h.filter(w=>!p.has(w.id)).map(w=>w.id),b=s.filter(w=>!m.has(w));return{selected:y,filteredOutIds:v,missingIds:b,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=tm(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let m=!d.has(p.id)&&a.has(p.id)?PG(p,o,i):fu(p.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function xG(t){return t==null?Yr.CLOUD_AGENT:void 0}function kG(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 Zk(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Ft(t,n):jt(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 EG(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=pu(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)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`}};let d=Zk(c,e.id,i,s);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=Zk(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 TG(t){let e=[],r=[],n=[];for(let o of t)bG(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 AG(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=RG(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}}function $G(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function hu(t){let e=t.client??new Ji(t.creds),{tenant:r,user:n,diagnostics:o}=await ig(e,xG(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=CG({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=TG(a),f=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...kG(u));let p=[],h=new Map,m=new Set(t.localServerNames),y=[...f.filter(w=>i.has(w.id)),...f.filter(w=>!i.has(w.id))];for(let w of y){let x=EG({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:m,workspaceRoot:t.workspaceRoot});$G(x,{servers:p,retainedNames:d,diagnostics:o,nameCollisionFallbacks:h})}let v=AG(p);d.push(...v.droppedNames),o.push(...v.diagnostics);let b=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&b.set(w.id,w.config.name);return{servers:v.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:b,nameCollisionFallbacks:h}}import{logger as MG}from"@hermes/logger";var qo=MG.child({prefix:"pi-mcp"});function Wk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){qo.warn("Embedded MCP config is missing an id; ignoring");return}let n=pu(r,"tenant");if(!n.ok){qo.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Ft(n.server,o):jt(n.server,o)}catch(s){qo.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function Bk(t,e){let r;try{r=JSON.parse(t)}catch(n){qo.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return Wk(r,e)}function mu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){qo.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){qo.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=Wk(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 Nt=IG.child({prefix:"pi-mcp"});function OG(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 Yt(t){Be({state:t.state,domain:st(t.configId),epoch:t.intentEpoch})}function zG(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 Vk(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"}),Nt.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function Mi(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Yt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Nt.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 NG(t,e){return e.flatMap(r=>Xc(t,r)?[r.config]:[])}function DG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function LG(t,e){let r=DG(e);if(r){if(Mi(t,r.error),r.error instanceof Pt)throw r.error;return}let n=NG(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){OG(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 Jk(t,e){try{LG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function jG(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 Nt.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 Nt.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 FG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await Jo(t.state,t.configId),t.superseded()){Yt(t);return}if(jG(t,e)){Yt(t);return}try{if(!await Sr({state:t.state,config:e,pi:t.activePi})){Yt(t);return}}catch(r){throw Mi(t,r),r}Nt.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);Jk(t,r??[])}catch(r){if(Mi(t,r),r instanceof Pt)throw r}}async function UG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Yt(t),Nt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){Kk(r,e),Nt.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),Yt(t);return}if(await Jo(r,n),o()){Yt(t);return}try{if((await Promise.all(e.servers.map(c=>Sr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Yt(t);return}}catch(a){throw Mi(t,a),a}Nt.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()){Yt(t);return}Kk(r,e),Jk(t,i??[])}function qG(t,e){if(typeof e=="string")return Bk(e,t.workspaceRoot??process.cwd())}function Yk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Nt.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();if(!Gi({state:r,configId:i,generation:s?.attachmentGeneration}))return Nt.info(`Ignoring stale live MCP add-server command for config id ${i}`),Promise.resolve();r.sessionRemovedConfigIds.delete(i);let a=Fi({state:r,domain:st(i),forceNew:!0}),c=zG(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 f=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,p={state:r,configId:i,activePi:u,connect:o?.connect??bt,report:o?.report??J,intentEpoch:a.epoch,superseded:f,sourceOwnership:()=>!f(),hasLiveHostForId:()=>Vk(r,i)},h=qG(r,s?.embeddedConfig),m;if(h)m=FG(p,h);else{let y=r.credentials;y?m=(o?.discover??hu)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(b=>UG(p,b)).catch(b=>{if(!(b instanceof Pt)){Mi(p,b);return}throw b}):(Nt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Yt(p),m=Promise.resolve())}return Zi({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>Vk(r,i)})}import{logger as HG}from"@hermes/logger";var Dt=HG.child({prefix:"pi-mcp"});function Qk(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function eE(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?Rt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ze(e,r),"retiring"):void 0:(Pe({state:e,name:r,owner:n.owner,revision:n.revision}),Ze(e,r),"released");let c=a.get(r),u=Bo({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:Ze(e,r),leaseRevision:u.lease.revision}}function GG(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=eE({state:e,name:r,lease:c,host:n,isDeselected:Qk({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"&&Pe({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function ZG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=eE({state:e,name:r,lease:n,isDeselected:Qk({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function WG(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=GG({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||ZG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function tE(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 f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=i.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){i.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&s.push(dt(t,l,f.id,f))}try{await Promise.all(s)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Pt(f)}let d=new Map;for(let[l,f]of i){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),We(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function BG(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:f}]of t.allConfigsById)n&&!n.has(l)||u.has(f)||d.has(f)||(d.add(f),a.push(f));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function VG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return mu(n,e.workspaceRoot??process.cwd())}async function KG(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(dt(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 Pt(c)}}function JG(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 YG(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function XG(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 QG(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 tE(e,r.servers,n,s,o!==void 0)}async function rE(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():Jo(t,r.id)))}async function Xk(t){return await rE(t.state,t.result),t.state.registryGeneration===t.generation&&await QG(t),t.result}function eZ(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Dt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=BG(n,r,s);return Xk({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=>Xk({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function tZ(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Dt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Dt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function rZ(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 nE(t){let{state:e,generation:r}=t;return n=>{if(e.registryGeneration!==r||n.id===void 0)return e.registryGeneration===r;let o=e.missingHostRemovalFences.get(n.id);return!e.sessionRemovedConfigIds.has(n.id)&&o?.registryGeneration!==r}}function rm(t){let{state:e,result:r,selection:n,slotReservations:o}=t,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&&Pe({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function nZ(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){rm({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),Dt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await rE(e,r),e.registryGeneration!==o)return;let c=nE({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>Sr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;tZ({state:e,result:r,selection:n}),rm({state:e,result:r,selection:n,slotReservations:a});let l=rZ({state:e,result:{...r,servers:u}});if(l.length===0)return;let f=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 Dt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let b=a.get(m.name)?.configRevision;if(b===void 0)return!0;let w=e.configDesiredRevisions.get(m.name);return w!==b?(Dt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${b} to ${w} by a concurrent operation`),!1):!0});if(f.length===0)return;Dt.info(`Registry discovery: connecting ${f.length} server(s)`);let h=(await s(f,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));await oZ({state:e,pi:i,result:r,generation:o,connect:s})}async function oZ(t){let{state:e,pi:r,result:n,generation:o,connect:s}=t,i=n.nameCollisionFallbacks;if(!(!i||i.size===0))for(let[a,c]of i)for(let u of c){let d=await sZ({state:e,pi:r,generation:o,connect:s,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function sZ(t){let{state:e,pi:r,generation:n,connect:o,name:s,candidate:i}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(s);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===i.id)return"settled";if(!await Sr({state:e,config:i,pi:r})||e.registryGeneration!==n)return"abort";Dt.info(`MCP auth fallback: "${s}" (id=${c}) landed ${a.status}; connecting same-named config id=${i.id} in its place`),await o([i],e,e.currentLoad?.latestPi??r,nE({state:e,generation:n}));let d=e.servers.get(s);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===i.id&&d.status==="success"?"settled":"next"}async function iZ(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Dt.warn(i),e.registryGeneration===n&&(await tE(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function aZ(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"}),Be({state:t,domain:n,epoch:o?.epoch})}}async function cZ(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await nZ({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),rm({state:t.resultArgs.state,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:t.resultArgs.state.registryGeneration===t.resultArgs.generation?t.resultArgs.selection:void 0,slotReservations:e}),r instanceof Pt)throw aZ(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 iZ({...t.resultArgs,error:r})}}function oE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??hu,i=o?.connect??bt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Dt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&xm(r,new Set(a.configIds.map(st)));let c=VG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Dt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let v of a.configIds??[])Be({state:r,domain:st(v)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=KG({state:r,previousSelectedIds:d,configIds:a.configIds}),f=JG({parsedEmbedded:c,configIds:a.configIds}),p=++r.registryGeneration,h=Promise.all([WG(r,a.configIds,f),l]).then(([v])=>v);YG(r);let m=a.configIds?[...a.configIds]:void 0,y=eZ({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:XG(r),previousSelectedIds:d,selection:m,generation:p,discover:s});return y?cZ({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:p,connect:i,pi:e}}):Promise.resolve()}import{logger as uZ}from"@hermes/logger";var Zr=uZ.child({prefix:"pi-mcp"});function dZ(t,e){Be({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 lZ(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function cE(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function fZ(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function sE(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&&(fZ({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 uE(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function iE(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 dE(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function pZ(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?Ln(n):void 0;if(s===void 0){Ze(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?hm({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):Pe({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(dE(e,r),Ze(e,r))}async function nm(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 b=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Zr.warn(b),e.diagnostics.push({message:b,origin:"registry"}),new Error(b)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=Ln(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,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ze(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,v=y?.result;if(d&&v?.status==="failed"&&v.transportDisposed!==!0){let b=v.error instanceof Error?v.error:new Error(String(v.error)),w=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Zr.warn(w),e.diagnostics.push({server:a,message:w}),b}try{await Ko(e,a,r,i)}catch(b){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let w=`Live MCP remove-server failed to detach ${a}: ${b instanceof Error?b.message:String(b)}`;throw Zr.warn(w),e.diagnostics.push({server:a,message:w}),b}cE({state:e,configId:r,fence:s})&&(uE(e,r),pZ({state:e,name:a,config:i,retirement:y})),Zr.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 aE(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)}`;Zr.warn(s),e.diagnostics.push({server:r,message:s})}async function hZ(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(aE({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Ko(e,r,n,o.config)]);return aE({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 mZ(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=Ze(e,n),f=Rt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),Zr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await hZ({state:e,name:n,configId:r,server:a});if(h&&cE({state:e,configId:r,fence:i})?uE(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:f,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&Pe({state:e,name:n,owner:c.owner,revision:c.revision})&&dE(e,n),s(p,e),!h)throw m}function lE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Zr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Gi({state:r,configId:i,generation:s?.attachmentGeneration}))return Zr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Zi({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=iE(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(i),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(i);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(sE({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>nm({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=dZ(r,i);if(u===void 0&&d===void 0)return a(nm({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=lZ({state:r,configId:i,liveEditGeneration:h});return a(sE({state:r,configId:i,fence:m,operation:()=>{let y=iE(r,i);return y===void 0?nm({state:r,configId:i,pi:e,report:c,sourceFence:m}):mZ({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as gZ}from"@hermes/logger";var Ii=gZ.child({prefix:"pi-mcp"}),fE=3,pE=6e4,yZ=1e3,vZ=8e3;function om(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Hr,i=o?.now??Date.now,a=o?.sleep??tn,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return Ii.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return Ii.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),f=r.mcpRestartState.get(d),p=f&&l-f.lastRestart<pE?f.count+1:1,h=r.currentLoad?.latestPi??e;if(p>fE)return Ii.warn(`augment:mcp-restart-server: ${d} exceeded ${fE} restarts within ${pE}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:p,lastRestart:l});let m=Math.min(yZ*2**(p-1),vZ);return(p>1?a(m):Promise.resolve()).then(()=>(Ii.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(v=>{let b=`Live MCP restart-server failed for ${d}: ${v instanceof Error?v.message:String(v)}`;Ii.warn(b),r.diagnostics.push({server:d,message:b})}).then(()=>{c(h,r)})}import{logger as _Z}from"@hermes/logger";var Oi=_Z.child({prefix:"pi-mcp"}),SZ=/^\d+$/,sm=1,hE="AUGMENT_ACTIVE_SPACE_ID",wZ="augment-mcp-access-token-";function gu(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function mE(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 yu=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??qu}lookupBody(e){let r={name:e};return!e.startsWith(wZ)&&Object.hasOwn(process.env,hE)&&(r.active_space_id=process.env[hE]??""),r}getSecret(e){let r=gu(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 rn(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=gu(e),i=(await this._callUpsert({name:o,value:r,scope:sm,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!SZ.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),Oi.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await rn(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=gu(e);this.cache.delete(r),await this._callDelete({name:r,scope:sm}),Oi.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>Qt?`${o.slice(0,Qt)}\u2026[truncated]`:o;throw new lt(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>Qt?`${o.slice(0,Qt)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=gu(e);try{let n=await rn(()=>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===sm||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:mE(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof lt&&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&&Oi.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await rn(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:mE(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof lt&&o.statusCode===404)return Oi.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Oi.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>Qt?`${s.slice(0,Qt)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}};function im(t){return{latestPi:t}}import{randomUUID as bZ}from"node:crypto";import{setToolSource as RZ}from"@augmentcode/auggie-v2";import{logger as PZ}from"@hermes/logger";import{Type as CZ}from"@sinclair/typebox";var yE=PZ.child({prefix:"pi-mcp"}),vu="attach-mcp-server",xZ="augment:mcp-attach-request",kZ=15e3,EZ={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 TZ(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],s=o.find(l=>l.id===r);if(s)return{kind:"match",entry:s};let i=o.filter(l=>l.name.toLowerCase()===n),a=i.length===1?i[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(i.length===0)return{kind:"none"};let c=new Set(Xr(t).map(l=>l.id)),u=i.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:i}}function AZ(t,e){let r=e.name.toLowerCase();return Xr(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function am(t,e){let r=AZ(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function $Z(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},kZ);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function gE(t){let e=Xr(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function MZ(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return be(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${am(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return be(`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.${am(r,e)}`)}function IZ(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return be(`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,be("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 be(`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 be(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return be(`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 be(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return be(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${am(n,e)}`);case"NO_ACTIVE_VM":return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return be(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function OZ(t,e,r){if(e.mcpAttachDisabled)return be("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(`${vu} requires a string "config_id" parameter. ${gE(e)}`);let o=TZ(e,n);if(o.kind==="none")return be(`No MCP server matching "${n}" is available to attach. ${gE(e)}`);if(o.kind==="ambiguous"){let d=o.candidates.map(l=>`"${l.name}" (id: ${l.id})`).join(", ");return be(`Multiple MCP servers match the name "${n}": ${d}. Retry with the exact id of the intended server.`)}let s=o.entry,i=MZ({entry:s,state:e});if(i!==void 0)return i;if(ju(e,s))return be(`MCP server "${s.name}" is already attached to this session. Use find-tool to discover its tools.`);if(s.state!=="available"&&s.state!=="opt_in_required")return be(`MCP server "${s.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=bZ();yE.info(`attach-mcp-server: requesting attach of "${s.name}" (config=${s.id} request=${a})`);let c=$Z(e,a);t.events.emit(xZ,{configId:s.id,requestId:a});let u=await c;return IZ({entry:s,result:u,state:e})}function cm(t,e){let r={name:vu,label:vu,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:CZ.Unsafe(EZ),execute:(n,o)=>OZ(t,e,o)};RZ(vu,"mcp"),t.registerTool(r),wr(r),yE.debug("Registered attach-mcp-server tool")}import{logger as zZ}from"@hermes/logger";var Ho=zZ.child({prefix:"pi-mcp"});async function NZ(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=Rt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ze(t,r);let i=dt(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"}}),Pe({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function DZ(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),Ho.warn(r.message))}function LZ(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"}),Ho.warn(a);return}try{let a=Un(r,n);return{...a.type==="stdio"?Ft(a,i):jt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Ct?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"}),Ho.warn(c);return}}function jZ(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=LZ({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function FZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function vE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??bt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return Ho.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&&FZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=NZ(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;DZ(r,i.diagnostics);let{servers:l,blockedNames:f}=jZ(r,i);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(Ho.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(p??[]).some(y=>y.config===m&&Xc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;Ho.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var nt=UZ.child({prefix:"pi-mcp"}),RE="augment:mcp-oauth-credentials",_E="augment:mcp-header-secrets",SE="augment:mcp-header-secret-failures",wE="augment:credentials",qZ="augment:mcp-config-ids",bE="augment:mcp-configs",HZ="augment:mcp-vfs-servers",GZ="augment:mcp-add-server",ZZ="augment:mcp-restart-server",WZ="augment:mcp-remove-server";function BZ(t){if(!t.secretsClient||t.tokens instanceof ts)return;let e=t.tokens;t.tokens=new ts(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),nt.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function VZ(t){if(!t||typeof t!="object"){nt.warn(`${RE} 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 KZ(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){Ux({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=r2({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)){om({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 JZ(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(RE,r=>{let n=VZ(r);n&&KZ({pi:t,state:e,payload:n})}))}function YZ(t){let{state:e,name:r,revision:n}=t,o=Kr(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 XZ(t){let{state:e,revision:r}=t,n=Kr(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function QZ(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=On(i);if(a===void 0){o[s]=i;continue}if(XZ({state:e,revision:a})){km({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(YZ({state:e,name:s,revision:a})){o[s]=i;continue}Cm({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function e2(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=On(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 t2(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"&&Hr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Ne(r)})}}function r2(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=QZ({state:r,credentials:n,suppressReconnect:o}),i=Qc(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return e2({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(nt.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),t2({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function n2(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(_E,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${_E} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);uy(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(SE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){nt.warn(`${SE} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);ly(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}))}function o2(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(wE,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){nt.warn(`${wE} 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 yu(e.credentials),BZ(e)}),t.events.on(qZ,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,cm(e.currentLoad?.latestPi??t,e)),oE({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;Ne(e),lu(n,e)})}))}function s2(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(bE,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){nt.warn(`${bE} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=mu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&Sr({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 i2(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(HZ,r=>{vE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Ne(e)})}))}function a2(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(GZ,r=>{Yk({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;Ne(e),lu(n,e)})}))}function c2(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(ZZ,r=>{om({pi:t,state:e,data:r}).then(()=>{Ne(e)})}))}function u2(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(WZ,r=>{lE({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;Ne(e),lu(n,e)})}))}function jX(t){return cy(t)}var PE=t=>{let e=ee();e.currentLoad=im(t);let r=!1;Lk(t,e),JZ(t,e),n2(t,e),o2(t,e),s2(t,e),i2(t,e),a2(t,e),c2(t,e),u2(t,e),Fk(t,e),Uk(t,e),e.mcpAttachCloudSignaled&&cm(t,e),t.on("session_start",(n,o)=>{e.currentLoad=im(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,Hk(e),e.connectStarted)Gn(e)?(en(t),Vi(t)):Gm(t,e),Ne(e);else{e.connectStarted=!0,Yo()&&en(t);let{servers:i,diagnostics:a}=qn(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),nt.warn(c.message);bt(i,e,t).then(()=>Lx(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Ne(e)})}r||(r=!0,t.events.emit(dk,mk(t,e)))}),t.on("session_shutdown",()=>{Gk(e)})};Fm(PE);var FX=PE;export{FX as default,jX as setMcpErrorReporter};
150
150
  /*! Bundled license information:
151
151
 
152
152
  content-type/index.js: