@augmentcode/onison 1.2.0-prerelease.202608141508 → 1.2.0-prerelease.202608170909

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- var Vk=Object.create;var ou=Object.defineProperty;var Bk=Object.getOwnPropertyDescriptor;var Wk=Object.getOwnPropertyNames;var Kk=Object.getPrototypeOf,Jk=Object.prototype.hasOwnProperty;var lr=(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)ou(t,r,{get:e[r],enumerable:!0})},Yk=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wk(e))!Jk.call(t,o)&&o!==r&&ou(t,o,{get:()=>e[o],enumerable:!(n=Bk(e,o))||n.enumerable});return t};var Ci=(t,e,r)=>(r=t!=null?Vk(Kk(t)):{},Yk(e||!t||!t.__esModule?ou(r,"default",{value:t,enumerable:!0}):r,t));var Ps=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 bs=class{};K._CodeOrName=bs;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var nn=class extends bs{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=nn;var mt=class extends bs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof nn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=mt;K.nil=new mt("");function bw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)zl(r,e[n]),r.push(t[++n]);return new mt(r)}K._=bw;var Il=new mt("+");function Rw(t,...e){let r=[Rs(t[0])],n=0;for(;n<e.length;)r.push(Il),zl(r,e[n]),r.push(Il,Rs(t[++n]));return yz(r),new mt(r)}K.str=Rw;function zl(t,e){e instanceof mt?t.push(...e._items):e instanceof nn?t.push(e):t.push(Sz(e))}K.addCodeArg=zl;function yz(t){let e=1;for(;e<t.length-1;){if(t[e]===Il){let r=vz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function vz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof nn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof nn))return`"${t}${e.slice(1)}`}function _z(t,e){return e.emptyStr()?t:t.emptyStr()?e:Rw`${t}${e}`}K.strConcat=_z;function Sz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Rs(Array.isArray(t)?t.join(","):t)}function wz(t){return new mt(Rs(t))}K.stringify=wz;function Rs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Rs;function bz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new mt(`.${t}`):bw`[${t}]`}K.getProperty=bz;function Rz(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new mt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=Rz;function Pz(t){return new mt(t.toString())}K.regexpCode=Pz});var Dl=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Xe=Ps(),Ol=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},La;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(La||(Qe.UsedValueState=La={}));Qe.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var ja=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Xe.Name?e:this.name(e)}name(e){return new Xe.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=ja;var Ua=class extends Xe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};Qe.ValueScopeName=Ua;var Cz=(0,Xe._)`\n`,Nl=class extends ja{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Cz:Xe.nil}}get(){return this._scope}name(e){return new Ua(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Xe.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,La.Started);let d=r(u);if(d){let l=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Xe._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Xe._)`${s}${d}${this.opts._n}`;else throw new Ol(u);c.set(u,La.Completed)})}return s}};Qe.ValueScope=Nl});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=Ps(),kt=Dl(),kr=Ps();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return kr._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return kr.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return kr.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return kr.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return kr.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return kr.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return kr.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return kr.Name}});var Ga=Dl();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Ga.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Ga.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Ga.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Ga.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 nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ll=class extends nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?kt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Qn(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},Fa=class extends nr{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=Qn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return Ha(e,this.rhs)}},jl=class extends Fa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Ul=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Fl=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ql=class extends nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Hl=class extends nr{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=Qn(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},Cs=class extends nr{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)||(xz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>an(e,r.names),{})}},or=class extends Cs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Gl=class extends Cs{},Xn=class extends or{};Xn.kind="else";var on=class t extends or{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 Xn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Pw(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=Qn(this.condition,e,r),this}get names(){let e=super.names;return Ha(e,this.condition),this.else&&an(e,this.else.names),e}};on.kind="if";var sn=class extends or{};sn.kind="for";var Zl=class extends sn{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=Qn(this.iteration,e,r),this}get names(){return an(super.names,this.iteration.names)}},Vl=class extends sn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ha(super.names,this.from);return Ha(e,this.to)}},qa=class extends sn{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=Qn(this.iterable,e,r),this}get names(){return an(super.names,this.iterable.names)}},xs=class extends or{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)}};xs.kind="func";var ks=class extends Cs{render(e){return"return "+super.render(e)}};ks.kind="return";var Bl=class extends or{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&&an(e,this.catch.names),this.finally&&an(e,this.finally.names),e}},Es=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Es.kind="catch";var Ts=class extends or{render(e){return"finally"+super.render(e)}};Ts.kind="finally";var Wl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new Gl]}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 Ll(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Fa(e,r,n))}add(e,r){return this._leafNode(new jl(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new Hl(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 on(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 on(e))}else(){return this._elseNode(new Xn)}endIf(){return this._endBlockNode(on,Xn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Zl(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new Vl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${i}.length`,a=>{this.var(s,(0,q._)`${i}[${a}]`),n(s)})}return this._for(new qa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,q._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new qa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(sn)}label(e){return this._leafNode(new Ul(e))}break(e){return this._leafNode(new Fl(e))}return(e){let r=new ks;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ks)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Bl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Es(s),r(s)}return n&&(this._currNode=o.finally=new Ts,this.code(n)),this._endBlockNode(Es,Ts)}throw(e){return this._leafNode(new ql(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 xs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(xs)}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 on))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=Wl;function an(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ha(t,e){return e instanceof q._CodeOrName?an(t,e.names):t}function Qn(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 xz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Pw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${Kl(t)}`}L.not=Pw;var kz=Cw(L.operators.AND);function Ez(...t){return t.reduce(kz)}L.and=Ez;var Tz=Cw(L.operators.OR);function Az(...t){return t.reduce(Tz)}L.or=Az;function Cw(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${Kl(e)} ${t} ${Kl(r)}`}function Kl(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 oe=D(),$z=Ps();function Mz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=Mz;function Iz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ew(t,e),!Tw(e,t.self.RULES.all))}j.alwaysValidSchema=Iz;function Ew(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]||Mw(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=Ew;function Tw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=Tw;function zz(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=zz;function Oz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,oe._)`${r}`}return(0,oe._)`${t}${e}${(0,oe.getProperty)(n)}`}j.schemaRefOrVal=Oz;function Nz(t){return Aw(decodeURIComponent(t))}j.unescapeFragment=Nz;function Dz(t){return encodeURIComponent(Yl(t))}j.escapeFragment=Dz;function Yl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Yl;function Aw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Aw;function Lz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=Lz;function xw({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof oe.Name?(s instanceof oe.Name?t(o,s,i):e(o,s,i),i):s instanceof oe.Name?(e(o,i,s),s):r(s,i);return a===oe.Name&&!(c instanceof oe.Name)?n(o,c):c}}j.mergeEvaluated={props:xw({mergeNames:(t,e,r)=>t.if((0,oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,oe._)`${r} || {}`).code((0,oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,oe._)`${r} || {}`),Xl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$w}),items:xw({mergeNames:(t,e,r)=>t.if((0,oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $w(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,oe._)`{}`);return e!==void 0&&Xl(t,r,e),r}j.evaluatedPropsToName=$w;function Xl(t,e,r){Object.keys(r).forEach(n=>t.assign((0,oe._)`${e}${(0,oe.getProperty)(n)}`,!0))}j.setEvaluated=Xl;var kw={};function jz(t,e){return t.scopeValue("func",{ref:e,code:kw[e.code]||(kw[e.code]=new $z._Code(e.code))})}j.useFunc=jz;var Jl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Jl||(j.Type=Jl={}));function Uz(t,e,r){if(t instanceof oe.Name){let n=e===Jl.Num;return r?n?(0,oe._)`"[" + ${t} + "]"`:(0,oe._)`"['" + ${t} + "']"`:n?(0,oe._)`"/" + ${t}`:(0,oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,oe.getProperty)(t).toString():"/"+Yl(t)}j.getErrorPath=Uz;function Mw(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=Mw});var sr=R(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Ne=D(),Fz={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};Ql.default=Fz});var As=R(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var G=D(),Za=H(),Ue=sr();De.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,G.str)`"${t}" keyword must be ${e} ($data)`:(0,G.str)`"${t}" keyword is invalid ($data)`};function qz(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Ow(t,e,r);n??(i||a)?Iw(s,c):zw(o,(0,G._)`[${c}]`)}De.reportError=qz;function Hz(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Ow(t,e,r);Iw(o,a),s||i||zw(n,Ue.default.vErrors)}De.reportExtraError=Hz;function Gz(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)))}De.resetErrorsCount=Gz;function Zz({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))})}De.extendErrors=Zz;function Iw(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 zw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,G._)`new ${t.ValidationError}(${e})`):(r.assign((0,G._)`${n}.errors`,e),r.return(!1))}var cn={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 Ow(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:Vz(t,e,r)}function Vz(t,e,r={}){let{gen:n,it:o}=t,s=[Bz(o,r),Wz(t,r)];return Kz(t,e,s),n.object(...s)}function Bz({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,Za.getErrorPath)(e,Za.Type.Str)}`:t;return[Ue.default.instancePath,(0,G.strConcat)(Ue.default.instancePath,r)]}function Wz({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,Za.getErrorPath)(r,Za.Type.Str)}`),[cn.schemaPath,o]}function Kz(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([cn.keyword,o],[cn.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([cn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([cn.schema,i],[cn.parentSchema,(0,G._)`${d}${l}`],[Ue.default.data,s]),u&&n.push([cn.propertyName,u])}});var Dw=R(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;var Jz=As(),Yz=D(),Xz=sr(),Qz={message:"boolean schema is false"};function eO(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Nw(t,!1):typeof r=="object"&&r.$async===!0?e.return(Xz.default.data):(e.assign((0,Yz._)`${n}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=eO;function tO(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Nw(t)):r.var(e,!0)}eo.boolOrEmptySchema=tO;function Nw(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 ep=R(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.getRules=to.isJSONType=void 0;var rO=["string","number","integer","boolean","null","object","array"],nO=new Set(rO);function oO(t){return typeof t=="string"&&nO.has(t)}to.isJSONType=oO;function sO(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}to.getRules=sO});var tp=R(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.shouldUseRule=Er.shouldUseGroup=Er.schemaHasRulesForType=void 0;function iO({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Lw(t,n)}Er.schemaHasRulesForType=iO;function Lw(t,e){return e.rules.some(r=>jw(t,r))}Er.shouldUseGroup=Lw;function jw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Er.shouldUseRule=jw});var $s=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var aO=ep(),cO=tp(),uO=As(),N=D(),Uw=H(),ro;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(ro||(Le.DataType=ro={}));function dO(t){let e=Fw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Le.getSchemaTypes=dO;function Fw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(aO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Fw;function lO(t,e){let{gen:r,data:n,opts:o}=t,s=pO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,cO.schemaHasRulesForType)(t,e[0]));if(i){let a=np(e,n,o.strictNumbers,ro.Wrong);r.if(a,()=>{s.length?fO(t,e,s):op(t)})}return i}Le.coerceAndCheckDataType=lO;var qw=new Set(["string","number","integer","boolean","null"]);function pO(t,e){return e?t.filter(r=>qw.has(r)||e==="array"&&r==="array"):[]}function fO(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(np(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(qw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),op(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),hO(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 Xk=Object.create;var su=Object.defineProperty;var Qk=Object.getOwnPropertyDescriptor;var eE=Object.getOwnPropertyNames;var tE=Object.getPrototypeOf,rE=Object.prototype.hasOwnProperty;var lr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var R=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},iu=(t,e)=>{for(var r in e)su(t,r,{get:e[r],enumerable:!0})},nE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of eE(e))!rE.call(t,o)&&o!==r&&su(t,o,{get:()=>e[o],enumerable:!(n=Qk(e,o))||n.enumerable});return t};var xi=(t,e,r)=>(r=t!=null?Xk(tE(t)):{},nE(e||!t||!t.__esModule?su(r,"default",{value:t,enumerable:!0}):r,t));var Cs=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 Rs=class{};K._CodeOrName=Rs;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var on=class extends Rs{constructor(e){if(super(),!K.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};K.Name=on;var mt=class extends Rs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof on&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=mt;K.nil=new mt("");function kw(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ol(r,e[n]),r.push(t[++n]);return new mt(r)}K._=kw;var zl=new mt("+");function Ew(t,...e){let r=[Ps(t[0])],n=0;for(;n<e.length;)r.push(zl),Ol(r,e[n]),r.push(zl,Ps(t[++n]));return Pz(r),new mt(r)}K.str=Ew;function Ol(t,e){e instanceof mt?t.push(...e._items):e instanceof on?t.push(e):t.push(kz(e))}K.addCodeArg=Ol;function Pz(t){let e=1;for(;e<t.length-1;){if(t[e]===zl){let r=Cz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Cz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof on||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof on))return`"${t}${e.slice(1)}`}function xz(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ew`${t}${e}`}K.strConcat=xz;function kz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ps(Array.isArray(t)?t.join(","):t)}function Ez(t){return new mt(Ps(t))}K.stringify=Ez;function Ps(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Ps;function Tz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new mt(`.${t}`):kw`[${t}]`}K.getProperty=Tz;function Az(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new mt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=Az;function $z(t){return new mt(t.toString())}K.regexpCode=$z});var Ll=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Xe=Cs(),Nl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ja;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ja||(Qe.UsedValueState=ja={}));Qe.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var Ua=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Xe.Name?e:this.name(e)}name(e){return new Xe.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=Ua;var Fa=class extends Xe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};Qe.ValueScopeName=Fa;var Mz=(0,Xe._)`\n`,Dl=class extends Ua{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Mz:Xe.nil}}get(){return this._scope}name(e){return new Fa(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Xe.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ja.Started);let d=r(u);if(d){let l=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Xe._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Xe._)`${s}${d}${this.opts._n}`;else throw new Nl(u);c.set(u,ja.Completed)})}return s}};Qe.ValueScope=Dl});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=Cs(),kt=Ll(),Er=Cs();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Er._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Er.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Er.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Er.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Er.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Er.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Er.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Er.Name}});var Za=Ll();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Za.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Za.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Za.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Za.varKinds}});L.operators={GT:new q._Code(">"),GTE:new q._Code(">="),LT:new q._Code("<"),LTE:new q._Code("<="),EQ:new q._Code("==="),NEQ:new q._Code("!=="),NOT:new q._Code("!"),OR:new q._Code("||"),AND:new q._Code("&&"),ADD:new q._Code("+")};var nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},jl=class extends nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?kt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=eo(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},qa=class extends nr{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof q.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=eo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return Ga(e,this.rhs)}},Ul=class extends qa{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Fl=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ql=class extends nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Hl=class extends nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Gl=class extends nr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=eo(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},xs=class extends nr{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)=>cn(e,r.names),{})}},or=class extends xs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Zl=class extends xs{},Qn=class extends or{};Qn.kind="else";var sn=class t extends or{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Qn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Tw(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=eo(this.condition,e,r),this}get names(){let e=super.names;return Ga(e,this.condition),this.else&&cn(e,this.else.names),e}};sn.kind="if";var an=class extends or{};an.kind="for";var Bl=class extends an{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=eo(this.iteration,e,r),this}get names(){return cn(super.names,this.iteration.names)}},Vl=class extends an{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ga(super.names,this.from);return Ga(e,this.to)}},Ha=class extends an{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=eo(this.iterable,e,r),this}get names(){return cn(super.names,this.iterable.names)}},ks=class extends or{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ks.kind="func";var Es=class extends xs{render(e){return"return "+super.render(e)}};Es.kind="return";var Wl=class extends or{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&cn(e,this.catch.names),this.finally&&cn(e,this.finally.names),e}},Ts=class extends or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ts.kind="catch";var As=class extends or{render(e){return"finally"+super.render(e)}};As.kind="finally";var Kl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new kt.Scope({parent:e}),this._nodes=[new Zl]}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 jl(e,s,n)),s}const(e,r,n){return this._def(kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new qa(e,r,n))}add(e,r){return this._leafNode(new Ul(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new Gl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,q.addCodeArg)(r,o));return r.push("}"),new q._Code(r)}if(e,r,n){if(this._blockNode(new sn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new sn(e))}else(){return this._elseNode(new Qn)}endIf(){return this._endBlockNode(sn,Qn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Bl(e),r)}forRange(e,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(e);return this._for(new Vl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof q.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,q._)`${i}.length`,a=>{this.var(s,(0,q._)`${i}[${a}]`),n(s)})}return this._for(new Ha("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,q._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ha("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(an)}label(e){return this._leafNode(new Fl(e))}break(e){return this._leafNode(new ql(e))}return(e){let r=new Es;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Es)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Wl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ts(s),r(s)}return n&&(this._currNode=o.finally=new As,this.code(n)),this._endBlockNode(Ts,As)}throw(e){return this._leafNode(new Hl(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 ks(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ks)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof sn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};L.CodeGen=Kl;function cn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ga(t,e){return e instanceof q._CodeOrName?cn(t,e.names):t}function eo(t,e,r){if(t instanceof q.Name)return n(t);if(!o(t))return t;return new q._Code(t._items.reduce((s,i)=>(i instanceof q.Name&&(i=n(i)),i instanceof q._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof q._Code&&s._items.some(i=>i instanceof q.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Iz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Tw(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${Jl(t)}`}L.not=Tw;var zz=Aw(L.operators.AND);function Oz(...t){return t.reduce(zz)}L.and=Oz;var Nz=Aw(L.operators.OR);function Dz(...t){return t.reduce(Nz)}L.or=Dz;function Aw(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${Jl(e)} ${t} ${Jl(r)}`}function Jl(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 oe=D(),Lz=Cs();function jz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=jz;function Uz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Iw(t,e),!zw(e,t.self.RULES.all))}j.alwaysValidSchema=Uz;function Iw(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]||Dw(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=Iw;function zw(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=zw;function Fz(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=Fz;function qz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,oe._)`${r}`}return(0,oe._)`${t}${e}${(0,oe.getProperty)(n)}`}j.schemaRefOrVal=qz;function Hz(t){return Ow(decodeURIComponent(t))}j.unescapeFragment=Hz;function Gz(t){return encodeURIComponent(Xl(t))}j.escapeFragment=Gz;function Xl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Xl;function Ow(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=Ow;function Zz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=Zz;function $w({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof oe.Name?(s instanceof oe.Name?t(o,s,i):e(o,s,i),i):s instanceof oe.Name?(e(o,i,s),s):r(s,i);return a===oe.Name&&!(c instanceof oe.Name)?n(o,c):c}}j.mergeEvaluated={props:$w({mergeNames:(t,e,r)=>t.if((0,oe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,oe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,oe._)`${r} || {}`).code((0,oe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,oe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,oe._)`${r} || {}`),Ql(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Nw}),items:$w({mergeNames:(t,e,r)=>t.if((0,oe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,oe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,oe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,oe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Nw(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,oe._)`{}`);return e!==void 0&&Ql(t,r,e),r}j.evaluatedPropsToName=Nw;function Ql(t,e,r){Object.keys(r).forEach(n=>t.assign((0,oe._)`${e}${(0,oe.getProperty)(n)}`,!0))}j.setEvaluated=Ql;var Mw={};function Bz(t,e){return t.scopeValue("func",{ref:e,code:Mw[e.code]||(Mw[e.code]=new Lz._Code(e.code))})}j.useFunc=Bz;var Yl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Yl||(j.Type=Yl={}));function Vz(t,e,r){if(t instanceof oe.Name){let n=e===Yl.Num;return r?n?(0,oe._)`"[" + ${t} + "]"`:(0,oe._)`"['" + ${t} + "']"`:n?(0,oe._)`"/" + ${t}`:(0,oe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,oe.getProperty)(t).toString():"/"+Xl(t)}j.getErrorPath=Vz;function Dw(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=Dw});var sr=R(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var Ne=D(),Wz={data:new Ne.Name("data"),valCxt:new Ne.Name("valCxt"),instancePath:new Ne.Name("instancePath"),parentData:new Ne.Name("parentData"),parentDataProperty:new Ne.Name("parentDataProperty"),rootData:new Ne.Name("rootData"),dynamicAnchors:new Ne.Name("dynamicAnchors"),vErrors:new Ne.Name("vErrors"),errors:new Ne.Name("errors"),this:new Ne.Name("this"),self:new Ne.Name("self"),scope:new Ne.Name("scope"),json:new Ne.Name("json"),jsonPos:new Ne.Name("jsonPos"),jsonLen:new Ne.Name("jsonLen"),jsonPart:new Ne.Name("jsonPart")};ep.default=Wz});var $s=R(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.extendErrors=De.resetErrorsCount=De.reportExtraError=De.reportError=De.keyword$DataError=De.keywordError=void 0;var G=D(),Ba=H(),Ue=sr();De.keywordError={message:({keyword:t})=>(0,G.str)`must pass "${t}" keyword validation`};De.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,G.str)`"${t}" keyword must be ${e} ($data)`:(0,G.str)`"${t}" keyword is invalid ($data)`};function Kz(t,e=De.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Uw(t,e,r);n??(i||a)?Lw(s,c):jw(o,(0,G._)`[${c}]`)}De.reportError=Kz;function Jz(t,e=De.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Uw(t,e,r);Lw(o,a),s||i||jw(n,Ue.default.vErrors)}De.reportExtraError=Jz;function Yz(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)))}De.resetErrorsCount=Yz;function Xz({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))})}De.extendErrors=Xz;function Lw(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 jw(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,G._)`new ${t.ValidationError}(${e})`):(r.assign((0,G._)`${n}.errors`,e),r.return(!1))}var un={keyword:new G.Name("keyword"),schemaPath:new G.Name("schemaPath"),params:new G.Name("params"),propertyName:new G.Name("propertyName"),message:new G.Name("message"),schema:new G.Name("schema"),parentSchema:new G.Name("parentSchema")};function Uw(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,G._)`{}`:Qz(t,e,r)}function Qz(t,e,r={}){let{gen:n,it:o}=t,s=[eO(o,r),tO(t,r)];return rO(t,e,s),n.object(...s)}function eO({errorPath:t},{instancePath:e}){let r=e?(0,G.str)`${t}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:t;return[Ue.default.instancePath,(0,G.strConcat)(Ue.default.instancePath,r)]}function tO({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,G.str)`${e}/${t}`;return r&&(o=(0,G.str)`${o}${(0,Ba.getErrorPath)(r,Ba.Type.Str)}`),[un.schemaPath,o]}function rO(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:l}=a;n.push([un.keyword,o],[un.params,typeof e=="function"?e(t):e||(0,G._)`{}`]),c.messages&&n.push([un.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([un.schema,i],[un.parentSchema,(0,G._)`${d}${l}`],[Ue.default.data,s]),u&&n.push([un.propertyName,u])}});var qw=R(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.boolOrEmptySchema=to.topBoolOrEmptySchema=void 0;var nO=$s(),oO=D(),sO=sr(),iO={message:"boolean schema is false"};function aO(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Fw(t,!1):typeof r=="object"&&r.$async===!0?e.return(sO.default.data):(e.assign((0,oO._)`${n}.errors`,null),e.return(!0))}to.topBoolOrEmptySchema=aO;function cO(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Fw(t)):r.var(e,!0)}to.boolOrEmptySchema=cO;function Fw(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,nO.reportError)(o,iO,void 0,e)}});var tp=R(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.getRules=ro.isJSONType=void 0;var uO=["string","number","integer","boolean","null","object","array"],dO=new Set(uO);function lO(t){return typeof t=="string"&&dO.has(t)}ro.isJSONType=lO;function pO(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}ro.getRules=pO});var rp=R(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.shouldUseRule=Tr.shouldUseGroup=Tr.schemaHasRulesForType=void 0;function fO({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Hw(t,n)}Tr.schemaHasRulesForType=fO;function Hw(t,e){return e.rules.some(r=>Gw(t,r))}Tr.shouldUseGroup=Hw;function Gw(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Tr.shouldUseRule=Gw});var Ms=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var hO=tp(),mO=rp(),gO=$s(),N=D(),Zw=H(),no;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(no||(Le.DataType=no={}));function yO(t){let e=Bw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Le.getSchemaTypes=yO;function Bw(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(hO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Bw;function vO(t,e){let{gen:r,data:n,opts:o}=t,s=_O(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,mO.schemaHasRulesForType)(t,e[0]));if(i){let a=op(e,n,o.strictNumbers,no.Wrong);r.if(a,()=>{s.length?SO(t,e,s):sp(t)})}return i}Le.coerceAndCheckDataType=vO;var Vw=new Set(["string","number","integer","boolean","null"]);function _O(t,e){return e?t.filter(r=>Vw.has(r)||e==="array"&&r==="array"):[]}function SO(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(op(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(Vw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),sp(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),wO(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 hO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function rp(t,e,r,n=ro.Correct){let o=n===ro.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===ro.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}Le.checkDataType=rp;function np(t,e,r,n){if(t.length===1)return rp(t[0],e,r,n);let o,s=(0,Uw.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,rp(i,e,r,n));return o}Le.checkDataTypes=np;var mO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function op(t){let e=gO(t);(0,uO.reportError)(e,mO)}Le.reportTypeError=op;function gO(t){let{gen:e,data:r,schema:n}=t,o=(0,Uw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Gw=R(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.assignDefaults=void 0;var no=D(),yO=H();function vO(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Hw(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Hw(t,s,o.default))}Va.assignDefaults=vO;function Hw(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,no._)`${s}${(0,no.getProperty)(e)}`;if(o){(0,yO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,no._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,no._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,no._)`${a} = ${(0,no.stringify)(r)}`)}});var gt=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ue=D(),sp=H(),Tr=sr(),_O=H();function SO(t,e){let{gen:r,data:n,it:o}=t;r.if(ap(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ue._)`${e}`},!0),t.error()})}te.checkReportMissingProp=SO;function wO({gen:t,data:e,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(ap(t,e,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}te.checkMissingProp=wO;function bO(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=bO;function Zw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Zw;function ip(t,e,r){return(0,ue._)`${Zw(t)}.call(${e}, ${r})`}te.isOwnProperty=ip;function RO(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${ip(t,e,r)}`:o}te.propertyInData=RO;function ap(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(ip(t,e,r))):o}te.noPropertyInData=ap;function Vw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=Vw;function PO(t,e){return Vw(e).filter(r=>!(0,sp.alwaysValidSchema)(t,e[r]))}te.schemaProperties=PO;function CO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,ue._)`${t}, ${e}, ${n}${o}`:e,l=[[Tr.default.instancePath,(0,ue.strConcat)(Tr.default.instancePath,s)],[Tr.default.parentData,i.parentData],[Tr.default.parentDataProperty,i.parentDataProperty],[Tr.default.rootData,Tr.default.rootData]];i.opts.dynamicRef&&l.push([Tr.default.dynamicAnchors,Tr.default.dynamicAnchors]);let p=(0,ue._)`${d}, ${r.object(...l)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${p})`:(0,ue._)`${a}(${p})`}te.callValidateCode=CO;var xO=(0,ue._)`new RegExp`;function kO({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ue._)`${o.code==="new RegExp"?xO:(0,_O.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=kO;function EO(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ue._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:sp.Type.Num},s),e.if((0,ue.not)(s),a)})}}te.validateArray=EO;function TO(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,sp.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ue._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=TO});var Kw=R(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.validateKeywordUsage=qt.validSchemaType=qt.funcKeywordCode=qt.macroKeywordCode=void 0;var Fe=D(),un=sr(),AO=gt(),$O=As();function MO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ww(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qt.macroKeywordCode=MO;function IO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;OO(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=Ww(n,o,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)m(),e.modifying&&Bw(t),y(()=>t.error());else{let S=e.async?f():h();e.modifying&&Bw(t),y(()=>zO(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Fe._)`await `),w=>n.assign(l,!1).if((0,Fe._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Fe._)`${w}.errors`),()=>n.throw(w))),S}function h(){let S=(0,Fe._)`${d}.errors`;return n.assign(S,null),m(Fe.nil),S}function m(S=e.async?(0,Fe._)`await `:Fe.nil){let w=c.opts.passContext?un.default.this:un.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Fe._)`${S}${(0,AO.callValidateCode)(t,d,w,b)}`,e.modifying)}function y(S){var w;n.if((0,Fe.not)((w=e.valid)!==null&&w!==void 0?w:l),S)}}qt.funcKeywordCode=IO;function Bw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}function zO(t,e){let{gen:r}=t;r.if((0,Fe._)`Array.isArray(${e})`,()=>{r.assign(un.default.vErrors,(0,Fe._)`${un.default.vErrors} === null ? ${e} : ${un.default.vErrors}.concat(${e})`).assign(un.default.errors,(0,Fe._)`${un.default.vErrors}.length`),(0,$O.extendErrors)(t)},()=>t.error())}function OO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ww(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,Fe.stringify)(r)})}function NO(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}qt.validSchemaType=NO;function DO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}qt.validateKeywordUsage=DO});var Yw=R(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.extendSubschemaMode=Ar.extendSubschemaData=Ar.getSubschema=void 0;var Ht=D(),Jw=H();function LO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Jw.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')}Ar.getSubschema=LO;function jO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,p=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Ht.str)`${u}${(0,Jw.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Ar.extendSubschemaData=jO;function UO(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}Ar.extendSubschemaMode=UO});var cp=R((x6,Xw)=>{"use strict";Xw.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 eb=R((k6,Qw)=>{"use strict";var $r=Qw.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(){};Ba(e,n,o,t,"",t)};$r.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};$r.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};$r.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};$r.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 Ba(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 $r.arrayKeywords)for(var p=0;p<l.length;p++)Ba(t,e,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in $r.propsKeywords){if(l&&typeof l=="object")for(var f in l)Ba(t,e,r,l[f],o+"/"+d+"/"+FO(f),s,o,d,n,f)}else(d in $r.keywords||t.allKeys&&!(d in $r.skipKeywords))&&Ba(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function FO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ms=R(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var qO=H(),HO=cp(),GO=eb(),ZO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function VO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!up(t):e?tb(t)<=e:!1}et.inlineRef=VO;var BO=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function up(t){for(let e in t){if(BO.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(up)||typeof r=="object"&&up(r))return!0}return!1}function tb(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!ZO.has(r)&&(typeof t[r]=="object"&&(0,qO.eachItem)(t[r],n=>e+=tb(n)),e===1/0))return 1/0}return e}function rb(t,e="",r){r!==!1&&(e=oo(e));let n=t.parse(e);return nb(t,n)}et.getFullPath=rb;function nb(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=nb;var WO=/#\/?$/;function oo(t){return t?t.replace(WO,""):""}et.normalizeId=oo;function KO(t,e,r){return r=oo(r),t.resolve(e,r)}et.resolveUrl=KO;var JO=/^[a-z_][-a-z0-9._]*$/i;function YO(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=oo(t[r]||e),s={"":o},i=rb(n,o,!1),a={},c=new Set;return GO(t,{allKeys:!0},(l,p,f,h)=>{if(h===void 0)return;let m=i+p,y=s[h];typeof l[r]=="string"&&(y=S.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=y;function S(b){let k=this.opts.uriResolver.resolve;if(b=oo(y?k(y,b):b),c.has(b))throw d(b);c.add(b);let _=this.refs[b];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?u(l,_.schema,b):b!==oo(m)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!JO.test(b))throw new Error(`invalid anchor "${b}"`);S.call(this,`#${b}`)}}}),a;function u(l,p,f){if(p!==void 0&&!HO(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}et.getSchemaRefs=YO});var Os=R(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.getData=Mr.KeywordCxt=Mr.validateFunctionCode=void 0;var cb=Dw(),ob=$s(),lp=tp(),Wa=$s(),XO=Gw(),zs=Kw(),dp=Yw(),T=D(),O=sr(),QO=Ms(),ir=H(),Is=As();function eN(t){if(lb(t)&&(pb(t),db(t))){nN(t);return}ub(t,()=>(0,cb.topBoolOrEmptySchema)(t))}Mr.validateFunctionCode=eN;function ub({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${O.default.data}, ${O.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${sb(r,o)}`),rN(t,o),t.code(s)}):t.func(e,(0,T._)`${O.default.data}, ${tN(o)}`,n.$async,()=>t.code(sb(r,o)).code(s))}function tN(t){return(0,T._)`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${t.dynamicRef?(0,T._)`, ${O.default.dynamicAnchors}={}`:T.nil}}={}`}function rN(t,e){t.if(O.default.valCxt,()=>{t.var(O.default.instancePath,(0,T._)`${O.default.valCxt}.${O.default.instancePath}`),t.var(O.default.parentData,(0,T._)`${O.default.valCxt}.${O.default.parentData}`),t.var(O.default.parentDataProperty,(0,T._)`${O.default.valCxt}.${O.default.parentDataProperty}`),t.var(O.default.rootData,(0,T._)`${O.default.valCxt}.${O.default.rootData}`),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,T._)`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{t.var(O.default.instancePath,(0,T._)`""`),t.var(O.default.parentData,(0,T._)`undefined`),t.var(O.default.parentDataProperty,(0,T._)`undefined`),t.var(O.default.rootData,O.default.data),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,T._)`{}`)})}function nN(t){let{schema:e,opts:r,gen:n}=t;ub(t,()=>{r.$comment&&e.$comment&&hb(t),cN(t),n.let(O.default.vErrors,null),n.let(O.default.errors,0),r.unevaluated&&oN(t),fb(t),lN(t)})}function oN(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 sb(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 sN(t,e){if(lb(t)&&(pb(t),db(t))){iN(t,e);return}(0,cb.boolOrEmptySchema)(t,e)}function db({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 lb(t){return typeof t.schema!="boolean"}function iN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&hb(t),uN(t),dN(t);let s=n.const("_errs",O.default.errors);fb(t,s),n.var(e,(0,T._)`${s} === ${O.default.errors}`)}function pb(t){(0,ir.checkUnknownRules)(t),aN(t)}function fb(t,e){if(t.opts.jtd)return ib(t,[],!1,e);let r=(0,ob.getSchemaTypes)(t.schema),n=(0,ob.coerceAndCheckDataType)(t,r);ib(t,r,!n,e)}function aN(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function cN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function uN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,QO.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function dN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function hb({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${O.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._)`${O.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function lN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${O.default.errors} === 0`,()=>e.return(O.default.data),()=>e.throw((0,T._)`new ${o}(${O.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,O.default.vErrors),s.unevaluated&&pN(t),e.return((0,T._)`${O.default.errors} === 0`))}function pN({gen:t,evaluated:e,props:r,items:n}){r instanceof T.Name&&t.assign((0,T._)`${e}.props`,r),n instanceof T.Name&&t.assign((0,T._)`${e}.items`,n)}function ib(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,ir.schemaHasRulesButRef)(s,d))){o.block(()=>gb(t,"$ref",d.all.$ref.definition));return}c.jtd||fN(t,e),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,lp.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Wa.checkDataType)(p.type,i,c.strictNumbers)),ab(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Wa.reportTypeError)(t)),o.endIf()):ab(t,p),a||o.if((0,T._)`${O.default.errors} === ${n||0}`))}}function ab(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,XO.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,lp.shouldUseRule)(n,s)&&gb(t,s.keyword,s.definition,e.type)})}function fN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(hN(t,e),t.opts.allowUnionTypes||mN(t,e),gN(t,t.dataTypes))}function hN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{mb(t.dataTypes,r)||pp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),vN(t,e)}}function mN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&pp(t,"use allowUnionTypes to allow union type keyword")}function gN(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,lp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>yN(e,i))&&pp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function yN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function mb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function vN(t,e){let r=[];for(let n of t.dataTypes)mb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function pp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var Ka=class{constructor(e,r,n){if((0,zs.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,ir.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",yb(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,zs.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",O.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?Is.reportExtraError:Is.reportError)(this,this.def.error,r)}$dataError(){(0,Is.reportError)(this,this.def.$dataError||Is.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Is.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,Wa.checkDataTypes)(c,r,s.opts.strictNumbers,Wa.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,dp.getSubschema)(this.it,e);(0,dp.extendSubschemaData)(n,this.it,e),(0,dp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return sN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ir.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}};Mr.KeywordCxt=Ka;function gb(t,e,r,n){let o=new Ka(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,zs.funcKeywordCode)(o,r):"macro"in r?(0,zs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,zs.funcKeywordCode)(o,r)}var _N=/^\/(?:[^~]|~0|~1)*$/,SN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function yb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return O.default.rootData;if(t[0]==="/"){if(!_N.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=O.default.rootData}else{let u=SN.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,ir.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Mr.getData=yb});var Ja=R(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var fp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};hp.default=fp});var Ns=R(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});var mp=Ms(),gp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,mp.resolveUrl)(e,r,n),this.missingSchema=(0,mp.normalizeId)((0,mp.getFullPath)(e,this.missingRef))}};yp.default=gp});var Xa=R(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Et=D(),wN=Ja(),dn=sr(),Tt=Ms(),vb=H(),bN=Os(),so=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=so;function _p(t){let e=_b.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:wN.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:dn.default.data,parentData:dn.default.parentData,parentDataProperty:dn.default.parentDataProperty,dataNames:[dn.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,bN.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(dn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${dn.default.self}`,`${dn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;f.evaluated={props:h instanceof Et.Name?void 0:h,items:m instanceof Et.Name?void 0:m,dynamicProps:h instanceof Et.Name,dynamicItems:m instanceof Et.Name},f.source&&(f.source.evaluated=(0,Et.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}yt.compileSchema=_p;function RN(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=xN.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 so({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=PN.call(this,s)}yt.resolveRef=RN;function PN(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:_p.call(this,t)}function _b(t){for(let e of this._compilations)if(CN(e,t))return e}yt.getCompilingSchema=_b;function CN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function xN(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ya.call(this,t,e)}function Ya(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return vp.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ya.call(this,t,i);return typeof a?.schema!="object"?void 0:vp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||_p.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new so({schema:a,schemaId:c,root:t,baseId:o})}return vp.call(this,r,i)}}yt.resolveSchema=Ya;var kN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function vp(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];!kN.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,vb.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ya.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new so({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Sb=R((I6,EN)=>{EN.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 bp=R((z6,xb)=>{"use strict";var TN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),bb=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),Sp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Rb=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),AN=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wp(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 $N=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wb(t){return t.length=0,!0}function MN(t,e,r){if(t.length){let n=wp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function IN(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=MN;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=wb}else{o.push(u);continue}}return o.length&&(a===wb?r.zone=o.join(""):i?n.push(o.join("")):n.push(wp(o))),r.address=n.join(""),r}function Pb(t){if(zN(t,":")<2)return{host:t,isIPV6:!1};let e=IN(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 zN(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function ON(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 NN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},DN=/[@/?#:]/g,LN=/[@/?#]/g;function Cb(t,e){let r=e?LN:DN;return r.lastIndex=0,t.replace(r,n=>NN[n])}function jN(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(Sp(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Rb(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function UN(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(Sp(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Rb(s)?e+=s:e+="%"+o,r+=2;continue}}AN(t[r])?e+=t[r]:e+=escape(t[r])}return e}function FN(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(Sp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function qN(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!bb(r)){let n=Pb(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Cb(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}xb.exports={nonSimpleDomain:$N,recomposeAuthority:qN,reescapeHostDelimiters:Cb,normalizePercentEncoding:jN,normalizePathEncoding:UN,escapePreservingEscapes:FN,removeDotSegments:ON,isIPv4:bb,isUUID:TN,normalizeIPv6:Pb,stringArrayToHexStripped:wp}});var $b=R((O6,Ab)=>{"use strict";var{isUUID:HN}=bp(),GN=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,ZN=["http","https","ws","wss","urn","urn:uuid"];function VN(t){return ZN.indexOf(t)!==-1}function Rp(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 kb(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Eb(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 BN(t){return t.secure=Rp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function WN(t){if((t.port===(Rp(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 KN(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(GN);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=Pp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function JN(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=Pp(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 YN(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!HN(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function XN(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Tb={scheme:"http",domainHost:!0,parse:kb,serialize:Eb},QN={scheme:"https",domainHost:Tb.domainHost,parse:kb,serialize:Eb},Qa={scheme:"ws",domainHost:!0,parse:BN,serialize:WN},eD={scheme:"wss",domainHost:Qa.domainHost,parse:Qa.parse,serialize:Qa.serialize},tD={scheme:"urn",parse:KN,serialize:JN,skipNormalize:!0},rD={scheme:"urn:uuid",parse:YN,serialize:XN,skipNormalize:!0},ec={http:Tb,https:QN,ws:Qa,wss:eD,urn:tD,"urn:uuid":rD};Object.setPrototypeOf(ec,null);function Pp(t){return t&&(ec[t]||ec[t.toLowerCase()])||void 0}Ab.exports={wsIsSecure:Rp,SCHEMES:ec,isValidSchemeName:VN,getSchemeHandler:Pp}});var Nb=R((N6,nc)=>{"use strict";var{normalizeIPv6:nD,removeDotSegments:Ds,recomposeAuthority:oD,normalizePercentEncoding:sD,normalizePathEncoding:iD,escapePreservingEscapes:aD,reescapeHostDelimiters:cD,isIPv4:uD,nonSimpleDomain:dD}=bp(),{SCHEMES:lD,getSchemeHandler:Ib}=$b();function pD(t,e){return typeof t=="string"?t=_D(t,e):typeof t=="object"&&(t=rc(ln(t,e),e)),t}function fD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=tc(t,n),{parsed:i,malformedAuthorityOrPort:a}=tc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=zb(o,i,n,!0);return n.skipEscape=!0,ln(c,n)}function zb(t,e,r,n){let o={};return n||(t=rc(ln(t,r),r),e=rc(ln(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=Ds(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=Ds(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ds(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=Ds(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 hD(t,e,r){let n=Mb(t,r),o=Mb(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function ln(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=Ib(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=sD(r.path):(r.path=aD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=oD(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=Ds(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 mD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,yD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function vD(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 tc(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(gD);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(mD);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=vD(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(uD(n.host)===!1){let p=nD(n.host);n.host=p.host.toLowerCase(),s=p.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=Ib(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&dD(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=cD(unescape(n.host),s))),n.path&&(n.path=iD(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 rc(t,e){return tc(t,e).parsed}function _D(t,e){return Ob(t,e).normalized}function Ob(t,e){let{parsed:r,malformedAuthorityOrPort:n}=tc(t,e);return{normalized:n?t:ln(r,e),malformedAuthorityOrPort:n}}function Mb(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Ob(t,e);return n?void 0:r}if(typeof t=="object")return ln(t,e)}var Cp={SCHEMES:lD,normalize:pD,resolve:fD,resolveComponent:zb,equal:hD,serialize:ln,parse:rc};nc.exports=Cp;nc.exports.default=Cp;nc.exports.fastUri=Cp});var Lb=R(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var Db=Nb();Db.code='require("ajv/dist/runtime/uri").default';xp.default=Db});var Vb=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var SD=Os();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return SD.KeywordCxt}});var io=D();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return io._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return io.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return io.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return io.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return io.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return io.CodeGen}});var wD=Ja(),Hb=Ns(),bD=ep(),Ls=Xa(),RD=D(),js=Ms(),oc=$s(),Ep=H(),jb=Sb(),PD=Lb(),Gb=(t,e)=>new RegExp(t,e);Gb.code="new RegExp";var CD=["removeAdditional","useDefaults","coerceTypes"],xD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),kD={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."},ED={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ub=200;function TD(t){var e,r,n,o,s,i,a,c,u,d,l,p,f,h,m,y,S,w,b,k,_,P,z,ge,ye;let Ze=t.strict,To=(e=t.code)===null||e===void 0?void 0:e.optimize,Ri=To===!0||To===void 0?1:To||0,Pi=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Gb,dr=(o=t.uriResolver)!==null&&o!==void 0?o:PD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:Ze)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:Ze)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Ri,regExp:Pi}:{optimize:Ri,regExp:Pi},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Ub,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Ub,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(z=t.validateFormats)!==null&&z!==void 0?z:!0,unicodeRegExp:(ge=t.unicodeRegExp)!==null&&ge!==void 0?ge:!0,int32range:(ye=t.int32range)!==null&&ye!==void 0?ye:!0,uriResolver:dr}}var Us=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,...TD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new RD.ValueScope({scope:{},prefixes:xD,es5:r,lines:n}),this.logger=OD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,bD.getRules)(),Fb.call(this,kD,e,"NOT SUPPORTED"),Fb.call(this,ED,e,"DEPRECATED","warn"),this._metaOpts=ID.call(this),e.formats&&$D.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&MD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),AD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=jb;n==="id"&&(o={...jb},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Hb.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,js.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=qb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ls.SchemaEnv({schema:{},schemaId:n});if(r=Ls.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=qb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,js.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(DD.call(this,n,r),!r)return(0,Ep.eachItem)(n,s=>kp.call(this,s)),this;jD.call(this,r);let o={...r,type:(0,oc.getJSONTypes)(r.type),schemaType:(0,oc.getJSONTypes)(r.schemaType)};return(0,Ep.eachItem)(n,o.type.length===0?s=>kp.call(this,s,o):s=>o.type.forEach(i=>kp.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]=Zb(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,js.normalizeId)(i||n);let u=js.getSchemaRefs.call(this,e,n);return c=new Ls.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):Ls.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{Ls.compileSchema.call(this,e)}finally{this.opts=r}}};Us.ValidationError=wD.default;Us.MissingRefError=Hb.default;Me.default=Us;function Fb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function qb(t){return t=(0,js.normalizeId)(t),this.schemas[t]||this.refs[t]}function AD(){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 $D(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function MD(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 ID(){let t={...this.opts};for(let e of CD)delete t[e];return t}var zD={log(){},warn(){},error(){}};function OD(t){if(t===!1)return zD;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 ND=/^[a-z_$][a-z0-9_$:-]*$/i;function DD(t,e){let{RULES:r}=this;if((0,Ep.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!ND.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function kp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES: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,oc.getJSONTypes)(e.type),schemaType:(0,oc.getJSONTypes)(e.schemaType)}};e.before?LD.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 LD(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 jD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Zb(e)),t.validateSchema=this.compile(e,!0))}var UD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zb(t){return{anyOf:[t,UD]}}});var Bb=R(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var FD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Tp.default=FD});var Yb=R(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.callRef=pn.getValidate=void 0;var qD=Ns(),Wb=gt(),tt=D(),ao=sr(),Kb=Xa(),sc=H(),HD={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=Kb.resolveRef.call(c,u,o,r);if(d===void 0)throw new qD.default(n.opts.uriResolver,o,r);if(d instanceof Kb.SchemaEnv)return p(d);return f(d);function l(){if(s===u)return ic(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return ic(t,(0,tt._)`${h}.validate`,u,u.$async)}function p(h){let m=Jb(t,h);ic(t,m,h,h.$async)}function f(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,tt.stringify)(h)}:{ref:h}),y=e.name("valid"),S=t.subschema({schema:h,dataTypes:[],schemaPath:tt.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function Jb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,tt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}pn.getValidate=Jb;function ic(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ao.default.this:tt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,tt._)`await ${(0,Wb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(h,!0)},m=>{o.if((0,tt._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,Wb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let m=(0,tt._)`${h}.errors`;o.assign(ao.default.vErrors,(0,tt._)`${ao.default.vErrors} === null ? ${m} : ${ao.default.vErrors}.concat(${m})`),o.assign(ao.default.errors,(0,tt._)`${ao.default.vErrors}.length`)}function f(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=sc.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,tt._)`${h}.evaluated.props`);s.props=sc.mergeEvaluated.props(o,S,s.props,tt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=sc.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,tt._)`${h}.evaluated.items`);s.items=sc.mergeEvaluated.items(o,S,s.items,tt.Name)}}}pn.callRef=ic;pn.default=HD});var Xb=R(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var GD=Bb(),ZD=Yb(),VD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GD.default,ZD.default];Ap.default=VD});var Qb=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var ac=D(),Ir=ac.operators,cc={maximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},minimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},exclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},exclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},BD={message:({keyword:t,schemaCode:e})=>(0,ac.str)`must be ${cc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ac._)`{comparison: ${cc[t].okStr}, limit: ${e}}`},WD={keyword:Object.keys(cc),type:"number",schemaType:"number",$data:!0,error:BD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ac._)`${r} ${cc[e].fail} ${n} || isNaN(${r})`)}};$p.default=WD});var eR=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var Fs=D(),KD={message:({schemaCode:t})=>(0,Fs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Fs._)`{multipleOf: ${t}}`},JD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:KD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Fs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Fs._)`${i} !== parseInt(${i})`;t.fail$data((0,Fs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Mp.default=JD});var rR=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});function tR(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}Ip.default=tR;tR.code='require("ajv/dist/runtime/ucs2length").default'});var nR=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var fn=D(),YD=H(),XD=rR(),QD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,fn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,fn._)`{limit: ${t}}`},eL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?fn.operators.GT:fn.operators.LT,i=o.opts.unicode===!1?(0,fn._)`${r}.length`:(0,fn._)`${(0,YD.useFunc)(t.gen,XD.default)}(${r})`;t.fail$data((0,fn._)`${i} ${s} ${n}`)}};zp.default=eL});var oR=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var tL=gt(),rL=H(),co=D(),nL={message:({schemaCode:t})=>(0,co.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,co._)`{pattern: ${t}}`},oL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:nL,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,co._)`new RegExp`:(0,rL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,co._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,co._)`!${d}`)}else{let c=(0,tL.usePattern)(t,o);t.fail$data((0,co._)`!${c}.test(${r})`)}}};Op.default=oL});var sR=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var qs=D(),sL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,qs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,qs._)`{limit: ${t}}`},iL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?qs.operators.GT:qs.operators.LT;t.fail$data((0,qs._)`Object.keys(${r}).length ${o} ${n}`)}};Np.default=iL});var iR=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var Hs=gt(),Gs=D(),aL=H(),cL={message:({params:{missingProperty:t}})=>(0,Gs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Gs._)`{missingProperty: ${t}}`},uL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(f?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,aL.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Gs.nil,l);else for(let f of r)(0,Hs.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Hs.checkMissingProp)(t,r,f)),(0,Hs.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Hs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,Hs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Gs.not)(h),()=>{t.error(),e.break()})},Gs.nil)}}};Dp.default=uL});var aR=R(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var Zs=D(),dL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Zs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Zs._)`{limit: ${t}}`},lL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Zs.operators.GT:Zs.operators.LT;t.fail$data((0,Zs._)`${r}.length ${o} ${n}`)}};Lp.default=lL});var uc=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var cR=cp();cR.code='require("ajv/dist/runtime/equal").default';jp.default=cR});var uR=R(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});var Up=$s(),Ie=D(),pL=H(),fL=uc(),hL={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},mL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hL,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,Up.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Ie._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Ie._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Ie._)`${h} > 1`,()=>(l()?p:f)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,m){let y=e.name("item"),S=(0,Up.checkDataTypes)(u,y,a.opts.strictNumbers,Up.DataType.Wrong),w=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${h}--;`,()=>{e.let(y,(0,Ie._)`${r}[${h}]`),e.if(S,(0,Ie._)`continue`),u.length>1&&e.if((0,Ie._)`typeof ${y} == "string"`,(0,Ie._)`${y} += "_"`),e.if((0,Ie._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Ie._)`${w}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ie._)`${w}[${y}] = ${h}`)})}function f(h,m){let y=(0,pL.useFunc)(e,fL.default),S=e.name("outer");e.label(S).for((0,Ie._)`;${h}--;`,()=>e.for((0,Ie._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Ie._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};Fp.default=mL});var dR=R(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var qp=D(),gL=H(),yL=uc(),vL={message:"must be equal to constant",params:({schemaCode:t})=>(0,qp._)`{allowedValue: ${t}}`},_L={keyword:"const",$data:!0,error:vL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,qp._)`!${(0,gL.useFunc)(e,yL.default)}(${r}, ${o})`):t.fail((0,qp._)`${s} !== ${r}`)}};Hp.default=_L});var lR=R(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var Vs=D(),SL=H(),wL=uc(),bL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vs._)`{allowedValues: ${t}}`},RL={keyword:"enum",schemaType:"array",$data:!0,error:bL,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,SL.useFunc)(e,wL.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);d=(0,Vs.or)(...o.map((h,m)=>p(f,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,Vs._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,h){let m=o[h];return typeof m=="object"&&m!==null?(0,Vs._)`${u()}(${r}, ${f}[${h}])`:(0,Vs._)`${r} === ${m}`}}};Gp.default=RL});var pR=R(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});var PL=Qb(),CL=eR(),xL=nR(),kL=oR(),EL=sR(),TL=iR(),AL=aR(),$L=uR(),ML=dR(),IL=lR(),zL=[PL.default,CL.default,xL.default,kL.default,EL.default,TL.default,AL.default,$L.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},ML.default,IL.default];Zp.default=zL});var Bp=R(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.validateAdditionalItems=void 0;var hn=D(),Vp=H(),OL={message:({params:{len:t}})=>(0,hn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,hn._)`{limit: ${t}}`},NL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:OL,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Vp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}fR(t,n)}};function fR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,hn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,hn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Vp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,hn._)`${a} <= ${e.length}`);r.if((0,hn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:Vp.Type.Num},u),i.allErrors||r.if((0,hn.not)(u),()=>r.break())})}}Bs.validateAdditionalItems=fR;Bs.default=NL});var Wp=R(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.validateTuple=void 0;var hR=D(),dc=H(),DL=gt(),LL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return mR(t,"additionalItems",e);r.items=!0,!(0,dc.alwaysValidSchema)(r,e)&&t.ok((0,DL.validateArray)(t))}};function mR(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=dc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,hR._)`${s}.length`);r.forEach((l,p)=>{(0,dc.alwaysValidSchema)(a,l)||(n.if((0,hR._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(p.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,dc.checkStrictMode)(a,y,p.strictTuples)}}}Ws.validateTuple=mR;Ws.default=LL});var gR=R(Kp=>{"use strict";Object.defineProperty(Kp,"__esModule",{value:!0});var jL=Wp(),UL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,jL.validateTuple)(t,"items")};Kp.default=UL});var vR=R(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var yR=D(),FL=H(),qL=gt(),HL=Bp(),GL={message:({params:{len:t}})=>(0,yR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,yR._)`{limit: ${t}}`},ZL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:GL,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,FL.alwaysValidSchema)(n,e)&&(o?(0,HL.validateAdditionalItems)(t,o):t.ok((0,qL.validateArray)(t)))}};Jp.default=ZL});var _R=R(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var vt=D(),lc=H(),VL={message:({params:{min:t,max:e}})=>e===void 0?(0,vt.str)`must contain at least ${t} valid item(s)`:(0,vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vt._)`{minContains: ${t}}`:(0,vt._)`{minContains: ${t}, maxContains: ${e}}`},BL={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:VL,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,vt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,lc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,lc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,lc.alwaysValidSchema)(s,r)){let m=(0,vt._)`${d} >= ${i}`;a!==void 0&&(m=(0,vt._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,vt._)`${o}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>t.reset());function p(){let m=e.name("_valid"),y=e.let("count",0);f(m,()=>e.if(m,()=>h(y)))}function f(m,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:lc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,vt._)`${m}++`),a===void 0?e.if((0,vt._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,vt._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,vt._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};Yp.default=BL});var bR=R(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateSchemaDeps=Gt.validatePropertyDeps=Gt.error=void 0;var Xp=D(),WL=H(),Ks=gt();Gt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Xp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Xp._)`{property: ${t},
5
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function wO({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function np(t,e,r,n=no.Correct){let o=n===no.Correct?N.operators.EQ:N.operators.NEQ,s;switch(t){case"null":return(0,N._)`${e} ${o} null`;case"array":s=(0,N._)`Array.isArray(${e})`;break;case"object":s=(0,N._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,N._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,N._)`typeof ${e} ${o} ${t}`}return n===no.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}Le.checkDataType=np;function op(t,e,r,n){if(t.length===1)return np(t[0],e,r,n);let o,s=(0,Zw.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,np(i,e,r,n));return o}Le.checkDataTypes=op;var bO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function sp(t){let e=RO(t);(0,gO.reportError)(e,bO)}Le.reportTypeError=sp;function RO(t){let{gen:e,data:r,schema:n}=t,o=(0,Zw.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Kw=R(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.assignDefaults=void 0;var oo=D(),PO=H();function CO(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Ww(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Ww(t,s,o.default))}Va.assignDefaults=CO;function Ww(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,oo._)`${s}${(0,oo.getProperty)(e)}`;if(o){(0,PO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,oo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,oo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,oo._)`${a} = ${(0,oo.stringify)(r)}`)}});var gt=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.validateUnion=te.validateArray=te.usePattern=te.callValidateCode=te.schemaProperties=te.allSchemaProperties=te.noPropertyInData=te.propertyInData=te.isOwnProperty=te.hasPropFunc=te.reportMissingProp=te.checkMissingProp=te.checkReportMissingProp=void 0;var ue=D(),ip=H(),Ar=sr(),xO=H();function kO(t,e){let{gen:r,data:n,it:o}=t;r.if(cp(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ue._)`${e}`},!0),t.error()})}te.checkReportMissingProp=kO;function EO({gen:t,data:e,it:{opts:r}},n,o){return(0,ue.or)(...n.map(s=>(0,ue.and)(cp(t,e,s,r.ownProperties),(0,ue._)`${o} = ${s}`)))}te.checkMissingProp=EO;function TO(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=TO;function Jw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ue._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Jw;function ap(t,e,r){return(0,ue._)`${Jw(t)}.call(${e}, ${r})`}te.isOwnProperty=ap;function AO(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} !== undefined`;return n?(0,ue._)`${o} && ${ap(t,e,r)}`:o}te.propertyInData=AO;function cp(t,e,r,n){let o=(0,ue._)`${e}${(0,ue.getProperty)(r)} === undefined`;return n?(0,ue.or)(o,(0,ue.not)(ap(t,e,r))):o}te.noPropertyInData=cp;function Yw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=Yw;function $O(t,e){return Yw(e).filter(r=>!(0,ip.alwaysValidSchema)(t,e[r]))}te.schemaProperties=$O;function MO({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,ue._)`${t}, ${e}, ${n}${o}`:e,l=[[Ar.default.instancePath,(0,ue.strConcat)(Ar.default.instancePath,s)],[Ar.default.parentData,i.parentData],[Ar.default.parentDataProperty,i.parentDataProperty],[Ar.default.rootData,Ar.default.rootData]];i.opts.dynamicRef&&l.push([Ar.default.dynamicAnchors,Ar.default.dynamicAnchors]);let p=(0,ue._)`${d}, ${r.object(...l)}`;return c!==ue.nil?(0,ue._)`${a}.call(${c}, ${p})`:(0,ue._)`${a}(${p})`}te.callValidateCode=MO;var IO=(0,ue._)`new RegExp`;function zO({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ue._)`${o.code==="new RegExp"?IO:(0,xO.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=zO;function OO(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ue._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ip.Type.Num},s),e.if((0,ue.not)(s),a)})}}te.validateArray=OO;function NO(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,ip.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ue._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=NO});var eb=R(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.validateKeywordUsage=qt.validSchemaType=qt.funcKeywordCode=qt.macroKeywordCode=void 0;var Fe=D(),dn=sr(),DO=gt(),LO=$s();function jO(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Qw(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}qt.macroKeywordCode=jO;function UO(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;qO(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=Qw(n,o,u),l=n.let("valid");t.block$data(l,p),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function p(){if(e.errors===!1)m(),e.modifying&&Xw(t),y(()=>t.error());else{let S=e.async?f():h();e.modifying&&Xw(t),y(()=>FO(t,S))}}function f(){let S=n.let("ruleErrs",null);return n.try(()=>m((0,Fe._)`await `),w=>n.assign(l,!1).if((0,Fe._)`${w} instanceof ${c.ValidationError}`,()=>n.assign(S,(0,Fe._)`${w}.errors`),()=>n.throw(w))),S}function h(){let S=(0,Fe._)`${d}.errors`;return n.assign(S,null),m(Fe.nil),S}function m(S=e.async?(0,Fe._)`await `:Fe.nil){let w=c.opts.passContext?dn.default.this:dn.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,Fe._)`${S}${(0,DO.callValidateCode)(t,d,w,b)}`,e.modifying)}function y(S){var w;n.if((0,Fe.not)((w=e.valid)!==null&&w!==void 0?w:l),S)}}qt.funcKeywordCode=UO;function Xw(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}function FO(t,e){let{gen:r}=t;r.if((0,Fe._)`Array.isArray(${e})`,()=>{r.assign(dn.default.vErrors,(0,Fe._)`${dn.default.vErrors} === null ? ${e} : ${dn.default.vErrors}.concat(${e})`).assign(dn.default.errors,(0,Fe._)`${dn.default.vErrors}.length`),(0,LO.extendErrors)(t)},()=>t.error())}function qO({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Qw(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,Fe.stringify)(r)})}function HO(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}qt.validSchemaType=HO;function GO({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}qt.validateKeywordUsage=GO});var rb=R($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.extendSubschemaMode=$r.extendSubschemaData=$r.getSubschema=void 0;var Ht=D(),tb=H();function ZO(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ht._)`${t.schemaPath}${(0,Ht.getProperty)(e)}${(0,Ht.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,tb.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}$r.getSubschema=ZO;function BO(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,p=a.let("data",(0,Ht._)`${e.data}${(0,Ht.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Ht.str)`${u}${(0,tb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Ht._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ht.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}$r.extendSubschemaData=BO;function VO(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}$r.extendSubschemaMode=VO});var up=R((N6,nb)=>{"use strict";nb.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 sb=R((D6,ob)=>{"use strict";var Mr=ob.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Wa(e,n,o,t,"",t)};Mr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Mr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Mr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Mr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Wa(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var d in n){var l=n[d];if(Array.isArray(l)){if(d in Mr.arrayKeywords)for(var p=0;p<l.length;p++)Wa(t,e,r,l[p],o+"/"+d+"/"+p,s,o,d,n,p)}else if(d in Mr.propsKeywords){if(l&&typeof l=="object")for(var f in l)Wa(t,e,r,l[f],o+"/"+d+"/"+WO(f),s,o,d,n,f)}else(d in Mr.keywords||t.allKeys&&!(d in Mr.skipKeywords))&&Wa(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function WO(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Is=R(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var KO=H(),JO=up(),YO=sb(),XO=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function QO(t,e=!0){return typeof t=="boolean"?!0:e===!0?!dp(t):e?ib(t)<=e:!1}et.inlineRef=QO;var eN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function dp(t){for(let e in t){if(eN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(dp)||typeof r=="object"&&dp(r))return!0}return!1}function ib(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!XO.has(r)&&(typeof t[r]=="object"&&(0,KO.eachItem)(t[r],n=>e+=ib(n)),e===1/0))return 1/0}return e}function ab(t,e="",r){r!==!1&&(e=so(e));let n=t.parse(e);return cb(t,n)}et.getFullPath=ab;function cb(t,e){return t.serialize(e).split("#")[0]+"#"}et._getFullPath=cb;var tN=/#\/?$/;function so(t){return t?t.replace(tN,""):""}et.normalizeId=so;function rN(t,e,r){return r=so(r),t.resolve(e,r)}et.resolveUrl=rN;var nN=/^[a-z_][-a-z0-9._]*$/i;function oN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=so(t[r]||e),s={"":o},i=ab(n,o,!1),a={},c=new Set;return YO(t,{allKeys:!0},(l,p,f,h)=>{if(h===void 0)return;let m=i+p,y=s[h];typeof l[r]=="string"&&(y=S.call(this,l[r])),w.call(this,l.$anchor),w.call(this,l.$dynamicAnchor),s[p]=y;function S(b){let k=this.opts.uriResolver.resolve;if(b=so(y?k(y,b):b),c.has(b))throw d(b);c.add(b);let _=this.refs[b];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?u(l,_.schema,b):b!==so(m)&&(b[0]==="#"?(u(l,a[b],b),a[b]=l):this.refs[b]=m),b}function w(b){if(typeof b=="string"){if(!nN.test(b))throw new Error(`invalid anchor "${b}"`);S.call(this,`#${b}`)}}}),a;function u(l,p,f){if(p!==void 0&&!JO(l,p))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}et.getSchemaRefs=oN});var Ns=R(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.getData=Ir.KeywordCxt=Ir.validateFunctionCode=void 0;var fb=qw(),ub=Ms(),pp=rp(),Ka=Ms(),sN=Kw(),Os=eb(),lp=rb(),T=D(),O=sr(),iN=Is(),ir=H(),zs=$s();function aN(t){if(gb(t)&&(yb(t),mb(t))){dN(t);return}hb(t,()=>(0,fb.topBoolOrEmptySchema)(t))}Ir.validateFunctionCode=aN;function hb({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${O.default.data}, ${O.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${db(r,o)}`),uN(t,o),t.code(s)}):t.func(e,(0,T._)`${O.default.data}, ${cN(o)}`,n.$async,()=>t.code(db(r,o)).code(s))}function cN(t){return(0,T._)`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${t.dynamicRef?(0,T._)`, ${O.default.dynamicAnchors}={}`:T.nil}}={}`}function uN(t,e){t.if(O.default.valCxt,()=>{t.var(O.default.instancePath,(0,T._)`${O.default.valCxt}.${O.default.instancePath}`),t.var(O.default.parentData,(0,T._)`${O.default.valCxt}.${O.default.parentData}`),t.var(O.default.parentDataProperty,(0,T._)`${O.default.valCxt}.${O.default.parentDataProperty}`),t.var(O.default.rootData,(0,T._)`${O.default.valCxt}.${O.default.rootData}`),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,T._)`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{t.var(O.default.instancePath,(0,T._)`""`),t.var(O.default.parentData,(0,T._)`undefined`),t.var(O.default.parentDataProperty,(0,T._)`undefined`),t.var(O.default.rootData,O.default.data),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,T._)`{}`)})}function dN(t){let{schema:e,opts:r,gen:n}=t;hb(t,()=>{r.$comment&&e.$comment&&_b(t),mN(t),n.let(O.default.vErrors,null),n.let(O.default.errors,0),r.unevaluated&&lN(t),vb(t),vN(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 db(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 pN(t,e){if(gb(t)&&(yb(t),mb(t))){fN(t,e);return}(0,fb.boolOrEmptySchema)(t,e)}function mb({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 gb(t){return typeof t.schema!="boolean"}function fN(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&_b(t),gN(t),yN(t);let s=n.const("_errs",O.default.errors);vb(t,s),n.var(e,(0,T._)`${s} === ${O.default.errors}`)}function yb(t){(0,ir.checkUnknownRules)(t),hN(t)}function vb(t,e){if(t.opts.jtd)return lb(t,[],!1,e);let r=(0,ub.getSchemaTypes)(t.schema),n=(0,ub.coerceAndCheckDataType)(t,r);lb(t,r,!n,e)}function hN(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ir.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function mN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ir.checkStrictMode)(t,"default is ignored in the schema root")}function gN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,iN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function yN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function _b({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${O.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._)`${O.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function vN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${O.default.errors} === 0`,()=>e.return(O.default.data),()=>e.throw((0,T._)`new ${o}(${O.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,O.default.vErrors),s.unevaluated&&_N(t),e.return((0,T._)`${O.default.errors} === 0`))}function _N({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 lb(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,ir.schemaHasRulesButRef)(s,d))){o.block(()=>wb(t,"$ref",d.all.$ref.definition));return}c.jtd||SN(t,e),o.block(()=>{for(let p of d.rules)l(p);l(d.post)});function l(p){(0,pp.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Ka.checkDataType)(p.type,i,c.strictNumbers)),pb(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Ka.reportTypeError)(t)),o.endIf()):pb(t,p),a||o.if((0,T._)`${O.default.errors} === ${n||0}`))}}function pb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,sN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,pp.shouldUseRule)(n,s)&&wb(t,s.keyword,s.definition,e.type)})}function SN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(wN(t,e),t.opts.allowUnionTypes||bN(t,e),RN(t,t.dataTypes))}function wN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Sb(t.dataTypes,r)||fp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),CN(t,e)}}function bN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&fp(t,"use allowUnionTypes to allow union type keyword")}function RN(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,pp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>PN(e,i))&&fp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function PN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Sb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function CN(t,e){let r=[];for(let n of t.dataTypes)Sb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function fp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ir.checkStrictMode)(t,e,t.opts.strictTypes)}var Ja=class{constructor(e,r,n){if((0,Os.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,ir.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,Os.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",O.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?zs.reportExtraError:zs.reportError)(this,this.def.error,r)}$dataError(){(0,zs.reportError)(this,this.def.$dataError||zs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,zs.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,Ka.checkDataTypes)(c,r,s.opts.strictNumbers,Ka.DataType.Wrong)}`}return T.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,T._)`!${c}(${r})`}return T.nil}}subschema(e,r){let n=(0,lp.getSubschema)(this.it,e);(0,lp.extendSubschemaData)(n,this.it,e),(0,lp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return pN(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ir.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ir.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,T.Name)),!0}};Ir.KeywordCxt=Ja;function wb(t,e,r,n){let o=new Ja(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Os.funcKeywordCode)(o,r):"macro"in r?(0,Os.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Os.funcKeywordCode)(o,r)}var xN=/^\/(?:[^~]|~0|~1)*$/,kN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function bb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return O.default.rootData;if(t[0]==="/"){if(!xN.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=O.default.rootData}else{let u=kN.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,ir.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}Ir.getData=bb});var Ya=R(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var hp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};mp.default=hp});var Ds=R(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var gp=Is(),yp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,gp.resolveUrl)(e,r,n),this.missingSchema=(0,gp.normalizeId)((0,gp.getFullPath)(e,this.missingRef))}};vp.default=yp});var Qa=R(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Et=D(),EN=Ya(),ln=sr(),Tt=Is(),Rb=H(),TN=Ns(),io=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Tt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=io;function Sp(t){let e=Pb.call(this,t);if(e)return e;let r=(0,Tt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Et.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:EN.default,code:(0,Et._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ln.default.data,parentData:ln.default.parentData,parentDataProperty:ln.default.parentDataProperty,dataNames:[ln.default.data],dataPathArr:[Et.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Et.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Et.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Et._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,TN.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(ln.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${ln.default.self}`,`${ln.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;f.evaluated={props:h instanceof Et.Name?void 0:h,items:m instanceof Et.Name?void 0:m,dynamicProps:h instanceof Et.Name,dynamicItems:m instanceof Et.Name},f.source&&(f.source.evaluated=(0,Et.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}yt.compileSchema=Sp;function AN(t,e,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=IN.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new io({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=$N.call(this,s)}yt.resolveRef=AN;function $N(t){return(0,Tt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sp.call(this,t)}function Pb(t){for(let e of this._compilations)if(MN(e,t))return e}yt.getCompilingSchema=Pb;function MN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function IN(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Xa.call(this,t,e)}function Xa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return _p.call(this,r,t);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Xa.call(this,t,i);return typeof a?.schema!="object"?void 0:_p.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Sp.call(this,i),s===(0,Tt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new io({schema:a,schemaId:c,root:t,baseId:o})}return _p.call(this,r,i)}}yt.resolveSchema=Xa;var zN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _p(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Rb.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!zN.has(a)&&u&&(e=(0,Tt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Rb.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Xa.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new io({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Cb=R((H6,ON)=>{ON.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Rp=R((G6,$b)=>{"use strict";var NN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),kb=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),wp=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Eb=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),DN=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function bp(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var LN=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function xb(t){return t.length=0,!0}function jN(t,e,r){if(t.length){let n=bp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function UN(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=jN;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=xb}else{o.push(u);continue}}return o.length&&(a===xb?r.zone=o.join(""):i?n.push(o.join("")):n.push(bp(o))),r.address=n.join(""),r}function Tb(t){if(FN(t,":")<2)return{host:t,isIPV6:!1};let e=UN(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 FN(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function qN(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 HN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},GN=/[@/?#:]/g,ZN=/[@/?#]/g;function Ab(t,e){let r=e?ZN:GN;return r.lastIndex=0,t.replace(r,n=>HN[n])}function BN(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(wp(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Eb(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function VN(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(wp(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Eb(s)?e+=s:e+="%"+o,r+=2;continue}}DN(t[r])?e+=t[r]:e+=escape(t[r])}return e}function WN(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(wp(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function KN(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!kb(r)){let n=Tb(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Ab(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}$b.exports={nonSimpleDomain:LN,recomposeAuthority:KN,reescapeHostDelimiters:Ab,normalizePercentEncoding:BN,normalizePathEncoding:VN,escapePreservingEscapes:WN,removeDotSegments:qN,isIPv4:kb,isUUID:NN,normalizeIPv6:Tb,stringArrayToHexStripped:bp}});var Nb=R((Z6,Ob)=>{"use strict";var{isUUID:JN}=Rp(),YN=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,XN=["http","https","ws","wss","urn","urn:uuid"];function QN(t){return XN.indexOf(t)!==-1}function Pp(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 Mb(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ib(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 eD(t){return t.secure=Pp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function tD(t){if((t.port===(Pp(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 rD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(YN);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=Cp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function nD(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=Cp(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 oD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!JN(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function sD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var zb={scheme:"http",domainHost:!0,parse:Mb,serialize:Ib},iD={scheme:"https",domainHost:zb.domainHost,parse:Mb,serialize:Ib},ec={scheme:"ws",domainHost:!0,parse:eD,serialize:tD},aD={scheme:"wss",domainHost:ec.domainHost,parse:ec.parse,serialize:ec.serialize},cD={scheme:"urn",parse:rD,serialize:nD,skipNormalize:!0},uD={scheme:"urn:uuid",parse:oD,serialize:sD,skipNormalize:!0},tc={http:zb,https:iD,ws:ec,wss:aD,urn:cD,"urn:uuid":uD};Object.setPrototypeOf(tc,null);function Cp(t){return t&&(tc[t]||tc[t.toLowerCase()])||void 0}Ob.exports={wsIsSecure:Pp,SCHEMES:tc,isValidSchemeName:QN,getSchemeHandler:Cp}});var Fb=R((B6,oc)=>{"use strict";var{normalizeIPv6:dD,removeDotSegments:Ls,recomposeAuthority:lD,normalizePercentEncoding:pD,normalizePathEncoding:fD,escapePreservingEscapes:hD,reescapeHostDelimiters:mD,isIPv4:gD,nonSimpleDomain:yD}=Rp(),{SCHEMES:vD,getSchemeHandler:Lb}=Nb();function _D(t,e){return typeof t=="string"?t=xD(t,e):typeof t=="object"&&(t=nc(pn(t,e),e)),t}function SD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=rc(t,n),{parsed:i,malformedAuthorityOrPort:a}=rc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=jb(o,i,n,!0);return n.skipEscape=!0,pn(c,n)}function jb(t,e,r,n){let o={};return n||(t=nc(pn(t,r),r),e=nc(pn(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ls(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=Ls(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ls(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=Ls(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=Db(t,r),o=Db(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function pn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Lb(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=pD(r.path):(r.path=hD(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=Ls(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 bD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,RD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,PD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function CD(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function rc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(RD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(PD);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(bD);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=CD(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(gD(n.host)===!1){let p=dD(n.host);n.host=p.host.toLowerCase(),s=p.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=Lb(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&yD(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=mD(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 nc(t,e){return rc(t,e).parsed}function xD(t,e){return Ub(t,e).normalized}function Ub(t,e){let{parsed:r,malformedAuthorityOrPort:n}=rc(t,e);return{normalized:n?t:pn(r,e),malformedAuthorityOrPort:n}}function Db(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Ub(t,e);return n?void 0:r}if(typeof t=="object")return pn(t,e)}var xp={SCHEMES:vD,normalize:_D,resolve:SD,resolveComponent:jb,equal:wD,serialize:pn,parse:nc};oc.exports=xp;oc.exports.default=xp;oc.exports.fastUri=xp});var Hb=R(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var qb=Fb();qb.code='require("ajv/dist/runtime/uri").default';kp.default=qb});var Yb=R(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=void 0;var kD=Ns();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return kD.KeywordCxt}});var ao=D();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return ao._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return ao.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return ao.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return ao.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return ao.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return ao.CodeGen}});var ED=Ya(),Wb=Ds(),TD=tp(),js=Qa(),AD=D(),Us=Is(),sc=Ms(),Tp=H(),Gb=Cb(),$D=Hb(),Kb=(t,e)=>new RegExp(t,e);Kb.code="new RegExp";var MD=["removeAdditional","useDefaults","coerceTypes"],ID=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),zD={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."},OD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Zb=200;function ND(t){var e,r,n,o,s,i,a,c,u,d,l,p,f,h,m,y,S,w,b,k,_,P,z,ge,ye;let Ze=t.strict,Ao=(e=t.code)===null||e===void 0?void 0:e.optimize,Pi=Ao===!0||Ao===void 0?1:Ao||0,Ci=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Kb,dr=(o=t.uriResolver)!==null&&o!==void 0?o:$D.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&d!==void 0?d:"log",strictTuples:(p=(l=t.strictTuples)!==null&&l!==void 0?l:Ze)!==null&&p!==void 0?p:"log",strictRequired:(h=(f=t.strictRequired)!==null&&f!==void 0?f:Ze)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Pi,regExp:Ci}:{optimize:Pi,regExp:Ci},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:Zb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Zb,meta:(S=t.meta)!==null&&S!==void 0?S:!0,messages:(w=t.messages)!==null&&w!==void 0?w:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(_=t.addUsedSchema)!==null&&_!==void 0?_:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(z=t.validateFormats)!==null&&z!==void 0?z:!0,unicodeRegExp:(ge=t.unicodeRegExp)!==null&&ge!==void 0?ge:!0,int32range:(ye=t.int32range)!==null&&ye!==void 0?ye:!0,uriResolver:dr}}var Fs=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,...ND(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new AD.ValueScope({scope:{},prefixes:ID,es5:r,lines:n}),this.logger=qD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,TD.getRules)(),Bb.call(this,zD,e,"NOT SUPPORTED"),Bb.call(this,OD,e,"DEPRECATED","warn"),this._metaOpts=UD.call(this),e.formats&&LD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),DD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Gb;n==="id"&&(o={...Gb},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let p=this._addSchema(d,l);return p.validate||i.call(this,p)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof Wb.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Us.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Vb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new js.SchemaEnv({schema:{},schemaId:n});if(r=js.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=Vb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Us.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(GD.call(this,n,r),!r)return(0,Tp.eachItem)(n,s=>Ep.call(this,s)),this;BD.call(this,r);let o={...r,type:(0,sc.getJSONTypes)(r.type),schemaType:(0,sc.getJSONTypes)(r.schemaType)};return(0,Tp.eachItem)(n,o.type.length===0?s=>Ep.call(this,s,o):s=>o.type.forEach(i=>Ep.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]=Jb(d))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Us.normalizeId)(i||n);let u=Us.getSchemaRefs.call(this,e,n);return c=new js.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):js.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{js.compileSchema.call(this,e)}finally{this.opts=r}}};Fs.ValidationError=ED.default;Fs.MissingRefError=Wb.default;Me.default=Fs;function Bb(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 Vb(t){return t=(0,Us.normalizeId)(t),this.schemas[t]||this.refs[t]}function DD(){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 LD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function jD(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 UD(){let t={...this.opts};for(let e of MD)delete t[e];return t}var FD={log(){},warn(){},error(){}};function qD(t){if(t===!1)return FD;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 HD=/^[a-z_$][a-z0-9_$:-]*$/i;function GD(t,e){let{RULES:r}=this;if((0,Tp.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!HD.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 Ep(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,sc.getJSONTypes)(e.type),schemaType:(0,sc.getJSONTypes)(e.schemaType)}};e.before?ZD.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 ZD(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 BD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Jb(e)),t.validateSchema=this.compile(e,!0))}var VD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Jb(t){return{anyOf:[t,VD]}}});var Xb=R(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var WD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ap.default=WD});var rR=R(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.callRef=fn.getValidate=void 0;var KD=Ds(),Qb=gt(),tt=D(),co=sr(),eR=Qa(),ic=H(),JD={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=eR.resolveRef.call(c,u,o,r);if(d===void 0)throw new KD.default(n.opts.uriResolver,o,r);if(d instanceof eR.SchemaEnv)return p(d);return f(d);function l(){if(s===u)return ac(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return ac(t,(0,tt._)`${h}.validate`,u,u.$async)}function p(h){let m=tR(t,h);ac(t,m,h,h.$async)}function f(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,tt.stringify)(h)}:{ref:h}),y=e.name("valid"),S=t.subschema({schema:h,dataTypes:[],schemaPath:tt.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(S),t.ok(y)}}};function tR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,tt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}fn.getValidate=tR;function ac(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?co.default.this:tt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,tt._)`await ${(0,Qb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(h,!0)},m=>{o.if((0,tt._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,Qb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(h){let m=(0,tt._)`${h}.errors`;o.assign(co.default.vErrors,(0,tt._)`${co.default.vErrors} === null ? ${m} : ${co.default.vErrors}.concat(${m})`),o.assign(co.default.errors,(0,tt._)`${co.default.vErrors}.length`)}function f(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ic.mergeEvaluated.props(o,y.props,s.props));else{let S=o.var("props",(0,tt._)`${h}.evaluated.props`);s.props=ic.mergeEvaluated.props(o,S,s.props,tt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ic.mergeEvaluated.items(o,y.items,s.items));else{let S=o.var("items",(0,tt._)`${h}.evaluated.items`);s.items=ic.mergeEvaluated.items(o,S,s.items,tt.Name)}}}fn.callRef=ac;fn.default=JD});var nR=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var YD=Xb(),XD=rR(),QD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",YD.default,XD.default];$p.default=QD});var oR=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var cc=D(),zr=cc.operators,uc={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},eL={message:({keyword:t,schemaCode:e})=>(0,cc.str)`must be ${uc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cc._)`{comparison: ${uc[t].okStr}, limit: ${e}}`},tL={keyword:Object.keys(uc),type:"number",schemaType:"number",$data:!0,error:eL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,cc._)`${r} ${uc[e].fail} ${n} || isNaN(${r})`)}};Mp.default=tL});var sR=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var qs=D(),rL={message:({schemaCode:t})=>(0,qs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,qs._)`{multipleOf: ${t}}`},nL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:rL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,qs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,qs._)`${i} !== parseInt(${i})`;t.fail$data((0,qs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ip.default=nL});var aR=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});function iR(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}zp.default=iR;iR.code='require("ajv/dist/runtime/ucs2length").default'});var cR=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var hn=D(),oL=H(),sL=aR(),iL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,hn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,hn._)`{limit: ${t}}`},aL={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"?hn.operators.GT:hn.operators.LT,i=o.opts.unicode===!1?(0,hn._)`${r}.length`:(0,hn._)`${(0,oL.useFunc)(t.gen,sL.default)}(${r})`;t.fail$data((0,hn._)`${i} ${s} ${n}`)}};Op.default=aL});var uR=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var cL=gt(),uL=H(),uo=D(),dL={message:({schemaCode:t})=>(0,uo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,uo._)`{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,uo._)`new RegExp`:(0,uL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,uo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,uo._)`!${d}`)}else{let c=(0,cL.usePattern)(t,o);t.fail$data((0,uo._)`!${c}.test(${r})`)}}};Np.default=lL});var dR=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var Hs=D(),pL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Hs.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Hs._)`{limit: ${t}}`},fL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:pL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Hs.operators.GT:Hs.operators.LT;t.fail$data((0,Hs._)`Object.keys(${r}).length ${o} ${n}`)}};Dp.default=fL});var lR=R(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});var Gs=gt(),Zs=D(),hL=H(),mL={message:({params:{missingProperty:t}})=>(0,Zs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Zs._)`{missingProperty: ${t}}`},gL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:mL,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(f?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,S=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,hL.checkStrictMode)(i,S,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Zs.nil,l);else for(let f of r)(0,Gs.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>p(f,h)),t.ok(h)}else e.if((0,Gs.checkMissingProp)(t,r,f)),(0,Gs.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Gs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,h){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(h,(0,Gs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Zs.not)(h),()=>{t.error(),e.break()})},Zs.nil)}}};Lp.default=gL});var pR=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Bs=D(),yL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Bs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Bs._)`{limit: ${t}}`},vL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Bs.operators.GT:Bs.operators.LT;t.fail$data((0,Bs._)`${r}.length ${o} ${n}`)}};jp.default=vL});var dc=R(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});var fR=up();fR.code='require("ajv/dist/runtime/equal").default';Up.default=fR});var hR=R(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Fp=Ms(),Ie=D(),_L=H(),SL=dc(),wL={message:({params:{i:t,j:e}})=>(0,Ie.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ie._)`{i: ${t}, j: ${e}}`},bL={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,Fp.getSchemaTypes)(s.items):[];t.block$data(c,d,(0,Ie._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,Ie._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,Ie._)`${h} > 1`,()=>(l()?p:f)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function p(h,m){let y=e.name("item"),S=(0,Fp.checkDataTypes)(u,y,a.opts.strictNumbers,Fp.DataType.Wrong),w=e.const("indices",(0,Ie._)`{}`);e.for((0,Ie._)`;${h}--;`,()=>{e.let(y,(0,Ie._)`${r}[${h}]`),e.if(S,(0,Ie._)`continue`),u.length>1&&e.if((0,Ie._)`typeof ${y} == "string"`,(0,Ie._)`${y} += "_"`),e.if((0,Ie._)`typeof ${w}[${y}] == "number"`,()=>{e.assign(m,(0,Ie._)`${w}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ie._)`${w}[${y}] = ${h}`)})}function f(h,m){let y=(0,_L.useFunc)(e,SL.default),S=e.name("outer");e.label(S).for((0,Ie._)`;${h}--;`,()=>e.for((0,Ie._)`${m} = ${h}; ${m}--;`,()=>e.if((0,Ie._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(S)})))}}};qp.default=bL});var mR=R(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var Hp=D(),RL=H(),PL=dc(),CL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Hp._)`{allowedValue: ${t}}`},xL={keyword:"const",$data:!0,error:CL,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Hp._)`!${(0,RL.useFunc)(e,PL.default)}(${r}, ${o})`):t.fail((0,Hp._)`${s} !== ${r}`)}};Gp.default=xL});var gR=R(Zp=>{"use strict";Object.defineProperty(Zp,"__esModule",{value:!0});var Vs=D(),kL=H(),EL=dc(),TL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vs._)`{allowedValues: ${t}}`},AL={keyword:"enum",schemaType:"array",$data:!0,error:TL,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,kL.useFunc)(e,EL.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);d=(0,Vs.or)(...o.map((h,m)=>p(f,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,f=>e.if((0,Vs._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function p(f,h){let m=o[h];return typeof m=="object"&&m!==null?(0,Vs._)`${u()}(${r}, ${f}[${h}])`:(0,Vs._)`${r} === ${m}`}}};Zp.default=AL});var yR=R(Bp=>{"use strict";Object.defineProperty(Bp,"__esModule",{value:!0});var $L=oR(),ML=sR(),IL=cR(),zL=uR(),OL=dR(),NL=lR(),DL=pR(),LL=hR(),jL=mR(),UL=gR(),FL=[$L.default,ML.default,IL.default,zL.default,OL.default,NL.default,DL.default,LL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},jL.default,UL.default];Bp.default=FL});var Wp=R(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.validateAdditionalItems=void 0;var mn=D(),Vp=H(),qL={message:({params:{len:t}})=>(0,mn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,mn._)`{limit: ${t}}`},HL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:qL,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Vp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}vR(t,n)}};function vR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,mn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,mn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Vp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,mn._)`${a} <= ${e.length}`);r.if((0,mn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:Vp.Type.Num},u),i.allErrors||r.if((0,mn.not)(u),()=>r.break())})}}Ws.validateAdditionalItems=vR;Ws.default=HL});var Kp=R(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.validateTuple=void 0;var _R=D(),lc=H(),GL=gt(),ZL={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return SR(t,"additionalItems",e);r.items=!0,!(0,lc.alwaysValidSchema)(r,e)&&t.ok((0,GL.validateArray)(t))}};function SR(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;d(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=lc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,_R._)`${s}.length`);r.forEach((l,p)=>{(0,lc.alwaysValidSchema)(a,l)||(n.if((0,_R._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function d(l){let{opts:p,errSchemaPath:f}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(p.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,lc.checkStrictMode)(a,y,p.strictTuples)}}}Ks.validateTuple=SR;Ks.default=ZL});var wR=R(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});var BL=Kp(),VL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,BL.validateTuple)(t,"items")};Jp.default=VL});var RR=R(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var bR=D(),WL=H(),KL=gt(),JL=Wp(),YL={message:({params:{len:t}})=>(0,bR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,bR._)`{limit: ${t}}`},XL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:YL,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,WL.alwaysValidSchema)(n,e)&&(o?(0,JL.validateAdditionalItems)(t,o):t.ok((0,KL.validateArray)(t)))}};Yp.default=XL});var PR=R(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var vt=D(),pc=H(),QL={message:({params:{min:t,max:e}})=>e===void 0?(0,vt.str)`must contain at least ${t} valid item(s)`:(0,vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vt._)`{minContains: ${t}}`:(0,vt._)`{minContains: ${t}, maxContains: ${e}}`},ej={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:QL,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,vt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pc.alwaysValidSchema)(s,r)){let m=(0,vt._)`${d} >= ${i}`;a!==void 0&&(m=(0,vt._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,vt._)`${o}.length > 0`,p)):(e.let(l,!1),p()),t.result(l,()=>t.reset());function p(){let m=e.name("_valid"),y=e.let("count",0);f(m,()=>e.if(m,()=>h(y)))}function f(m,y){e.forRange("i",0,d,S=>{t.subschema({keyword:"contains",dataProp:S,dataPropType:pc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,vt._)`${m}++`),a===void 0?e.if((0,vt._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,vt._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,vt._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};Xp.default=ej});var kR=R(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateSchemaDeps=Gt.validatePropertyDeps=Gt.error=void 0;var Qp=D(),tj=H(),Js=gt();Gt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Qp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Qp._)`{property: ${t},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${e},
8
- deps: ${r}}`};var KL={keyword:"dependencies",type:"object",schemaType:"object",error:Gt.error,code(t){let[e,r]=JL(t);SR(t,e),wR(t,r)}};function JL({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 SR(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,Ks.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,Ks.checkReportMissingProp)(t,u)}):(r.if((0,Xp._)`${c} && (${(0,Ks.checkMissingProp)(t,a,s)})`),(0,Ks.reportMissingProp)(t,s),r.else())}}Gt.validatePropertyDeps=SR;function wR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,WL.alwaysValidSchema)(s,e[a])||(r.if((0,Ks.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Gt.validateSchemaDeps=wR;Gt.default=KL});var PR=R(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var RR=D(),YL=H(),XL={message:"property name must be valid",params:({params:t})=>(0,RR._)`{propertyName: ${t.propertyName}}`},QL={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XL,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,YL.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,RR.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Qp.default=QL});var tf=R(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var pc=gt(),At=D(),ej=sr(),fc=H(),tj={message:"must NOT have additional properties",params:({params:t})=>(0,At._)`{additionalProperty: ${t.additionalProperty}}`},rj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:tj,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,fc.alwaysValidSchema)(i,r))return;let u=(0,pc.allSchemaProperties)(n.properties),d=(0,pc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,At._)`${s} === ${ej.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let w=(0,fc.schemaRefOrVal)(i,n.properties,"properties");S=(0,pc.isOwnProperty)(e,w,y)}else u.length?S=(0,At.or)(...u.map(w=>(0,At._)`${y} === ${w}`)):S=At.nil;return d.length&&(S=(0,At.or)(S,...d.map(w=>(0,At._)`${(0,pc.usePattern)(t,w)}.test(${y})`))),(0,At.not)(S)}function f(y){e.code((0,At._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,fc.alwaysValidSchema)(i,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,At.not)(S),()=>{t.reset(),f(y)})):(m(y,S),a||e.if((0,At.not)(S),()=>e.break()))}}function m(y,S,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:fc.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,S)}}};ef.default=rj});var kR=R(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var nj=Os(),CR=gt(),rf=H(),xR=tf(),oj={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&&xR.default.code(new nj.KeywordCxt(s,xR.default,"additionalProperties"));let i=(0,CR.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=rf.mergeEvaluated.props(e,(0,rf.toHash)(i),s.props));let a=i.filter(l=>!(0,rf.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,CR.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)}}};nf.default=oj});var $R=R(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var ER=gt(),hc=D(),TR=H(),AR=H(),sj={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,ER.allSchemaProperties)(r),c=a.filter(m=>(0,TR.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 hc.Name)&&(s.props=(0,AR.evaluatedPropsToName)(e,s.props));let{props:l}=s;p();function p(){for(let m of a)u&&f(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function f(m){for(let y in u)new RegExp(m).test(y)&&(0,TR.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,hc._)`${(0,ER.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:AR.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,hc._)`${l}[${y}]`,!0):!S&&!s.allErrors&&e.if((0,hc.not)(d),()=>e.break())})})}}};of.default=sj});var MR=R(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var ij=H(),aj={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,ij.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"}};sf.default=aj});var IR=R(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var cj=gt(),uj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:cj.validateUnion,error:{message:"must match a schema in anyOf"}};af.default=uj});var zR=R(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var mc=D(),dj=H(),lj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,mc._)`{passingSchemas: ${t.passing}}`},pj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:lj,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let p;(0,dj.alwaysValidSchema)(o,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,mc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,mc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,mc.Name)})})}}};cf.default=pj});var OR=R(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var fj=H(),hj={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,fj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};uf.default=hj});var LR=R(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var gc=D(),DR=H(),mj={message:({params:t})=>(0,gc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,gc._)`{failingKeyword: ${t.ifClause}}`},gj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:mj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,DR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=NR(n,"then"),s=NR(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,gc.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,gc._)`${d}`):t.setParams({ifClause:d})}}}};function NR(t,e){let r=t.schema[e];return r!==void 0&&!(0,DR.alwaysValidSchema)(t,r)}df.default=gj});var jR=R(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var yj=H(),vj={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`)}};lf.default=vj});var UR=R(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var _j=Bp(),Sj=gR(),wj=Wp(),bj=vR(),Rj=_R(),Pj=bR(),Cj=PR(),xj=tf(),kj=kR(),Ej=$R(),Tj=MR(),Aj=IR(),$j=zR(),Mj=OR(),Ij=LR(),zj=jR();function Oj(t=!1){let e=[Tj.default,Aj.default,$j.default,Mj.default,Ij.default,zj.default,Cj.default,xj.default,Pj.default,kj.default,Ej.default];return t?e.push(Sj.default,bj.default):e.push(_j.default,wj.default),e.push(Rj.default),e}pf.default=Oj});var FR=R(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var _e=D(),Nj={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},Dj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Nj,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(S,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(S,m)),t.fail$data((0,_e.or)(w(),b()));function w(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${S}`}function b(){let k=d.$async?(0,_e._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,_e._)`${S}(${n})`,_=(0,_e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,_e._)`${S} && ${S} !== true && ${y} === ${e} && !${_}`}}function f(){let h=l.formats[s];if(!h){w();return}if(h===!0)return;let[m,y,S]=b(h);m===e&&t.pass(k());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(_){let P=_ instanceof RegExp?(0,_e.regexpCode)(_):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,z=r.scopeValue("formats",{key:s,ref:_,code:P});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,_e._)`${z}.validate`]:["string",_,z]}function k(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${S}(${n})`}return typeof y=="function"?(0,_e._)`${S}(${n})`:(0,_e._)`${S}.test(${n})`}}}};ff.default=Dj});var qR=R(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Lj=FR(),jj=[Lj.default];hf.default=jj});var HR=R(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.contentVocabulary=uo.metadataVocabulary=void 0;uo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];uo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var ZR=R(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var Uj=Xb(),Fj=pR(),qj=UR(),Hj=qR(),GR=HR(),Gj=[Uj.default,Fj.default,(0,qj.default)(),Hj.default,GR.metadataVocabulary,GR.contentVocabulary];mf.default=Gj});var BR=R(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.DiscrError=void 0;var VR;(function(t){t.Tag="tag",t.Mapping="mapping"})(VR||(yc.DiscrError=VR={}))});var KR=R(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var lo=D(),gf=BR(),WR=Xa(),Zj=Ns(),Vj=H(),Bj={message:({params:{discrError:t,tagName:e}})=>t===gf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Wj={keyword:"discriminator",type:"object",schemaType:"object",error:Bj,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,lo._)`${r}${(0,lo.getProperty)(a)}`);e.if((0,lo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:gf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,lo._)`${u} === ${h}`),e.assign(c,l(f[h]));e.else(),t.error(!1,{discrError:gf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(m,lo.Name),h}function p(){var f;let h={},m=S(o),y=!0;for(let k=0;k<i.length;k++){let _=i[k];if(_?.$ref&&!(0,Vj.schemaHasRulesButRef)(_,s.self.RULES)){let z=_.$ref;if(_=WR.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,z),_ instanceof WR.SchemaEnv&&(_=_.schema),_===void 0)throw new Zj.default(s.opts.uriResolver,s.baseId,z)}let P=(f=_?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||S(_)),w(P,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:k}){return Array.isArray(k)&&k.includes(a)}function w(k,_){if(k.const)b(k.const,_);else if(k.enum)for(let P of k.enum)b(P,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(k,_){if(typeof k!="string"||k in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[k]=_}}}};yf.default=Wj});var JR=R((PJ,Kj)=>{Kj.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 _f=R((de,vf)=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.MissingRefError=de.ValidationError=de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=de.Ajv=void 0;var Jj=Vb(),Yj=ZR(),Xj=KR(),YR=JR(),Qj=["/properties"],vc="http://json-schema.org/draft-07/schema",po=class extends Jj.default{_addVocabularies(){super._addVocabularies(),Yj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Xj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(YR,Qj):YR;this.addMetaSchema(e,vc,!1),this.refs["http://json-schema.org/schema"]=vc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(vc)?vc:void 0)}};de.Ajv=po;vf.exports=de=po;vf.exports.Ajv=po;Object.defineProperty(de,"__esModule",{value:!0});de.default=po;var e1=Os();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return e1.KeywordCxt}});var fo=D();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return fo._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return fo.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return fo.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return fo.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return fo.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return fo.CodeGen}});var t1=Ja();Object.defineProperty(de,"ValidationError",{enumerable:!0,get:function(){return t1.default}});var r1=Ns();Object.defineProperty(de,"MissingRefError",{enumerable:!0,get:function(){return r1.default}})});var sP=R(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.formatNames=Vt.fastFormats=Vt.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Vt.fullFormats={date:Zt(tP,Rf),time:Zt(wf(!0),Pf),"date-time":Zt(XR(!0),nP),"iso-time":Zt(wf(),rP),"iso-date-time":Zt(XR(),oP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:c1,"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:m1,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:u1,int32:{type:"number",validate:p1},int64:{type:"number",validate:f1},float:{type:"number",validate:eP},double:{type:"number",validate:eP},password:!0,binary:!0};Vt.fastFormats={...Vt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Rf),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Pf),"date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nP),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,rP),"iso-date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,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};Vt.formatNames=Object.keys(Vt.fullFormats);function n1(t){return t%4===0&&(t%100!==0||t%400===0)}var o1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,s1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function tP(t){let e=o1.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&&n1(r)?29:s1[n])}function Rf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function wf(t){return function(r){let n=Sf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Pf(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 rP(t,e){if(!(t&&e))return;let r=Sf.exec(t),n=Sf.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 bf=/t|\s/i;function XR(t){let e=wf(t);return function(n){let o=n.split(bf);return o.length===2&&tP(o[0])&&e(o[1])}}function nP(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(bf),[o,s]=e.split(bf),i=Rf(r,o);if(i!==void 0)return i||Pf(n,s)}var i1=/\/|:/,a1=/^(?:[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 c1(t){return i1.test(t)&&a1.test(t)}var QR=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function u1(t){return QR.lastIndex=0,QR.test(t)}var d1=-(2**31),l1=2**31-1;function p1(t){return Number.isInteger(t)&&t<=l1&&t>=d1}function f1(t){return Number.isInteger(t)}function eP(){return!0}var h1=/[^\\]\\Z/;function m1(t){if(h1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var iP=R(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.formatLimitDefinition=void 0;var g1=_f(),$t=D(),zr=$t.operators,_c={formatMaximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},formatMinimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},formatExclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},formatExclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},y1={message:({keyword:t,schemaCode:e})=>(0,$t.str)`should be ${_c[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$t._)`{comparison: ${_c[t].okStr}, limit: ${e}}`};ho.formatLimitDefinition={keyword:Object.keys(_c),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 g1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,$t._)`${p}[${c.schemaCode}]`);t.fail$data((0,$t.or)((0,$t._)`typeof ${f} != "object"`,(0,$t._)`${f} instanceof RegExp`,(0,$t._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(p)}`:void 0});t.fail$data(l(h))}function l(p){return(0,$t._)`${p}.compare(${r}, ${n}) ${_c[o].fail} 0`}},dependencies:["format"]};var v1=t=>(t.addKeyword(ho.formatLimitDefinition),t);ho.default=v1});var dP=R((Js,uP)=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});var mo=sP(),_1=iP(),Cf=D(),aP=new Cf.Name("fullFormats"),S1=new Cf.Name("fastFormats"),xf=(t,e={keywords:!0})=>{if(Array.isArray(e))return cP(t,e,mo.fullFormats,aP),t;let[r,n]=e.mode==="fast"?[mo.fastFormats,S1]:[mo.fullFormats,aP],o=e.formats||mo.formatNames;return cP(t,o,r,n),e.keywords&&(0,_1.default)(t),t};xf.get=(t,e="full")=>{let n=(e==="fast"?mo.fastFormats:mo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function cP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Cf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}uP.exports=Js=xf;Object.defineProperty(Js,"__esModule",{value:!0});Js.default=xf});var jP=R((i5,LP)=>{LP.exports=DP;DP.sync=X1;var OP=lr("fs");function Y1(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 NP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:Y1(e,r)}function DP(t,e,r){OP.stat(t,function(n,o){r(n,n?!1:NP(o,t,e))})}function X1(t,e){return NP(OP.statSync(t),t,e)}});var GP=R((a5,HP)=>{HP.exports=FP;FP.sync=Q1;var UP=lr("fs");function FP(t,e,r){UP.stat(t,function(n,o){r(n,n?!1:qP(o,e))})}function Q1(t,e){return qP(UP.statSync(t),e)}function qP(t,e){return t.isFile()&&eU(t,e)}function eU(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 VP=R((u5,ZP)=>{var c5=lr("fs"),Ac;process.platform==="win32"||global.TESTING_WINDOWS?Ac=jP():Ac=GP();ZP.exports=Zf;Zf.sync=tU;function Zf(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){Zf(t,e||{},function(s,i){s?o(s):n(i)})})}Ac(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function tU(t,e){try{return Ac.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var QP=R((d5,XP)=>{var Ro=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",BP=lr("path"),rU=Ro?";":":",WP=VP(),KP=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),JP=(t,e)=>{let r=e.colon||rU,n=t.match(/\//)||Ro&&t.match(/\\/)?[""]:[...Ro?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Ro?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Ro?o.split(r):[""];return Ro&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},YP=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=JP(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(KP(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=BP.join(f,t),m=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((p,f)=>{if(l===o.length)return p(a(d+1));let h=o[l];WP(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return p(u+h);return p(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},nU=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=JP(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=BP.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let p=d+n[l];try{if(WP.sync(p,{pathExt:o}))if(e.all)s.push(p);else return p}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw KP(t)};XP.exports=YP;YP.sync=nU});var tC=R((l5,Vf)=>{"use strict";var eC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Vf.exports=eC;Vf.exports.default=eC});var sC=R((p5,oC)=>{"use strict";var rC=lr("path"),oU=QP(),sU=tC();function nC(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=oU.sync(t.command,{path:r[sU({env:r})],pathExt:e?rC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=rC.resolve(o?t.options.cwd:"",i)),i}function iU(t){return nC(t)||nC(t,!0)}oC.exports=iU});var iC=R((f5,Wf)=>{"use strict";var Bf=/([()\][%!^"`<>&|;, *?])/g;function aU(t){return t=t.replace(Bf,"^$1"),t}function cU(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Bf,"^$1"),e&&(t=t.replace(Bf,"^$1")),t}Wf.exports.command=aU;Wf.exports.argument=cU});var cC=R((h5,aC)=>{"use strict";aC.exports=/^#!(.*)/});var dC=R((m5,uC)=>{"use strict";var uU=cC();uC.exports=(t="")=>{let e=t.match(uU);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var pC=R((g5,lC)=>{"use strict";var Kf=lr("fs"),dU=dC();function lU(t){let r=Buffer.alloc(150),n;try{n=Kf.openSync(t,"r"),Kf.readSync(n,r,0,150,0),Kf.closeSync(n)}catch{}return dU(r.toString())}lC.exports=lU});var gC=R((y5,mC)=>{"use strict";var pU=lr("path"),fC=sC(),hC=iC(),fU=pC(),hU=process.platform==="win32",mU=/\.(?:com|exe)$/i,gU=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function yU(t){t.file=fC(t);let e=t.file&&fU(t.file);return e?(t.args.unshift(t.file),t.command=e,fC(t)):t.file}function vU(t){if(!hU)return t;let e=yU(t),r=!mU.test(e);if(t.options.forceShell||r){let n=gU.test(e);t.command=pU.normalize(t.command),t.command=hC.command(t.command),t.args=t.args.map(s=>hC.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 _U(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:vU(n)}mC.exports=_U});var _C=R((v5,vC)=>{"use strict";var Jf=process.platform==="win32";function Yf(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 SU(t,e){if(!Jf)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=yC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function yC(t,e){return Jf&&t===1&&!e.file?Yf(e.original,"spawn"):null}function wU(t,e){return Jf&&t===1&&!e.file?Yf(e.original,"spawnSync"):null}vC.exports={hookChildProcess:SU,verifyENOENT:yC,verifyENOENTSync:wU,notFoundError:Yf}});var bC=R((_5,Po)=>{"use strict";var SC=lr("child_process"),Xf=gC(),Qf=_C();function wC(t,e,r){let n=Xf(t,e,r),o=SC.spawn(n.command,n.args,n.options);return Qf.hookChildProcess(o,n),o}function bU(t,e,r){let n=Xf(t,e,r),o=SC.spawnSync(n.command,n.args,n.options);return o.error=o.error||Qf.verifyENOENTSync(o.status,n),o}Po.exports=wC;Po.exports.spawn=wC;Po.exports.sync=bU;Po.exports._parse=Xf;Po.exports._enoent=Qf});var EC=R(th=>{"use strict";var CC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,kU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,xC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,EU=/\\([\u000b\u0020-\u00ff])/g,TU=/([\\"])/g,kC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;th.format=AU;th.parse=$U;function AU(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!kC.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],!xC.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+IU(e[o])}return n}function $U(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?MU(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(!kC.test(n))throw new TypeError("invalid media type");var o=new zU(n.toLowerCase());if(r!==-1){var s,i,a;for(CC.lastIndex=r;i=CC.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(EU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function MU(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 IU(t){var e=String(t);if(xC.test(e))return e;if(e.length>0&&!kU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(TU,"\\$1")+'"'}function zU(t){this.parameters=Object.create(null),this.type=t}});import{logger as GG}from"@hermes/logger";import{logger as QF}from"@hermes/logger";var Xk="mcp-auth";function Oe(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(Xk,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as TF}from"@augmentcode/auggie-v2";import{logger as AF}from"@hermes/logger";import{logger as SE}from"@hermes/logger";import{logger as eE}from"@hermes/logger";function Qk(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 pr(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":Qk(t,e,r)?"plugin":"local"}function tE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var Uh=eE.child({prefix:"pi-mcp"}),rE="augment:mcp-status-report";function fr(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 xi(t,e,r,n){let o=fr(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=fr(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=fr(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 ki=3e4;function oE(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>=ki?"failed":void 0}default:return}}var Fh="authentication required",sE="Authentication refresh is pending in the backend; retry shortly.",iE="timed out connecting after 30s",aE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",cE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",uE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).";function dE(t,e){let r=new Set;for(let i of t.servers.values())i.config.id!==void 0&&r.add(i.config.id);let n=new Set(e.map(i=>i.mcpConfigId).filter(i=>i!==void 0)),o=new Set(e.map(i=>i.name)),s=i=>t.registryConfigNamesById.get(i)??i;for(let i of t.failedAddConfigIds){if(r.has(i)||n.has(i))continue;let a=s(i);n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(i)?cE:aE,mcpConfigId:i,dynamicallyAdded:!0})}for(let i of t.selectedRegistryConfigIds??[]){if(r.has(i)||n.has(i)||t.sessionRemovedConfigIds.has(i))continue;let a=s(i);o.has(a)||(n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:uE,mcpConfigId:i}))}}function lE(t,e){return e!==void 0?e.isAuthError?Fh:e.error:t.status==="initializing"?iE:t.lastError??(t.status==="auth_required"?Fh:void 0)}function pE(t,e){let r=oE(t);if(r===void 0)return;let n=nE(e,t.name),o=r==="connected"?tE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:pr(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"?sE: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=pE(r,t);n!==void 0&&e.push(n)}return dE(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(rE,o),Uh.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){Uh.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Ei={local:4,registry:3,plugin:2,vfs:1};function Ot(t){return t.hostLeases??=new Map,t.hostLeases}function hE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Ao(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function $o(t,e){return t.kind===e.kind&&t.identity===e.identity}function qh(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 iu(t,e){let r=hE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Ti(t,e,r){if(r.kind==="registry"){Ao(t).set(e,{kind:"domain",domain:r.identity});return}Ao(t).set(e,{kind:"blocked"})}function au(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 kn(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=Ot(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?kn(i,s):{kind:s??"local",identity:e},c={owner:a,revision:iu(t,e),host:r};return n.set(e,c),Ti(t,e,a),c}function Hh(t){let{state:e,name:r,host:n}=t,o=Ot(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:iu(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),Ti(e,r,i.owner),i}function Mo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Ot(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Ei[n.kind]>Ei[a.owner.kind],p=Ei[n.kind]===Ei[a.owner.kind],f=o===a.revision&&(s===void 0||s===a.host);if(!(l||p&&f))return}let c=a?.host,u=a?qh(a):void 0;au(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:iu(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),Ti(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function cu(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=Ot(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Ao(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function Ai(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e).get(r);return!i||i.revision!==o||!$o(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 wt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e).get(r);if(!i||i.revision!==o||!$o(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=qh(i);if(a)return au(e,r,s),i.host=void 0,i.retirement=a,a}function Gh(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Ot(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!$o(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!$o(i.owner,n)||i.revision!==o.incumbent.revision?(Ti(e,r,i.owner),!0):(s.delete(r),Ao(e).set(r,{kind:"blocked"}),!0))}function be(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e),a=i.get(r);return!a||a.revision!==o||!$o(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(au(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),Ao(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return Ot(t).get(e)}function Zh(t,e,r){return Ot(t).get(e)?.host===r}function Io(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function hr(t){if(!(t.type!=="http"&&t.type!=="sse"||t.auth!=="oauth"))return{id:t.id,name:t.name,type:t.type,url:t.url,auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Ve(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 uu(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function mE(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 gE(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!Ve(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function Vh(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!uu(e,r):n!==void 0&&e!==n}function Bh(t,e,r){return r&&e!==void 0&&t!==void 0&&uu(t,e)}function yE(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!uu(s,n))}function Wh(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(gE({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||Vh({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&Vh({identity:i.domain,...l})?!0:yE({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function vE(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return hr(r);if(n!==void 0)return{id:n,name:e}}function _E(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!hr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function Kh(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=mE({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,p=Wh({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),f=Bh(s,u,d),h=Bh(i,u,d),m=!p,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,w=p&&!(m||f||h||y);if(o==="durable"){let P=vE({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:w})}let b=Wh({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),k=m&&!b,_=!1;return t.equalRevisionRebindDomains?.delete(e),(k||f)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),_=!0),(k||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),_=!0),k&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),_E({state:t,name:e,mode:o,stillOwnsNameScopedRevision:k,retiredConfig:c}),_&&(Io(t,e),ot(t,e),t.authRefreshNeededReportKeys?.delete(e)),k}function ct(t,e,r,n){return Kh(t,e,r,n,"durable")}function zo(t,e,r,n){return Kh(t,e,r,n,"session")}function mr(t,e){let r=t.replace(/^0+(?=\d)/,""),n=e.replace(/^0+(?=\d)/,"");return r.length!==n.length?r.length<n.length?-1:1:r===n?0:r<n?-1:1}var Jh="augment:mcp-oauth-credentials",Yh=300*1e3,wE=256,Xh=SE.child({prefix:"pi-mcp"}),bt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function We(t){return`user:${t}`}function jr(t){let{state:e,name:r,revision:n}=t;if(e.credentialRevisions??=new Map,e.oauthCredentialRevisions??=new Map,e.oauthCredentialDomains??=new Map,e.hostedCredentialOwnership?.delete(r),n===void 0){e.credentialRevisions.delete(r),e.oauthCredentialDomains.delete(r),e.authRefreshNeededReportKeys?.delete(r);return}let o={...n,revision:n.revision.replace(/^0+(?=\d)/,"")},s=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(s?.revision!==o.revision||s?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let i=e.oauthCredentialRevisions.get(o.domain);(i===void 0||mr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function ut(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="user"&&r!=="tenant"?t:We(t.slice(e+1))}function bE(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function RE(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 PE(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function CE(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&bE(t.credentialRevisions.get(e),r.credentialRevision)&&PE(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function xE(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 kE(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??"")||!Ve(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Ur(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function Lr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function Qh(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=Yh&&Lr(t,n)}function EE(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&Lr(t,e)}function em(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Ur(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();Qh(e,a);let c=ut(n.domain),u=i.get(c),d=u?.credential.credential_revision??u?.credential.credentialRevision;if(typeof d=="string"&&mr(n.revision,d)<=0)return;!u&&i.size>=wE&&EE(e),Lr(e,c);let l={credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(c,l),l.expiryTimer=setTimeout(()=>{i.get(c)===l&&Lr(e,c)},Yh),l.expiryTimer.unref?.(),Xh.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function TE(t,e){Ur(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;Ur(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||Lr(e,r)}}function $i(t){let{state:e,domain:r,forceNew:n=!1}=t;Ur(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let s=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Be({state:e,domain:r,epoch:o.epoch});let i={epoch:TE(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 tm(t,e){Ur(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()??[])e.has(r)||Lr(t,r);for(let r of e){let n=t.registryCredentialIntents.get(r);$i({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function AE(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;Ur(e);let n=We(r.id),o=xE(r),s=kE({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=$i({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),$E({state:e,config:r,domain:n}),{domain:n,...i}}function rm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Ur(e);let s=ut(r.domain),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:mr(r.revision,a),p=l===0;l!==void 0&&l<0||p&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&mr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:p})}function $E(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n}),(o===void 0||ut(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),ot(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function ME(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(Jh,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function IE(t){let{state:e,domain:r}=t,n=Date.now();Qh(e,n);let o=e.bootOAuthCredentialBuffer?.get(r);return Lr(e,r),o}function zE(t){let{config:e,pi:r,buffered:n}=t;Xh.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`);let o={[e.name]:n.credential};r.events.emit(Jh,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function OE(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(Ve(n,r)){if(n.name===r.name)return;await zo(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await ct(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function NE(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=CE(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 bt(a)}async function DE(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 OE({state:e,config:r,previousConfig:s})}catch(h){throw NE({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 p={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,p),e.registryCredentialConfigsById.set(l,p),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),ME({state:e,config:r,pi:n,intent:o});let f=IE({state:e,domain:o.domain});return Be({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),f&&zE({config:r,pi:n,buffered:f}),!0}function Fr(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=AE({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=RE(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 DE({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 XE}from"@augmentcode/auggie-v2";import{homedir as nm}from"node:os";import{sep as LE}from"node:path";var du=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},jE=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,UE=/\\\$\{/g,FE=new Set(["workspaceFolder","augmentToken"]),om="${workspaceFolder}";function sm(t,e){return t.includes(om)?t.split(om).join(e):t}function im(t,e){return t.includes("${")?t.replace(jE,(n,o,s)=>{if(FE.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new du(o)}).replace(UE,"${"):t}function qE(t){return t.startsWith("~")?t==="~"?nm():t.startsWith("~/")||t.startsWith(`~${LE}`)?nm()+t.slice(1):t:t}function lu(t,e,r){return qE(im(sm(t,e),r))}function Mi(t,e,r){return im(sm(t,e),r)}function am(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Mi(s,e,r);return n}var HE="$augment-";function GE(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(HE)?s:Mi(s,e,r);return n}function Nt(t,e){let r=process.env;return{...t,url:Mi(t.url,e,r),headers:GE(t.headers,e,r)}}function Dt(t,e){let r=process.env;return{...t,command:lu(t.command,e,r),args:t.args,env:t.env?am(t.env,e,r):void 0,cwd:t.cwd?lu(t.cwd,e,r):e}}import{readFileSync as WE}from"node:fs";import{logger as ZE}from"@hermes/logger";var VE=ZE.child({prefix:"pi-mcp"}),Rt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function En(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 BE(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 Tn(t,e){let r=En(e);if(!r)throw new Rt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Rt(`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 Rt(`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&&VE.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:BE(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var dm=t=>WE(t,"utf8");function Ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function cm(t){return Ii(t)&&("command"in t||"url"in t)}function fu(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function um(t,e){return fu(t.name)??e}function pu(t,e){let r=En(t);if(r==="http"||r==="sse")return fu(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return fu(t.name,t.title,n)??e}function KE(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[pu(n,String(r)),n]});if(Ii(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[pu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(Ii(n))return Object.entries(n).map(([o,s])=>{let i=s;return[um(i,o),i]})}if(cm(t)){let r=t;return[[pu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(cm))return Object.entries(t).map(([r,n])=>{if(!Ii(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[um(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 hu(t){return t instanceof Error?t.message:String(t)}function JE(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}": ${hu(s)}`});return}}function YE(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=JE(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}: ${hu(c)}`}),[]}try{return KE(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${hu(c)}`}),[]}}function mu(t,e=dm){let r={},n=[];for(let o of t)for(let[s,i]of YE(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function gu(t,e=dm){return!t||t.length===0?new Set:new Set(Object.keys(mu(t,e).servers))}var QE=["global","project","local","managed"];function eT(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 tT(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 rT(t,e,r){let n=mu(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 nT(t,e,r){let n=XE.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 tT(QE.map(o=>eT(n,o)))}function An(t,e,r,n){let o=[],s=r&&r.length>0?rT(r,n,o):nT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Tn(a,c);i.push(u.type==="stdio"?Dt(u,t):Nt(u,t))}catch(u){let d=u instanceof Rt?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 fm}from"@augmentcode/auggie-v2";import{logger as hT}from"@hermes/logger";import{Type as mT}from"@sinclair/typebox";var $n=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;get(e){return this._tokens.get(e)}commit(e,r){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e)}set(e,r,n){this.commit(e,r)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,s){return this.persist(e,n,o)}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,s)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations)}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n)}delete(e,r){this._tokens.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};var zi=Symbol.for("__pi_mcp_state__");function oT(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 sT(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&&oT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&sT(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 aT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&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 Oo(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 Oi(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 cT(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 lm(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Ni(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()?cT({state:e,configId:r,generation:n}):lm({state:e,configId:r,generation:n}),i),i=>{throw lm({state:e,configId:r,generation:n}),i})}function se(){let t=globalThis;if(t[zi])return aT(t[zi]),t[zi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new $n,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:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1};return t[zi]=e,e}function Di(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 uT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function dT(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 lT(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
- `).trim()}function yu(t,e,r){if(t.isError){let o=lT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=dT(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 pm(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Di(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=uT(t.params),o=await e.callTool(r,n,t.signal);return yu(o,t.serverName,r)}var pT=/[^a-zA-Z0-9_-]/g;function vu(t){return t.replace(pT,"_")}function fT(t,e){let r=vu(e),n=vu(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var gr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=fT(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=`_${vu(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var _u=hT.child({prefix:"pi-mcp"});function Li(){return se().toolRegistrationsByPi}function hm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=mT.Unsafe(n.inputSchema??{})}catch(c){_u.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>se().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,p)=>pm({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(f=>f.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function Su(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n);e.ownerByToolName.delete(n),t.unregisterTool(n),gT(t,e,n,r,o)}function gT(t,e,r,n,o){let s=se();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 gr(i);for(let d of c.listTools()){let{namespaced:l,collision:p}=u.put(d.name);if(p||l!==r)continue;let f=hm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!f)return;fm(r,"mcp"),t.registerTool(f),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function yT(t,e){let r=Li(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=se().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)Su(t,n,s,a);let i={generation:o,host:e,map:new gr(e.name),registeredNames:new Set};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function wu(t,e){let{registration:r,replaced:n}=yT(t,e),o=new Set(r.registeredNames),s=new gr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:p}=s.put(d.name);if(p){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=se();y.diagnostics.some(w=>w.server===i&&w.message.includes(`both map to "${l}"`))||(_u.warn(m),y.diagnostics.push({server:i,message:m}));continue}let f=hm({pi:t,serverName:i,tool:d,map:s,namespaced:l});f&&(fm(l,"mcp"),t.registerTool(f),Li().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Li().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&Su(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&_u.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function bu(t,e,r){let n=Li().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)Su(t,n,o,s);return n.byServer.delete(e.name),!0}function mm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&wu(t,r)}import{getToolSource as ET}from"@augmentcode/auggie-v2";import{Type as vT}from"@sinclair/typebox";var _T="cliMcpToolSearchAutoEnable",ST="cliMcpToolSearchTokenThreshold",wT=!1,gm=2e4;function bT(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function RT(t){let e=0;for(let r of t.servers.values())e+=PT(r);return e}function PT(t){if(t.status!=="success")return 0;let e=new gr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||CT(n.inputSchema)&&(r+=bT(n))}return r}function CT(t){try{return vT.Unsafe(t??{}),!0}catch{return!1}}function xT(t){let r=t.featureFlags?.flags?.[_T];return typeof r=="boolean"?r:wT}function kT(t){let r=t.featureFlags?.flags?.[ST];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:gm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:gm}function ym(t){return xT(t)?RT(t)>=kT(t):!1}var TT="AUGGIE_ENABLE_TOOL_SEARCH",AT=new Set(["find-tool","execute-tool","attach-mcp-server"]);function No(){return process.env[TT]==="1"}function Mn(t){return No()||t.toolSearchLatched?!0:ym(t)?(t.toolSearchLatched=!0,!0):!1}function ji(t){let e=t.getActiveTools(),r=e.filter(n=>!$T(n)||AT.has(n));r.length!==e.length&&t.setActiveTools(r)}function $T(t){return ET(t)==="mcp"}import{setToolSource as Cm}from"@augmentcode/auggie-v2";import{logger as YT}from"@hermes/logger";import{Type as xm}from"@sinclair/typebox";import{logger as MT}from"@hermes/logger";var Do={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},qr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var vm=MT.child({prefix:"pi-mcp"}),IT=5e3,zT=1,OT=2,NT=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),DT=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function LT(t){if(typeof t=="number")return t===2||t===3;if(typeof t=="string"){let e=t.toUpperCase();return e.includes("OAUTH")||e.includes("API_KEY")}return!1}function jT(t){return t===zT||typeof t=="string"&&NT.has(t)?"available":t===OT||typeof t=="string"&&DT.has(t)?"opt_in_required":"unknown"}function UT(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:LT(t.auth_type),state:jT(t.state)}}function Ru(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 Lo(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Ru(t,r))}async function _m(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:qr.UNSPECIFIED}),signal:AbortSignal.timeout(r??IT)});if(!s.ok)return vm.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=UT(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return vm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var FT="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",qT=`You are a tool search assistant. Given a user's query and a list of available tools, identify the single best matching tool.
8
+ deps: ${r}}`};var rj={keyword:"dependencies",type:"object",schemaType:"object",error:Gt.error,code(t){let[e,r]=nj(t);CR(t,e),xR(t,r)}};function nj({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 CR(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,Js.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,Js.checkReportMissingProp)(t,u)}):(r.if((0,Qp._)`${c} && (${(0,Js.checkMissingProp)(t,a,s)})`),(0,Js.reportMissingProp)(t,s),r.else())}}Gt.validatePropertyDeps=CR;function xR(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,tj.alwaysValidSchema)(s,e[a])||(r.if((0,Js.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Gt.validateSchemaDeps=xR;Gt.default=rj});var TR=R(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var ER=D(),oj=H(),sj={message:"property name must be valid",params:({params:t})=>(0,ER._)`{propertyName: ${t.propertyName}}`},ij={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:sj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,oj.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,ER.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};ef.default=ij});var rf=R(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var fc=gt(),At=D(),aj=sr(),hc=H(),cj={message:"must NOT have additional properties",params:({params:t})=>(0,At._)`{additionalProperty: ${t.additionalProperty}}`},uj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:cj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,hc.alwaysValidSchema)(i,r))return;let u=(0,fc.allSchemaProperties)(n.properties),d=(0,fc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,At._)`${s} === ${aj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(p(y),()=>h(y))})}function p(y){let S;if(u.length>8){let w=(0,hc.schemaRefOrVal)(i,n.properties,"properties");S=(0,fc.isOwnProperty)(e,w,y)}else u.length?S=(0,At.or)(...u.map(w=>(0,At._)`${y} === ${w}`)):S=At.nil;return d.length&&(S=(0,At.or)(S,...d.map(w=>(0,At._)`${(0,fc.usePattern)(t,w)}.test(${y})`))),(0,At.not)(S)}function f(y){e.code((0,At._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,hc.alwaysValidSchema)(i,r)){let S=e.name("valid");c.removeAdditional==="failing"?(m(y,S,!1),e.if((0,At.not)(S),()=>{t.reset(),f(y)})):(m(y,S),a||e.if((0,At.not)(S),()=>e.break()))}}function m(y,S,w){let b={keyword:"additionalProperties",dataProp:y,dataPropType:hc.Type.Str};w===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,S)}}};tf.default=uj});var MR=R(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var dj=Ns(),AR=gt(),nf=H(),$R=rf(),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&&$R.default.code(new dj.KeywordCxt(s,$R.default,"additionalProperties"));let i=(0,AR.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=nf.mergeEvaluated.props(e,(0,nf.toHash)(i),s.props));let a=i.filter(l=>!(0,nf.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,AR.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)}}};of.default=lj});var NR=R(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var IR=gt(),mc=D(),zR=H(),OR=H(),pj={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,IR.allSchemaProperties)(r),c=a.filter(m=>(0,zR.alwaysValidSchema)(s,r[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,d=e.name("valid");s.props!==!0&&!(s.props instanceof mc.Name)&&(s.props=(0,OR.evaluatedPropsToName)(e,s.props));let{props:l}=s;p();function p(){for(let m of a)u&&f(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function f(m){for(let y in u)new RegExp(m).test(y)&&(0,zR.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,mc._)`${(0,IR.usePattern)(t,m)}.test(${y})`,()=>{let S=c.includes(m);S||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:OR.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,mc._)`${l}[${y}]`,!0):!S&&!s.allErrors&&e.if((0,mc.not)(d),()=>e.break())})})}}};sf.default=pj});var DR=R(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var fj=H(),hj={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"}};af.default=hj});var LR=R(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var mj=gt(),gj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:mj.validateUnion,error:{message:"must match a schema in anyOf"}};cf.default=gj});var jR=R(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var gc=D(),yj=H(),vj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gc._)`{passingSchemas: ${t.passing}}`},_j={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:vj,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let p;(0,yj.alwaysValidSchema)(o,d)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,gc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),p&&t.mergeEvaluated(p,gc.Name)})})}}};uf.default=_j});var UR=R(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var Sj=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,Sj.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};df.default=wj});var HR=R(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var yc=D(),qR=H(),bj={message:({params:t})=>(0,yc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yc._)`{failingKeyword: ${t.ifClause}}`},Rj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:bj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,qR.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=FR(n,"then"),s=FR(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let d=e.let("ifClause");t.setParams({ifClause:d}),e.if(a,u("then",d),u("else",d))}else o?e.if(a,u("then")):e.if((0,yc.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let p=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(p,i),l?e.assign(l,(0,yc._)`${d}`):t.setParams({ifClause:d})}}}};function FR(t,e){let r=t.schema[e];return r!==void 0&&!(0,qR.alwaysValidSchema)(t,r)}lf.default=Rj});var GR=R(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var Pj=H(),Cj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Pj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};pf.default=Cj});var ZR=R(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var xj=Wp(),kj=wR(),Ej=Kp(),Tj=RR(),Aj=PR(),$j=kR(),Mj=TR(),Ij=rf(),zj=MR(),Oj=NR(),Nj=DR(),Dj=LR(),Lj=jR(),jj=UR(),Uj=HR(),Fj=GR();function qj(t=!1){let e=[Nj.default,Dj.default,Lj.default,jj.default,Uj.default,Fj.default,Mj.default,Ij.default,$j.default,zj.default,Oj.default];return t?e.push(kj.default,Tj.default):e.push(xj.default,Ej.default),e.push(Aj.default),e}ff.default=qj});var BR=R(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var _e=D(),Hj={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},Gj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Hj,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?p():f();function p(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),S=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(S,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(S,m)),t.fail$data((0,_e.or)(w(),b()));function w(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${S}`}function b(){let k=d.$async?(0,_e._)`(${m}.async ? await ${S}(${n}) : ${S}(${n}))`:(0,_e._)`${S}(${n})`,_=(0,_e._)`(typeof ${S} == "function" ? ${k} : ${S}.test(${n}))`;return(0,_e._)`${S} && ${S} !== true && ${y} === ${e} && !${_}`}}function f(){let h=l.formats[s];if(!h){w();return}if(h===!0)return;let[m,y,S]=b(h);m===e&&t.pass(k());function w(){if(c.strictSchema===!1){l.logger.warn(_());return}throw new Error(_());function _(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(_){let P=_ instanceof RegExp?(0,_e.regexpCode)(_):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,z=r.scopeValue("formats",{key:s,ref:_,code:P});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0,_e._)`${z}.validate`]:["string",_,z]}function k(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${S}(${n})`}return typeof y=="function"?(0,_e._)`${S}(${n})`:(0,_e._)`${S}.test(${n})`}}}};hf.default=Gj});var VR=R(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var Zj=BR(),Bj=[Zj.default];mf.default=Bj});var WR=R(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.contentVocabulary=lo.metadataVocabulary=void 0;lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var JR=R(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var Vj=nR(),Wj=yR(),Kj=ZR(),Jj=VR(),KR=WR(),Yj=[Vj.default,Wj.default,(0,Kj.default)(),Jj.default,KR.metadataVocabulary,KR.contentVocabulary];gf.default=Yj});var XR=R(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});vc.DiscrError=void 0;var YR;(function(t){t.Tag="tag",t.Mapping="mapping"})(YR||(vc.DiscrError=YR={}))});var eP=R(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var po=D(),yf=XR(),QR=Qa(),Xj=Ds(),Qj=H(),e1={message:({params:{discrError:t,tagName:e}})=>t===yf.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}}`},t1={keyword:"discriminator",type:"object",schemaType:"object",error:e1,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:yf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=p();e.if(!1);for(let h in f)e.elseIf((0,po._)`${u} === ${h}`),e.assign(c,l(f[h]));e.else(),t.error(!1,{discrError:yf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:f},h);return t.mergeEvaluated(m,po.Name),h}function p(){var f;let h={},m=S(o),y=!0;for(let k=0;k<i.length;k++){let _=i[k];if(_?.$ref&&!(0,Qj.schemaHasRulesButRef)(_,s.self.RULES)){let z=_.$ref;if(_=QR.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,z),_ instanceof QR.SchemaEnv&&(_=_.schema),_===void 0)throw new Xj.default(s.opts.uriResolver,s.baseId,z)}let P=(f=_?.properties)===null||f===void 0?void 0:f[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||S(_)),w(P,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function S({required:k}){return Array.isArray(k)&&k.includes(a)}function w(k,_){if(k.const)b(k.const,_);else if(k.enum)for(let P of k.enum)b(P,_);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(k,_){if(typeof k!="string"||k in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[k]=_}}}};vf.default=t1});var tP=R((zJ,r1)=>{r1.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 Sf=R((de,_f)=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.MissingRefError=de.ValidationError=de.CodeGen=de.Name=de.nil=de.stringify=de.str=de._=de.KeywordCxt=de.Ajv=void 0;var n1=Yb(),o1=JR(),s1=eP(),rP=tP(),i1=["/properties"],_c="http://json-schema.org/draft-07/schema",fo=class extends n1.default{_addVocabularies(){super._addVocabularies(),o1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(s1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(rP,i1):rP;this.addMetaSchema(e,_c,!1),this.refs["http://json-schema.org/schema"]=_c}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_c)?_c:void 0)}};de.Ajv=fo;_f.exports=de=fo;_f.exports.Ajv=fo;Object.defineProperty(de,"__esModule",{value:!0});de.default=fo;var a1=Ns();Object.defineProperty(de,"KeywordCxt",{enumerable:!0,get:function(){return a1.KeywordCxt}});var ho=D();Object.defineProperty(de,"_",{enumerable:!0,get:function(){return ho._}});Object.defineProperty(de,"str",{enumerable:!0,get:function(){return ho.str}});Object.defineProperty(de,"stringify",{enumerable:!0,get:function(){return ho.stringify}});Object.defineProperty(de,"nil",{enumerable:!0,get:function(){return ho.nil}});Object.defineProperty(de,"Name",{enumerable:!0,get:function(){return ho.Name}});Object.defineProperty(de,"CodeGen",{enumerable:!0,get:function(){return ho.CodeGen}});var c1=Ya();Object.defineProperty(de,"ValidationError",{enumerable:!0,get:function(){return c1.default}});var u1=Ds();Object.defineProperty(de,"MissingRefError",{enumerable:!0,get:function(){return u1.default}})});var dP=R(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.formatNames=Bt.fastFormats=Bt.fullFormats=void 0;function Zt(t,e){return{validate:t,compare:e}}Bt.fullFormats={date:Zt(iP,Pf),time:Zt(bf(!0),Cf),"date-time":Zt(nP(!0),cP),"iso-time":Zt(bf(),aP),"iso-date-time":Zt(nP(),uP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:m1,"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:b1,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:g1,int32:{type:"number",validate:_1},int64:{type:"number",validate:S1},float:{type:"number",validate:sP},double:{type:"number",validate:sP},password:!0,binary:!0};Bt.fastFormats={...Bt.fullFormats,date:Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pf),time:Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Cf),"date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,cP),"iso-time":Zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,aP),"iso-date-time":Zt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,uP),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Bt.formatNames=Object.keys(Bt.fullFormats);function d1(t){return t%4===0&&(t%100!==0||t%400===0)}var l1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,p1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function iP(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:p1[n])}function Pf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var wf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function bf(t){return function(r){let n=wf.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,p=o-u*c-(l<0?1:0);return(p===23||p===-1)&&(l===59||l===-1)&&i<61}}function Cf(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function aP(t,e){if(!(t&&e))return;let r=wf.exec(t),n=wf.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 Rf=/t|\s/i;function nP(t){let e=bf(t);return function(n){let o=n.split(Rf);return o.length===2&&iP(o[0])&&e(o[1])}}function cP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function uP(t,e){if(!(t&&e))return;let[r,n]=t.split(Rf),[o,s]=e.split(Rf),i=Pf(r,o);if(i!==void 0)return i||Cf(n,s)}var f1=/\/|:/,h1=/^(?:[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 m1(t){return f1.test(t)&&h1.test(t)}var oP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function g1(t){return oP.lastIndex=0,oP.test(t)}var y1=-(2**31),v1=2**31-1;function _1(t){return Number.isInteger(t)&&t<=v1&&t>=y1}function S1(t){return Number.isInteger(t)}function sP(){return!0}var w1=/[^\\]\\Z/;function b1(t){if(w1.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var lP=R(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.formatLimitDefinition=void 0;var R1=Sf(),$t=D(),Or=$t.operators,Sc={formatMaximum:{okStr:"<=",ok:Or.LTE,fail:Or.GT},formatMinimum:{okStr:">=",ok:Or.GTE,fail:Or.LT},formatExclusiveMaximum:{okStr:"<",ok:Or.LT,fail:Or.GTE},formatExclusiveMinimum:{okStr:">",ok:Or.GT,fail:Or.LTE}},P1={message:({keyword:t,schemaCode:e})=>(0,$t.str)`should be ${Sc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,$t._)`{comparison: ${Sc[t].okStr}, limit: ${e}}`};mo.formatLimitDefinition={keyword:Object.keys(Sc),type:"string",schemaType:"string",$data:!0,error:P1,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 R1.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,$t._)`${p}[${c.schemaCode}]`);t.fail$data((0,$t.or)((0,$t._)`typeof ${f} != "object"`,(0,$t._)`${f} instanceof RegExp`,(0,$t._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let h=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(p)}`:void 0});t.fail$data(l(h))}function l(p){return(0,$t._)`${p}.compare(${r}, ${n}) ${Sc[o].fail} 0`}},dependencies:["format"]};var C1=t=>(t.addKeyword(mo.formatLimitDefinition),t);mo.default=C1});var mP=R((Ys,hP)=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});var go=dP(),x1=lP(),xf=D(),pP=new xf.Name("fullFormats"),k1=new xf.Name("fastFormats"),kf=(t,e={keywords:!0})=>{if(Array.isArray(e))return fP(t,e,go.fullFormats,pP),t;let[r,n]=e.mode==="fast"?[go.fastFormats,k1]:[go.fullFormats,pP],o=e.formats||go.formatNames;return fP(t,o,r,n),e.keywords&&(0,x1.default)(t),t};kf.get=(t,e="full")=>{let n=(e==="fast"?go.fastFormats:go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function fP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,xf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}hP.exports=Ys=kf;Object.defineProperty(Ys,"__esModule",{value:!0});Ys.default=kf});var GP=R((g5,HP)=>{HP.exports=qP;qP.sync=sU;var UP=lr("fs");function oU(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 FP(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:oU(e,r)}function qP(t,e,r){UP.stat(t,function(n,o){r(n,n?!1:FP(o,t,e))})}function sU(t,e){return FP(UP.statSync(t),t,e)}});var KP=R((y5,WP)=>{WP.exports=BP;BP.sync=iU;var ZP=lr("fs");function BP(t,e,r){ZP.stat(t,function(n,o){r(n,n?!1:VP(o,e))})}function iU(t,e){return VP(ZP.statSync(t),e)}function VP(t,e){return t.isFile()&&aU(t,e)}function aU(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 YP=R((_5,JP)=>{var v5=lr("fs"),$c;process.platform==="win32"||global.TESTING_WINDOWS?$c=GP():$c=KP();JP.exports=Bf;Bf.sync=cU;function Bf(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){Bf(t,e||{},function(s,i){s?o(s):n(i)})})}$c(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function cU(t,e){try{return $c.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var oC=R((S5,nC)=>{var Po=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",XP=lr("path"),uU=Po?";":":",QP=YP(),eC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),tC=(t,e)=>{let r=e.colon||uU,n=t.match(/\//)||Po&&t.match(/\\/)?[""]:[...Po?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Po?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Po?o.split(r):[""];return Po&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},rC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=tC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(eC(t));let p=n[u],f=/^".*"$/.test(p)?p.slice(1,-1):p,h=XP.join(f,t),m=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((p,f)=>{if(l===o.length)return p(a(d+1));let h=o[l];QP(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return p(u+h);return p(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},dU=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=tC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=XP.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let p=d+n[l];try{if(QP.sync(p,{pathExt:o}))if(e.all)s.push(p);else return p}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw eC(t)};nC.exports=rC;rC.sync=dU});var iC=R((w5,Vf)=>{"use strict";var sC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};Vf.exports=sC;Vf.exports.default=sC});var dC=R((b5,uC)=>{"use strict";var aC=lr("path"),lU=oC(),pU=iC();function cC(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=lU.sync(t.command,{path:r[pU({env:r})],pathExt:e?aC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=aC.resolve(o?t.options.cwd:"",i)),i}function fU(t){return cC(t)||cC(t,!0)}uC.exports=fU});var lC=R((R5,Kf)=>{"use strict";var Wf=/([()\][%!^"`<>&|;, *?])/g;function hU(t){return t=t.replace(Wf,"^$1"),t}function mU(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(Wf,"^$1"),e&&(t=t.replace(Wf,"^$1")),t}Kf.exports.command=hU;Kf.exports.argument=mU});var fC=R((P5,pC)=>{"use strict";pC.exports=/^#!(.*)/});var mC=R((C5,hC)=>{"use strict";var gU=fC();hC.exports=(t="")=>{let e=t.match(gU);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var yC=R((x5,gC)=>{"use strict";var Jf=lr("fs"),yU=mC();function vU(t){let r=Buffer.alloc(150),n;try{n=Jf.openSync(t,"r"),Jf.readSync(n,r,0,150,0),Jf.closeSync(n)}catch{}return yU(r.toString())}gC.exports=vU});var wC=R((k5,SC)=>{"use strict";var _U=lr("path"),vC=dC(),_C=lC(),SU=yC(),wU=process.platform==="win32",bU=/\.(?:com|exe)$/i,RU=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function PU(t){t.file=vC(t);let e=t.file&&SU(t.file);return e?(t.args.unshift(t.file),t.command=e,vC(t)):t.file}function CU(t){if(!wU)return t;let e=PU(t),r=!bU.test(e);if(t.options.forceShell||r){let n=RU.test(e);t.command=_U.normalize(t.command),t.command=_C.command(t.command),t.args=t.args.map(s=>_C.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 xU(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:CU(n)}SC.exports=xU});var PC=R((E5,RC)=>{"use strict";var Yf=process.platform==="win32";function Xf(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 kU(t,e){if(!Yf)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 Yf&&t===1&&!e.file?Xf(e.original,"spawn"):null}function EU(t,e){return Yf&&t===1&&!e.file?Xf(e.original,"spawnSync"):null}RC.exports={hookChildProcess:kU,verifyENOENT:bC,verifyENOENTSync:EU,notFoundError:Xf}});var kC=R((T5,Co)=>{"use strict";var CC=lr("child_process"),Qf=wC(),eh=PC();function xC(t,e,r){let n=Qf(t,e,r),o=CC.spawn(n.command,n.args,n.options);return eh.hookChildProcess(o,n),o}function TU(t,e,r){let n=Qf(t,e,r),o=CC.spawnSync(n.command,n.args,n.options);return o.error=o.error||eh.verifyENOENTSync(o.status,n),o}Co.exports=xC;Co.exports.spawn=xC;Co.exports.sync=TU;Co.exports._parse=Qf;Co.exports._enoent=eh});var IC=R(rh=>{"use strict";var AC=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,zU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,$C=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,OU=/\\([\u000b\u0020-\u00ff])/g,NU=/([\\"])/g,MC=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;rh.format=DU;rh.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||!MC.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],!$C.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+UU(e[o])}return n}function LU(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?jU(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(!MC.test(n))throw new TypeError("invalid media type");var o=new FU(n.toLowerCase());if(r!==-1){var s,i,a;for(AC.lastIndex=r;i=AC.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(OU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function jU(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 UU(t){var e=String(t);if($C.test(e))return e;if(e.length>0&&!zU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(NU,"\\$1")+'"'}function FU(t){this.parameters=Object.create(null),this.type=t}});import{logger as YG}from"@hermes/logger";import{logger as iq}from"@hermes/logger";var oE="mcp-auth";function Oe(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(oE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as NF}from"@augmentcode/auggie-v2";import{logger as DF}from"@hermes/logger";import{logger as xE}from"@hermes/logger";import{logger as iE}from"@hermes/logger";function sE(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 pr(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":sE(t,e,r)?"plugin":"local"}function aE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var Fh=iE.child({prefix:"pi-mcp"}),cE="augment:mcp-status-report";function fr(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 ki(t,e,r,n){let o=fr(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=fr(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 uE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=fr(t,e);if(r?.serverGeneration===n.serverGeneration&&r.mcpConfigId===n.mcpConfigId&&r.credentialRevision===n.credentialRevision&&r.credentialRevisionDomain===n.credentialRevisionDomain)return r.category;t.statusFailureCategories.delete(e),t.authRefreshNeededReportKeys?.delete(e)}var Ei=3e4;function 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>=Ei?"failed":void 0}default:return}}var qh="authentication required",lE="Authentication refresh is pending in the backend; retry shortly.",pE="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.",hE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",mE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).";function gE(t,e){let r=new Set;for(let i of t.servers.values())i.config.id!==void 0&&r.add(i.config.id);let n=new Set(e.map(i=>i.mcpConfigId).filter(i=>i!==void 0)),o=new Set(e.map(i=>i.name)),s=i=>t.registryConfigNamesById.get(i)??i;for(let i of t.failedAddConfigIds){if(r.has(i)||n.has(i))continue;let a=s(i);n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(i)?hE:fE,mcpConfigId:i,dynamicallyAdded:!0})}for(let i of t.selectedRegistryConfigIds??[]){if(r.has(i)||n.has(i)||t.sessionRemovedConfigIds.has(i))continue;let a=s(i);o.has(a)||(n.add(i),o.add(a),e.push({name:a,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:mE,mcpConfigId:i}))}}function yE(t,e){return e!==void 0?e.isAuthError?qh:e.error:t.status==="initializing"?pE:t.lastError??(t.status==="auth_required"?qh:void 0)}function vE(t,e){let r=dE(t);if(r===void 0)return;let n=uE(e,t.name),o=r==="connected"?aE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:pr(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:yE(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 _E(t){let e=[];for(let r of t.servers.values()){let n=vE(r,t);n!==void 0&&e.push(n)}return gE(t,e),e}function J(t,e){try{let r=_E(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(cE,o),Fh.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){Fh.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Ti={local:4,registry:3,plugin:2,vfs:1};function Ot(t){return t.hostLeases??=new Map,t.hostLeases}function SE(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function $o(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Mo(t,e){return t.kind===e.kind&&t.identity===e.identity}function Hh(t){if(!t.host)return t.retirement;let e=()=>{},r=new Promise(n=>{e=n});return{incumbent:{owner:t.owner,revision:t.revision,host:t.host},teardown:r,settled:!1,resolve:e}}function au(t,e){let r=SE(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function Ai(t,e,r){if(r.kind==="registry"){$o(t).set(e,{kind:"domain",domain:r.identity});return}$o(t).set(e,{kind:"blocked"})}function cu(t,e,r){r&&t.servers.get(e)===r&&t.servers.delete(e),r&&t.pluginServerHosts.get(e)===r&&(t.pluginServerHosts.delete(e),t.pluginServerNames.delete(e))}function En(t,e){return t.registrySource!==void 0?{kind:"registry",identity:`user:${t.id??t.name}`}:t.vfsSource!==void 0?{kind:"vfs",identity:t.id??t.name}:{kind:e??"local",identity:t.id??t.name}}function Q(t,e,r){let n=Ot(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?En(i,s):{kind:s??"local",identity:e},c={owner:a,revision:au(t,e),host:r};return n.set(e,c),Ai(t,e,a),c}function Gh(t){let{state:e,name:r,host:n}=t,o=Ot(e),s=o.get(r);if(!s||s.host!==n||s.owner.kind!=="local"||e.servers.get(r)!==n)return;let i={owner:{kind:"plugin",identity:n.config.id??r},revision:au(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),Ai(e,r,i.owner),i}function Io(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Ot(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Ti[n.kind]>Ti[a.owner.kind],p=Ti[n.kind]===Ti[a.owner.kind],f=o===a.revision&&(s===void 0||s===a.host);if(!(l||p&&f))return}let c=a?.host,u=a?Hh(a):void 0;cu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:au(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),Ai(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function uu(t){if(!t)return;let e=await t.teardown;if(e.status==="failed")throw e.error instanceof Error?e.error:new Error(String(e.error))}function we(t){let{state:e,name:r,retirement:n,result:o}=t;if(n.settled)return!1;n.settled=!0,n.result=o;let i=Ot(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,$o(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function $i(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e).get(r);return!i||i.revision!==o||!Mo(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 wt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e).get(r);if(!i||i.revision!==o||!Mo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=Hh(i);if(a)return cu(e,r,s),i.host=void 0,i.retirement=a,a}function Zh(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Ot(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Mo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Mo(i.owner,n)||i.revision!==o.incumbent.revision?(Ai(e,r,i.owner),!0):(s.delete(r),$o(e).set(r,{kind:"blocked"}),!0))}function be(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ot(e),a=i.get(r);return!a||a.revision!==o||!Mo(a.owner,n)||a.host!==s||a.retirement!==void 0?!1:(cu(e,r,a.host),a.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r)),i.delete(r),$o(e).set(r,{kind:"blocked"}),!0)}function Z(t,e){return Ot(t).get(e)}function Bh(t,e,r){return Ot(t).get(e)?.host===r}function zo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function hr(t){if(!(t.type!=="http"&&t.type!=="sse"||t.auth!=="oauth"))return{id:t.id,name:t.name,type:t.type,url:t.url,auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Be(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:t.url===e.url&&t.auth===e.auth}function du(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function wE(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 bE(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 Vh(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!du(e,r):n!==void 0&&e!==n}function Wh(t,e,r){return r&&e!==void 0&&t!==void 0&&du(t,e)}function RE(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!du(s,n))}function Kh(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(bE({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||Vh({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&Vh({identity:i.domain,...l})?!0:RE({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function PE(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return hr(r);if(n!==void 0)return{id:n,name:e}}function CE(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!hr(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function Jh(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=wE({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,p=Kh({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),f=Wh(s,u,d),h=Wh(i,u,d),m=!p,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,w=p&&!(m||f||h||y);if(o==="durable"){let P=PE({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:w})}let b=Kh({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),k=m&&!b,_=!1;return t.equalRevisionRebindDomains?.delete(e),(k||f)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),_=!0),(k||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),_=!0),k&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),CE({state:t,name:e,mode:o,stillOwnsNameScopedRevision:k,retiredConfig:c}),_&&(zo(t,e),ot(t,e),t.authRefreshNeededReportKeys?.delete(e)),k}function ct(t,e,r,n){return Jh(t,e,r,n,"durable")}function Oo(t,e,r,n){return Jh(t,e,r,n,"session")}function mr(t,e){let r=t.replace(/^0+(?=\d)/,""),n=e.replace(/^0+(?=\d)/,"");return r.length!==n.length?r.length<n.length?-1:1:r===n?0:r<n?-1:1}var Yh="augment:mcp-oauth-credentials",Xh=300*1e3,kE=256,Qh=xE.child({prefix:"pi-mcp"}),bt=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function We(t){return`user:${t}`}function Ur(t){let{state:e,name:r,revision:n}=t;if(e.credentialRevisions??=new Map,e.oauthCredentialRevisions??=new Map,e.oauthCredentialDomains??=new Map,e.hostedCredentialOwnership?.delete(r),n===void 0){e.credentialRevisions.delete(r),e.oauthCredentialDomains.delete(r),e.authRefreshNeededReportKeys?.delete(r);return}let o={...n,revision:n.revision.replace(/^0+(?=\d)/,"")},s=e.credentialRevisions.get(r);e.credentialRevisions.set(r,o),(s?.revision!==o.revision||s?.domain!==o.domain)&&e.authRefreshNeededReportKeys?.delete(r);let i=e.oauthCredentialRevisions.get(o.domain);(i===void 0||mr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function ut(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="user"&&r!=="tenant"?t:We(t.slice(e+1))}function EE(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function TE(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 AE(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function $E(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&EE(t.credentialRevisions.get(e),r.credentialRevision)&&AE(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function ME(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 IE(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 Fr(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function jr(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function em(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=Xh&&jr(t,n)}function zE(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&jr(t,e)}function tm(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Fr(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();em(e,a);let c=ut(n.domain),u=i.get(c),d=u?.credential.credential_revision??u?.credential.credentialRevision;if(typeof d=="string"&&mr(n.revision,d)<=0)return;!u&&i.size>=kE&&zE(e),jr(e,c);let l={credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(c,l),l.expiryTimer=setTimeout(()=>{i.get(c)===l&&jr(e,c)},Xh),l.expiryTimer.unref?.(),Qh.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function OE(t,e){Fr(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;Fr(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||jr(e,r)}}function Mi(t){let{state:e,domain:r,forceNew:n=!1}=t;Fr(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:OE(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 rm(t,e){Fr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Ve({state:t,domain:r,epoch:n.epoch});for(let r of t.pendingRegistryCredentialDomains)e.has(r)||(t.pendingRegistryCredentialDomains.delete(r),t.stagedOAuthCredentials.delete(r));for(let r of t.stagedOAuthCredentials.keys())e.has(r)||t.stagedOAuthCredentials.delete(r);for(let r of t.bootOAuthCredentialBuffer?.keys()??[])e.has(r)||jr(t,r);for(let r of e){let n=t.registryCredentialIntents.get(r);Mi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function NE(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||Z(e,r.name)?.owner.kind==="local")return;Fr(e);let n=We(r.id),o=ME(r),s=IE({state:e,config:r,domain:n});s||e.equalRevisionRebindDomains.delete(r.name);let i=e.registryCredentialIntents.get(n);if(i&&i.configFingerprint===void 0){i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s;let a=e.stagedOAuthCredentials.get(n);a?.intentEpoch===i.epoch&&(a.configFingerprint=o)}else i&&i.configFingerprint!==o?(Ve({state:e,domain:n,epoch:i.epoch}),i=void 0):i&&(i.allowEqualRevisionRebind=s);if(!i){let a=Mi({state:e,domain:n});if(i=e.registryCredentialIntents.get(n),!i||i.epoch!==a.epoch)return;i.configFingerprint=o,i.configName=r.name,i.allowEqualRevisionRebind=s}return e.pendingRegistryCredentialDomains.add(n),DE({state:e,config:r,domain:n}),{domain:n,...i}}function nm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Fr(e);let s=ut(r.domain),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:mr(r.revision,a),p=l===0;l!==void 0&&l<0||p&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&mr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:p})}function DE(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n}),(o===void 0||ut(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),ot(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function LE(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(Yh,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function jE(t){let{state:e,domain:r}=t,n=Date.now();em(e,n);let o=e.bootOAuthCredentialBuffer?.get(r);return jr(e,r),o}function UE(t){let{config:e,pi:r,buffered:n}=t;Qh.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`);let o={[e.name]:n.credential};r.events.emit(Yh,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function FE(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(Be(n,r)){if(n.name===r.name)return;await Oo(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await ct(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function qE(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=$E(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 bt(a)}async function HE(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 FE({state:e,config:r,previousConfig:s})}catch(h){throw qE({state:e,config:r,intent:o,rollbackSnapshot:i,cause:h})}let u=e.registryCredentialIntents.get(o.domain);c&&u?.epoch===o.epoch&&e.expectedCredentialDomains.get(r.name)===c&&e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let d=e.expectedCredentialDomains.get(r.name);if(u?.epoch!==o.epoch||u.configFingerprint!==o.configFingerprint||d?.kind!=="domain"||d.domain!==o.domain)return Ve({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let p={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,p),e.registryCredentialConfigsById.set(l,p),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),LE({state:e,config:r,pi:n,intent:o});let f=jE({state:e,domain:o.domain});return Ve({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),f&&UE({config:r,pi:n,buffered:f}),!0}function qr(t){let{state:e,config:r,pi:n}=t;if(r.id===void 0||r.registrySource===void 0)return Promise.resolve(!0);let o=e.statusFailureCategories.get(r.name),s=NE({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=TE(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 HE({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 om}from"node:os";import{sep as GE}from"node:path";var lu=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},ZE=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,BE=/\\\$\{/g,VE=new Set(["workspaceFolder","augmentToken"]),sm="${workspaceFolder}";function im(t,e){return t.includes(sm)?t.split(sm).join(e):t}function am(t,e){return t.includes("${")?t.replace(ZE,(n,o,s)=>{if(VE.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new lu(o)}).replace(BE,"${"):t}function WE(t){return t.startsWith("~")?t==="~"?om():t.startsWith("~/")||t.startsWith(`~${GE}`)?om()+t.slice(1):t:t}function pu(t,e,r){return WE(am(im(t,e),r))}function Ii(t,e,r){return am(im(t,e),r)}function cm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Ii(s,e,r);return n}var KE="$augment-";function JE(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(KE)?s:Ii(s,e,r);return n}function Nt(t,e){let r=process.env;return{...t,url:Ii(t.url,e,r),headers:JE(t.headers,e,r)}}function Dt(t,e){let r=process.env;return{...t,command:pu(t.command,e,r),args:t.args,env:t.env?cm(t.env,e,r):void 0,cwd:t.cwd?pu(t.cwd,e,r):e}}import{readFileSync as eT}from"node:fs";import{logger as YE}from"@hermes/logger";var XE=YE.child({prefix:"pi-mcp"}),Rt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function Tn(t){if(t.type==="stdio"||t.type==="http"||t.type==="sse")return t.type;if(t.url)return"http";if(t.command)return"stdio"}function QE(t){if(!t)return;let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=String(n));return Object.keys(e).length>0?e:void 0}function An(t,e){let r=Tn(e);if(!r)throw new Rt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new Rt(`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 Rt(`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&&XE.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:QE(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var lm=t=>eT(t,"utf8");function zi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function um(t){return zi(t)&&("command"in t||"url"in t)}function hu(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function dm(t,e){return hu(t.name)??e}function fu(t,e){let r=Tn(t);if(r==="http"||r==="sse")return hu(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return hu(t.name,t.title,n)??e}function tT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[fu(n,String(r)),n]});if(zi(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[fu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(zi(n))return Object.entries(n).map(([o,s])=>{let i=s;return[dm(i,o),i]})}if(um(t)){let r=t;return[[fu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(um))return Object.entries(t).map(([r,n])=>{if(!zi(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[dm(o,r),o]})}throw new Error("unrecognized MCP config JSON shape (expected an array of servers, a { servers|mcpServers } array/record, a single server object, or a Claude-Desktop-style record)")}function mu(t){return t instanceof Error?t.message:String(t)}function 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}": ${mu(s)}`});return}}function nT(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}: ${mu(c)}`}),[]}try{return tT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${mu(c)}`}),[]}}function gu(t,e=lm){let r={},n=[];for(let o of t)for(let[s,i]of nT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function yu(t,e=lm){return!t||t.length===0?new Set:new Set(Object.keys(gu(t,e).servers))}var sT=["global","project","local","managed"];function iT(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 aT(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 cT(t,e,r){let n=gu(t);r.push(...n.diagnostics);let o=n.servers;if(!e||e.size===0)return o;for(let[s,i]of Object.entries(o)){let a=e.get(s);a!==void 0&&(o[s]={...i,disabled:a})}return o}function uT(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 aT(sT.map(o=>iT(n,o)))}function $n(t,e,r,n){let o=[],s=r&&r.length>0?cT(r,n,o):uT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=An(a,c);i.push(u.type==="stdio"?Dt(u,t):Nt(u,t))}catch(u){let d=u instanceof Rt?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 vm}from"@augmentcode/auggie-v2";import{logger as wT}from"@hermes/logger";import{Type as bT}from"@sinclair/typebox";var Mn=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;get(e){return this._tokens.get(e)}commit(e,r){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e)}set(e,r,n){this.commit(e,r)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,s){return this.persist(e,n,o)}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,s)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations)}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n)}delete(e,r){this._tokens.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};var Oi=Symbol.for("__pi_mcp_state__");function dT(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 lT(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function pT(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&dT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&lT(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 fT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&pT(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 No(t,e){for(;;){let r=t.missingHostRemovals.get(e);if(!r)return;try{await r.promise}catch{}if(t.missingHostRemovals.get(e)===r)return}}function Ni(t){let{state:e,configId:r,generation:n}=t;e.attachmentCommandGenerations??=new Map,e.attachmentCommandInFlightGenerations??=new Map,e.attachmentCommandAppliedGenerations??=new Map;let o=e.attachmentCommandGenerations.get(r)??0;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o===0:n<o||n===e.attachmentCommandInFlightGenerations.get(r)||n===e.attachmentCommandAppliedGenerations.get(r)?!1:(e.attachmentCommandGenerations.set(r,n),e.attachmentCommandInFlightGenerations.set(r,n),!0)}function hT(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 pm(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Di(t){let{state:e,configId:r,generation:n,operation:o,wasApplied:s}=t;return typeof n!="number"||!Number.isSafeInteger(n)||n<=0?o:o.then(i=>(s()?hT({state:e,configId:r,generation:n}):pm({state:e,configId:r,generation:n}),i),i=>{throw pm({state:e,configId:r,generation:n}),i})}function se(){let t=globalThis;if(t[Oi])return fT(t[Oi]),t[Oi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Mn,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations:new Map,serverGenerations:new Map,configRevisions:new Map,configDesiredRevisions:new Map,configDesiredSources:new Map,credentialRevisions:new Map,oauthCredentialRevisions:new Map,oauthCredentialDomains:new Map,equalRevisionRebindDomains:new Map,preservedCredentialIdentities:new Map,stagedOAuthCredentials:new Map,bootOAuthCredentialBuffer:new Map,pendingRegistryCredentialDomains:new Set,registryCredentialIntents:new Map,registryCredentialIntentEpochs:new Map,registryCredentialFinalizationsByName:new Map,statusHostGeneration:1,statusReportSequence:0,statusFailureCategories:new Map,authRefreshNeededReportKeys:new Map,hostedCredentialOwnership:new Map,shouldProactivelyRefreshTokens:!0,backgroundRefreshIntervalId:void 0,credsListenerBound:!1,configIdsListenerBound:!1,registryGeneration:0,liveEditGenerations:new Map,attachmentCommandGenerations:new Map,attachmentCommandInFlightGenerations:new Map,attachmentCommandAppliedGenerations:new Map,mcpConfigsListenerBound:!1,embeddedRegistryConfigs:void 0,vfsListenerBound:!1,addServerListenerBound:!1,restartServerListenerBound:!1,removeServerListenerBound:!1,mcpRestartState:new Map,vfsGeneration:0,lastSuccessfulVfsMcpSignature:void 0,blockedVfsMcpNames:new Set,credentials:void 0,secretsClient:void 0,headerSecrets:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1};return t[Oi]=e,e}var fm=Symbol.for("__hermes_mcp_tool_registry__"),mT=Symbol.for("__hermes_mcp_extension_factory__");function hm(){let t=globalThis;return t[fm]??=new Map,t[fm]}function gr(t){hm().set(t.name,t)}function mm(t,e){let r=hm();(e===void 0||r.get(t)===e)&&r.delete(t)}function gm(t){Reflect.set(t,mT,!0)}function Li(t,e,r,n){return r.includes(t)?n.includes(t)?`"${t}" is a built-in tool, not an MCP server. Call it directly.`:`Built-in tool "${t}" is not available (disabled).`:`MCP server "${t}" is not available (status: ${e??"unknown"}).`}function gT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function yT(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 vu(t,e,r){if(t.isError){let o=vT(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=yT(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 ym(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Li(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=gT(t.params),o=await e.callTool(r,n,t.signal);return vu(o,t.serverName,r)}var _T=/[^a-zA-Z0-9_-]/g;function _u(t){return t.replace(_T,"_")}function ST(t,e){let r=_u(e),n=_u(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var yr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=ST(this._serverName,e),n=this._map.get(r),o=n!==void 0&&n!==e;return n===void 0&&this._map.set(r,e),{namespaced:r,collision:o}}resolve(e){let r=this._map.get(e);if(r)return r;let n=`_${_u(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Su=wT.child({prefix:"pi-mcp"});function ji(){return se().toolRegistrationsByPi}function _m(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=bT.Unsafe(n.inputSchema??{})}catch(c){Su.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>se().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,p)=>ym({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(f=>f.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function wu(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n),s=r.definitionsByName?.get(n);e.ownerByToolName.delete(n),t.unregisterTool(n),mm(n,s),r.definitionsByName?.delete(n),RT(t,e,n,r,o)}function RT(t,e,r,n,o){let s=se();for(let[i,a]of e.byServer){if(a===n||!a.registeredNames.has(r))continue;let c=s.servers.get(i);if(c===void 0||c!==a.host||c.status!=="success"||s.serverGenerations?.get(i)!==a.generation)continue;let u=new yr(i);for(let d of c.listTools()){let{namespaced:l,collision:p}=u.put(d.name);if(p||l!==r)continue;let f=_m({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!f)return;vm(r,"mcp"),t.registerTool(f),gr(f),a.definitionsByName??=new Map,a.definitionsByName.set(r,f),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function PT(t,e){let r=ji(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=se().serverGenerations?.get(e.name),s=n.byServer.get(e.name);if(s?.host===e&&s.generation===o)return{registration:s,replaced:!1};if(s)for(let a of s.registeredNames)wu(t,n,s,a);let i={generation:o,host:e,map:new yr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function bu(t,e){let{registration:r,replaced:n}=PT(t,e),o=new Set(r.registeredNames),s=new yr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:p}=s.put(d.name);if(p){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=se();y.diagnostics.some(w=>w.server===i&&w.message.includes(`both map to "${l}"`))||(Su.warn(m),y.diagnostics.push({server:i,message:m}));continue}let f=_m({pi:t,serverName:i,tool:d,map:s,namespaced:l});f&&(vm(l,"mcp"),t.registerTool(f),gr(f),r.definitionsByName??=new Map,r.definitionsByName.set(l,f),ji().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=ji().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&wu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Su.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Ru(t,e,r){let n=ji().get(t);if(!n)return!1;let o=n.byServer.get(e.name);if(!o||o.host!==e||o.generation!==r)return!1;for(let s of o.registeredNames)wu(t,n,o,s);return n.byServer.delete(e.name),!0}function Sm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&bu(t,r)}import{getToolSource as OT}from"@augmentcode/auggie-v2";import{Type as CT}from"@sinclair/typebox";var xT="cliMcpToolSearchAutoEnable",kT="cliMcpToolSearchTokenThreshold",ET=!1,wm=2e4;function TT(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function AT(t){let e=0;for(let r of t.servers.values())e+=$T(r);return e}function $T(t){if(t.status!=="success")return 0;let e=new yr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||MT(n.inputSchema)&&(r+=TT(n))}return r}function MT(t){try{return CT.Unsafe(t??{}),!0}catch{return!1}}function IT(t){let r=t.featureFlags?.flags?.[xT];return typeof r=="boolean"?r:ET}function zT(t){let r=t.featureFlags?.flags?.[kT];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:wm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:wm}function bm(t){return IT(t)?AT(t)>=zT(t):!1}var NT="AUGGIE_ENABLE_TOOL_SEARCH",DT=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Do(){return process.env[NT]==="1"}function In(t){return Do()||t.toolSearchLatched?!0:bm(t)?(t.toolSearchLatched=!0,!0):!1}function Ui(t){let e=t.getActiveTools(),r=e.filter(n=>!LT(n)||DT.has(n));r.length!==e.length&&t.setActiveTools(r)}function LT(t){return OT(t)==="mcp"}import{setToolSource as Am}from"@augmentcode/auggie-v2";import{logger as oA}from"@hermes/logger";import{Type as $m}from"@sinclair/typebox";import{logger as jT}from"@hermes/logger";var Lo={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},Hr={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Rm=jT.child({prefix:"pi-mcp"}),UT=5e3,FT=1,qT=2,HT=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),GT=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function ZT(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 BT(t){return t===FT||typeof t=="string"&&HT.has(t)?"available":t===qT||typeof t=="string"&&GT.has(t)?"opt_in_required":"unknown"}function VT(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:ZT(t.auth_type),state:BT(t.state)}}function Pu(t,e){if(t.servers.has(e.name))return!0;for(let r of t.servers.values())if(r.config?.id===e.id)return!0;return!1}function jo(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Pu(t,r))}async function Pm(t,e,r){let n=t.apiUrl.replace(/\/+$/,""),o=e??fetch;try{let s=await o(`${n}/settings/get-mcp-catalog-metadata`,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({product_type:Hr.UNSPECIFIED}),signal:AbortSignal.timeout(r??UT)});if(!s.ok)return Rm.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=VT(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Rm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var WT="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",KT=`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).`,HT=/[\n\r]/g,GT=/</g,ZT=/>/g;function Hr(t){return t.replace(HT," ").replace(GT,"\u2039").replace(ZT,"\u203A").trim()}function VT(){let t=process.env[FT];return t?.trim()?t:qT}var BT=/\{\{(query|server_name|tool_list)\}\}/g;function Sm(t,e,r){let n={"{{query}}":Hr(t),"{{server_name}}":Hr(e),"{{tool_list}}":r};return VT().replace(BT,o=>n[o]??o)}function Re(t){return{content:[{type:"text",text:t}],details:void 0}}function wm(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Pu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Ui(t,e,r){let n={mcp_server:t,tools:wm(e).map(Pu),note:r};return Re(JSON.stringify(n,null,2))}function bm(t){return wm(t).map(e=>{let r=Hr(e.name),n=Hr(e.description??"");return`- ${r}: ${n}`}).join(`
17
- `)}function Rm(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 WT}from"@earendil-works/pi-ai";var KT="augment:tool-search-usage";function JT(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Pm(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 WT(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(KT,a),JT(i)}var Em=YT.child({prefix:"pi-mcp"}),jo="find-tool",Gr="execute-tool",XT=10,km=15,QT=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 Tm(t,e){let r=se(),n=r.servers.get(e);if(!n||n.status!=="success"){let o=t.getAllTools().map(c=>c.name),s=t.getActiveTools(),i=e.trim().toLowerCase(),a=Lo(r).find(c=>c.id===e.trim()||c.name.toLowerCase()===i);throw a&&!o.includes(e)?new Error(`MCP server "${a.name}" is available but not attached. Call attach-mcp-server now with config_id "${a.id}"; it attaches directly without requiring user approval.`):new Error(Di(e,n?.status,o,s))}return n}function rA(t){if(t==null)throw new Error(`${Gr} 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(`${Gr} "arguments" must be an object, not ${e}.`)}return t}async function nA(t,e,r,n,o){let s=Sm(r,n,bm(o)),i=await Pm(t,e,s);if(!i)return;let a=Rm(i);return o.find(c=>c.name===a)}async function oA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${jo} requires string "query" and "mcp_server" parameters.`);let s=Tm(t,o).listTools();if(s.length===0)throw new Error(`No tools available on MCP server "${o}".`);if(s.length<=XT)return Ui(o,s,"All tools on this server.");try{let i=await nA(t,e,n,o,s);return i?Re(JSON.stringify(Pu(i),null,2)):Ui(o,s,"No single best match; all tools listed.")}catch(i){return Em.warn(`${jo} LLM match failed: ${i instanceof Error?i.message:String(i)}`),Ui(o,s,"Search failed; all tools listed.")}}async function sA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Gr} requires string "mcp_server" and "tool_name" parameters.`);let i=rA(s),c=await Tm(t,n).callTool(o,i,r);return yu(c,n,o)}function iA(){let t=se(),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 ${Gr}.`,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,km).join(", "),u=a.length>km?", \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).`,JT=/[\n\r]/g,YT=/</g,XT=/>/g;function Gr(t){return t.replace(JT," ").replace(YT,"\u2039").replace(XT,"\u203A").trim()}function QT(){let t=process.env[WT];return t?.trim()?t:KT}var eA=/\{\{(query|server_name|tool_list)\}\}/g;function Cm(t,e,r){let n={"{{query}}":Gr(t),"{{server_name}}":Gr(e),"{{tool_list}}":r};return QT().replace(eA,o=>n[o]??o)}function Re(t){return{content:[{type:"text",text:t}],details:void 0}}function xm(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Cu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Fi(t,e,r){let n={mcp_server:t,tools:xm(e).map(Cu),note:r};return Re(JSON.stringify(n,null,2))}function km(t){return xm(t).map(e=>{let r=Gr(e.name),n=Gr(e.description??"");return`- ${r}: ${n}`}).join(`
17
+ `)}function Em(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 tA}from"@earendil-works/pi-ai";var rA="augment:tool-search-usage";function nA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function Tm(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 tA(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),nA(i)}var Im=oA.child({prefix:"pi-mcp"}),Uo="find-tool",Zr="execute-tool",sA=10,Mm=15,iA=20,aA={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"]},cA={type:"object",properties:{mcp_server:{type:"string",description:"Name of the MCP server hosting the tool."},tool_name:{type:"string",description:"Original MCP tool name returned by find-tool."},arguments:{type:"object",description:"Arguments object to pass to the tool."}},required:["mcp_server","tool_name","arguments"]};function zm(t,e){let r=se(),n=r.servers.get(e);if(!n||n.status!=="success"){let o=t.getAllTools().map(c=>c.name),s=t.getActiveTools(),i=e.trim().toLowerCase(),a=jo(r).find(c=>c.id===e.trim()||c.name.toLowerCase()===i);throw a&&!o.includes(e)?new Error(`MCP server "${a.name}" is available but not attached. Call attach-mcp-server now with config_id "${a.id}"; it attaches directly without requiring user approval.`):new Error(Li(e,n?.status,o,s))}return n}function uA(t){if(t==null)throw new Error(`${Zr} requires an "arguments" object with the tool's parameters.`);if(typeof t!="object"||Array.isArray(t)){let e=Array.isArray(t)?"an array":typeof t;throw new Error(`${Zr} "arguments" must be an object, not ${e}.`)}return t}async function dA(t,e,r,n,o){let s=Cm(r,n,km(o)),i=await Tm(t,e,s);if(!i)return;let a=Em(i);return o.find(c=>c.name===a)}async function lA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Uo} requires string "query" and "mcp_server" parameters.`);let s=zm(t,o).listTools();if(s.length===0)throw new Error(`No tools available on MCP server "${o}".`);if(s.length<=sA)return Fi(o,s,"All tools on this server.");try{let i=await dA(t,e,n,o,s);return i?Re(JSON.stringify(Cu(i),null,2)):Fi(o,s,"No single best match; all tools listed.")}catch(i){return Im.warn(`${Uo} LLM match failed: ${i instanceof Error?i.message:String(i)}`),Fi(o,s,"Search failed; all tools listed.")}}async function pA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Zr} requires string "mcp_server" and "tool_name" parameters.`);let i=uA(s),c=await zm(t,n).callTool(o,i,r);return vu(c,n,o)}function fA(){let t=se(),e=[...t.servers.values()].filter(s=>s.status==="success"),r=`Search for the right MCP tool. Call with a natural-language query and the target MCP server name to get the best-matching tool, then run it with ${Zr}.`,n=[];if(e.length===0)n.push(`${r} No MCP servers are currently connected.`);else{let s=e.map(i=>{let a=i.listTools().map(d=>d.name),c=a.slice(0,Mm).join(", "),u=a.length>Mm?", \u2026":"";return`- ${i.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
18
18
  ${s.join(`
19
- `)}`)}let o=Lo(t).slice(0,QT);if(o.length>0){let s=o.map(i=>{let a=Hr(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=jo(t).slice(0,iA);if(o.length>0){let s=o.map(i=>{let a=Gr(i.description),c=i.requiresAuth?" [requires auth]":"";return`- ${i.name}${a?` \u2014 ${a}`:""}${c}`});n.push(`Available but not attached (use attach-mcp-server to enable):
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 Zr(t){let e={name:jo,label:jo,description:iA(),parameters:xm.Unsafe(eA),execute:(n,o,s,i,a)=>oA(t,a,o)},r={name:Gr,label:Gr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:xm.Unsafe(tA),execute:(n,o,s)=>sA(t,o,s)};Cm(jo,"mcp"),Cm(Gr,"mcp"),t.registerTool(e),t.registerTool(r),Em.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as UU}from"@hermes/logger";import{logger as dA}from"@hermes/logger";import{logger as aA}from"@hermes/logger";function Vr(t){return new Promise(e=>setTimeout(e,t))}var Am=aA.child({prefix:"pi-mcp"}),Uo={maxTries:3,initialMs:500,mult:2,maxMs:2e3},Cu=3e4,Jt=200,dt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function xu(t){return t instanceof dt?t.statusCode>=500:!0}async function Br(t){let e;for(let r=0;r<Uo.maxTries;r++)try{return await t()}catch(n){if(e=n,!xu(n))throw n;if(r<Uo.maxTries-1){let o=Math.min(Uo.initialMs*Uo.mult**r,Uo.maxMs);await Vr(o)}}throw e}var Fi=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??Cu}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>Jt?`${s.slice(0,Jt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return Br(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return Br(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function $m(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)}`;Am.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)}`;Am.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function cA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var Mm=32;function uA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>Mm&&(e=e.slice(0,Mm)),e=e.replace(/_+$/,""),e}function Im(t,e){let r=e?uA(e):"",n=cA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function zm(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}function Om(t){let e=JSON.parse(t);if(typeof e.accessToken!="string")throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:e.accessToken,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Lt=dA.child({prefix:"pi-mcp"}),V=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},zn=class extends Error{},Dm=[100,500],lA=Dm.length+1,pA=t=>new Promise(e=>{setTimeout(e,t)});function Nm(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Eu="augment.mcp-access-token.",fA=JSON.stringify({retired:!0}),qi=3;function jt(t){return`${Eu}${t}`}function Hi(t){return`legacy:${t}`}function Yt(t){return t?.id?Im(t.id,t.name):void 0}function Gi(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 yr(t){let e=Gi(t);return e?JSON.stringify(e):void 0}function hA(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 Tu(t){if(typeof t=="string")try{return Tu(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 mA(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function In(t){try{let e=JSON.parse(t);return{credentialIdentity:Tu(e.credentialIdentity),state:mA(e)}}catch{return{}}}function Fo(t,e){let r={...t,type:"oauth",credentialIdentity:Gi(e)};return JSON.stringify(r)}function Wr(t,e){let r=zm({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:Gi(e),credentialState:"active"})}function gA(t){return JSON.stringify({credentialIdentity:Gi(t),credentialState:"retired",retired:!0})}function yA(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=hA(e),s=Tu(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 ku(t){try{let e=Om(t),r=e.serverMetadata,n=e.client;if(!r||!n||typeof e.accessToken!="string"||e.accessToken.length===0||typeof r.authorization_endpoint!="string"||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var qo=class{_memory=new $n;_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=pA){this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"&&this._memory.seed(n)}get(e){return this._memory.get(e)}commit(e,r){this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,o)}).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r,n),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,o)});return}await this._persist(e,r,n,!1),this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}_beginRegistryMemoryWrite(e,r){let n=yr(r);if(!n)throw new V;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=Yt(e),n=yr(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 V}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<qi;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new V}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=In(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new V;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=ku(i.value);if(!c)throw new V;try{await r.upsertUserSecret(n,Wr(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Yt(e),n=yr(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new V;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new V;let i=In(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!ku(s.value))throw new V;return s.version})}catch{throw new V}}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=Yt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,Wr(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 V;if(c)return{revision:await this._asPersistenceResult(c()),domain:Hi(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=Yt(o),c;if(a&&o){if(!i||s?.domain!==`private:${o.id}`)throw new V;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 V;if(a&&o){try{await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredential({client:i,key:jt(e),persistedToken:r,currentToken:n,registry:o}))}catch{Lt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return c}if(s?.domain!==Hi(e))throw new V;try{return await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredentialExact({client:i,key:jt(e),serverName:e,persistedToken:r,currentToken:n,registry:o,persistedRevision:s}))}catch{throw new V}}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!==Fo(s,a)))try{return{revision:await r.upsertUserSecret(n,Fo(i,a),c.revision),domain:Hi(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!==Wr(o,i)))try{return{revision:await r.upsertUserSecret(n,Wr(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!==Fo(o,i)))try{await r.upsertUserSecret(n,Fo(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 V}if(o?.(),s?.id&&!i)throw new V;try{await n?.()}catch{Lt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return s?.id&&i?{revision:i,domain:`private:${s.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let s=yr(o);if(!s)throw new V;for(let i=0;i<qi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?In(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new V;try{return await this._upsertUserSecretOnce(e,r,Wr(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new V}async _retireRegistryCredential(e,r,n){let o=yr(n);if(!o)throw new V;for(let s=0;s<qi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?In(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new V;try{await this._upsertUserSecretOnce(e,r,gA(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new V}_isVersionConflict(e){return e instanceof dt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=Yt(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 V;if(u)return{revision:await this._asPersistenceResult(u()),domain:Hi(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new V}}_enqueueWrite(e,r,n){let o=Nm(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?lA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new zn;try{return await n()}catch(a){this._throwIfPersistenceCanceled(e,r,o);let c=this._persistenceRetryDelay(a,i,o);if(c===void 0)throw a;await this._delay(c)}}throw new V}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new zn}_persistenceRetryDelay(e,r,n){let o=n?Dm[r]:void 0,s=!(e instanceof V)&&xu(e);if(o===void 0||!s){n&&Lt.warn("MCP OAuth credential persistence exhausted retries",{attempts:r+1,credentialShape:n.credentialShape,operation:n.operation});return}return o}_upsertUserSecretOnce(e,r,n,o){return typeof e.upsertUserSecretOnce=="function"?e.upsertUserSecretOnce(r,n,o):e.upsertUserSecret(r,n,o)}_deleteUserSecretOnce(e,r){return typeof e.deleteUserSecretOnce=="function"?e.deleteUserSecretOnce(r):e.deleteUserSecret(r)}_writeLegacyKey(e,r,n,o){let s=0,i=this._enqueueWrite(jt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,jt(e),Fo(r,o));return this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e),c},{credentialShape:"legacy",operation:"write",onGeneration:a=>{s=a,this._dirtyGenerations.set(e,a)}});return i.catch(a=>{(a instanceof zn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=yr(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=Yt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let f=this._getClient();if(!f)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(f,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new V));let l=this._shouldPersist()&&!i,p;return l&&(c?p=this._enqueueWrite(jt(e),async()=>{let f=await c.upsertUserSecret(jt(e),fA)}):p=Promise.reject(new V)),this._awaitRetirements(e,d,p).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Lt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Lt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(s.status==="rejected")throw s.reason}delete(e,r){if(this._memory.delete(e),this._memory.clearAuthRequired(e),this._dirtyGenerations.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._retireRegistryKey(r),!this._shouldPersist()){this._dirtyGenerations.delete(e);return}let n=jt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let i=this._getClient();if(!i)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(i,n)},{credentialShape:"legacy",operation:"delete",onGeneration:i=>{o=i,this._dirtyGenerations.set(e,i)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(i=>{i instanceof zn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Yt(e);!r||!e||!this._canScheduleDurableOperation(r)||this._enqueueWrite(r,async()=>{let n=this._getClient();if(!n)throw new Error("MCP secrets client unavailable");await this._retireRegistryCredential(n,r,e)},{credentialShape:"registry",operation:"delete"}).catch(()=>{Lt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(Nm(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=Yt(r),o=yr(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<qi;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=In(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=ku(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,Wr(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=Yt(n),i=yr(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=In(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,Wr(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(jt(r));return o?yA(o,n):void 0}catch{return}}async ensureLoaded(e,r){if(this._memory.get(e)||!this._shouldPersist()||this.hasInFlightWrite(e))return;let o=this._getClient();if(!o)return;let s=this._memory.credentialRetirementGeneration(e),i=await this._loadRegistryToken(o,r);if(i.identityRejected)return;let a=i.token;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,i.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Lt.debug(`Backend secret for MCP server "${e}" is not a usable OAuth token; ignoring`);return}this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s||(this._memory.set(e,a),Lt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var Lm="Augment Code",jm="https://augmentcode.com",Um="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var _A=1e3,SA=500;function $u(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Ho(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Au=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function Fm(t){return new URLSearchParams({k:t}).toString().slice(2)}function wA(t,e){let r=`${Fm(t)}:${Fm(e)}`;return`Basic ${btoa(r)}`}function Zm(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function bA(t){return t.client.token_endpoint_auth_method==="none"||!Zm(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function RA(t){return t==="basic"?"body":t==="body"?"basic":void 0}function PA(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var CA=401,Vm=500;function Mu(t,...e){return t.status<Vm&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function qm(t){return Mu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===CA}async function Hm(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=Zm(t);e==="basic"&&s?n.Authorization=wA(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=PA(c),d=c.slice(0,SA);throw new Kr(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Au;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*_A:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function Gm(t,e){try{return await Hm(t,e,t.resource)}catch(r){if(r instanceof Kr&&t.resource&&Mu(r,"invalid_target"))return await Hm(t,e,void 0);throw r}}var Kr=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 Iu(t){return!(t instanceof Kr)||t.status>=Vm?!1:Mu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function zu(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=bA(t);try{return await Gm(e,r)}catch(n){let o=RA(r);if(!(n instanceof Kr)||!o||!qm(n))throw n;try{return await Gm(e,o)}catch(s){throw s instanceof Kr&&qm(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as _0}from"@hermes/logger";var Du;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Du="oauth4webapi/v3.8.6");function Ln(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 Ut="ERR_INVALID_ARG_VALUE",Ke="ERR_INVALID_ARG_TYPE";function le(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var qu=Symbol(),xA=Symbol(),kA=Symbol(),Yr=Symbol();var Bm=Symbol();var EA=new TextEncoder,TA=new TextDecoder;function Lu(t){return typeof t=="string"?EA.encode(t):TA.decode(t)}var ju;Uint8Array.prototype.toBase64?ju=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):ju=e=>{e instanceof ArrayBuffer&&(e=new Uint8Array(e));let r=[];for(let n=0;n<e.byteLength;n+=32768)r.push(String.fromCharCode.apply(null,e.subarray(n,n+32768)));return btoa(r.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var Uu;Uint8Array.fromBase64?Uu=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw le("The input to be decoded is not correctly encoded.",Ut,e)}}:Uu=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw le("The input to be decoded is not correctly encoded.",Ut,e)}};function Vi(t){return typeof t=="string"?Uu(t):ju(t)}var Nn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=a0,Error.captureStackTrace?.(this,this.constructor)}},Go=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function I(t,e,r){return new Go(t,{code:e,cause:r})}function Bi(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Hu(t){Ln(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Du&&!e.has("user-agent")&&e.set("user-agent",Du),e.has("authorization"))throw le('"options.headers" must not include the "authorization" header name',Ut);return e}function Gu(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw le('"options.signal" must return or be an instance of AbortSignal',Ke);return e}}function AA(t){return t.includes("//")?t.replace("//","/"):t}function $A(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=AA(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function MA(t,e,r,n){if(!(t instanceof URL))throw le(`"${e}" must be an instance of URL`,Ke);og(t,n?.[qu]!==!0);let o=r(new URL(t.href)),s=Hu(n?.headers);return s.set("accept","application/json"),(n?.[Yr]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:Gu(o,n?.signal)})}function On(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw le(`${r} must be a number`,Ke,o);if(t>0)return;if(e){if(t!==0)throw le(`${r} must be a non-negative number`,Ut,o);return}throw le(`${r} must be a positive number`,Ut,o)}catch(s){throw n?I(s.message,n,o):s}}function Ee(t,e,r,n){try{if(typeof t!="string")throw le(`${e} must be a string`,Ke,n);if(t.length===0)throw le(`${e} must not be empty`,Ut,n)}catch(o){throw r?I(o.message,r,n):o}}async function Jm(t,e){let r=t;if(!(r instanceof URL)&&r!==Ji)throw le('"expectedIssuerIdentifier" must be an instance of URL',Ke);if(!Ln(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Xu,e);Bo(e);let n=await ea(e);if(Ee(n.issuer,'"response" body "issuer" property',B,{body:n}),r!==Ji&&new URL(n.issuer).href!==r.href)throw I('"response" body "issuer" property does not match the expected value',Xi,{expected:r.href,body:n,attribute:"issuer"});return n}function Ym(t){zA(t,"application/json")}function IA(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return I(r,u0,t)}function zA(t,e){if(VA(t)!==e)throw IA(t,e)}function Zu(){return Vi(crypto.getRandomValues(new Uint8Array(32)))}function Xm(){return Zu()}function Qm(){return Zu()}function eg(){return Zu()}async function tg(t){return Ee(t,"codeVerifier"),Vi(await crypto.subtle.digest("SHA-256",Lu(t)))}function Vu(t){let e=t?.[xA];return typeof e=="number"&&Number.isFinite(e)?e:0}function Bu(t){let e=t?.[kA];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Wu(){return Math.floor(Date.now()/1e3)}function Yi(t){if(typeof t!="object"||t===null)throw le('"as" must be an object',Ke);Ee(t.issuer,'"as.issuer"')}function Ku(t){if(typeof t!="object"||t===null)throw le('"client" must be an object',Ke);Ee(t.client_id,'"client.client_id"')}function Wm(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 Ju(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function rg(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{let s=Wm(r.client_id),i=Wm(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function ng(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var OA=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function og(t,e){if(e&&t.protocol!=="https:")throw I("only requests to HTTPS are allowed",d0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw I("only HTTP and HTTPS requests are allowed",l0,t)}function Km(t,e,r,n){let o;if(typeof t!="string"||!(o=OA(t)))throw I(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?p0:f0,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return og(o,n),o}function sg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Km(t.mtls_endpoint_aliases[e],e,r,n):Km(t[e],e,r,n)}var Dn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=i0,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)}},Zo=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=c0,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)}},Vo=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=s0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Wi="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",NA="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",DA='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',LA="("+Wi+")\\s*=\\s*"+DA,jA="("+Wi+")\\s*=\\s*("+Wi+")",UA=new RegExp("^[,\\s]*("+Wi+")"),FA=new RegExp("^[,\\s]*"+LA+"[,\\s]*(.*)"),qA=new RegExp("^[,\\s]*"+jA+"[,\\s]*(.*)"),HA=new RegExp("^("+NA+")(?:$|[,\\s])(.*)");function GA(t){if(!Ln(t,Response))throw le('"response" must be an instance of Response',Ke);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(UA),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let p,f;if(o=n.match(FA)){if([,p,f,n]=o,f.includes("\\"))try{f=JSON.parse(`"${f}"`)}catch{}u[p.toLowerCase()]=f;continue}if(o=n.match(qA)){[,p,f,n]=o,u[p.toLowerCase()]=f;continue}if(o=n.match(HA)){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 ZA(t){if(t.status>399&&t.status<500){Bo(t),Ym(t);try{let e=await t.clone().json();if(Bi(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function ig(t,e,r){if(t.status!==e){JA(t);let n;throw(n=await ZA(t))?(await t.body?.cancel(),new Dn("server responded with an error in the response body",{cause:n,response:t})):I(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Xu,t)}}function ag(t){if(!Yu.has(t))throw le('"options.DPoP" is not a valid DPoPHandle',Ut)}function VA(t){return t.headers.get("content-type")?.split(";")[0]}async function BA(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?.[Yr]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Gu(n,i?.signal)})}async function WA(t,e,r,n,o,s){let i=sg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[qu]!==!0);o.set("grant_type",n);let a=Hu(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(ag(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await BA(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var cg=new WeakMap,KA=new WeakMap;function ug(t){if(!t.id_token)return;let e=cg.get(t);if(!e)throw le('"ref" was already garbage collected or did not resolve from the proper sources',Ut);return e}async function dg(t,e,r,n,o,s){if(Yi(t),Ku(e),!Ln(r,Response))throw le('"response" must be an instance of Response',Ke);await ig(r,200,"Token Endpoint"),Bo(r);let i=await ea(r);if(Ee(i.access_token,'"response" body "access_token" property',B,{body:i}),Ee(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;On(a,!0,'"response" body "expires_in" property',B,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ee(i.refresh_token,'"response" body "refresh_token" property',B,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw I('"response" body "scope" property must be a string',B,{body:i});if(i.id_token!==void 0){Ee(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&&(On(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await h0(i.id_token,m0.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Vu(e),Bu(e),o).then(r0.bind(void 0,a)).then(XA.bind(void 0,t)).then(YA.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw I('ID Token "aud" (audience) claim includes additional untrusted audiences',vr,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw I('unexpected ID Token "azp" (authorized party) claim value',vr,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&On(c.auth_time,!0,'ID Token "auth_time" (authentication time)',B,{claims:c}),KA.set(r,u),cg.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 Nn("unsupported `token_type` value",{cause:{body:i}});return i}function JA(t){let e;if(e=GA(t))throw new Vo("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function YA(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw I('unexpected JWT "aud" (audience) claim value',vr,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw I('unexpected JWT "aud" (audience) claim value',vr,{expected:t,claims:e.claims,claim:"aud"});return e}function XA(t,e){let r=t[v0]?.(e)??t.issuer;if(e.claims.iss!==r)throw I('unexpected JWT "iss" (issuer) claim value',vr,{expected:r,claims:e.claims,claim:"iss"});return e}var Yu=new WeakSet;function QA(t){return Yu.add(t),t}var e0=Symbol();async function lg(t,e,r,n,o,s,i){if(Yi(t),Ku(e),!Yu.has(n))throw le('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ut);Ee(o,'"redirectUri"');let a=Jr(n,"code");if(!a)throw I('no authorization code in "callbackParameters"',B);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==e0&&(Ee(s,'"codeVerifier"'),c.set("code_verifier",s)),WA(t,e,r,"authorization_code",c,i)}var t0={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 r0(t,e){for(let r of t)if(e.claims[r]===void 0)throw I(`JWT "${r}" (${t0[r]}) claim missing`,B,{claims:e.claims});return e}var Ou=Symbol(),Nu=Symbol();async function pg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?n0(t,e,r,n.expectedNonce,n.maxAge,n[Bm],n.recognizedTokenTypes):o0(t,e,r,n?.[Bm],n?.recognizedTokenTypes)}async function n0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=Ou;break;case Ou:break;default:Ee(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Nu;break;case Nu:break;default:On(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await dg(t,e,r,a,s,i);Ee(c.id_token,'"response" body "id_token" property',B,{body:c});let u=ug(c);if(o!==Nu){let d=Wu()+Vu(e),l=Bu(e);if(u.auth_time+o<d-l)throw I("too much time has elapsed since the last End-User authentication",Ki,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===Ou){if(u.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',vr,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw I('unexpected ID Token "nonce" claim value',vr,{expected:n,claims:u,claim:"nonce"});return c}async function o0(t,e,r,n,o){let s=await dg(t,e,r,void 0,n,o),i=ug(s);if(i){if(e.default_max_age!==void 0){On(e.default_max_age,!0,'"client.default_max_age"');let a=Wu()+Vu(e),c=Bu(e);if(i.auth_time+e.default_max_age<a-c)throw I("too much time has elapsed since the last End-User authentication",Ki,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',vr,{expected:void 0,claims:i,claim:"nonce"})}return s}var s0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",i0="OAUTH_RESPONSE_BODY_ERROR",a0="OAUTH_UNSUPPORTED_OPERATION",c0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Fu="OAUTH_PARSE_ERROR",B="OAUTH_INVALID_RESPONSE";var u0="OAUTH_RESPONSE_IS_NOT_JSON",Xu="OAUTH_RESPONSE_IS_NOT_CONFORM",d0="OAUTH_HTTP_REQUEST_FORBIDDEN",l0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Ki="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",vr="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Xi="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var p0="OAUTH_MISSING_SERVER_METADATA",f0="OAUTH_INVALID_SERVER_METADATA";function Bo(t){if(t.bodyUsed)throw le('"response" body has been used already',Ut)}async function h0(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 Nn("JWE decryption is not configured",{cause:t});if(a!==3)throw I("Invalid JWT",B,t);let c;try{c=JSON.parse(Lu(Vi(s)))}catch(l){throw I("failed to parse JWT Header body as base64url encoded JSON",Fu,l)}if(!Bi(c))throw I("JWT Header must be a top level object",B,t);if(e(c),c.crit!==void 0)throw new Nn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Lu(Vi(i)))}catch(l){throw I("failed to parse JWT Payload body as base64url encoded JSON",Fu,l)}if(!Bi(u))throw I("JWT Payload must be a top level object",B,t);let d=Wu()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw I('unexpected JWT "exp" (expiration time) claim type',B,{claims:u});if(u.exp<=d-n)throw I('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Ki,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw I('unexpected JWT "iat" (issued at) claim type',B,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw I('unexpected JWT "iss" (issuer) claim type',B,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw I('unexpected JWT "nbf" (not before) claim type',B,{claims:u});if(u.nbf>d+n)throw I('unexpected JWT "nbf" (not before) claim value',Ki,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw I('unexpected JWT "aud" (audience) claim type',B,{claims:u});return{header:c,claims:u,jwt:t}}function m0(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw I('unexpected JWT "alg" header parameter',B,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw I('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 I('unexpected JWT "alg" header parameter',B,{header:n,expected:r,reason:"default value"});return}throw I('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Jr(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw I(`"${e}" parameter must be provided only once`,B);return r}var g0=Symbol(),y0=Symbol();function fg(t,e,r,n){if(Yi(t),Ku(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw le('"parameters" must be an instance of URLSearchParams, or URL',Ke);if(Jr(r,"response"))throw I('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',B,{parameters:r});let o=Jr(r,"iss"),s=Jr(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw I('response parameter "iss" (issuer) missing',B,{parameters:r});if(o&&o!==t.issuer)throw I('unexpected "iss" (issuer) response parameter value',B,{expected:t.issuer,parameters:r});switch(n){case void 0:case y0:if(s!==void 0)throw I('unexpected "state" response parameter encountered',B,{expected:void 0,parameters:r});break;case g0:break;default:if(Ee(n,'"expectedState" argument'),s!==n)throw I(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',B,{expected:n,parameters:r})}if(Jr(r,"error"))throw new Zo("authorization response from the server is an error",{cause:r});let a=Jr(r,"id_token"),c=Jr(r,"token");if(a!==void 0||c!==void 0)throw new Nn("implicit and hybrid flows are not supported");return QA(new URLSearchParams(r))}async function hg(t,e,r){Yi(t);let n=sg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[qu]!==!0),o=Hu(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(ag(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?.[Yr]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:Gu(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function mg(t){if(!Ln(t,Response))throw le('"response" must be an instance of Response',Ke);await ig(t,201,"Dynamic Client Registration Endpoint"),Bo(t);let e=await ea(t);return Ee(e.client_id,'"response" body "client_id" property',B,{body:e}),e.client_secret!==void 0&&Ee(e.client_secret,'"response" body "client_secret" property',B,{body:e}),e.client_secret&&On(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',B,{body:e}),e}async function gg(t,e){return MA(t,"resourceIdentifier",r=>($A(r,".well-known/oauth-protected-resource",!0),r),e)}async function Qi(t,e){let r=t;if(!(r instanceof URL)&&r!==Ji)throw le('"expectedResourceIdentifier" must be an instance of URL',Ke);if(!Ln(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',Xu,e);Bo(e);let n=await ea(e);if(Ee(n.resource,'"response" body "resource" property',B,{body:n}),r!==Ji&&new URL(n.resource).href!==r.href)throw I('"response" body "resource" property does not match the expected value',Xi,{expected:r.href,body:n,attribute:"resource"});return n}async function ea(t,e=Ym){let r;try{r=await t.json()}catch(n){throw e(t),I('failed to parse "response" body as JSON',Fu,n)}if(!Bi(r))throw I('"response" body must be a top level object',B,{body:r});return r}var Ji=Symbol(),v0=Symbol();var _g=_0.child({prefix:"pi-mcp"}),Wo=1e4,S0=1e3,w0=401,yg=200,b0=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,R0=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Sg;function jn(){return Sg??globalThis.fetch}function wg(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function bg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function ed(t){let e=bg(t);try{let r=await P0(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await T0(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ta(r)}throw new Error("Failed to discover metadata URL")}async function P0(t){try{let e=await gg(t,{signal:AbortSignal.timeout(Wo),[Yr]:Sg??void 0});return e.ok?await Qi(t,e):(e.body?.cancel().catch(()=>{}),await Rg(t,e.headers.get("www-authenticate"))??await vg(t))}catch{return await vg(t)}}async function vg(t){for(let e of["HEAD","GET"])try{let r=await jn()(t,{method:e,signal:AbortSignal.timeout(Wo)});r.body?.cancel().catch(()=>{});let n=await Rg(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Rg(t,e){let r=E0(e);if(r)try{let n=await jn()(r,{signal:AbortSignal.timeout(Wo)});return await C0(t,n)}catch{return}}async function C0(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await Qi(t,new Response(r,n))}catch(o){if(!(o instanceof Go)||o.code!==Xi)throw o;let s=x0(r);if(!s||!k0(s,t))throw o;return await Qi(s,new Response(r,n))}}function x0(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function k0(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 E0(t){if(!t)return;let e=t.match(b0),r=t.match(R0),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function T0(t){for(let e of A0(t))try{let r=new URL(e,t),n=await jn()(r,{signal:AbortSignal.timeout(Wo)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function A0(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 td(t){try{let e=await jn()(t,{signal:AbortSignal.timeout(Wo)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await $0(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await Jm(o,new Response(r,n))}catch(e){throw ta(e)}}async function $0(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 Qu=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 M0(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 rd({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return M0({...t,clientId:n});if(!e.registration_endpoint)throw new Qu(e.issuer);return await I0(e,r)}async function I0(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await hg(t,{client_name:Lm,client_uri:jm,logo_uri:Um,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[Yr]:z0});return n.ok||_g.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await mg(n)}catch(r){throw ta(r)}}async function z0(t,e){let r=await jn()(t,wg(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||_g.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${N0(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 O0(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}),jn()(t,wg(o))}function N0(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>yg?`${t.slice(0,yg)}\u2026`:t}}async function nd(t,e,r,n,o,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let i=Xm(),a=await tg(i),c=Qm(),u,d=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean).join(" ")||void 0,l=bg(s??t).toString(),p=new URL(r.authorization_endpoint);return p.searchParams.set("response_type","code"),p.searchParams.set("client_id",e.client_id),p.searchParams.set("code_challenge",a),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("redirect_uri",n),p.searchParams.set("resource",l),p.searchParams.set("state",c),d&&p.searchParams.set("scope",d),r.code_challenge_methods_supported?.includes("S256")||(u=eg(),p.searchParams.set("nonce",u)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:i,nonce:u,scope:d,state:c,resource:l,authUri:p}}async function D0(t,e,r){let n=await lg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[Yr]:O0,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return pg(t.serverMetadata,t.client,await L0(n))}async function od(t,e){try{let r=fg(e.serverMetadata,e.client,t,e.state),n=await U0(e.client,o=>D0(e,r,o));return H0(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ta(r)}}async function L0(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 Pg(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function j0(t){let e=Pg(t);return e===void 0?ng():t.token_endpoint_auth_method==="client_secret_basic"?rg(e):Ju(e)}async function U0(t,e){try{return await e(j0(t))}catch(r){let n=F0(t);if(n&&q0(r))return await e(n);throw r}}function F0(t){let e=Pg(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return Ju(e)}function q0(t){return t instanceof Dn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof Vo?t.status===w0||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function H0(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*S0:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ta(t){if(t instanceof Dn||t instanceof Zo){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 G0=/(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,Cg=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,xg=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,kg=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Ko="[redacted]";function Z0(t){return Cg.test(t)||xg.test(t)||kg.test(t)}var V0=new RegExp(Cg.source,"g"),B0=new RegExp(xg.source,"gi"),W0=new RegExp(kg.source,"g");function Eg(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function id(t){return t&&Eg(t,8192).replace(V0,Ko).replace(B0,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Ko}`).replace(W0,Ko)}function sd(t,e,r){if(e)return Ko;if(typeof t=="string")return Z0(t)?Ko:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>sd(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=sd(s,G0.test(o),r+1);return n}function Tg(t,e=500){if(t==null)return;let r=sd(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return Eg(n,e)}var $g={reportError:()=>{}},Ag=Symbol.for("__pi_mcp_error_reporter_slot__");function Mg(){let t=globalThis,e=t[Ag];return e||(e={reporter:null},t[Ag]=e),e}function Ig(t){let e=Mg(),r=e.reporter??$g;return e.reporter=t,r}function K0(){return Mg().reporter??$g}function ad(t,e){try{K0().reportError(t,e)}catch{}}import{logger as J0}from"@hermes/logger";var zg=J0.child({prefix:"pi-mcp"});function Og(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++):zg.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,zg.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function Ng(t){return e=>{if(!e.startsWith(Eu)){let n=t.headerSecrets[e];if(n!==void 0)return Promise.resolve(n)}let r=t.secretsClient;return r?r.getSecret(e):Promise.resolve(void 0)}}function Dg(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0}import{logger as Y0}from"@hermes/logger";var Jo=Y0.child({prefix:"pi-mcp"}),X0="$augment-",Yo=/\$augment-[a-zA-Z0-9_.-]+/g,Q0=new RegExp(Yo.source);function ra(t){return Q0.test(t)}function na(t){return t.slice(X0.length)}function cd(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(Yo))e.add(na(n[0]));return[...e].sort()}var Pt=class extends Error{serverName;missingKeys;constructor(e,r,n){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}};async function Lg(t,e,r,n,o,s){let i=[...t.matchAll(Yo)];if(i.length===0)return t;let a=t;for(let c=i.length-1;c>=0;c--){let u=i[c],d=u[0],l=u.index,p=na(d);try{let f=await r(p);if(f===void 0){n.add(p),Jo.warn(`Secret "${p}" not found for "${e}"; leaving reference as-is`);continue}f.trim()===""&&(o.add(p),Jo.warn(`Secret "${p}" resolved empty for "${e}"`));let h=a.slice(0,l),m=s?s(f,h):f;a=h+m+a.slice(l+d.length),Jo.debug(`Resolved secret reference for "${e}"`)}catch(f){n.add(p);let h=f instanceof Error?f.message:String(f);Jo.error(`Failed to resolve secret "${p}" for "${e}": ${h}; leaving reference as-is`)}}return a}async function jg({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set;for(let[i,a]of Object.entries(t)){if(!ra(a)){n[i]=a;continue}if(i in e){Jo.debug(`"${i}" references a secret but is already set in the local environment; using local value`),n[i]=e[i];continue}n[i]=await Lg(a,i,r,o,s)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort()}}var e$=/["$`\\]/g;function t$(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 r$(t,e){let r=t$(e);if(r==="double")return t.replace(e$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function Ug(t,e){let r=new Set,n=new Set;return{resolved:await Lg(t,"command",e,r,n,r$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort()}}import{AsyncLocalStorage as NU}from"node:async_hooks";var Fg,ud=Object.freeze({status:"aborted"});function v(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let p=d[l];p in a||(a[p]=u[p].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ft=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Un=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Fg=globalThis).__zod_globalConfig??(Fg.__zod_globalConfig={});var Fn=globalThis.__zod_globalConfig;function Je(t){return t&&Object.assign(Fn,t),Fn}var F={};su(F,{BIGINT_FORMAT_RANGES:()=>Zg,Class:()=>ld,NUMBER_FORMAT_RANGES:()=>yd,aborted:()=>wr,allowsEval:()=>hd,assert:()=>a$,assertEqual:()=>n$,assertIs:()=>s$,assertNever:()=>i$,assertNotEqual:()=>o$,assignProp:()=>_r,base64ToUint8Array:()=>Bg,base64urlToUint8Array:()=>P$,cached:()=>Hn,captureStackTrace:()=>ia,cleanEnum:()=>R$,cleanRegex:()=>ts,clone:()=>lt,cloneDef:()=>u$,createTransparentProxy:()=>m$,defineLazy:()=>Y,esc:()=>sa,escapeRegex:()=>Qt,explicitlyAborted:()=>vd,extend:()=>v$,finalizeIssue:()=>pt,floatSafeRemainder:()=>pd,getElementAtPath:()=>d$,getEnumValues:()=>Qo,getLengthableOrigin:()=>rs,getParsedType:()=>h$,getSizableOrigin:()=>Vg,hexToUint8Array:()=>x$,isObject:()=>Xr,isPlainObject:()=>Sr,issue:()=>Gn,joinValues:()=>oa,jsonStringifyReplacer:()=>qn,merge:()=>S$,mergeDefs:()=>Xt,normalizeParams:()=>A,nullish:()=>es,numKeys:()=>f$,objectClone:()=>c$,omit:()=>y$,optionalKeys:()=>gd,parsedType:()=>_d,partial:()=>w$,pick:()=>g$,prefixIssues:()=>er,primitiveTypes:()=>Gg,promiseAllObject:()=>l$,propertyKeyTypes:()=>md,randomString:()=>p$,required:()=>b$,safeExtend:()=>_$,shallowClone:()=>Hg,slugify:()=>fd,stringifyPrimitive:()=>aa,uint8ArrayToBase64:()=>Wg,uint8ArrayToBase64url:()=>C$,uint8ArrayToHex:()=>k$,unwrapMessage:()=>Xo});function n$(t){return t}function o$(t){return t}function s$(t){}function i$(t){throw new Error("Unexpected value in exhaustive check")}function a$(t){}function Qo(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 oa(t,e="|"){return t.map(r=>aa(r)).join(e)}function qn(t,e){return typeof e=="bigint"?e.toString():e}function Hn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function es(t){return t==null}function ts(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function pd(t,e){let r=t/e,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}var qg=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==qg)return n===void 0&&(n=qg,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function c$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function _r(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Xt(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function u$(t){return Xt(t._zod.def)}function d$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function l$(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function p$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function sa(t){return JSON.stringify(t)}function fd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var ia="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Xr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hd=Hn(()=>{if(Fn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Sr(t){if(Xr(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Xr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Hg(t){return Sr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function f$(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var h$=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}`)}},md=new Set(["string","number","symbol"]),Gg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(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 m$(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 aa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function gd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var yd={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]},Zg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function g$(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=Xt(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 _r(this,"shape",i),i},checks:[]});return lt(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=Xt(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 _r(this,"shape",i),i},checks:[]});return lt(t,s)}function v$(t,e){if(!Sr(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=Xt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return _r(this,"shape",s),s}});return lt(t,o)}function _$(t,e){if(!Sr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Xt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return _r(this,"shape",n),n}});return lt(t,r)}function S$(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=Xt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return _r(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return lt(t,r)}function w$(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=Xt(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 _r(this,"shape",c),c},checks:[]});return lt(e,i)}function b$(t,e,r){let n=Xt(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 _r(this,"shape",s),s}});return lt(e,n)}function wr(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 vd(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 er(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Xo(t){return typeof t=="string"?t:t?.message}function pt(t,e,r){let n=t.message?t.message:Xo(t.inst?._zod.def?.error?.(t))??Xo(e?.error?.(t))??Xo(r.customError?.(t))??Xo(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 Vg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function rs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _d(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 Gn(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function R$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Bg(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 Wg(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function P$(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Bg(e+r)}function C$(t){return Wg(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function x$(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 k$(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var ld=class{constructor(...e){}};var Kg=(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,qn,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ca=v("$ZodError",Kg),Sd=v("$ZodError",Kg,{Parent:Error});function wd(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 bd(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 ua=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 Ft;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>pt(c,s,Je())));throw ia(a,o?.callee),a}return i.value};var da=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=>pt(c,s,Je())));throw ia(a,o?.callee),a}return i.value};var ns=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 Ft;return s.issues.length?{success:!1,error:new(t??ca)(s.issues.map(i=>pt(i,o,Je())))}:{success:!0,data:s.value}},os=ns(Sd),ss=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=>pt(i,o,Je())))}:{success:!0,data:s.value}},la=ss(Sd),Jg=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ua(t)(e,r,o)};var Yg=t=>(e,r,n)=>ua(t)(e,r,n);var Xg=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return da(t)(e,r,o)};var Qg=t=>async(e,r,n)=>da(t)(e,r,n);var ey=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ns(t)(e,r,o)};var ty=t=>(e,r,n)=>ns(t)(e,r,n);var ry=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return ss(t)(e,r,o)};var ny=t=>async(e,r,n)=>ss(t)(e,r,n);var oy=/^[cC][0-9a-z]{6,}$/,sy=/^[0-9a-z]+$/,iy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ay=/^[0-9a-vA-V]{20}$/,cy=/^[A-Za-z0-9]{27}$/,uy=/^[a-zA-Z0-9_-]{21}$/,dy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var ly=/^([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})$/,Rd=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 py=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var T$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fy(){return new RegExp(T$,"u")}var hy=/^(?:(?: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])$/,my=/^(([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 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])\/([0-9]|[1-2][0-9]|3[0-2])$/,yy=/^(([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}=))?$/,Pd=/^[A-Za-z0-9_-]*$/;var _y=/^https?$/,Sy=/^\+[1-9]\d{6,14}$/,wy="(?:(?:\\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])))",by=new RegExp(`^${wy}$`);function Ry(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 Py(t){return new RegExp(`^${Ry(t)}$`)}function Cy(t){let e=Ry({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(`^${wy}T(?:${n})$`)}var xy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},ky=/^-?\d+n?$/,Ey=/^-?\d+$/,Cd=/^-?\d+(?:\.\d+)?$/,Ty=/^(?:true|false)$/i,Ay=/^null$/i;var $y=/^[^A-Z]*$/,My=/^[^a-z]*$/;var Te=v("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Iy={number:"number",bigint:"bigint",object:"date"},xd=v("$ZodCheckLessThan",(t,e)=>{Te.init(t,e);let r=Iy[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})}}),kd=v("$ZodCheckGreaterThan",(t,e)=>{Te.init(t,e);let r=Iy[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zy=v("$ZodCheckMultipleOf",(t,e)=>{Te.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):pd(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})}}),Oy=v("$ZodCheckNumberFormat",(t,e)=>{Te.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=yd[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=Ey)}),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 Ny=v("$ZodCheckMaxLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!es(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=rs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Dy=v("$ZodCheckMinLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!es(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=rs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ly=v("$ZodCheckLengthEquals",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!es(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=rs(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})}}),as=v("$ZodCheckStringFormat",(t,e)=>{var r,n;Te.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),jy=v("$ZodCheckRegex",(t,e)=>{as.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})}}),Uy=v("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=$y),as.init(t,e)}),Fy=v("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=My),as.init(t,e)}),qy=v("$ZodCheckIncludes",(t,e)=>{Te.init(t,e);let r=Qt(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})}}),Hy=v("$ZodCheckStartsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`^${Qt(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})}}),Gy=v("$ZodCheckEndsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`.*${Qt(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 Zy=v("$ZodCheckOverwrite",(t,e)=>{Te.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var pa=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 Br(t){let e={name:Uo,label:Uo,description:fA(),parameters:$m.Unsafe(aA),execute:(n,o,s,i,a)=>lA(t,a,o)},r={name:Zr,label:Zr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:$m.Unsafe(cA),execute:(n,o,s)=>pA(t,o,s)};Am(Uo,"mcp"),Am(Zr,"mcp"),t.registerTool(e),t.registerTool(r),gr(e),gr(r),Im.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as VU}from"@hermes/logger";import{logger as yA}from"@hermes/logger";import{logger as hA}from"@hermes/logger";function Vr(t){return new Promise(e=>setTimeout(e,t))}var Om=hA.child({prefix:"pi-mcp"}),Fo={maxTries:3,initialMs:500,mult:2,maxMs:2e3},xu=3e4,Jt=200,dt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function ku(t){return t instanceof dt?t.statusCode>=500:!0}async function Wr(t){let e;for(let r=0;r<Fo.maxTries;r++)try{return await t()}catch(n){if(e=n,!ku(n))throw n;if(r<Fo.maxTries-1){let o=Math.min(Fo.initialMs*Fo.mult**r,Fo.maxMs);await Vr(o)}}throw e}var qi=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??xu}async callApi(e,r){let o=await(this.fetchImpl??fetch)(`${this.apiUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:r===void 0?"{}":JSON.stringify({product_type:r}),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let s=await o.text().catch(()=>""),i=s.length>Jt?`${s.slice(0,Jt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return Wr(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return Wr(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function Nm(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)}`;Om.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)}`;Om.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function mA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var Dm=32;function gA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>Dm&&(e=e.slice(0,Dm)),e=e.replace(/_+$/,""),e}function Lm(t,e){let r=e?gA(e):"",n=mA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function jm(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}function Um(t){let e=JSON.parse(t);if(typeof e.accessToken!="string")throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:e.accessToken,refreshToken:typeof e.refreshToken=="string"?e.refreshToken:void 0,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:typeof e.expiresAt=="number"?e.expiresAt:void 0,resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Lt=yA.child({prefix:"pi-mcp"}),B=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},On=class extends Error{},qm=[100,500],vA=qm.length+1,_A=t=>new Promise(e=>{setTimeout(e,t)});function Fm(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Tu="augment.mcp-access-token.",SA=JSON.stringify({retired:!0}),Hi=3;function jt(t){return`${Tu}${t}`}function Gi(t){return`legacy:${t}`}function Yt(t){return t?.id?Lm(t.id,t.name):void 0}function Zi(t){if(t?.id)return{type:t.type??null,id:t.id,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function vr(t){let e=Zi(t);return e?JSON.stringify(e):void 0}function wA(t){if(t)return JSON.stringify({type:t.type??null,id:t.id??null,name:t.name??null,url:t.url??null,auth:t.auth??null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null})}function Au(t){if(typeof t=="string")try{return Au(JSON.parse(t))??t}catch{return t}if(typeof t!="object"||t===null||Array.isArray(t))return t===void 0?void 0:JSON.stringify(t);let e=t;return typeof e.id!="string"||e.id.length===0?JSON.stringify(t):JSON.stringify({type:e.type??null,id:e.id,name:e.name??null,url:e.url??null,auth:e.auth??null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function bA(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function zn(t){try{let e=JSON.parse(t);return{credentialIdentity:Au(e.credentialIdentity),state:bA(e)}}catch{return{}}}function qo(t,e){let r={...t,type:"oauth",credentialIdentity:Zi(e)};return JSON.stringify(r)}function Kr(t,e){let r=jm({accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.client.client_secret,expiresAt:t.expiresAt,resource:t.resource,serverMetadata:t.serverMetadata,client:t.client});return JSON.stringify({...JSON.parse(r),credentialIdentity:Zi(e),credentialState:"active"})}function RA(t){return JSON.stringify({credentialIdentity:Zi(t),credentialState:"retired",retired:!0})}function PA(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=wA(e),s=Au(n.credentialIdentity);if(!(o&&s!==void 0&&s!==o)&&!(typeof n.accessToken!="string"||n.accessToken.length===0||typeof n.serverMetadata!="object"||n.serverMetadata===null||typeof n.client!="object"||n.client===null))return n}function Eu(t){try{let e=Um(t),r=e.serverMetadata,n=e.client;if(!r||!n||typeof e.accessToken!="string"||e.accessToken.length===0||typeof r.authorization_endpoint!="string"||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var Ho=class{_memory=new Mn;_getClient;_shouldPersist;_dirtyGenerations=new Map;_durableQueues=new Map;_registryMemoryWriteGenerations=new Map;_registryMemoryAuthorities=new Map;_registryMemoryCommittedAuthorities=new Map;_delay;_nextGeneration=0;constructor(e,r,n,o=_A){this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"&&this._memory.seed(n)}get(e){return this._memory.get(e)}commit(e,r){this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,o)}).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r,n),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).catch(()=>{Lt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,o)});return}await this._persist(e,r,n,!1),this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.delete(e)}_beginRegistryMemoryWrite(e,r){let n=vr(r);if(!n)throw new B;let o=(this._registryMemoryWriteGenerations.get(e)??0)+1;return this._registryMemoryWriteGenerations.set(e,o),this._registryMemoryAuthorities.set(e,n),{generation:o,identity:n,retirementGeneration:this._memory.credentialRetirementGeneration(e)}}_commitRegistryMemoryWrite(e,r,n){this._registryMemoryWriteGenerations.get(e)!==n.generation||this._registryMemoryAuthorities.get(e)!==n.identity||this._memory.credentialRetirementGeneration(e)!==n.retirementGeneration||(this._memory.commit(e,r),this._registryMemoryCommittedAuthorities.set(e,n.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=Yt(e),n=vr(e),o=this._getClient();if(!(!r||!n||!o||!e))try{return await this._enqueueWrite(r,()=>this._captureAuthenticatedIdentityVersion({client:o,key:r,identity:n,registry:e}))}catch{throw new B}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<Hi;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new B}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=zn(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new B;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=Eu(i.value);if(!c)throw new B;try{await r.upsertUserSecret(n,Kr(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=Yt(e),n=vr(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new B;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new B;let i=zn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Eu(s.value))throw new B;return s.version})}catch{throw new B}}persistAuthenticated(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}persistRefresh(e,r,n,o){return this._persistAuthenticated(e,r,n,o)}async _persistAuthenticated(e,r,n,o){let s=this._getClient(),i=Yt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,Kr(r,n),o)):void 0,c=this._shouldPersist()&&s?()=>this._writeLegacyKey(e,r,!1,n):void 0;if(a)return this._drainRegistryWrites(e,a,c,void 0,n);if(n?.id||this._shouldPersist()&&!s)throw new B;if(c)return{revision:await this._asPersistenceResult(c()),domain:Gi(e)}}restoreAfterSupersededRefresh(e,r,n,o,s){return this.restoreAfterSupersededAuthentication(e,r,n,o,s)}async restoreAfterSupersededAuthentication(e,r,n,o,s){let i=this._getClient(),a=Yt(o),c;if(a&&o){if(!i||s?.domain!==`private:${o.id}`)throw new B;if(c=await this._enqueueWrite(a,()=>this._restoreRegistryCredential({client:i,key:a,persistedToken:r,currentToken:n,registry:o,persistedRevision:s})),!c)return}if(!this._shouldPersist())return c;if(!i)throw new B;if(a&&o){try{await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredential({client:i,key:jt(e),persistedToken:r,currentToken:n,registry:o}))}catch{Lt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return c}if(s?.domain!==Gi(e))throw new B;try{return await this._enqueueWrite(jt(e),()=>this._restoreLegacyCredentialExact({client:i,key:jt(e),serverName:e,persistedToken:r,currentToken:n,registry:o,persistedRevision:s}))}catch{throw new B}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:s,currentToken:i,registry:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==qo(s,a)))try{return{revision:await r.upsertUserSecret(n,qo(i,a),c.revision),domain:Gi(o)}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i,persistedRevision:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.version!==a.revision||c.value!==Kr(o,i)))try{return{revision:await r.upsertUserSecret(n,Kr(s,i),a.revision),domain:`private:${i.id}`}}catch(u){if(this._isVersionConflict(u))return;throw u}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,registry:i}=e,a=await r.getUserSecretWithVersion(n);if(!(!a||a.value!==qo(o,i)))try{await r.upsertUserSecret(n,qo(s,i),a.version)}catch(c){if(!this._isVersionConflict(c))throw c}}async _drainRegistryWrites(e,r,n,o,s){let i;try{i=await r}catch{throw new B}if(o?.(),s?.id&&!i)throw new B;try{await n?.()}catch{Lt.error(`Failed to mirror MCP OAuth token for "${e}" to the legacy key`)}return s?.id&&i?{revision:i,domain:`private:${s.id}`}:void 0}async _writeRegistryCredential(e,r,n,o){let s=vr(o);if(!s)throw new B;for(let i=0;i<Hi;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?zn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new B;try{return await this._upsertUserSecretOnce(e,r,Kr(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new B}async _retireRegistryCredential(e,r,n){let o=vr(n);if(!o)throw new B;for(let s=0;s<Hi;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?zn(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,RA(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new B}_isVersionConflict(e){return e instanceof dt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=Yt(n),c=a&&n&&i?this._enqueueWrite(a,()=>{let d=this._getClient();if(!d)throw new Error("MCP secrets client unavailable");return this._writeRegistryCredential(d,a,r,n)},{credentialShape:"registry",operation:"write"}):void 0,u=this._shouldPersist()&&i?()=>this._writeLegacyKey(e,r,o,n):void 0;if(c)return this._drainRegistryWrites(e,c,u,s,n);if(n?.id||this._shouldPersist()&&!i)throw new B;if(u)return{revision:await this._asPersistenceResult(u()),domain:Gi(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new B}}_enqueueWrite(e,r,n){let o=Fm(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?vA:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new On;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 On}_persistenceRetryDelay(e,r,n){let o=n?qm[r]:void 0,s=!(e instanceof B)&&ku(e);if(o===void 0||!s){n&&Lt.warn("MCP OAuth credential persistence exhausted retries",{attempts:r+1,credentialShape:n.credentialShape,operation:n.operation});return}return o}_upsertUserSecretOnce(e,r,n,o){return typeof e.upsertUserSecretOnce=="function"?e.upsertUserSecretOnce(r,n,o):e.upsertUserSecret(r,n,o)}_deleteUserSecretOnce(e,r){return typeof e.deleteUserSecretOnce=="function"?e.deleteUserSecretOnce(r):e.deleteUserSecret(r)}_writeLegacyKey(e,r,n,o){let s=0,i=this._enqueueWrite(jt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,jt(e),qo(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 On||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=vr(r),s=this._registryMemoryCommittedAuthorities.get(e),i=n?.preserveNameState===!0&&(s===void 0||s!==o),a=(this._registryMemoryWriteGenerations.get(e)??0)+1;this._registryMemoryWriteGenerations.set(e,a),this._registryMemoryAuthorities.delete(e);let c=this._getClient(),u=Yt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let f=this._getClient();if(!f)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(f,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new B));let l=this._shouldPersist()&&!i,p;return l&&(c?p=this._enqueueWrite(jt(e),async()=>{let f=await c.upsertUserSecret(jt(e),SA)}):p=Promise.reject(new B)),this._awaitRetirements(e,d,p).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Lt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Lt.error(`Failed to retire legacy MCP OAuth credential for "${e}" durably`),o.status==="rejected")throw o.reason;if(s.status==="rejected")throw s.reason}delete(e,r){if(this._memory.delete(e),this._memory.clearAuthRequired(e),this._dirtyGenerations.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._retireRegistryKey(r),!this._shouldPersist()){this._dirtyGenerations.delete(e);return}let n=jt(e);if(!this._canScheduleDurableOperation(n)){this._dirtyGenerations.delete(e);return}let o=0;this._enqueueWrite(n,async()=>{let i=this._getClient();if(!i)throw new Error("MCP secrets client unavailable");await this._deleteUserSecretOnce(i,n)},{credentialShape:"legacy",operation:"delete",onGeneration:i=>{o=i,this._dirtyGenerations.set(e,i)}}).then(()=>{this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)}).catch(i=>{i instanceof On&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=Yt(e);!r||!e||!this._canScheduleDurableOperation(r)||this._enqueueWrite(r,async()=>{let n=this._getClient();if(!n)throw new Error("MCP secrets client unavailable");await this._retireRegistryCredential(n,r,e)},{credentialShape:"registry",operation:"delete"}).catch(()=>{Lt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(Fm(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=Yt(r),o=vr(r);if(!n||!o||!r)return{identityRejected:!1};try{return await this._enqueueWrite(n,()=>this._readRegistryToken({client:e,key:n,expectedIdentity:o,registry:r}))}catch{return{identityRejected:!0}}}async _readRegistryToken(e){for(let r=0;r<Hi;r+=1){let n=await this._readRegistryTokenAttempt(e);if(n!==void 0)return n}return{identityRejected:!0}}async _readRegistryTokenAttempt(e){let{client:r,key:n,expectedIdentity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return{identityRejected:!1,authorityVersion:"0"};let a=zn(i.value);if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return{identityRejected:!0};let c=Eu(i.value);if(!c)return{identityRejected:!0};if(a.credentialIdentity===o&&a.state==="active")return{identityRejected:!1,token:c};try{return await r.upsertUserSecret(n,Kr(c,s),i.version),{identityRejected:!1,token:c}}catch(u){return this._isVersionConflict(u)?void 0:{identityRejected:!0}}}async _importLegacyToken(e,r,n,o){let s=Yt(n),i=vr(n);if(!s||!i||!n||o===void 0)return;let a=await this._loadLegacyToken(e,r,n);if(a)try{return await this._enqueueWrite(s,async()=>{let c=await e.getUserSecretWithVersion(s);if((c?.version??"0")===o){if(c){let u=zn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,Kr(a,n),o),a}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(jt(r));return o?PA(o,n):void 0}catch{return}}async ensureLoaded(e,r){if(this._memory.get(e)||!this._shouldPersist()||this.hasInFlightWrite(e))return;let o=this._getClient();if(!o)return;let s=this._memory.credentialRetirementGeneration(e),i=await this._loadRegistryToken(o,r);if(i.identityRejected)return;let a=i.token;if(!(this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s)){if(!a){if(this._memory.isCredentialRetired(e))return;a=r?.id?await this._importLegacyToken(o,e,r,i.authorityVersion):await this._loadLegacyToken(o,e,r)}if(!a){Lt.debug(`Backend secret for MCP server "${e}" is not a usable OAuth token; ignoring`);return}this._memory.get(e)||this.hasInFlightWrite(e)||this._memory.credentialRetirementGeneration(e)!==s||(this._memory.set(e,a),Lt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var Hm="Augment Code",Gm="https://augmentcode.com",Zm="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var xA=1e3,kA=500;function Mu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function Go(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var $u=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function Bm(t){return new URLSearchParams({k:t}).toString().slice(2)}function EA(t,e){let r=`${Bm(t)}:${Bm(e)}`;return`Basic ${btoa(r)}`}function Jm(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function TA(t){return t.client.token_endpoint_auth_method==="none"||!Jm(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function AA(t){return t==="basic"?"body":t==="body"?"basic":void 0}function $A(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var MA=401,Ym=500;function Iu(t,...e){return t.status<Ym&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function Vm(t){return Iu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===MA}async function Wm(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=Jm(t);e==="basic"&&s?n.Authorization=EA(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=$A(c),d=c.slice(0,kA);throw new Jr(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new $u;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*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 Km(t,e){try{return await Wm(t,e,t.resource)}catch(r){if(r instanceof Jr&&t.resource&&Iu(r,"invalid_target"))return await Wm(t,e,void 0);throw r}}var Jr=class t extends Error{status;statusText;body;oauthErrorCode;clientAuthPlacementsExhausted;constructor(e,r,n,o,s=!1){super(`Token refresh failed: ${e} ${r}${n?` \u2014 ${n}`:""}`),this.name="RefreshHttpError",this.status=e,this.statusText=r,this.body=n,this.oauthErrorCode=o,this.clientAuthPlacementsExhausted=s}withClientAuthPlacementsExhausted(){return new t(this.status,this.statusText,this.body,this.oauthErrorCode,!0)}};function zu(t){return!(t instanceof Jr)||t.status>=Ym?!1:Iu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function Ou(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=TA(t);try{return await Km(e,r)}catch(n){let o=AA(r);if(!(n instanceof Jr)||!o||!Vm(n))throw n;try{return await Km(e,o)}catch(s){throw s instanceof Jr&&Vm(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as x0}from"@hermes/logger";var Lu;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Lu="oauth4webapi/v3.8.6");function jn(t,e){if(t==null)return!1;try{return t instanceof e||Object.getPrototypeOf(t)[Symbol.toStringTag]===e.prototype[Symbol.toStringTag]}catch{return!1}}var Ut="ERR_INVALID_ARG_VALUE",Ke="ERR_INVALID_ARG_TYPE";function le(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var Hu=Symbol(),IA=Symbol(),zA=Symbol(),Xr=Symbol();var Xm=Symbol();var OA=new TextEncoder,NA=new TextDecoder;function ju(t){return typeof t=="string"?OA.encode(t):NA.decode(t)}var Uu;Uint8Array.prototype.toBase64?Uu=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):Uu=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 Fu;Uint8Array.fromBase64?Fu=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw le("The input to be decoded is not correctly encoded.",Ut,e)}}:Fu=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw le("The input to be decoded is not correctly encoded.",Ut,e)}};function Vi(t){return typeof t=="string"?Fu(t):Uu(t)}var Dn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=h0,Error.captureStackTrace?.(this,this.constructor)}},Zo=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function I(t,e,r){return new Zo(t,{code:e,cause:r})}function Wi(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function Gu(t){jn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(Lu&&!e.has("user-agent")&&e.set("user-agent",Lu),e.has("authorization"))throw le('"options.headers" must not include the "authorization" header name',Ut);return e}function Zu(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw le('"options.signal" must return or be an instance of AbortSignal',Ke);return e}}function DA(t){return t.includes("//")?t.replace("//","/"):t}function LA(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=DA(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function jA(t,e,r,n){if(!(t instanceof URL))throw le(`"${e}" must be an instance of URL`,Ke);ug(t,n?.[Hu]!==!0);let o=r(new URL(t.href)),s=Gu(n?.headers);return s.set("accept","application/json"),(n?.[Xr]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:Zu(o,n?.signal)})}function Nn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw le(`${r} must be a number`,Ke,o);if(t>0)return;if(e){if(t!==0)throw le(`${r} must be a non-negative number`,Ut,o);return}throw le(`${r} must be a positive number`,Ut,o)}catch(s){throw n?I(s.message,n,o):s}}function Ee(t,e,r,n){try{if(typeof t!="string")throw le(`${e} must be a string`,Ke,n);if(t.length===0)throw le(`${e} must not be empty`,Ut,n)}catch(o){throw r?I(o.message,r,n):o}}async function tg(t,e){let r=t;if(!(r instanceof URL)&&r!==Yi)throw le('"expectedIssuerIdentifier" must be an instance of URL',Ke);if(!jn(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Qu,e);Wo(e);let n=await ta(e);if(Ee(n.issuer,'"response" body "issuer" property',V,{body:n}),r!==Yi&&new URL(n.issuer).href!==r.href)throw I('"response" body "issuer" property does not match the expected value',Qi,{expected:r.href,body:n,attribute:"issuer"});return n}function rg(t){FA(t,"application/json")}function UA(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return I(r,g0,t)}function FA(t,e){if(QA(t)!==e)throw UA(t,e)}function Bu(){return Vi(crypto.getRandomValues(new Uint8Array(32)))}function ng(){return Bu()}function og(){return Bu()}function sg(){return Bu()}async function ig(t){return Ee(t,"codeVerifier"),Vi(await crypto.subtle.digest("SHA-256",ju(t)))}function Vu(t){let e=t?.[IA];return typeof e=="number"&&Number.isFinite(e)?e:0}function Wu(t){let e=t?.[zA];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function Ku(){return Math.floor(Date.now()/1e3)}function Xi(t){if(typeof t!="object"||t===null)throw le('"as" must be an object',Ke);Ee(t.issuer,'"as.issuer"')}function Ju(t){if(typeof t!="object"||t===null)throw le('"client" must be an object',Ke);Ee(t.client_id,'"client.client_id"')}function Qm(t){return encodeURIComponent(t).replace(/(?:[-_.!~*'()]|%20)/g,e=>{switch(e){case"-":case"_":case".":case"!":case"~":case"*":case"'":case"(":case")":return`%${e.charCodeAt(0).toString(16).toUpperCase()}`;case"%20":return"+";default:throw new Error}})}function Yu(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function ag(t){return Ee(t,'"clientSecret"'),(e,r,n,o)=>{let s=Qm(r.client_id),i=Qm(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function cg(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var qA=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function ug(t,e){if(e&&t.protocol!=="https:")throw I("only requests to HTTPS are allowed",y0,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw I("only HTTP and HTTPS requests are allowed",v0,t)}function eg(t,e,r,n){let o;if(typeof t!="string"||!(o=qA(t)))throw I(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?_0:S0,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return ug(o,n),o}function dg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?eg(t.mtls_endpoint_aliases[e],e,r,n):eg(t[e],e,r,n)}var Ln=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=f0,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)}},Bo=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=m0,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)}},Vo=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=p0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ki="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",HA="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",GA='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',ZA="("+Ki+")\\s*=\\s*"+GA,BA="("+Ki+")\\s*=\\s*("+Ki+")",VA=new RegExp("^[,\\s]*("+Ki+")"),WA=new RegExp("^[,\\s]*"+ZA+"[,\\s]*(.*)"),KA=new RegExp("^[,\\s]*"+BA+"[,\\s]*(.*)"),JA=new RegExp("^("+HA+")(?:$|[,\\s])(.*)");function YA(t){if(!jn(t,Response))throw le('"response" must be an instance of Response',Ke);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(VA),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let p,f;if(o=n.match(WA)){if([,p,f,n]=o,f.includes("\\"))try{f=JSON.parse(`"${f}"`)}catch{}u[p.toLowerCase()]=f;continue}if(o=n.match(KA)){[,p,f,n]=o,u[p.toLowerCase()]=f;continue}if(o=n.match(JA)){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 XA(t){if(t.status>399&&t.status<500){Wo(t),rg(t);try{let e=await t.clone().json();if(Wi(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function lg(t,e,r){if(t.status!==e){n0(t);let n;throw(n=await XA(t))?(await t.body?.cancel(),new Ln("server responded with an error in the response body",{cause:n,response:t})):I(`"response" is not a conform ${r} response (unexpected HTTP status code)`,Qu,t)}}function pg(t){if(!Xu.has(t))throw le('"options.DPoP" is not a valid DPoPHandle',Ut)}function QA(t){return t.headers.get("content-type")?.split(";")[0]}async function e0(t,e,r,n,o,s,i){return await r(t,e,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(i?.[Xr]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:Zu(n,i?.signal)})}async function t0(t,e,r,n,o,s){let i=dg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[Hu]!==!0);o.set("grant_type",n);let a=Gu(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(pg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await e0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var fg=new WeakMap,r0=new WeakMap;function hg(t){if(!t.id_token)return;let e=fg.get(t);if(!e)throw le('"ref" was already garbage collected or did not resolve from the proper sources',Ut);return e}async function mg(t,e,r,n,o,s){if(Xi(t),Ju(e),!jn(r,Response))throw le('"response" must be an instance of Response',Ke);await lg(r,200,"Token Endpoint"),Wo(r);let i=await ta(r);if(Ee(i.access_token,'"response" body "access_token" property',V,{body:i}),Ee(i.token_type,'"response" body "token_type" property',V,{body:i}),i.token_type=i.token_type.toLowerCase(),i.expires_in!==void 0){let a=typeof i.expires_in!="number"?parseFloat(i.expires_in):i.expires_in;Nn(a,!0,'"response" body "expires_in" property',V,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ee(i.refresh_token,'"response" body "refresh_token" property',V,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw I('"response" body "scope" property must be a string',V,{body:i});if(i.id_token!==void 0){Ee(i.id_token,'"response" body "id_token" property',V,{body:i});let a=["aud","exp","iat","iss","sub"];e.require_auth_time===!0&&a.push("auth_time"),e.default_max_age!==void 0&&(Nn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await w0(i.id_token,b0.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),Vu(e),Wu(e),o).then(u0.bind(void 0,a)).then(s0.bind(void 0,t)).then(o0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw I('ID Token "aud" (audience) claim includes additional untrusted audiences',_r,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw I('unexpected ID Token "azp" (authorized party) claim value',_r,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Nn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',V,{claims:c}),r0.set(r,u),fg.set(i,c)}if(s?.[i.token_type]!==void 0)s[i.token_type](r,i);else if(i.token_type!=="dpop"&&i.token_type!=="bearer")throw new Dn("unsupported `token_type` value",{cause:{body:i}});return i}function n0(t){let e;if(e=YA(t))throw new Vo("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function o0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw I('unexpected JWT "aud" (audience) claim value',_r,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw I('unexpected JWT "aud" (audience) claim value',_r,{expected:t,claims:e.claims,claim:"aud"});return e}function s0(t,e){let r=t[C0]?.(e)??t.issuer;if(e.claims.iss!==r)throw I('unexpected JWT "iss" (issuer) claim value',_r,{expected:r,claims:e.claims,claim:"iss"});return e}var Xu=new WeakSet;function i0(t){return Xu.add(t),t}var a0=Symbol();async function gg(t,e,r,n,o,s,i){if(Xi(t),Ju(e),!Xu.has(n))throw le('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Ut);Ee(o,'"redirectUri"');let a=Yr(n,"code");if(!a)throw I('no authorization code in "callbackParameters"',V);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==a0&&(Ee(s,'"codeVerifier"'),c.set("code_verifier",s)),t0(t,e,r,"authorization_code",c,i)}var c0={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 u0(t,e){for(let r of t)if(e.claims[r]===void 0)throw I(`JWT "${r}" (${c0[r]}) claim missing`,V,{claims:e.claims});return e}var Nu=Symbol(),Du=Symbol();async function yg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?d0(t,e,r,n.expectedNonce,n.maxAge,n[Xm],n.recognizedTokenTypes):l0(t,e,r,n?.[Xm],n?.recognizedTokenTypes)}async function d0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=Nu;break;case Nu:break;default:Ee(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=Du;break;case Du:break;default:Nn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await mg(t,e,r,a,s,i);Ee(c.id_token,'"response" body "id_token" property',V,{body:c});let u=hg(c);if(o!==Du){let d=Ku()+Vu(e),l=Wu(e);if(u.auth_time+o<d-l)throw I("too much time has elapsed since the last End-User authentication",Ji,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===Nu){if(u.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',_r,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw I('unexpected ID Token "nonce" claim value',_r,{expected:n,claims:u,claim:"nonce"});return c}async function l0(t,e,r,n,o){let s=await mg(t,e,r,void 0,n,o),i=hg(s);if(i){if(e.default_max_age!==void 0){Nn(e.default_max_age,!0,'"client.default_max_age"');let a=Ku()+Vu(e),c=Wu(e);if(i.auth_time+e.default_max_age<a-c)throw I("too much time has elapsed since the last End-User authentication",Ji,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw I('unexpected ID Token "nonce" claim value',_r,{expected:void 0,claims:i,claim:"nonce"})}return s}var p0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",f0="OAUTH_RESPONSE_BODY_ERROR",h0="OAUTH_UNSUPPORTED_OPERATION",m0="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var qu="OAUTH_PARSE_ERROR",V="OAUTH_INVALID_RESPONSE";var g0="OAUTH_RESPONSE_IS_NOT_JSON",Qu="OAUTH_RESPONSE_IS_NOT_CONFORM",y0="OAUTH_HTTP_REQUEST_FORBIDDEN",v0="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",Ji="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",_r="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Qi="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var _0="OAUTH_MISSING_SERVER_METADATA",S0="OAUTH_INVALID_SERVER_METADATA";function Wo(t){if(t.bodyUsed)throw le('"response" body has been used already',Ut)}async function w0(t,e,r,n,o){let{0:s,1:i,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:s,1:i,length:a}=t.split(".");else throw new Dn("JWE decryption is not configured",{cause:t});if(a!==3)throw I("Invalid JWT",V,t);let c;try{c=JSON.parse(ju(Vi(s)))}catch(l){throw I("failed to parse JWT Header body as base64url encoded JSON",qu,l)}if(!Wi(c))throw I("JWT Header must be a top level object",V,t);if(e(c),c.crit!==void 0)throw new Dn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(ju(Vi(i)))}catch(l){throw I("failed to parse JWT Payload body as base64url encoded JSON",qu,l)}if(!Wi(u))throw I("JWT Payload must be a top level object",V,t);let d=Ku()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw I('unexpected JWT "exp" (expiration time) claim type',V,{claims:u});if(u.exp<=d-n)throw I('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',Ji,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw I('unexpected JWT "iat" (issued at) claim type',V,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw I('unexpected JWT "iss" (issuer) claim type',V,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw I('unexpected JWT "nbf" (not before) claim type',V,{claims:u});if(u.nbf>d+n)throw I('unexpected JWT "nbf" (not before) claim value',Ji,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw I('unexpected JWT "aud" (audience) claim type',V,{claims:u});return{header:c,claims:u,jwt:t}}function b0(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw I('unexpected JWT "alg" header parameter',V,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw I('unexpected JWT "alg" header parameter',V,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw I('unexpected JWT "alg" header parameter',V,{header:n,expected:r,reason:"default value"});return}throw I('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function Yr(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw I(`"${e}" parameter must be provided only once`,V);return r}var R0=Symbol(),P0=Symbol();function vg(t,e,r,n){if(Xi(t),Ju(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw le('"parameters" must be an instance of URLSearchParams, or URL',Ke);if(Yr(r,"response"))throw I('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',V,{parameters:r});let o=Yr(r,"iss"),s=Yr(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw I('response parameter "iss" (issuer) missing',V,{parameters:r});if(o&&o!==t.issuer)throw I('unexpected "iss" (issuer) response parameter value',V,{expected:t.issuer,parameters:r});switch(n){case void 0:case P0:if(s!==void 0)throw I('unexpected "state" response parameter encountered',V,{expected:void 0,parameters:r});break;case R0:break;default:if(Ee(n,'"expectedState" argument'),s!==n)throw I(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',V,{expected:n,parameters:r})}if(Yr(r,"error"))throw new Bo("authorization response from the server is an error",{cause:r});let a=Yr(r,"id_token"),c=Yr(r,"token");if(a!==void 0||c!==void 0)throw new Dn("implicit and hybrid flows are not supported");return i0(new URLSearchParams(r))}async function _g(t,e,r){Xi(t);let n=dg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[Hu]!==!0),o=Gu(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(pg(r.DPoP),await r.DPoP.addProof(n,o,s,r.initialAccessToken)),r?.initialAccessToken&&o.set("authorization",`${o.has("dpop")?"DPoP":"Bearer"} ${r.initialAccessToken}`);let i=await(r?.[Xr]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:Zu(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Sg(t){if(!jn(t,Response))throw le('"response" must be an instance of Response',Ke);await lg(t,201,"Dynamic Client Registration Endpoint"),Wo(t);let e=await ta(t);return Ee(e.client_id,'"response" body "client_id" property',V,{body:e}),e.client_secret!==void 0&&Ee(e.client_secret,'"response" body "client_secret" property',V,{body:e}),e.client_secret&&Nn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',V,{body:e}),e}async function wg(t,e){return jA(t,"resourceIdentifier",r=>(LA(r,".well-known/oauth-protected-resource",!0),r),e)}async function ea(t,e){let r=t;if(!(r instanceof URL)&&r!==Yi)throw le('"expectedResourceIdentifier" must be an instance of URL',Ke);if(!jn(e,Response))throw le('"response" must be an instance of Response',Ke);if(e.status!==200)throw I('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',Qu,e);Wo(e);let n=await ta(e);if(Ee(n.resource,'"response" body "resource" property',V,{body:n}),r!==Yi&&new URL(n.resource).href!==r.href)throw I('"response" body "resource" property does not match the expected value',Qi,{expected:r.href,body:n,attribute:"resource"});return n}async function ta(t,e=rg){let r;try{r=await t.json()}catch(n){throw e(t),I('failed to parse "response" body as JSON',qu,n)}if(!Wi(r))throw I('"response" body must be a top level object',V,{body:r});return r}var Yi=Symbol(),C0=Symbol();var Pg=x0.child({prefix:"pi-mcp"}),Ko=1e4,k0=1e3,E0=401,bg=200,T0=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,A0=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,Cg;function Un(){return Cg??globalThis.fetch}function xg(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function kg(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function td(t){let e=kg(t);try{let r=await $0(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await N0(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ra(r)}throw new Error("Failed to discover metadata URL")}async function $0(t){try{let e=await wg(t,{signal:AbortSignal.timeout(Ko),[Xr]:Cg??void 0});return e.ok?await ea(t,e):(e.body?.cancel().catch(()=>{}),await Eg(t,e.headers.get("www-authenticate"))??await Rg(t))}catch{return await Rg(t)}}async function Rg(t){for(let e of["HEAD","GET"])try{let r=await Un()(t,{method:e,signal:AbortSignal.timeout(Ko)});r.body?.cancel().catch(()=>{});let n=await Eg(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function Eg(t,e){let r=O0(e);if(r)try{let n=await Un()(r,{signal:AbortSignal.timeout(Ko)});return await M0(t,n)}catch{return}}async function M0(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await ea(t,new Response(r,n))}catch(o){if(!(o instanceof Zo)||o.code!==Qi)throw o;let s=I0(r);if(!s||!z0(s,t))throw o;return await ea(s,new Response(r,n))}}function I0(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function z0(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 O0(t){if(!t)return;let e=t.match(T0),r=t.match(A0),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function N0(t){for(let e of D0(t))try{let r=new URL(e,t),n=await Un()(r,{signal:AbortSignal.timeout(Ko)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function D0(t){let e=t.pathname.startsWith("/")?t.pathname.slice(1):t.pathname;return[...e.length>0?[new URL(`/.well-known/oauth-authorization-server/${e}`,t),new URL(`/.well-known/openid-configuration/${e}`,t),new URL(`/${e}/.well-known/openid-configuration`,t)]:[],new URL("/.well-known/oauth-authorization-server",t),new URL("/.well-known/openid-configuration",t)]}async function rd(t){try{let e=await Un()(t,{signal:AbortSignal.timeout(Ko)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await L0(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await tg(o,new Response(r,n))}catch(e){throw ra(e)}}async function L0(t){if(!t.ok)throw new Error("Invalid status code from discovery response");let e=await t.json();if(!e.issuer||typeof e.issuer!="string")throw new Error("Invalid issuer from discovery response");return new URL(e.issuer)}var ed=class extends Error{issuer;constructor(e){super(`This MCP server's authorization server (\`${e}\`) does not support Dynamic Client Registration. Configure a static OAuth Client ID and Secret in the Advanced section.`),this.name="McpOAuthDcrUnsupportedError",this.issuer=e}};function j0(t){if(!t.clientId)throw new Error("clientId is required to build client from config");let e=t.clientSecret?.trim();return{client_id:t.clientId,...e?{client_secret:e}:{}}}async function nd({config:t,serverMetadata:e,redirectUris:r}){let n=t.clientId?.trim(),o=t.clientSecret?.trim();if(!!n&&(!!o||!e.registration_endpoint))return j0({...t,clientId:n});if(!e.registration_endpoint)throw new ed(e.issuer);return await U0(e,r)}async function U0(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await _g(t,{client_name:Hm,client_uri:Gm,logo_uri:Zm,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[Xr]:F0});return n.ok||Pg.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Sg(n)}catch(r){throw ra(r)}}async function F0(t,e){let r=await Un()(t,xg(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||Pg.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${H0(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 q0(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}),Un()(t,xg(o))}function H0(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>bg?`${t.slice(0,bg)}\u2026`:t}}async function od(t,e,r,n,o,s){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let i=ng(),a=await ig(i),c=og(),u,d=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean).join(" ")||void 0,l=kg(s??t).toString(),p=new URL(r.authorization_endpoint);return p.searchParams.set("response_type","code"),p.searchParams.set("client_id",e.client_id),p.searchParams.set("code_challenge",a),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("redirect_uri",n),p.searchParams.set("resource",l),p.searchParams.set("state",c),d&&p.searchParams.set("scope",d),r.code_challenge_methods_supported?.includes("S256")||(u=sg(),p.searchParams.set("nonce",u)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:i,nonce:u,scope:d,state:c,resource:l,authUri:p}}async function G0(t,e,r){let n=await gg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[Xr]:q0,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return yg(t.serverMetadata,t.client,await Z0(n))}async function sd(t,e){try{let r=vg(e.serverMetadata,e.client,t,e.state),n=await V0(e.client,o=>G0(e,r,o));return J0(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ra(r)}}async function Z0(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 Tg(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function B0(t){let e=Tg(t);return e===void 0?cg():t.token_endpoint_auth_method==="client_secret_basic"?ag(e):Yu(e)}async function V0(t,e){try{return await e(B0(t))}catch(r){let n=W0(t);if(n&&K0(r))return await e(n);throw r}}function W0(t){let e=Tg(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return Yu(e)}function K0(t){return t instanceof Ln?t.error==="invalid_client"||t.error==="unauthorized":t instanceof Vo?t.status===E0||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function J0(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*k0:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ra(t){if(t instanceof Ln||t instanceof Bo){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 Y0=/(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,Ag=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,$g=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,Mg=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,Jo="[redacted]";function X0(t){return Ag.test(t)||$g.test(t)||Mg.test(t)}var Q0=new RegExp(Ag.source,"g"),e$=new RegExp($g.source,"gi"),t$=new RegExp(Mg.source,"g");function Ig(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function ad(t){return t&&Ig(t,8192).replace(Q0,Jo).replace(e$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${Jo}`).replace(t$,Jo)}function id(t,e,r){if(e)return Jo;if(typeof t=="string")return X0(t)?Jo:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>id(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=id(s,Y0.test(o),r+1);return n}function zg(t,e=500){if(t==null)return;let r=id(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return Ig(n,e)}var Ng={reportError:()=>{}},Og=Symbol.for("__pi_mcp_error_reporter_slot__");function Dg(){let t=globalThis,e=t[Og];return e||(e={reporter:null},t[Og]=e),e}function Lg(t){let e=Dg(),r=e.reporter??Ng;return e.reporter=t,r}function r$(){return Dg().reporter??Ng}function cd(t,e){try{r$().reportError(t,e)}catch{}}import{logger as n$}from"@hermes/logger";var jg=n$.child({prefix:"pi-mcp"});function Ug(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++):jg.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,jg.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function Fg(t){return e=>{if(!e.startsWith(Tu)){let n=t.headerSecrets[e];if(n!==void 0)return Promise.resolve(n)}let r=t.secretsClient;return r?r.getSecret(e):Promise.resolve(void 0)}}function qg(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0}import{logger as o$}from"@hermes/logger";var Yo=o$.child({prefix:"pi-mcp"}),s$="$augment-",Xo=/\$augment-[a-zA-Z0-9_.-]+/g,i$=new RegExp(Xo.source);function na(t){return i$.test(t)}function oa(t){return t.slice(s$.length)}function ud(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(Xo))e.add(oa(n[0]));return[...e].sort()}var Pt=class extends Error{serverName;missingKeys;constructor(e,r,n){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}};async function Hg(t,e,r,n,o,s){let i=[...t.matchAll(Xo)];if(i.length===0)return t;let a=t;for(let c=i.length-1;c>=0;c--){let u=i[c],d=u[0],l=u.index,p=oa(d);try{let f=await r(p);if(f===void 0){n.add(p),Yo.warn(`Secret "${p}" not found for "${e}"; leaving reference as-is`);continue}f.trim()===""&&(o.add(p),Yo.warn(`Secret "${p}" resolved empty for "${e}"`));let h=a.slice(0,l),m=s?s(f,h):f;a=h+m+a.slice(l+d.length),Yo.debug(`Resolved secret reference for "${e}"`)}catch(f){n.add(p);let h=f instanceof Error?f.message:String(f);Yo.error(`Failed to resolve secret "${p}" for "${e}": ${h}; leaving reference as-is`)}}return a}async function Gg({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set;for(let[i,a]of Object.entries(t)){if(!na(a)){n[i]=a;continue}if(i in e){Yo.debug(`"${i}" references a secret but is already set in the local environment; using local value`),n[i]=e[i];continue}n[i]=await Hg(a,i,r,o,s)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort()}}var a$=/["$`\\]/g;function c$(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 u$(t,e){let r=c$(e);if(r==="double")return t.replace(a$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function Zg(t,e){let r=new Set,n=new Set;return{resolved:await Hg(t,"command",e,r,n,u$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort()}}import{AsyncLocalStorage as HU}from"node:async_hooks";var Bg,dd=Object.freeze({status:"aborted"});function v(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let p=d[l];p in a||(a[p]=u[p].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ft=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Fn=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Bg=globalThis).__zod_globalConfig??(Bg.__zod_globalConfig={});var qn=globalThis.__zod_globalConfig;function Je(t){return t&&Object.assign(qn,t),qn}var F={};iu(F,{BIGINT_FORMAT_RANGES:()=>Jg,Class:()=>pd,NUMBER_FORMAT_RANGES:()=>vd,aborted:()=>br,allowsEval:()=>md,assert:()=>h$,assertEqual:()=>d$,assertIs:()=>p$,assertNever:()=>f$,assertNotEqual:()=>l$,assignProp:()=>Sr,base64ToUint8Array:()=>Xg,base64urlToUint8Array:()=>$$,cached:()=>Gn,captureStackTrace:()=>aa,cleanEnum:()=>A$,cleanRegex:()=>rs,clone:()=>lt,cloneDef:()=>g$,createTransparentProxy:()=>b$,defineLazy:()=>Y,esc:()=>ia,escapeRegex:()=>Qt,explicitlyAborted:()=>_d,extend:()=>C$,finalizeIssue:()=>pt,floatSafeRemainder:()=>fd,getElementAtPath:()=>y$,getEnumValues:()=>es,getLengthableOrigin:()=>ns,getParsedType:()=>w$,getSizableOrigin:()=>Yg,hexToUint8Array:()=>I$,isObject:()=>Qr,isPlainObject:()=>wr,issue:()=>Zn,joinValues:()=>sa,jsonStringifyReplacer:()=>Hn,merge:()=>k$,mergeDefs:()=>Xt,normalizeParams:()=>A,nullish:()=>ts,numKeys:()=>S$,objectClone:()=>m$,omit:()=>P$,optionalKeys:()=>yd,parsedType:()=>Sd,partial:()=>E$,pick:()=>R$,prefixIssues:()=>er,primitiveTypes:()=>Kg,promiseAllObject:()=>v$,propertyKeyTypes:()=>gd,randomString:()=>_$,required:()=>T$,safeExtend:()=>x$,shallowClone:()=>Wg,slugify:()=>hd,stringifyPrimitive:()=>ca,uint8ArrayToBase64:()=>Qg,uint8ArrayToBase64url:()=>M$,uint8ArrayToHex:()=>z$,unwrapMessage:()=>Qo});function d$(t){return t}function l$(t){return t}function p$(t){}function f$(t){throw new Error("Unexpected value in exhaustive check")}function h$(t){}function es(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function sa(t,e="|"){return t.map(r=>ca(r)).join(e)}function Hn(t,e){return typeof e=="bigint"?e.toString():e}function Gn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ts(t){return t==null}function rs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fd(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 Vg=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Vg)return n===void 0&&(n=Vg,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function m$(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Sr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Xt(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function g$(t){return Xt(t._zod.def)}function y$(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function v$(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 _$(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ia(t){return JSON.stringify(t)}function hd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var aa="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Qr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var md=Gn(()=>{if(qn.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function wr(t){if(Qr(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(Qr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Wg(t){return wr(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function S$(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}`)}},gd=new Set(["string","number","symbol"]),Kg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function lt(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 b$(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function ca(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var vd={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]},Jg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function R$(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=Xt(t._zod.def,{get shape(){let i={};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(i[a]=r.shape[a])}return Sr(this,"shape",i),i},checks:[]});return lt(t,s)}function P$(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=Xt(t._zod.def,{get shape(){let i={...t._zod.def.shape};for(let a in e){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete i[a]}return Sr(this,"shape",i),i},checks:[]});return lt(t,s)}function C$(t,e){if(!wr(e))throw new Error("Invalid input to extend: expected a plain object");let r=t._zod.def.checks;if(r&&r.length>0){let s=t._zod.def.shape;for(let i in e)if(Object.getOwnPropertyDescriptor(s,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=Xt(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Sr(this,"shape",s),s}});return lt(t,o)}function x$(t,e){if(!wr(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=Xt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Sr(this,"shape",n),n}});return lt(t,r)}function k$(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=Xt(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Sr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return lt(t,r)}function E$(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=Xt(e._zod.def,{get shape(){let a=e._zod.def.shape,c={...a};if(r)for(let u in r){if(!(u in a))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(c[u]=t?new t({type:"optional",innerType:a[u]}):a[u])}else for(let u in a)c[u]=t?new t({type:"optional",innerType:a[u]}):a[u];return Sr(this,"shape",c),c},checks:[]});return lt(e,i)}function T$(t,e,r){let n=Xt(e._zod.def,{get shape(){let o=e._zod.def.shape,s={...o};if(r)for(let i in r){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);r[i]&&(s[i]=new t({type:"nonoptional",innerType:o[i]}))}else for(let i in o)s[i]=new t({type:"nonoptional",innerType:o[i]});return Sr(this,"shape",s),s}});return lt(e,n)}function br(t,e=0){if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function _d(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 er(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Qo(t){return typeof t=="string"?t:t?.message}function pt(t,e,r){let n=t.message?t.message:Qo(t.inst?._zod.def?.error?.(t))??Qo(e?.error?.(t))??Qo(r.customError?.(t))??Qo(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 Yg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ns(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Sd(t){let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"nan":"number";case"object":{if(t===null)return"null";if(Array.isArray(t))return"array";let r=t;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return e}function Zn(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function A$(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Xg(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 Qg(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function $$(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Xg(e+r)}function M$(t){return Qg(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function I$(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 z$(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var pd=class{constructor(...e){}};var ey=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Hn,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ua=v("$ZodError",ey),wd=v("$ZodError",ey,{Parent:Error});function bd(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 Rd(t,e=r=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(e(i));else{let c=r,u=0;for(;u<a.length;){let d=a[u];u===a.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(e(i))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return n(t),r}var da=t=>(e,r,n,o)=>{let s=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ft;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>pt(c,s,Je())));throw aa(a,o?.callee),a}return i.value};var la=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>pt(c,s,Je())));throw aa(a,o?.callee),a}return i.value};var os=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 Ft;return s.issues.length?{success:!1,error:new(t??ua)(s.issues.map(i=>pt(i,o,Je())))}:{success:!0,data:s.value}},ss=os(wd),is=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=>pt(i,o,Je())))}:{success:!0,data:s.value}},pa=is(wd),ty=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return da(t)(e,r,o)};var ry=t=>(e,r,n)=>da(t)(e,r,n);var ny=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return la(t)(e,r,o)};var oy=t=>async(e,r,n)=>la(t)(e,r,n);var sy=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return os(t)(e,r,o)};var iy=t=>(e,r,n)=>os(t)(e,r,n);var ay=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return is(t)(e,r,o)};var cy=t=>async(e,r,n)=>is(t)(e,r,n);var uy=/^[cC][0-9a-z]{6,}$/,dy=/^[0-9a-z]+$/,ly=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,py=/^[0-9a-vA-V]{20}$/,fy=/^[A-Za-z0-9]{27}$/,hy=/^[a-zA-Z0-9_-]{21}$/,my=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var gy=/^([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})$/,Pd=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 yy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var N$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function vy(){return new RegExp(N$,"u")}var _y=/^(?:(?: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])$/,Sy=/^(([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])$/,Ry=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Cd=/^[A-Za-z0-9_-]*$/;var Py=/^https?$/,Cy=/^\+[1-9]\d{6,14}$/,xy="(?:(?:\\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])))",ky=new RegExp(`^${xy}$`);function Ey(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 Ty(t){return new RegExp(`^${Ey(t)}$`)}function Ay(t){let e=Ey({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(`^${xy}T(?:${n})$`)}var $y=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},My=/^-?\d+n?$/,Iy=/^-?\d+$/,xd=/^-?\d+(?:\.\d+)?$/,zy=/^(?:true|false)$/i,Oy=/^null$/i;var Ny=/^[^A-Z]*$/,Dy=/^[^a-z]*$/;var Te=v("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ly={number:"number",bigint:"bigint",object:"date"},kd=v("$ZodCheckLessThan",(t,e)=>{Te.init(t,e);let r=Ly[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})}}),Ed=v("$ZodCheckGreaterThan",(t,e)=>{Te.init(t,e);let r=Ly[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})}}),jy=v("$ZodCheckMultipleOf",(t,e)=>{Te.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):fd(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})}}),Uy=v("$ZodCheckNumberFormat",(t,e)=>{Te.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=vd[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=Iy)}),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 Fy=v("$ZodCheckMaxLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ts(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=ns(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),qy=v("$ZodCheckMinLength",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ts(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=ns(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Hy=v("$ZodCheckLengthEquals",(t,e)=>{var r;Te.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ts(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=ns(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})}}),cs=v("$ZodCheckStringFormat",(t,e)=>{var r,n;Te.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Gy=v("$ZodCheckRegex",(t,e)=>{cs.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})}}),Zy=v("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ny),cs.init(t,e)}),By=v("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Dy),cs.init(t,e)}),Vy=v("$ZodCheckIncludes",(t,e)=>{Te.init(t,e);let r=Qt(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})}}),Wy=v("$ZodCheckStartsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`^${Qt(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})}}),Ky=v("$ZodCheckEndsWith",(t,e)=>{Te.init(t,e);let r=new RegExp(`.*${Qt(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 Jy=v("$ZodCheckOverwrite",(t,e)=>{Te.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var fa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
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 By={major:4,minor:4,patch:3};var ee=v("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=By;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=wr(i),d;for(let l of a){if(l._zod.def.when){if(vd(i)||!l._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=l._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new Ft;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=wr(i,p)))});else{if(i.issues.length===p)continue;u||(u=wr(i,p))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(wr(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ft;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 Ft;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=os(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return la(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),ma=v("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??xy(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ae=v("$ZodStringFormat",(t,e)=>{as.init(t,e),ma.init(t,e)}),rv=v("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=ly),ae.init(t,e)}),nv=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=Rd(n))}else e.pattern??(e.pattern=Rd());ae.init(t,e)}),ov=v("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=py),ae.init(t,e)}),sv=v("$ZodURL",(t,e)=>{ae.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===_y.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})}}}),iv=v("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=fy()),ae.init(t,e)}),av=v("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=uy),ae.init(t,e)}),cv=v("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=oy),ae.init(t,e)}),uv=v("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sy),ae.init(t,e)}),dv=v("$ZodULID",(t,e)=>{e.pattern??(e.pattern=iy),ae.init(t,e)}),lv=v("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ay),ae.init(t,e)}),pv=v("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=cy),ae.init(t,e)}),fv=v("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Cy(e)),ae.init(t,e)}),hv=v("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=by),ae.init(t,e)}),mv=v("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Py(e)),ae.init(t,e)}),gv=v("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=dy),ae.init(t,e)}),yv=v("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=hy),ae.init(t,e),t._zod.bag.format="ipv4"}),vv=v("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=my),ae.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var _v=v("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=gy),ae.init(t,e)}),Sv=v("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=yy),ae.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function wv(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var bv=v("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=vy),ae.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{wv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function M$(t){if(!Pd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return wv(r)}var Rv=v("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Pd),ae.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{M$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Pv=v("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Sy),ae.init(t,e)});function I$(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 Cv=v("$ZodJWT",(t,e)=>{ae.init(t,e),t._zod.check=r=>{I$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Td=v("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??Cd,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}}),xv=v("$ZodNumberFormat",(t,e)=>{Oy.init(t,e),Td.init(t,e)}),kv=v("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=Ty,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}}),Ev=v("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=ky,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 Tv=v("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=Ay,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}}),Av=v("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),$v=v("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),Mv=v("$ZodNever",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Iv=v("$ZodDate",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});function Wy(t,e,r){t.issues.length&&e.issues.push(...er(r,t.issues)),e.value[r]=t.value}var zv=v("$ZodArray",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Wy(u,r,i))):Wy(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ha(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...er(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 Ov(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=gd(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Nv(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(h=>ha(h,r,p,e,d,l))):ha(f,r,p,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var z$=v("$ZodObject",(t,e)=>{if(ee.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Hn(()=>Ov(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=Xr,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let p of i.keys){let f=l[p],h=f._zod.optin==="optional",m=f._zod.optout==="optional",y=f._zod.run({value:u[p],issues:[]},c);y instanceof Promise?d.push(y.then(S=>ha(S,a,p,u,h,m))):ha(y,a,p,u,h,m)}return s?Nv(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),Dv=v("$ZodObjectJIT",(t,e)=>{z$.init(t,e);let r=t._zod.parse,n=Hn(()=>Ov(e)),o=p=>{let f=new pa(["shape","payload","ctx"]),h=n.value,m=b=>{let k=sa(b);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),S=0;for(let b of h.keys)y[b]=`key_${S++}`;f.write("const newResult = {};");for(let b of h.keys){let k=y[b],_=sa(b),P=p[b],z=P?._zod?.optin==="optional",ge=P?._zod?.optout==="optional";f.write(`const ${k} = ${m(b)};`),z&&ge?f.write(`
26
+ `))}};var Xy={major:4,minor:4,patch:3};var ee=v("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xy;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,a,c)=>{let u=br(i),d;for(let l of a){if(l._zod.def.when){if(_d(i)||!l._zod.def.when(i))continue}else if(u)continue;let p=i.issues.length,f=l._zod.check(i);if(f instanceof Promise&&c?.async===!1)throw new Ft;if(d||f instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await f,i.issues.length!==p&&(u||(u=br(i,p)))});else{if(i.issues.length===p)continue;u||(u=br(i,p))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if(br(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Ft;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 Ft;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=ss(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return pa(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),ga=v("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??$y(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ae=v("$ZodStringFormat",(t,e)=>{cs.init(t,e),ga.init(t,e)}),av=v("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=gy),ae.init(t,e)}),cv=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=Pd(n))}else e.pattern??(e.pattern=Pd());ae.init(t,e)}),uv=v("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=yy),ae.init(t,e)}),dv=v("$ZodURL",(t,e)=>{ae.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===Py.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})}}}),lv=v("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=vy()),ae.init(t,e)}),pv=v("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=hy),ae.init(t,e)}),fv=v("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=uy),ae.init(t,e)}),hv=v("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=dy),ae.init(t,e)}),mv=v("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ly),ae.init(t,e)}),gv=v("$ZodXID",(t,e)=>{e.pattern??(e.pattern=py),ae.init(t,e)}),yv=v("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=fy),ae.init(t,e)}),vv=v("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ay(e)),ae.init(t,e)}),_v=v("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ky),ae.init(t,e)}),Sv=v("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ty(e)),ae.init(t,e)}),wv=v("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=my),ae.init(t,e)}),bv=v("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=_y),ae.init(t,e),t._zod.bag.format="ipv4"}),Rv=v("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Sy),ae.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var Pv=v("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wy),ae.init(t,e)}),Cv=v("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=by),ae.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function xv(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var kv=v("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ry),ae.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{xv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function j$(t){if(!Cd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return xv(r)}var Ev=v("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Cd),ae.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{j$(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Tv=v("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Cy),ae.init(t,e)});function U$(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 Av=v("$ZodJWT",(t,e)=>{ae.init(t,e),t._zod.check=r=>{U$(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Ad=v("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??xd,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}}),$v=v("$ZodNumberFormat",(t,e)=>{Uy.init(t,e),Ad.init(t,e)}),Mv=v("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=zy,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}}),Iv=v("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=My,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 zv=v("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=Oy,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}}),Ov=v("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),Nv=v("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),Dv=v("$ZodNever",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});var Lv=v("$ZodDate",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});function Qy(t,e,r){t.issues.length&&e.issues.push(...er(r,t.issues)),e.value[r]=t.value}var jv=v("$ZodArray",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Qy(u,r,i))):Qy(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ma(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...er(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 Uv(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=yd(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function Fv(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let p in e){if(p==="__proto__"||a.has(p))continue;if(u==="never"){i.push(p);continue}let f=c.run({value:e[p],issues:[]},n);f instanceof Promise?t.push(f.then(h=>ma(h,r,p,e,d,l))):ma(f,r,p,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var F$=v("$ZodObject",(t,e)=>{if(ee.init(t,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let c={...a};return Object.defineProperty(e,"shape",{value:c}),c}})}let n=Gn(()=>Uv(e));Y(t._zod,"propValues",()=>{let a=e.shape,c={};for(let u in a){let d=a[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(let l of d.values)c[u].add(l)}}return c});let o=Qr,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let p of i.keys){let f=l[p],h=f._zod.optin==="optional",m=f._zod.optout==="optional",y=f._zod.run({value:u[p],issues:[]},c);y instanceof Promise?d.push(y.then(S=>ma(S,a,p,u,h,m))):ma(y,a,p,u,h,m)}return s?Fv(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),qv=v("$ZodObjectJIT",(t,e)=>{F$.init(t,e);let r=t._zod.parse,n=Gn(()=>Uv(e)),o=p=>{let f=new fa(["shape","payload","ctx"]),h=n.value,m=b=>{let k=ia(b);return`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`};f.write("const input = payload.value;");let y=Object.create(null),S=0;for(let b of h.keys)y[b]=`key_${S++}`;f.write("const newResult = {};");for(let b of h.keys){let k=y[b],_=ia(b),P=p[b],z=P?._zod?.optin==="optional",ge=P?._zod?.optout==="optional";f.write(`const ${k} = ${m(b)};`),z&&ge?f.write(`
27
27
  if (${k}.issues.length) {
28
28
  if (${_} in input) {
29
29
  payload.issues = payload.issues.concat(${k}.issues.map(iss => ({
@@ -82,23 +82,23 @@ When the user's request requires one of these servers, call attach-mcp-server im
82
82
  }
83
83
  }
84
84
 
85
- `)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,k)=>w(p,b,k)},s,i=Xr,a=!Fn.jitless,u=a&&hd.value,d=e.catchall,l;t._zod.parse=(p,f)=>{l??(l=n.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),d?Nv([],h,p,f,l,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function Ky(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=>!wr(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=>pt(i,n,Je())))}),e)}var Ad=v("$ZodUnion",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Y(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Y(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Y(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>ts(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=>Ky(a,n,t,o)):Ky(i,n,t,o)}});var Lv=v("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Ad.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=Hn(()=>{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(!Xr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),jv=v("$ZodIntersection",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Jy(r,c,u)):Jy(r,s,i)}});function Ed(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(Sr(t)&&Sr(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=Ed(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=Ed(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 Jy(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}),wr(t))return t;let i=Ed(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 Uv=v("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Sr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(f=>pt(f,n,Je())),input:u,path:[u],inst:t});continue}let l=d.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...er(u,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...er(u,p.issues)),r.value[l]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Cd.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=>pt(l,n,Je())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&r.issues.push(...er(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...er(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Fv=v("$ZodEnum",(t,e)=>{ee.init(t,e);let r=Qo(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>md.has(typeof o)).map(o=>typeof o=="string"?Qt(o):o.toString()).join("|")})$`),t._zod.parse=(o,s)=>{let i=o.value;return n.has(i)||o.issues.push({code:"invalid_value",values:r,input:i,inst:t}),o}}),qv=v("$ZodLiteral",(t,e)=>{if(ee.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Qt(n):n?Qt(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 Hv=v("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Un(t.constructor.name);let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r.fallback=!0,r));if(o instanceof Promise)throw new Ft;return r.value=o,r.fallback=!0,r}});function Yy(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var $d=v("$ZodOptional",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Y(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ts(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=>Yy(i,o)):Yy(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Gv=v("$ZodExactOptional",(t,e)=>{$d.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)}),Zv=v("$ZodNullable",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.innerType._zod.optin),Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ts(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)}),Vv=v("$ZodDefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Xy(s,e)):Xy(o,e)}});function Xy(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Bv=v("$ZodPrefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Wv=v("$ZodNonOptional",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Qy(s,t)):Qy(o,t)}});function Qy(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 Kv=v("$ZodCatch",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>pt(i,n,Je()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>pt(s,n,Je()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Md=v("$ZodPipe",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>e.in._zod.values),Y(t._zod,"optin",()=>e.in._zod.optin),Y(t._zod,"optout",()=>e.out._zod.optout),Y(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>fa(i,e.in,n)):fa(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>fa(s,e.out,n)):fa(o,e.out,n)}});function fa(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 Jv=v("$ZodPreprocess",(t,e)=>{Md.init(t,e)}),Yv=v("$ZodReadonly",(t,e)=>{ee.init(t,e),Y(t._zod,"propValues",()=>e.innerType._zod.propValues),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"optin",()=>e.innerType?._zod?.optin),Y(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ev):ev(o)}});function ev(t){return t.value=Object.freeze(t.value),t}var Xv=v("$ZodCustom",(t,e)=>{Te.init(t,e),ee.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>tv(s,r,n,t));tv(o,r,n,t)}});function tv(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(Gn(o))}}var O$=()=>{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=_d(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${aa(o.values[0])}`:`Invalid option: expected one of ${oa(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":""}: ${oa(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 Qv(){return{localeError:O$()}}var e_;var Id=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 t_(){return new Id}(e_=globalThis).__zod_globalRegistry??(e_.__zod_globalRegistry=t_());var br=globalThis.__zod_globalRegistry;function r_(t,e){return new t({type:"string",...A(e)})}function n_(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 zd(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function s_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function i_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function a_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function c_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Od(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function u_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function d_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function l_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function p_(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function f_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function h_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function m_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function g_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function y_(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 __(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function S_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function w_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function b_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function R_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function P_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function C_(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function x_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function k_(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function E_(t,e){return new t({type:"number",checks:[],...A(e)})}function T_(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function A_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function $_(t,e){return new t({type:"boolean",...A(e)})}function M_(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function I_(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function z_(t,e){return new t({type:"null",...A(e)})}function O_(t){return new t({type:"any"})}function N_(t){return new t({type:"unknown"})}function D_(t,e){return new t({type:"never",...A(e)})}function L_(t,e){return new t({type:"date",coerce:!0,...A(e)})}function Zn(t,e){return new xd({check:"less_than",...A(e),value:t,inclusive:!1})}function tr(t,e){return new xd({check:"less_than",...A(e),value:t,inclusive:!0})}function Vn(t,e){return new kd({check:"greater_than",...A(e),value:t,inclusive:!1})}function Ct(t,e){return new kd({check:"greater_than",...A(e),value:t,inclusive:!0})}function cs(t,e){return new zy({check:"multiple_of",...A(e),value:t})}function ga(t,e){return new Ny({check:"max_length",...A(e),maximum:t})}function Bn(t,e){return new Dy({check:"min_length",...A(e),minimum:t})}function ya(t,e){return new Ly({check:"length_equals",...A(e),length:t})}function Nd(t,e){return new jy({check:"string_format",format:"regex",...A(e),pattern:t})}function Dd(t){return new Uy({check:"string_format",format:"lowercase",...A(t)})}function Ld(t){return new Fy({check:"string_format",format:"uppercase",...A(t)})}function jd(t,e){return new qy({check:"string_format",format:"includes",...A(e),includes:t})}function Ud(t,e){return new Hy({check:"string_format",format:"starts_with",...A(e),prefix:t})}function Fd(t,e){return new Gy({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Rr(t){return new Zy({check:"overwrite",tx:t})}function qd(t){return Rr(e=>e.normalize(t))}function Hd(){return Rr(t=>t.trim())}function Gd(){return Rr(t=>t.toLowerCase())}function Zd(){return Rr(t=>t.toUpperCase())}function Vd(){return Rr(t=>fd(t))}function j_(t,e,r){return new t({type:"array",element:e,...A(r)})}function U_(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function F_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function q_(t,e){let r=N$(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Gn(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(Gn(s))}},t(n.value,n)),e);return r}function N$(t,e){let r=new Te({check:"custom",...A(e)});return r._zod.check=t,r}function Bd(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??br,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&je(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Wd(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
85
+ `)}f.write("payload.value = newResult;"),f.write("return payload;");let w=f.compile();return(b,k)=>w(p,b,k)},s,i=Qr,a=!qn.jitless,u=a&&md.value,d=e.catchall,l;t._zod.parse=(p,f)=>{l??(l=n.value);let h=p.value;return i(h)?a&&u&&f?.async===!1&&f.jitless!==!0?(s||(s=o(e.shape)),p=s(p,f),d?Fv([],h,p,f,l,t):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p)}});function ev(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;let o=t.filter(s=>!br(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>pt(i,n,Je())))}),e)}var $d=v("$ZodUnion",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Y(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Y(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Y(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${n.map(o=>rs(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=>ev(a,n,t,o)):ev(i,n,t,o)}});var Hv=v("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,$d.init(t,e);let r=t._zod.parse;Y(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Gn(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Qr(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback||s.direction==="backward"?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,options:Array.from(n.value.keys()),input:i,path:[e.discriminator],inst:t}),o)}}),Gv=v("$ZodIntersection",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>tv(r,c,u)):tv(r,s,i)}});function Td(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(wr(t)&&wr(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Td(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=Td(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 tv(t,e,r){let n=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else t.issues.push(a);let s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),br(t))return t;let i=Td(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 Zv=v("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!wr(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(f=>pt(f,n,Je())),input:u,path:[u],inst:t});continue}let l=d.value,p=e.valueType._zod.run({value:o[u],issues:[]},n);p instanceof Promise?s.push(p.then(f=>{f.issues.length&&r.issues.push(...er(u,f.issues)),r.value[l]=f.value})):(p.issues.length&&r.issues.push(...er(u,p.issues)),r.value[l]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&xd.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=>pt(l,n,Je())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&r.issues.push(...er(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...er(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Bv=v("$ZodEnum",(t,e)=>{ee.init(t,e);let r=es(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>gd.has(typeof o)).map(o=>typeof o=="string"?Qt(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}}),Vv=v("$ZodLiteral",(t,e)=>{if(ee.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let r=new Set(e.values);t._zod.values=r,t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Qt(n):n?Qt(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 Wv=v("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Fn(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 Ft;return r.value=o,r.fallback=!0,r}});function rv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Md=v("$ZodOptional",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Y(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rs(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=>rv(i,o)):rv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),Kv=v("$ZodExactOptional",(t,e)=>{Md.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)}),Jv=v("$ZodNullable",(t,e)=>{ee.init(t,e),Y(t._zod,"optin",()=>e.innerType._zod.optin),Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${rs(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)}),Yv=v("$ZodDefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>nv(s,e)):nv(o,e)}});function nv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Xv=v("$ZodPrefault",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Qv=v("$ZodNonOptional",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ov(s,t)):ov(o,t)}});function ov(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 e_=v("$ZodCatch",(t,e)=>{ee.init(t,e),t._zod.optin="optional",Y(t._zod,"optout",()=>e.innerType._zod.optout),Y(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>pt(i,n,Je()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>pt(s,n,Je()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var Id=v("$ZodPipe",(t,e)=>{ee.init(t,e),Y(t._zod,"values",()=>e.in._zod.values),Y(t._zod,"optin",()=>e.in._zod.optin),Y(t._zod,"optout",()=>e.out._zod.optout),Y(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=e.out._zod.run(r,n);return s instanceof Promise?s.then(i=>ha(i,e.in,n)):ha(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ha(s,e.out,n)):ha(o,e.out,n)}});function ha(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var t_=v("$ZodPreprocess",(t,e)=>{Id.init(t,e)}),r_=v("$ZodReadonly",(t,e)=>{ee.init(t,e),Y(t._zod,"propValues",()=>e.innerType._zod.propValues),Y(t._zod,"values",()=>e.innerType._zod.values),Y(t._zod,"optin",()=>e.innerType?._zod?.optin),Y(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(r,n)=>{if(n.direction==="backward")return e.innerType._zod.run(r,n);let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(sv):sv(o)}});function sv(t){return t.value=Object.freeze(t.value),t}var n_=v("$ZodCustom",(t,e)=>{Te.init(t,e),ee.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>iv(s,r,n,t));iv(o,r,n,t)}});function iv(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Zn(o))}}var q$=()=>{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=Sd(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${ca(o.values[0])}`:`Invalid option: expected one of ${sa(o.values,"|")}`;case"too_big":{let s=o.inclusive?"<=":"<",i=e(o.origin);return i?`Too big: expected ${o.origin??"value"} to have ${s}${o.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${o.origin??"value"} to be ${s}${o.maximum.toString()}`}case"too_small":{let s=o.inclusive?">=":">",i=e(o.origin);return i?`Too small: expected ${o.origin} to have ${s}${o.minimum.toString()} ${i.unit}`:`Too small: expected ${o.origin} to be ${s}${o.minimum.toString()}`}case"invalid_format":{let s=o;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??o.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${o.divisor}`;case"unrecognized_keys":return`Unrecognized key${o.keys.length>1?"s":""}: ${sa(o.keys,", ")}`;case"invalid_key":return`Invalid key in ${o.origin}`;case"invalid_union":return o.options&&Array.isArray(o.options)&&o.options.length>0?`Invalid discriminator value. Expected ${o.options.map(i=>`'${i}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${o.origin}`;default:return"Invalid input"}}};function o_(){return{localeError:q$()}}var s_;var zd=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];return this._map.set(e,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function i_(){return new zd}(s_=globalThis).__zod_globalRegistry??(s_.__zod_globalRegistry=i_());var Rr=globalThis.__zod_globalRegistry;function a_(t,e){return new t({type:"string",...A(e)})}function c_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function u_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function Od(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function d_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function l_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function p_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function f_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function Nd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function h_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function m_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function g_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function y_(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function v_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function __(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function S_(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 R_(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function P_(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function C_(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function x_(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function k_(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function E_(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function T_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function A_(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function $_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function M_(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function I_(t,e){return new t({type:"number",checks:[],...A(e)})}function z_(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function O_(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function N_(t,e){return new t({type:"boolean",...A(e)})}function D_(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function L_(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function j_(t,e){return new t({type:"null",...A(e)})}function U_(t){return new t({type:"any"})}function F_(t){return new t({type:"unknown"})}function q_(t,e){return new t({type:"never",...A(e)})}function H_(t,e){return new t({type:"date",coerce:!0,...A(e)})}function Bn(t,e){return new kd({check:"less_than",...A(e),value:t,inclusive:!1})}function tr(t,e){return new kd({check:"less_than",...A(e),value:t,inclusive:!0})}function Vn(t,e){return new Ed({check:"greater_than",...A(e),value:t,inclusive:!1})}function Ct(t,e){return new Ed({check:"greater_than",...A(e),value:t,inclusive:!0})}function us(t,e){return new jy({check:"multiple_of",...A(e),value:t})}function ya(t,e){return new Fy({check:"max_length",...A(e),maximum:t})}function Wn(t,e){return new qy({check:"min_length",...A(e),minimum:t})}function va(t,e){return new Hy({check:"length_equals",...A(e),length:t})}function Dd(t,e){return new Gy({check:"string_format",format:"regex",...A(e),pattern:t})}function Ld(t){return new Zy({check:"string_format",format:"lowercase",...A(t)})}function jd(t){return new By({check:"string_format",format:"uppercase",...A(t)})}function Ud(t,e){return new Vy({check:"string_format",format:"includes",...A(e),includes:t})}function Fd(t,e){return new Wy({check:"string_format",format:"starts_with",...A(e),prefix:t})}function qd(t,e){return new Ky({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Pr(t){return new Jy({check:"overwrite",tx:t})}function Hd(t){return Pr(e=>e.normalize(t))}function Gd(){return Pr(t=>t.trim())}function Zd(){return Pr(t=>t.toLowerCase())}function Bd(){return Pr(t=>t.toUpperCase())}function Vd(){return Pr(t=>hd(t))}function G_(t,e,r){return new t({type:"array",element:e,...A(r)})}function Z_(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function B_(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function V_(t,e){let r=H$(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Zn(o,n.value,r._zod.def));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Zn(s))}},t(n.value,n)),e);return r}function H$(t,e){let r=new Te({check:"custom",...A(e)});return r._zod.check=t,r}function Wd(t){let e=t?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:t?.metadata??Rr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let p=i.schema,f=e.processors[o.type];if(!f)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);f(t,e,p,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&je(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function Kd(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,p=t.external.uri??(h=>h);if(l)return{ref:p(l)};let f=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=f,{defId:f,ref:`${p("__shared")}#/${a}/${f}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
86
86
 
87
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function Kd(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let f=t.seen.get(l),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:us(e,"input",t.processors),output:us(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function je(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return je(n.element,r);if(n.type==="set")return je(n.valueType,r);if(n.type==="lazy")return je(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return je(n.innerType,r);if(n.type==="intersection")return je(n.left,r)||je(n.right,r);if(n.type==="record"||n.type==="map")return je(n.keyType,r)||je(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:je(n.in,r)||je(n.out,r);if(n.type==="object"){for(let o in n.shape)if(je(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(je(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(je(o,r))return!0;return!!(n.rest&&je(n.rest,r))}return!1}var H_=(t,e={})=>r=>{let n=Bd({...r,processors:e});return ve(t,n),Wd(n,t),Kd(n,t)},us=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Bd({...o??{},target:s,io:e,processors:r});return ve(t,i),Wd(i,t),Kd(i,t)};var D$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},G_=(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=D$[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}))])}},Z_=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";l?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},V_=(t,e,r,n)=>{r.type="boolean"},B_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var W_=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var K_=(t,e,r,n)=>{r.not={}},J_=(t,e,r,n)=>{},Y_=(t,e,r,n)=>{},X_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Q_=(t,e,r,n)=>{let o=t._zod.def,s=Qo(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},eS=(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 tS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var rS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var nS=(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)},sS=(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},iS=(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 aS=(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)}},cS=(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"}]},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},dS=(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))},lS=(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)))},pS=(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},fS=(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},hS=(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 Jd=(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 va(t){return!!t._zod}function xt(t,e){return va(t)?os(t,e):t.safeParse(e)}function _a(t){if(!t)return;let e;if(va(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Sa(t){if(va(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 ds={};su(ds,{ZodISODate:()=>gS,ZodISODateTime:()=>mS,ZodISODuration:()=>vS,ZodISOTime:()=>yS,date:()=>Xd,datetime:()=>Yd,duration:()=>el,time:()=>Qd});var mS=v("ZodISODateTime",(t,e)=>{fv.init(t,e),pe.init(t,e)});function Yd(t){return P_(mS,t)}var gS=v("ZodISODate",(t,e)=>{hv.init(t,e),pe.init(t,e)});function Xd(t){return C_(gS,t)}var yS=v("ZodISOTime",(t,e)=>{mv.init(t,e),pe.init(t,e)});function Qd(t){return x_(yS,t)}var vS=v("ZodISODuration",(t,e)=>{gv.init(t,e),pe.init(t,e)});function el(t){return k_(vS,t)}var Z$=(t,e)=>{ca.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>bd(t,r)},flatten:{value:r=>wd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,qn,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,qn,2)}},isEmpty:{get(){return t.issues.length===0}}})};var st=v("ZodError",Z$,{Parent:Error});var SS=ua(st),wS=da(st),bS=ns(st),RS=ss(st),PS=Jg(st),CS=Yg(st),xS=Xg(st),kS=Qg(st),ES=ey(st),TS=ty(st),AS=ry(st),$S=ny(st);var MS=new WeakMap;function ls(t,e,r){let n=Object.getPrototypeOf(t),o=MS.get(n);if(o||(o=new Set,MS.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 re=v("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:us(t,"input"),output:us(t,"output")}}),t.toJSONSchema=H_(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>SS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>bS(t,r,n),t.parseAsync=async(r,n)=>wS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>RS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>PS(t,r,n),t.decode=(r,n)=>CS(t,r,n),t.encodeAsync=async(r,n)=>xS(t,r,n),t.decodeAsync=async(r,n)=>kS(t,r,n),t.safeEncode=(r,n)=>ES(t,r,n),t.safeDecode=(r,n)=>TS(t,r,n),t.safeEncodeAsync=async(r,n)=>AS(t,r,n),t.safeDecodeAsync=async(r,n)=>$S(t,r,n),ls(t,"ZodType",{check(...r){let n=this.def;return this.clone(F.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 lt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(IM(r,n))},superRefine(r,n){return this.check(zM(r,n))},overwrite(r){return this.check(Rr(r))},optional(){return he(this)},exactOptional(){return wM(this)},nullable(){return NS(this)},nullish(){return he(NS(this))},nonoptional(r){return kM(this,r)},array(){return C(this)},or(r){return ce([this,r])},and(r){return Ra(this,r)},transform(r){return DS(this,BS(r))},default(r){return PM(this,r)},prefault(r){return xM(this,r)},catch(r){return TM(this,r)},pipe(r){return DS(this,r)},readonly(){return MM(this)},describe(r){let n=this.clone();return br.add(n,{description:r}),n},meta(...r){if(r.length===0)return br.get(this);let n=this.clone();return br.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 br.get(t)?.description},configurable:!0}),t)),LS=v("_ZodString",(t,e)=>{ma.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>G_(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,ls(t,"_ZodString",{regex(...n){return this.check(Nd(...n))},includes(...n){return this.check(jd(...n))},startsWith(...n){return this.check(Ud(...n))},endsWith(...n){return this.check(Fd(...n))},min(...n){return this.check(Bn(...n))},max(...n){return this.check(ga(...n))},length(...n){return this.check(ya(...n))},nonempty(...n){return this.check(Bn(1,...n))},lowercase(n){return this.check(Dd(n))},uppercase(n){return this.check(Ld(n))},trim(){return this.check(Hd())},normalize(...n){return this.check(qd(...n))},toLowerCase(){return this.check(Gd())},toUpperCase(){return this.check(Zd())},slugify(){return this.check(Vd())}})}),rl=v("ZodString",(t,e)=>{ma.init(t,e),LS.init(t,e),t.email=r=>t.check(o_(B$,r)),t.url=r=>t.check(Od(jS,r)),t.jwt=r=>t.check(R_(cM,r)),t.emoji=r=>t.check(u_(W$,r)),t.guid=r=>t.check(zd(IS,r)),t.uuid=r=>t.check(s_(wa,r)),t.uuidv4=r=>t.check(i_(wa,r)),t.uuidv6=r=>t.check(a_(wa,r)),t.uuidv7=r=>t.check(c_(wa,r)),t.nanoid=r=>t.check(d_(K$,r)),t.guid=r=>t.check(zd(IS,r)),t.cuid=r=>t.check(l_(J$,r)),t.cuid2=r=>t.check(p_(Y$,r)),t.ulid=r=>t.check(f_(X$,r)),t.base64=r=>t.check(S_(sM,r)),t.base64url=r=>t.check(w_(iM,r)),t.xid=r=>t.check(h_(Q$,r)),t.ksuid=r=>t.check(m_(eM,r)),t.ipv4=r=>t.check(g_(tM,r)),t.ipv6=r=>t.check(y_(rM,r)),t.cidrv4=r=>t.check(v_(nM,r)),t.cidrv6=r=>t.check(__(oM,r)),t.e164=r=>t.check(b_(aM,r)),t.datetime=r=>t.check(Yd(r)),t.date=r=>t.check(Xd(r)),t.time=r=>t.check(Qd(r)),t.duration=r=>t.check(el(r))});function g(t){return r_(rl,t)}var pe=v("ZodStringFormat",(t,e)=>{ae.init(t,e),LS.init(t,e)}),B$=v("ZodEmail",(t,e)=>{ov.init(t,e),pe.init(t,e)});var IS=v("ZodGUID",(t,e)=>{rv.init(t,e),pe.init(t,e)});var wa=v("ZodUUID",(t,e)=>{nv.init(t,e),pe.init(t,e)});var jS=v("ZodURL",(t,e)=>{sv.init(t,e),pe.init(t,e)});function US(t){return Od(jS,t)}var W$=v("ZodEmoji",(t,e)=>{iv.init(t,e),pe.init(t,e)});var K$=v("ZodNanoID",(t,e)=>{av.init(t,e),pe.init(t,e)});var J$=v("ZodCUID",(t,e)=>{cv.init(t,e),pe.init(t,e)});var Y$=v("ZodCUID2",(t,e)=>{uv.init(t,e),pe.init(t,e)});var X$=v("ZodULID",(t,e)=>{dv.init(t,e),pe.init(t,e)});var Q$=v("ZodXID",(t,e)=>{lv.init(t,e),pe.init(t,e)});var eM=v("ZodKSUID",(t,e)=>{pv.init(t,e),pe.init(t,e)});var tM=v("ZodIPv4",(t,e)=>{yv.init(t,e),pe.init(t,e)});var rM=v("ZodIPv6",(t,e)=>{vv.init(t,e),pe.init(t,e)});var nM=v("ZodCIDRv4",(t,e)=>{_v.init(t,e),pe.init(t,e)});var oM=v("ZodCIDRv6",(t,e)=>{Sv.init(t,e),pe.init(t,e)});var sM=v("ZodBase64",(t,e)=>{bv.init(t,e),pe.init(t,e)});var iM=v("ZodBase64URL",(t,e)=>{Rv.init(t,e),pe.init(t,e)});var aM=v("ZodE164",(t,e)=>{Pv.init(t,e),pe.init(t,e)});var cM=v("ZodJWT",(t,e)=>{Cv.init(t,e),pe.init(t,e)});var ba=v("ZodNumber",(t,e)=>{Td.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Z_(t,n,o,s),ls(t,"ZodNumber",{gt(n,o){return this.check(Vn(n,o))},gte(n,o){return this.check(Ct(n,o))},min(n,o){return this.check(Ct(n,o))},lt(n,o){return this.check(Zn(n,o))},lte(n,o){return this.check(tr(n,o))},max(n,o){return this.check(tr(n,o))},int(n){return this.check(zS(n))},safe(n){return this.check(zS(n))},positive(n){return this.check(Vn(0,n))},nonnegative(n){return this.check(Ct(0,n))},negative(n){return this.check(Zn(0,n))},nonpositive(n){return this.check(tr(0,n))},multipleOf(n,o){return this.check(cs(n,o))},step(n,o){return this.check(cs(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 E_(ba,t)}var uM=v("ZodNumberFormat",(t,e)=>{xv.init(t,e),ba.init(t,e)});function zS(t){return A_(uM,t)}var nl=v("ZodBoolean",(t,e)=>{kv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>V_(t,r,n,o)});function ne(t){return $_(nl,t)}var FS=v("ZodBigInt",(t,e)=>{Ev.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>B_(t,n,o,s),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.gt=(n,o)=>t.check(Vn(n,o)),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.lt=(n,o)=>t.check(Zn(n,o)),t.lte=(n,o)=>t.check(tr(n,o)),t.max=(n,o)=>t.check(tr(n,o)),t.positive=n=>t.check(Vn(BigInt(0),n)),t.negative=n=>t.check(Zn(BigInt(0),n)),t.nonpositive=n=>t.check(tr(BigInt(0),n)),t.nonnegative=n=>t.check(Ct(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(cs(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var dM=v("ZodNull",(t,e)=>{Tv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>W_(t,r,n,o)});function qS(t){return z_(dM,t)}var lM=v("ZodAny",(t,e)=>{Av.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>J_(t,r,n,o)});function HS(){return O_(lM)}var pM=v("ZodUnknown",(t,e)=>{$v.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Y_(t,r,n,o)});function fe(){return N_(pM)}var fM=v("ZodNever",(t,e)=>{Mv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>K_(t,r,n,o)});function hM(t){return D_(fM,t)}var GS=v("ZodDate",(t,e)=>{Iv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>X_(t,n,o,s),t.min=(n,o)=>t.check(Ct(n,o)),t.max=(n,o)=>t.check(tr(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 mM=v("ZodArray",(t,e)=>{zv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nS(t,r,n,o),t.element=e.element,ls(t,"ZodArray",{min(r,n){return this.check(Bn(r,n))},nonempty(r){return this.check(Bn(1,r))},max(r,n){return this.check(ga(r,n))},length(r,n){return this.check(ya(r,n))},unwrap(){return this.element}})});function C(t,e){return j_(mM,t,e)}var ZS=v("ZodObject",(t,e)=>{Dv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>oS(t,r,n,o),F.defineLazy(t,"shape",()=>e.shape),ls(t,"ZodObject",{keyof(){return Ye(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:fe()})},loose(){return this.clone({...this._zod.def,catchall:fe()})},strict(){return this.clone({...this._zod.def,catchall:hM()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return F.extend(this,r)},safeExtend(r){return F.safeExtend(this,r)},merge(r){return F.merge(this,r)},pick(r){return F.pick(this,r)},omit(r){return F.omit(this,r)},partial(...r){return F.partial(WS,this,r[0])},required(...r){return F.required(KS,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...F.normalizeParams(e)};return new ZS(r)}function Pe(t,e){return new ZS({type:"object",shape:t,catchall:fe(),...F.normalizeParams(e)})}var VS=v("ZodUnion",(t,e)=>{Ad.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sS(t,r,n,o),t.options=e.options});function ce(t,e){return new VS({type:"union",options:t,...F.normalizeParams(e)})}var gM=v("ZodDiscriminatedUnion",(t,e)=>{VS.init(t,e),Lv.init(t,e)});function ol(t,e,r){return new gM({type:"union",options:e,discriminator:t,...F.normalizeParams(r)})}var yM=v("ZodIntersection",(t,e)=>{jv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>iS(t,r,n,o)});function Ra(t,e){return new yM({type:"intersection",left:t,right:e})}var OS=v("ZodRecord",(t,e)=>{Uv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ie(t,e,r){return!e||!e._zod?new OS({type:"record",keyType:g(),valueType:t,...F.normalizeParams(e)}):new OS({type:"record",keyType:t,valueType:e,...F.normalizeParams(r)})}var tl=v("ZodEnum",(t,e)=>{Fv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>Q_(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 tl({...e,checks:[],...F.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 tl({...e,checks:[],...F.normalizeParams(o),entries:s})}});function Ye(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new tl({type:"enum",entries:r,...F.normalizeParams(e)})}var vM=v("ZodLiteral",(t,e)=>{qv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>eS(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 vM({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var _M=v("ZodTransform",(t,e)=>{Hv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Un(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(F.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(F.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 BS(t){return new _M({type:"transform",transform:t})}var WS=v("ZodOptional",(t,e)=>{$d.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function he(t){return new WS({type:"optional",innerType:t})}var SM=v("ZodExactOptional",(t,e)=>{Gv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function wM(t){return new SM({type:"optional",innerType:t})}var bM=v("ZodNullable",(t,e)=>{Zv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function NS(t){return new bM({type:"nullable",innerType:t})}var RM=v("ZodDefault",(t,e)=>{Vv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function PM(t,e){return new RM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var CM=v("ZodPrefault",(t,e)=>{Bv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function xM(t,e){return new CM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var KS=v("ZodNonOptional",(t,e)=>{Wv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function kM(t,e){return new KS({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var EM=v("ZodCatch",(t,e)=>{Kv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function TM(t,e){return new EM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var JS=v("ZodPipe",(t,e)=>{Md.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fS(t,r,n,o),t.in=e.in,t.out=e.out});function DS(t,e){return new JS({type:"pipe",in:t,out:e})}var AM=v("ZodPreprocess",(t,e)=>{JS.init(t,e),Jv.init(t,e)}),$M=v("ZodReadonly",(t,e)=>{Yv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function MM(t){return new $M({type:"readonly",innerType:t})}var YS=v("ZodCustom",(t,e)=>{Xv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tS(t,r,n,o)});function XS(t,e){return U_(YS,t??(()=>!0),e)}function IM(t,e={}){return F_(YS,t,e)}function zM(t,e){return q_(t,e)}function sl(t,e){return new AM({type:"pipe",in:BS(t),out:e})}var ew={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 QS;QS||(QS={});var Pa={};su(Pa,{bigint:()=>LM,boolean:()=>DM,date:()=>jM,number:()=>NM,string:()=>OM});function OM(t){return n_(rl,t)}function NM(t){return T_(ba,t)}function DM(t){return M_(nl,t)}function LM(t){return I_(FS,t)}function jM(t){return L_(GS,t)}Je(Qv());var Jn="2025-11-25";var tw=[Jn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Pr="io.modelcontextprotocol/related-task",xa="2.0",Ce=XS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),rw=ce([g(),W().int()]),nw=g(),CV=Pe({ttl:W().optional(),pollInterval:W().optional()}),FM=x({ttl:W().optional()}),qM=x({taskId:g()}),al=Pe({progressToken:rw.optional(),[Pr]:qM.optional()}),it=x({_meta:al.optional()}),ps=it.extend({task:FM.optional()}),ow=t=>ps.safeParse(t).success,Ae=x({method:g(),params:it.loose().optional()}),ft=x({_meta:al.optional()}),ht=x({method:g(),params:ft.loose().optional()}),xe=Pe({_meta:al.optional()}),ka=ce([g(),W().int()]),sw=x({jsonrpc:E(xa),id:ka,...Ae.shape}).strict(),fs=t=>sw.safeParse(t).success,iw=x({jsonrpc:E(xa),...ht.shape}).strict(),aw=t=>iw.safeParse(t).success,cl=x({jsonrpc:E(xa),id:ka,result:xe}).strict(),Qr=t=>cl.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 ul=x({jsonrpc:E(xa),id:ka.optional(),error:x({code:W().int(),message:g(),data:fe().optional()})}).strict();var cw=t=>ul.safeParse(t).success;var Cr=ce([sw,iw,cl,ul]),xV=ce([cl,ul]),en=xe.strict(),HM=ft.extend({requestId:ka.optional(),reason:g().optional()}),Ea=ht.extend({method:E("notifications/cancelled"),params:HM}),GM=x({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Ye(["light","dark"]).optional()}),hs=x({icons:C(GM).optional()}),Kn=x({name:g(),title:g().optional()}),uw=Kn.extend({...Kn.shape,...hs.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),ZM=Ra(x({applyDefaults:ne().optional()}),ie(g(),fe())),VM=sl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ra(x({form:ZM.optional(),url:Ce.optional()}),ie(g(),fe()).optional())),BM=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({sampling:Pe({createMessage:Ce.optional()}).optional(),elicitation:Pe({create:Ce.optional()}).optional()}).optional()}),WM=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({tools:Pe({call:Ce.optional()}).optional()}).optional()}),KM=x({experimental:ie(g(),Ce).optional(),sampling:x({context:Ce.optional(),tools:Ce.optional()}).optional(),elicitation:VM.optional(),roots:x({listChanged:ne().optional()}).optional(),tasks:BM.optional(),extensions:ie(g(),Ce).optional()}),JM=it.extend({protocolVersion:g(),capabilities:KM,clientInfo:uw}),YM=Ae.extend({method:E("initialize"),params:JM});var XM=x({experimental:ie(g(),Ce).optional(),logging:Ce.optional(),completions:Ce.optional(),prompts:x({listChanged:ne().optional()}).optional(),resources:x({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:x({listChanged:ne().optional()}).optional(),tasks:WM.optional(),extensions:ie(g(),Ce).optional()}),dl=xe.extend({protocolVersion:g(),capabilities:XM,serverInfo:uw,instructions:g().optional()}),dw=ht.extend({method:E("notifications/initialized"),params:ft.optional()}),lw=t=>dw.safeParse(t).success,Ta=Ae.extend({method:E("ping"),params:it.optional()}),QM=x({progress:W(),total:he(W()),message:he(g())}),eI=x({...ft.shape,...QM.shape,progressToken:rw}),Aa=ht.extend({method:E("notifications/progress"),params:eI}),tI=it.extend({cursor:nw.optional()}),ms=Ae.extend({params:tI.optional()}),gs=xe.extend({nextCursor:nw.optional()}),rI=Ye(["working","input_required","completed","failed","cancelled"]),ys=x({taskId:g(),status:rI,ttl:ce([W(),qS()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:he(W()),statusMessage:he(g())}),tn=xe.extend({task:ys}),nI=ft.merge(ys),vs=ht.extend({method:E("notifications/tasks/status"),params:nI}),$a=Ae.extend({method:E("tasks/get"),params:it.extend({taskId:g()})}),Ma=xe.merge(ys),Ia=Ae.extend({method:E("tasks/result"),params:it.extend({taskId:g()})}),kV=xe.loose(),za=ms.extend({method:E("tasks/list")}),Oa=gs.extend({tasks:C(ys)}),Na=Ae.extend({method:E("tasks/cancel"),params:it.extend({taskId:g()})}),pw=xe.merge(ys),fw=x({uri:g(),mimeType:he(g()),_meta:ie(g(),fe()).optional()}),hw=fw.extend({text:g()}),ll=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mw=fw.extend({blob:ll}),_s=Ye(["user","assistant"]),Yn=x({audience:C(_s).optional(),priority:W().min(0).max(1).optional(),lastModified:ds.datetime({offset:!0}).optional()}),gw=x({...Kn.shape,...hs.shape,uri:g(),description:he(g()),mimeType:he(g()),size:he(W()),annotations:Yn.optional(),_meta:he(Pe({}))}),oI=x({...Kn.shape,...hs.shape,uriTemplate:g(),description:he(g()),mimeType:he(g()),annotations:Yn.optional(),_meta:he(Pe({}))}),sI=ms.extend({method:E("resources/list")}),pl=gs.extend({resources:C(gw)}),iI=ms.extend({method:E("resources/templates/list")}),fl=gs.extend({resourceTemplates:C(oI)}),hl=it.extend({uri:g()}),aI=hl,cI=Ae.extend({method:E("resources/read"),params:aI}),ml=xe.extend({contents:C(ce([hw,mw]))}),gl=ht.extend({method:E("notifications/resources/list_changed"),params:ft.optional()}),uI=hl,dI=Ae.extend({method:E("resources/subscribe"),params:uI}),lI=hl,pI=Ae.extend({method:E("resources/unsubscribe"),params:lI}),fI=ft.extend({uri:g()}),hI=ht.extend({method:E("notifications/resources/updated"),params:fI}),mI=x({name:g(),description:he(g()),required:he(ne())}),gI=x({...Kn.shape,...hs.shape,description:he(g()),arguments:he(C(mI)),_meta:he(Pe({}))}),yI=ms.extend({method:E("prompts/list")}),yl=gs.extend({prompts:C(gI)}),vI=it.extend({name:g(),arguments:ie(g(),g()).optional()}),_I=Ae.extend({method:E("prompts/get"),params:vI}),vl=x({type:E("text"),text:g(),annotations:Yn.optional(),_meta:ie(g(),fe()).optional()}),_l=x({type:E("image"),data:ll,mimeType:g(),annotations:Yn.optional(),_meta:ie(g(),fe()).optional()}),Sl=x({type:E("audio"),data:ll,mimeType:g(),annotations:Yn.optional(),_meta:ie(g(),fe()).optional()}),SI=x({type:E("tool_use"),name:g(),id:g(),input:ie(g(),fe()),_meta:ie(g(),fe()).optional()}),wI=x({type:E("resource"),resource:ce([hw,mw]),annotations:Yn.optional(),_meta:ie(g(),fe()).optional()}),bI=gw.extend({type:E("resource_link")}),wl=ce([vl,_l,Sl,bI,wI]),RI=x({role:_s,content:wl}),bl=xe.extend({description:g().optional(),messages:C(RI)}),Rl=ht.extend({method:E("notifications/prompts/list_changed"),params:ft.optional()}),PI=x({title:g().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),CI=x({taskSupport:Ye(["required","optional","forbidden"]).optional()}),yw=x({...Kn.shape,...hs.shape,description:g().optional(),inputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()),outputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()).optional(),annotations:PI.optional(),execution:CI.optional(),_meta:ie(g(),fe()).optional()}),xI=ms.extend({method:E("tools/list")}),Pl=gs.extend({tools:C(yw)}),rn=xe.extend({content:C(wl).default([]),structuredContent:ie(g(),fe()).optional(),isError:ne().optional()}),EV=rn.or(xe.extend({toolResult:fe()})),kI=ps.extend({name:g(),arguments:ie(g(),fe()).optional()}),EI=Ae.extend({method:E("tools/call"),params:kI}),Ss=ht.extend({method:E("notifications/tools/list_changed"),params:ft.optional()}),vw=x({autoRefresh:ne().default(!0),debounceMs:W().int().nonnegative().default(300)}),_w=Ye(["debug","info","notice","warning","error","critical","alert","emergency"]),TI=it.extend({level:_w}),AI=Ae.extend({method:E("logging/setLevel"),params:TI}),$I=ft.extend({level:_w,logger:g().optional(),data:fe()}),MI=ht.extend({method:E("notifications/message"),params:$I}),II=x({name:g().optional()}),zI=x({hints:C(II).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),OI=x({mode:Ye(["auto","required","none"]).optional()}),NI=x({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(wl).default([]),structuredContent:x({}).loose().optional(),isError:ne().optional(),_meta:ie(g(),fe()).optional()}),DI=ol("type",[vl,_l,Sl]),Ca=ol("type",[vl,_l,Sl,SI,NI]),LI=x({role:_s,content:ce([Ca,C(Ca)]),_meta:ie(g(),fe()).optional()}),jI=ps.extend({messages:C(LI),modelPreferences:zI.optional(),systemPrompt:g().optional(),includeContext:Ye(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:C(g()).optional(),metadata:Ce.optional(),tools:C(yw).optional(),toolChoice:OI.optional()}),Cl=Ae.extend({method:E("sampling/createMessage"),params:jI}),xl=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens"]).or(g())),role:_s,content:DI}),kl=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:_s,content:ce([Ca,C(Ca)])}),UI=x({type:E("boolean"),title:g().optional(),description:g().optional(),default:ne().optional()}),FI=x({type:E("string"),title:g().optional(),description:g().optional(),minLength:W().optional(),maxLength:W().optional(),format:Ye(["email","uri","date","date-time"]).optional(),default:g().optional()}),qI=x({type:Ye(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),HI=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),GI=x({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(x({const:g(),title:g()})),default:g().optional()}),ZI=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),VI=ce([HI,GI]),BI=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()}),WI=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()}),KI=ce([BI,WI]),JI=ce([ZI,VI,KI]),YI=ce([JI,UI,FI,qI]),XI=ps.extend({mode:E("form").optional(),message:g(),requestedSchema:x({type:E("object"),properties:ie(g(),YI),required:C(g()).optional()})}),QI=ps.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),ez=ce([XI,QI]),El=Ae.extend({method:E("elicitation/create"),params:ez}),tz=ft.extend({elicitationId:g()}),rz=ht.extend({method:E("notifications/elicitation/complete"),params:tz}),Tl=xe.extend({action:Ye(["accept","decline","cancel"]),content:sl(t=>t===null?void 0:t,ie(g(),ce([g(),W(),ne(),C(g())])).optional())}),nz=x({type:E("ref/resource"),uri:g()});var oz=x({type:E("ref/prompt"),name:g()}),sz=it.extend({ref:ce([oz,nz]),argument:x({name:g(),value:g()}),context:x({arguments:ie(g(),g()).optional()}).optional()}),iz=Ae.extend({method:E("completion/complete"),params:sz});var Al=xe.extend({completion:Pe({values:C(g()).max(100),total:he(W().int()),hasMore:he(ne())})}),az=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ie(g(),fe()).optional()}),cz=Ae.extend({method:E("roots/list"),params:it.optional()}),uz=xe.extend({roots:C(az)}),dz=ht.extend({method:E("notifications/roots/list_changed"),params:ft.optional()}),TV=ce([Ta,YM,iz,AI,_I,yI,sI,iI,cI,dI,pI,EI,xI,$a,Ia,za,Na]),AV=ce([Ea,Aa,dw,dz,vs]),$V=ce([en,xl,kl,Tl,uz,Ma,Oa,tn]),MV=ce([Ta,Cl,El,cz,$a,Ia,za,Na]),IV=ce([Ea,Aa,MI,hI,gl,Ss,Rl,vs,rz]),zV=ce([en,dl,Al,bl,yl,pl,fl,ml,rn,Pl,Ma,Oa,tn]),$=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 il(o.elicitations,r)}return new t(e,r,n)}},il=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 xr(t){return t==="completed"||t==="failed"||t==="cancelled"}var fB=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function $l(t){let r=_a(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Sa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ml(t,e){let r=xt(t,e);if(!r.success)throw r.error;return r.data}var gz=6e4,Da=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(Ea,r=>{this._oncancel(r)}),this.setNotificationHandler(Aa,r=>{this._onprogress(r)}),this.setRequestHandler(Ta,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($a,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(Ia,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new $(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!xr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(xr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Pr]:{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(Na,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(xr(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),Qr(s)||cw(s)?this._onresponse(s):fs(s)?this._onrequest(s,i):aw(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?.[Pr]?.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,p)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Qr(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(Qr(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),Qr(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,tn,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},xr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=w=>{d(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){l(w);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Pr]:c}});let h=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let b=w instanceof $?w:new $(M.RequestTimeout,String(w));d(b)};this._responseHandlers.set(p,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=xt(r,w.result);b.success?u(b.data):d(b.error)}catch(b){d(b)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??gz,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(p,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let w=b=>{let k=this._responseHandlers.get(p);k?k(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),d(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ma,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},Oa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},pw,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||{},[Pr]: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||{},[Pr]: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||{},[Pr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=$l(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ml(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=$l(e);this._notificationHandlers.set(n,o=>{let s=Ml(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"&&fs(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=vs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),xr(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(xr(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=vs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),xr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Sw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ww(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];Sw(i)&&Sw(s)?r[o]={...i,...s}:r[o]=s}return r}var lP=Ci(_f(),1),pP=Ci(dP(),1);function w1(){let t=new lP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,pP.default)(t),t}var Sc=class{constructor(e){this._ajv=e??w1()}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 wc=class{constructor(e){this._client=e}async*callToolStream(e,r=rn,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 fP(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 hP(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 bc(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&&bc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&bc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&bc(r,e)}}function b1(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 Rc=class extends Da{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 Sc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ss,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Rl,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",gl,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new wc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ww(this._capabilities,e)}setRequestHandler(e,r){let o=_a(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Sa(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let d=xt(El,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=b1(this._capabilities.elicitation);if(l.mode==="form"&&!p)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!f)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=xt(tn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new $(M.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let m=xt(Tl,h);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${w}`)}let y=m.data,S=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{bc(S,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=xt(Cl,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let y=xt(tn,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=l.tools||l.toolChoice?kl:xl,m=xt(h,p);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Jn,capabilities:this._capabilities,clientInfo:this._clientInfo}},dl,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!tw.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){fP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&hP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},en,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Al,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},en,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},bl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},yl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},pl,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},fl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ml,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},en,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},en,r)}async callTool(e,r=rn,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},Pl,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 p=l instanceof Error?l:new Error(String(l));c(p,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Ys=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}},mP=10,R1=13,mn=32;function kf(t){}function Pc(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=kf,onError:r=kf,onRetry:n=kf,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,p,f=!1;function h(_){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,_.charCodeAt(0)===239&&_.charCodeAt(1)===187&&_.charCodeAt(2)===191&&(_=_.slice(3))),i.length===0){let ge=y(_);ge!==""&&(i.push(ge),a=ge.length),m();return}if(_.indexOf(`
88
- `)===-1&&_.indexOf("\r")===-1){i.push(_),a+=_.length,m();return}i.push(_);let P=i.join("");i.length=0,a=0;let z=y(P);z!==""&&(i.push(z),a=z.length),m()}function m(){s!==void 0&&(a+d.length<=s||(f=!0,i.length=0,a=0,u=void 0,d="",l=0,p=void 0,r(new Ys(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(_){let P=0;if(_.indexOf("\r")===-1){let z=_.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 Jd(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let f=t.seen.get(l),h=f.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&f.def)for(let y in u)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(u[y])===JSON.stringify(f.def[y])&&delete u[y]}let p=a._zod.parent;if(p&&p!==l){n(p);let f=t.seen.get(p);if(f?.schema.$ref&&(u.$ref=f.schema.$ref,f.def))for(let h in u)h==="$ref"||h==="allOf"||h in f.def&&JSON.stringify(u[h])===JSON.stringify(f.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:ds(e,"input",t.processors),output:ds(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function je(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return je(n.element,r);if(n.type==="set")return je(n.valueType,r);if(n.type==="lazy")return je(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return je(n.innerType,r);if(n.type==="intersection")return je(n.left,r)||je(n.right,r);if(n.type==="record"||n.type==="map")return je(n.keyType,r)||je(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:je(n.in,r)||je(n.out,r);if(n.type==="object"){for(let o in n.shape)if(je(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(je(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(je(o,r))return!0;return!!(n.rest&&je(n.rest,r))}return!1}var W_=(t,e={})=>r=>{let n=Wd({...r,processors:e});return ve(t,n),Kd(n,t),Jd(n,t)},ds=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=Wd({...o??{},target:s,io:e,processors:r});return ve(t,i),Kd(i,t),Jd(i,t)};var G$={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},K_=(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=G$[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}))])}},J_=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),p=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";l?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),p?f?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},Y_=(t,e,r,n)=>{r.type="boolean"},X_=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var Q_=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var eS=(t,e,r,n)=>{r.not={}},tS=(t,e,r,n)=>{},rS=(t,e,r,n)=>{},nS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},oS=(t,e,r,n)=>{let o=t._zod.def,s=es(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},sS=(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 iS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var aS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var cS=(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"]})},uS=(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)},dS=(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},lS=(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 pS=(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)}},fS=(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"}]},hS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},mS=(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))},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,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},yS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},vS=(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},_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,r.readOnly=!0};var Yd=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType};function _a(t){return!!t._zod}function xt(t,e){return _a(t)?ss(t,e):t.safeParse(e)}function Sa(t){if(!t)return;let e;if(_a(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function wa(t){if(_a(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ls={};iu(ls,{ZodISODate:()=>wS,ZodISODateTime:()=>SS,ZodISODuration:()=>RS,ZodISOTime:()=>bS,date:()=>Qd,datetime:()=>Xd,duration:()=>tl,time:()=>el});var SS=v("ZodISODateTime",(t,e)=>{vv.init(t,e),pe.init(t,e)});function Xd(t){return T_(SS,t)}var wS=v("ZodISODate",(t,e)=>{_v.init(t,e),pe.init(t,e)});function Qd(t){return A_(wS,t)}var bS=v("ZodISOTime",(t,e)=>{Sv.init(t,e),pe.init(t,e)});function el(t){return $_(bS,t)}var RS=v("ZodISODuration",(t,e)=>{wv.init(t,e),pe.init(t,e)});function tl(t){return M_(RS,t)}var X$=(t,e)=>{ua.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Rd(t,r)},flatten:{value:r=>bd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,Hn,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,Hn,2)}},isEmpty:{get(){return t.issues.length===0}}})};var st=v("ZodError",X$,{Parent:Error});var CS=da(st),xS=la(st),kS=os(st),ES=is(st),TS=ty(st),AS=ry(st),$S=ny(st),MS=oy(st),IS=sy(st),zS=iy(st),OS=ay(st),NS=cy(st);var DS=new WeakMap;function ps(t,e,r){let n=Object.getPrototypeOf(t),o=DS.get(n);if(o||(o=new Set,DS.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 re=v("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:ds(t,"input"),output:ds(t,"output")}}),t.toJSONSchema=W_(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>CS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>kS(t,r,n),t.parseAsync=async(r,n)=>xS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ES(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>TS(t,r,n),t.decode=(r,n)=>AS(t,r,n),t.encodeAsync=async(r,n)=>$S(t,r,n),t.decodeAsync=async(r,n)=>MS(t,r,n),t.safeEncode=(r,n)=>IS(t,r,n),t.safeDecode=(r,n)=>zS(t,r,n),t.safeEncodeAsync=async(r,n)=>OS(t,r,n),t.safeDecodeAsync=async(r,n)=>NS(t,r,n),ps(t,"ZodType",{check(...r){let n=this.def;return this.clone(F.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 lt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(UM(r,n))},superRefine(r,n){return this.check(FM(r,n))},overwrite(r){return this.check(Pr(r))},optional(){return he(this)},exactOptional(){return EM(this)},nullable(){return FS(this)},nullish(){return he(FS(this))},nonoptional(r){return zM(this,r)},array(){return C(this)},or(r){return ce([this,r])},and(r){return Pa(this,r)},transform(r){return qS(this,XS(r))},default(r){return $M(this,r)},prefault(r){return IM(this,r)},catch(r){return NM(this,r)},pipe(r){return qS(this,r)},readonly(){return jM(this)},describe(r){let n=this.clone();return Rr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Rr.get(this);let n=this.clone();return Rr.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return Rr.get(t)?.description},configurable:!0}),t)),HS=v("_ZodString",(t,e)=>{ga.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>K_(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(Dd(...n))},includes(...n){return this.check(Ud(...n))},startsWith(...n){return this.check(Fd(...n))},endsWith(...n){return this.check(qd(...n))},min(...n){return this.check(Wn(...n))},max(...n){return this.check(ya(...n))},length(...n){return this.check(va(...n))},nonempty(...n){return this.check(Wn(1,...n))},lowercase(n){return this.check(Ld(n))},uppercase(n){return this.check(jd(n))},trim(){return this.check(Gd())},normalize(...n){return this.check(Hd(...n))},toLowerCase(){return this.check(Zd())},toUpperCase(){return this.check(Bd())},slugify(){return this.check(Vd())}})}),nl=v("ZodString",(t,e)=>{ga.init(t,e),HS.init(t,e),t.email=r=>t.check(u_(eM,r)),t.url=r=>t.check(Nd(GS,r)),t.jwt=r=>t.check(E_(mM,r)),t.emoji=r=>t.check(h_(tM,r)),t.guid=r=>t.check(Od(LS,r)),t.uuid=r=>t.check(d_(ba,r)),t.uuidv4=r=>t.check(l_(ba,r)),t.uuidv6=r=>t.check(p_(ba,r)),t.uuidv7=r=>t.check(f_(ba,r)),t.nanoid=r=>t.check(m_(rM,r)),t.guid=r=>t.check(Od(LS,r)),t.cuid=r=>t.check(g_(nM,r)),t.cuid2=r=>t.check(y_(oM,r)),t.ulid=r=>t.check(v_(sM,r)),t.base64=r=>t.check(C_(pM,r)),t.base64url=r=>t.check(x_(fM,r)),t.xid=r=>t.check(__(iM,r)),t.ksuid=r=>t.check(S_(aM,r)),t.ipv4=r=>t.check(w_(cM,r)),t.ipv6=r=>t.check(b_(uM,r)),t.cidrv4=r=>t.check(R_(dM,r)),t.cidrv6=r=>t.check(P_(lM,r)),t.e164=r=>t.check(k_(hM,r)),t.datetime=r=>t.check(Xd(r)),t.date=r=>t.check(Qd(r)),t.time=r=>t.check(el(r)),t.duration=r=>t.check(tl(r))});function g(t){return a_(nl,t)}var pe=v("ZodStringFormat",(t,e)=>{ae.init(t,e),HS.init(t,e)}),eM=v("ZodEmail",(t,e)=>{uv.init(t,e),pe.init(t,e)});var LS=v("ZodGUID",(t,e)=>{av.init(t,e),pe.init(t,e)});var ba=v("ZodUUID",(t,e)=>{cv.init(t,e),pe.init(t,e)});var GS=v("ZodURL",(t,e)=>{dv.init(t,e),pe.init(t,e)});function ZS(t){return Nd(GS,t)}var tM=v("ZodEmoji",(t,e)=>{lv.init(t,e),pe.init(t,e)});var rM=v("ZodNanoID",(t,e)=>{pv.init(t,e),pe.init(t,e)});var nM=v("ZodCUID",(t,e)=>{fv.init(t,e),pe.init(t,e)});var oM=v("ZodCUID2",(t,e)=>{hv.init(t,e),pe.init(t,e)});var sM=v("ZodULID",(t,e)=>{mv.init(t,e),pe.init(t,e)});var iM=v("ZodXID",(t,e)=>{gv.init(t,e),pe.init(t,e)});var aM=v("ZodKSUID",(t,e)=>{yv.init(t,e),pe.init(t,e)});var cM=v("ZodIPv4",(t,e)=>{bv.init(t,e),pe.init(t,e)});var uM=v("ZodIPv6",(t,e)=>{Rv.init(t,e),pe.init(t,e)});var dM=v("ZodCIDRv4",(t,e)=>{Pv.init(t,e),pe.init(t,e)});var lM=v("ZodCIDRv6",(t,e)=>{Cv.init(t,e),pe.init(t,e)});var pM=v("ZodBase64",(t,e)=>{kv.init(t,e),pe.init(t,e)});var fM=v("ZodBase64URL",(t,e)=>{Ev.init(t,e),pe.init(t,e)});var hM=v("ZodE164",(t,e)=>{Tv.init(t,e),pe.init(t,e)});var mM=v("ZodJWT",(t,e)=>{Av.init(t,e),pe.init(t,e)});var Ra=v("ZodNumber",(t,e)=>{Ad.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>J_(t,n,o,s),ps(t,"ZodNumber",{gt(n,o){return this.check(Vn(n,o))},gte(n,o){return this.check(Ct(n,o))},min(n,o){return this.check(Ct(n,o))},lt(n,o){return this.check(Bn(n,o))},lte(n,o){return this.check(tr(n,o))},max(n,o){return this.check(tr(n,o))},int(n){return this.check(jS(n))},safe(n){return this.check(jS(n))},positive(n){return this.check(Vn(0,n))},nonnegative(n){return this.check(Ct(0,n))},negative(n){return this.check(Bn(0,n))},nonpositive(n){return this.check(tr(0,n))},multipleOf(n,o){return this.check(us(n,o))},step(n,o){return this.check(us(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 I_(Ra,t)}var gM=v("ZodNumberFormat",(t,e)=>{$v.init(t,e),Ra.init(t,e)});function jS(t){return O_(gM,t)}var ol=v("ZodBoolean",(t,e)=>{Mv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Y_(t,r,n,o)});function ne(t){return N_(ol,t)}var BS=v("ZodBigInt",(t,e)=>{Iv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>X_(t,n,o,s),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.gt=(n,o)=>t.check(Vn(n,o)),t.gte=(n,o)=>t.check(Ct(n,o)),t.min=(n,o)=>t.check(Ct(n,o)),t.lt=(n,o)=>t.check(Bn(n,o)),t.lte=(n,o)=>t.check(tr(n,o)),t.max=(n,o)=>t.check(tr(n,o)),t.positive=n=>t.check(Vn(BigInt(0),n)),t.negative=n=>t.check(Bn(BigInt(0),n)),t.nonpositive=n=>t.check(tr(BigInt(0),n)),t.nonnegative=n=>t.check(Ct(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(us(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});var yM=v("ZodNull",(t,e)=>{zv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Q_(t,r,n,o)});function VS(t){return j_(yM,t)}var vM=v("ZodAny",(t,e)=>{Ov.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tS(t,r,n,o)});function WS(){return U_(vM)}var _M=v("ZodUnknown",(t,e)=>{Nv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rS(t,r,n,o)});function fe(){return F_(_M)}var SM=v("ZodNever",(t,e)=>{Dv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>eS(t,r,n,o)});function wM(t){return q_(SM,t)}var KS=v("ZodDate",(t,e)=>{Lv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>nS(t,n,o,s),t.min=(n,o)=>t.check(Ct(n,o)),t.max=(n,o)=>t.check(tr(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 bM=v("ZodArray",(t,e)=>{jv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cS(t,r,n,o),t.element=e.element,ps(t,"ZodArray",{min(r,n){return this.check(Wn(r,n))},nonempty(r){return this.check(Wn(1,r))},max(r,n){return this.check(ya(r,n))},length(r,n){return this.check(va(r,n))},unwrap(){return this.element}})});function C(t,e){return G_(bM,t,e)}var JS=v("ZodObject",(t,e)=>{qv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uS(t,r,n,o),F.defineLazy(t,"shape",()=>e.shape),ps(t,"ZodObject",{keyof(){return Ye(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:fe()})},loose(){return this.clone({...this._zod.def,catchall:fe()})},strict(){return this.clone({...this._zod.def,catchall:wM()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return F.extend(this,r)},safeExtend(r){return F.safeExtend(this,r)},merge(r){return F.merge(this,r)},pick(r){return F.pick(this,r)},omit(r){return F.omit(this,r)},partial(...r){return F.partial(QS,this,r[0])},required(...r){return F.required(ew,this,r[0])}})});function x(t,e){let r={type:"object",shape:t??{},...F.normalizeParams(e)};return new JS(r)}function Pe(t,e){return new JS({type:"object",shape:t,catchall:fe(),...F.normalizeParams(e)})}var YS=v("ZodUnion",(t,e)=>{$d.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dS(t,r,n,o),t.options=e.options});function ce(t,e){return new YS({type:"union",options:t,...F.normalizeParams(e)})}var RM=v("ZodDiscriminatedUnion",(t,e)=>{YS.init(t,e),Hv.init(t,e)});function sl(t,e,r){return new RM({type:"union",options:e,discriminator:t,...F.normalizeParams(r)})}var PM=v("ZodIntersection",(t,e)=>{Gv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o)});function Pa(t,e){return new PM({type:"intersection",left:t,right:e})}var US=v("ZodRecord",(t,e)=>{Zv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ie(t,e,r){return!e||!e._zod?new US({type:"record",keyType:g(),valueType:t,...F.normalizeParams(e)}):new US({type:"record",keyType:t,valueType:e,...F.normalizeParams(r)})}var rl=v("ZodEnum",(t,e)=>{Bv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(n,o,s)=>oS(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 rl({...e,checks:[],...F.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 rl({...e,checks:[],...F.normalizeParams(o),entries:s})}});function Ye(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new rl({type:"enum",entries:r,...F.normalizeParams(e)})}var CM=v("ZodLiteral",(t,e)=>{Vv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sS(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 CM({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var xM=v("ZodTransform",(t,e)=>{Wv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Fn(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(F.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(F.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 XS(t){return new xM({type:"transform",transform:t})}var QS=v("ZodOptional",(t,e)=>{Md.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function he(t){return new QS({type:"optional",innerType:t})}var kM=v("ZodExactOptional",(t,e)=>{Kv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Yd(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function EM(t){return new kM({type:"optional",innerType:t})}var TM=v("ZodNullable",(t,e)=>{Jv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function FS(t){return new TM({type:"nullable",innerType:t})}var AM=v("ZodDefault",(t,e)=>{Yv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function $M(t,e){return new AM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var MM=v("ZodPrefault",(t,e)=>{Xv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function IM(t,e){return new MM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var ew=v("ZodNonOptional",(t,e)=>{Qv.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function zM(t,e){return new ew({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var OM=v("ZodCatch",(t,e)=>{e_.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>yS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function NM(t,e){return new OM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var tw=v("ZodPipe",(t,e)=>{Id.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vS(t,r,n,o),t.in=e.in,t.out=e.out});function qS(t,e){return new tw({type:"pipe",in:t,out:e})}var DM=v("ZodPreprocess",(t,e)=>{tw.init(t,e),t_.init(t,e)}),LM=v("ZodReadonly",(t,e)=>{r_.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function jM(t){return new LM({type:"readonly",innerType:t})}var rw=v("ZodCustom",(t,e)=>{n_.init(t,e),re.init(t,e),t._zod.processJSONSchema=(r,n,o)=>iS(t,r,n,o)});function nw(t,e){return Z_(rw,t??(()=>!0),e)}function UM(t,e={}){return B_(rw,t,e)}function FM(t,e){return V_(t,e)}function il(t,e){return new DM({type:"pipe",in:XS(t),out:e})}var sw={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 ow;ow||(ow={});var Ca={};iu(Ca,{bigint:()=>ZM,boolean:()=>GM,date:()=>BM,number:()=>HM,string:()=>qM});function qM(t){return c_(nl,t)}function HM(t){return z_(Ra,t)}function GM(t){return D_(ol,t)}function ZM(t){return L_(BS,t)}function BM(t){return H_(KS,t)}Je(o_());var Yn="2025-11-25";var iw=[Yn,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cr="io.modelcontextprotocol/related-task",ka="2.0",Ce=nw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),aw=ce([g(),W().int()]),cw=g(),OB=Pe({ttl:W().optional(),pollInterval:W().optional()}),WM=x({ttl:W().optional()}),KM=x({taskId:g()}),cl=Pe({progressToken:aw.optional(),[Cr]:KM.optional()}),it=x({_meta:cl.optional()}),fs=it.extend({task:WM.optional()}),uw=t=>fs.safeParse(t).success,Ae=x({method:g(),params:it.loose().optional()}),ft=x({_meta:cl.optional()}),ht=x({method:g(),params:ft.loose().optional()}),xe=Pe({_meta:cl.optional()}),Ea=ce([g(),W().int()]),dw=x({jsonrpc:E(ka),id:Ea,...Ae.shape}).strict(),hs=t=>dw.safeParse(t).success,lw=x({jsonrpc:E(ka),...ht.shape}).strict(),pw=t=>lw.safeParse(t).success,ul=x({jsonrpc:E(ka),id:Ea,result:xe}).strict(),en=t=>ul.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 dl=x({jsonrpc:E(ka),id:Ea.optional(),error:x({code:W().int(),message:g(),data:fe().optional()})}).strict();var fw=t=>dl.safeParse(t).success;var xr=ce([dw,lw,ul,dl]),NB=ce([ul,dl]),tn=xe.strict(),JM=ft.extend({requestId:Ea.optional(),reason:g().optional()}),Ta=ht.extend({method:E("notifications/cancelled"),params:JM}),YM=x({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Ye(["light","dark"]).optional()}),ms=x({icons:C(YM).optional()}),Jn=x({name:g(),title:g().optional()}),hw=Jn.extend({...Jn.shape,...ms.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),XM=Pa(x({applyDefaults:ne().optional()}),ie(g(),fe())),QM=il(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Pa(x({form:XM.optional(),url:Ce.optional()}),ie(g(),fe()).optional())),eI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({sampling:Pe({createMessage:Ce.optional()}).optional(),elicitation:Pe({create:Ce.optional()}).optional()}).optional()}),tI=Pe({list:Ce.optional(),cancel:Ce.optional(),requests:Pe({tools:Pe({call:Ce.optional()}).optional()}).optional()}),rI=x({experimental:ie(g(),Ce).optional(),sampling:x({context:Ce.optional(),tools:Ce.optional()}).optional(),elicitation:QM.optional(),roots:x({listChanged:ne().optional()}).optional(),tasks:eI.optional(),extensions:ie(g(),Ce).optional()}),nI=it.extend({protocolVersion:g(),capabilities:rI,clientInfo:hw}),oI=Ae.extend({method:E("initialize"),params:nI});var sI=x({experimental:ie(g(),Ce).optional(),logging:Ce.optional(),completions:Ce.optional(),prompts:x({listChanged:ne().optional()}).optional(),resources:x({subscribe:ne().optional(),listChanged:ne().optional()}).optional(),tools:x({listChanged:ne().optional()}).optional(),tasks:tI.optional(),extensions:ie(g(),Ce).optional()}),ll=xe.extend({protocolVersion:g(),capabilities:sI,serverInfo:hw,instructions:g().optional()}),mw=ht.extend({method:E("notifications/initialized"),params:ft.optional()}),gw=t=>mw.safeParse(t).success,Aa=Ae.extend({method:E("ping"),params:it.optional()}),iI=x({progress:W(),total:he(W()),message:he(g())}),aI=x({...ft.shape,...iI.shape,progressToken:aw}),$a=ht.extend({method:E("notifications/progress"),params:aI}),cI=it.extend({cursor:cw.optional()}),gs=Ae.extend({params:cI.optional()}),ys=xe.extend({nextCursor:cw.optional()}),uI=Ye(["working","input_required","completed","failed","cancelled"]),vs=x({taskId:g(),status:uI,ttl:ce([W(),VS()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:he(W()),statusMessage:he(g())}),rn=xe.extend({task:vs}),dI=ft.merge(vs),_s=ht.extend({method:E("notifications/tasks/status"),params:dI}),Ma=Ae.extend({method:E("tasks/get"),params:it.extend({taskId:g()})}),Ia=xe.merge(vs),za=Ae.extend({method:E("tasks/result"),params:it.extend({taskId:g()})}),DB=xe.loose(),Oa=gs.extend({method:E("tasks/list")}),Na=ys.extend({tasks:C(vs)}),Da=Ae.extend({method:E("tasks/cancel"),params:it.extend({taskId:g()})}),yw=xe.merge(vs),vw=x({uri:g(),mimeType:he(g()),_meta:ie(g(),fe()).optional()}),_w=vw.extend({text:g()}),pl=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Sw=vw.extend({blob:pl}),Ss=Ye(["user","assistant"]),Xn=x({audience:C(Ss).optional(),priority:W().min(0).max(1).optional(),lastModified:ls.datetime({offset:!0}).optional()}),ww=x({...Jn.shape,...ms.shape,uri:g(),description:he(g()),mimeType:he(g()),size:he(W()),annotations:Xn.optional(),_meta:he(Pe({}))}),lI=x({...Jn.shape,...ms.shape,uriTemplate:g(),description:he(g()),mimeType:he(g()),annotations:Xn.optional(),_meta:he(Pe({}))}),pI=gs.extend({method:E("resources/list")}),fl=ys.extend({resources:C(ww)}),fI=gs.extend({method:E("resources/templates/list")}),hl=ys.extend({resourceTemplates:C(lI)}),ml=it.extend({uri:g()}),hI=ml,mI=Ae.extend({method:E("resources/read"),params:hI}),gl=xe.extend({contents:C(ce([_w,Sw]))}),yl=ht.extend({method:E("notifications/resources/list_changed"),params:ft.optional()}),gI=ml,yI=Ae.extend({method:E("resources/subscribe"),params:gI}),vI=ml,_I=Ae.extend({method:E("resources/unsubscribe"),params:vI}),SI=ft.extend({uri:g()}),wI=ht.extend({method:E("notifications/resources/updated"),params:SI}),bI=x({name:g(),description:he(g()),required:he(ne())}),RI=x({...Jn.shape,...ms.shape,description:he(g()),arguments:he(C(bI)),_meta:he(Pe({}))}),PI=gs.extend({method:E("prompts/list")}),vl=ys.extend({prompts:C(RI)}),CI=it.extend({name:g(),arguments:ie(g(),g()).optional()}),xI=Ae.extend({method:E("prompts/get"),params:CI}),_l=x({type:E("text"),text:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),Sl=x({type:E("image"),data:pl,mimeType:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),wl=x({type:E("audio"),data:pl,mimeType:g(),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),kI=x({type:E("tool_use"),name:g(),id:g(),input:ie(g(),fe()),_meta:ie(g(),fe()).optional()}),EI=x({type:E("resource"),resource:ce([_w,Sw]),annotations:Xn.optional(),_meta:ie(g(),fe()).optional()}),TI=ww.extend({type:E("resource_link")}),bl=ce([_l,Sl,wl,TI,EI]),AI=x({role:Ss,content:bl}),Rl=xe.extend({description:g().optional(),messages:C(AI)}),Pl=ht.extend({method:E("notifications/prompts/list_changed"),params:ft.optional()}),$I=x({title:g().optional(),readOnlyHint:ne().optional(),destructiveHint:ne().optional(),idempotentHint:ne().optional(),openWorldHint:ne().optional()}),MI=x({taskSupport:Ye(["required","optional","forbidden"]).optional()}),bw=x({...Jn.shape,...ms.shape,description:g().optional(),inputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()),outputSchema:x({type:E("object"),properties:ie(g(),Ce).optional(),required:C(g()).optional()}).catchall(fe()).optional(),annotations:$I.optional(),execution:MI.optional(),_meta:ie(g(),fe()).optional()}),II=gs.extend({method:E("tools/list")}),Cl=ys.extend({tools:C(bw)}),nn=xe.extend({content:C(bl).default([]),structuredContent:ie(g(),fe()).optional(),isError:ne().optional()}),LB=nn.or(xe.extend({toolResult:fe()})),zI=fs.extend({name:g(),arguments:ie(g(),fe()).optional()}),OI=Ae.extend({method:E("tools/call"),params:zI}),ws=ht.extend({method:E("notifications/tools/list_changed"),params:ft.optional()}),Rw=x({autoRefresh:ne().default(!0),debounceMs:W().int().nonnegative().default(300)}),Pw=Ye(["debug","info","notice","warning","error","critical","alert","emergency"]),NI=it.extend({level:Pw}),DI=Ae.extend({method:E("logging/setLevel"),params:NI}),LI=ft.extend({level:Pw,logger:g().optional(),data:fe()}),jI=ht.extend({method:E("notifications/message"),params:LI}),UI=x({name:g().optional()}),FI=x({hints:C(UI).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),qI=x({mode:Ye(["auto","required","none"]).optional()}),HI=x({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(bl).default([]),structuredContent:x({}).loose().optional(),isError:ne().optional(),_meta:ie(g(),fe()).optional()}),GI=sl("type",[_l,Sl,wl]),xa=sl("type",[_l,Sl,wl,kI,HI]),ZI=x({role:Ss,content:ce([xa,C(xa)]),_meta:ie(g(),fe()).optional()}),BI=fs.extend({messages:C(ZI),modelPreferences:FI.optional(),systemPrompt:g().optional(),includeContext:Ye(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:C(g()).optional(),metadata:Ce.optional(),tools:C(bw).optional(),toolChoice:qI.optional()}),xl=Ae.extend({method:E("sampling/createMessage"),params:BI}),kl=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens"]).or(g())),role:Ss,content:GI}),El=xe.extend({model:g(),stopReason:he(Ye(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Ss,content:ce([xa,C(xa)])}),VI=x({type:E("boolean"),title:g().optional(),description:g().optional(),default:ne().optional()}),WI=x({type:E("string"),title:g().optional(),description:g().optional(),minLength:W().optional(),maxLength:W().optional(),format:Ye(["email","uri","date","date-time"]).optional(),default:g().optional()}),KI=x({type:Ye(["number","integer"]),title:g().optional(),description:g().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),JI=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),YI=x({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(x({const:g(),title:g()})),default:g().optional()}),XI=x({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),QI=ce([JI,YI]),ez=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()}),tz=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()}),rz=ce([ez,tz]),nz=ce([XI,QI,rz]),oz=ce([nz,VI,WI,KI]),sz=fs.extend({mode:E("form").optional(),message:g(),requestedSchema:x({type:E("object"),properties:ie(g(),oz),required:C(g()).optional()})}),iz=fs.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),az=ce([sz,iz]),Tl=Ae.extend({method:E("elicitation/create"),params:az}),cz=ft.extend({elicitationId:g()}),uz=ht.extend({method:E("notifications/elicitation/complete"),params:cz}),Al=xe.extend({action:Ye(["accept","decline","cancel"]),content:il(t=>t===null?void 0:t,ie(g(),ce([g(),W(),ne(),C(g())])).optional())}),dz=x({type:E("ref/resource"),uri:g()});var lz=x({type:E("ref/prompt"),name:g()}),pz=it.extend({ref:ce([lz,dz]),argument:x({name:g(),value:g()}),context:x({arguments:ie(g(),g()).optional()}).optional()}),fz=Ae.extend({method:E("completion/complete"),params:pz});var $l=xe.extend({completion:Pe({values:C(g()).max(100),total:he(W().int()),hasMore:he(ne())})}),hz=x({uri:g().startsWith("file://"),name:g().optional(),_meta:ie(g(),fe()).optional()}),mz=Ae.extend({method:E("roots/list"),params:it.optional()}),gz=xe.extend({roots:C(hz)}),yz=ht.extend({method:E("notifications/roots/list_changed"),params:ft.optional()}),jB=ce([Aa,oI,fz,DI,xI,PI,pI,fI,mI,yI,_I,OI,II,Ma,za,Oa,Da]),UB=ce([Ta,$a,mw,yz,_s]),FB=ce([tn,kl,El,Al,gz,Ia,Na,rn]),qB=ce([Aa,xl,Tl,mz,Ma,za,Oa,Da]),HB=ce([Ta,$a,jI,wI,yl,ws,Pl,_s,uz]),GB=ce([tn,ll,$l,Rl,vl,fl,hl,gl,nn,Cl,Ia,Na,rn]),$=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===M.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new al(o.elicitations,r)}return new t(e,r,n)}},al=class extends ${constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(M.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function kr(t){return t==="completed"||t==="failed"||t==="cancelled"}var RV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ml(t){let r=Sa(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Il(t,e){let r=xt(t,e);if(!r.success)throw r.error;return r.data}var Rz=6e4,La=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Ta,r=>{this._oncancel(r)}),this.setNotificationHandler($a,r=>{this._onprogress(r)}),this.setRequestHandler(Aa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ma,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(za,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,p=new $(l.error.code,l.error.message,l.error.data);d(p)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!kr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(kr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Cr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Oa,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new $(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Da,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(kr(o.status))throw new $(M.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new $(M.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof $?o:new $(M.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),$.fromError(M.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),en(s)||fw(s)?this._onresponse(s):hs(s)?this._onrequest(s,i):pw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=$.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Cr]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:M.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId).catch(l=>this._onerror(new Error(`Failed to enqueue error response: ${l}`))):o?.send(d).catch(l=>this._onerror(new Error(`Failed to send an error response: ${l}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=uw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,p)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let h=f.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),en(e))n(e);else{let i=new $(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(en(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),en(e))o(e);else{let i=$.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}return}let s;try{let i=await this.request(e,rn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new $(M.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},kr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=w=>{d(w)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(w){l(w);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Cr]:c}});let h=w=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(w)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let b=w instanceof $?w:new $(M.RequestTimeout,String(w));d(b)};this._responseHandlers.set(p,w=>{if(!n?.signal?.aborted){if(w instanceof Error)return d(w);try{let b=xt(r,w.result);b.success?u(b.data):d(b.error)}catch(b){d(b)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??Rz,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(p,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let S=c?.taskId;if(S){let w=b=>{let k=this._responseHandlers.get(p);k?k(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,w),this._enqueueTaskMessage(S,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),d(b)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(w=>{this._cleanupTimeout(p),d(w)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ia,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Na,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},yw,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Cr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Cr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Cr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ml(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Il(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=Ml(e);this._notificationHandlers.set(n,o=>{let s=Il(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"&&hs(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),kr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new $(M.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(kr(a.status))throw new $(M.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=_s.parse({method:"notifications/tasks/status",params:c});await this.notification(u),kr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Cw(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function xw(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];Cw(i)&&Cw(s)?r[o]={...i,...s}:r[o]=s}return r}var gP=xi(Sf(),1),yP=xi(mP(),1);function E1(){let t=new gP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,yP.default)(t),t}var wc=class{constructor(e){this._ajv=e??E1()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var bc=class{constructor(e){this._client=e}async*callToolStream(e,r=nn,n){let o=this._client,s={...n,task:n?.task??(o.isToolTask(e.name)?{}:void 0)},i=o.requestStream({method:"tools/call",params:e},r,s),a=o.getToolOutputValidator(e.name);for await(let c of i){if(c.type==="result"&&a){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new $(M.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let d=a(u.structuredContent);if(!d.valid){yield{type:"error",error:new $(M.InvalidParams,`Structured content does not match the tool's output schema: ${d.errorMessage}`)};return}}catch(d){if(d instanceof $){yield{type:"error",error:d};return}yield{type:"error",error:new $(M.InvalidParams,`Failed to validate structured content: ${d instanceof Error?d.message:String(d)}`)};return}}yield c}}async getTask(e,r){return this._client.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._client.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._client.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._client.cancelTask({taskId:e},r)}requestStream(e,r,n){return this._client.requestStream(e,r,n)}};function vP(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 _P(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Rc(t,e){if(!(!t||e===null||typeof e!="object")){if(t.type==="object"&&t.properties&&typeof t.properties=="object"){let r=e,n=t.properties;for(let o of Object.keys(n)){let s=n[o];r[o]===void 0&&Object.prototype.hasOwnProperty.call(s,"default")&&(r[o]=s.default),r[o]!==void 0&&Rc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Rc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Rc(r,e)}}function T1(t){if(!t)return{supportsFormMode:!1,supportsUrlMode:!1};let e=t.form!==void 0,r=t.url!==void 0;return{supportsFormMode:e||!e&&!r,supportsUrlMode:r}}var Pc=class extends La{constructor(e,r){super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=r?.capabilities??{},this._jsonSchemaValidator=r?.jsonSchemaValidator??new wc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",ws,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Pl,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",yl,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=xw(this._capabilities,e)}setRequestHandler(e,r){let o=Sa(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=wa(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");let i=s;if(i==="elicitation/create"){let a=async(c,u)=>{let d=xt(Tl,c);if(!d.success){let w=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=T1(this._capabilities.elicitation);if(l.mode==="form"&&!p)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!f)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let w=xt(rn,h);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new $(M.InvalidParams,`Invalid task creation result: ${b}`)}return w.data}let m=xt(Al,h);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${w}`)}let y=m.data,S=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{Rc(S,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=xt(xl,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,p=await Promise.resolve(r(c,u));if(l.task){let y=xt(rn,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let h=l.tools||l.toolChoice?El:kl,m=xt(h,p);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Yn,capabilities:this._capabilities,clientInfo:this._clientInfo}},ll,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!iw.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){vP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&_P(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},tn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},$l,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},tn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Rl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},vl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},fl,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},hl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},gl,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},tn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},tn,r)}async callTool(e,r=nn,n){if(this.isToolTaskRequired(e.name))throw new $(M.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let o=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!o.structuredContent&&!o.isError)throw new $(M.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent)try{let i=s(o.structuredContent);if(!i.valid)throw new $(M.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof $?i:new $(M.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return o}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let r of e){if(r.outputSchema){let o=this._jsonSchemaValidator.getValidator(r.outputSchema);this._cachedToolOutputValidators.set(r.name,o)}let n=r.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(r.name),n==="required"&&this._cachedRequiredTaskTools.add(r.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},Cl,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Rw.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let p=l instanceof Error?l:new Error(String(l));c(p,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let p=setTimeout(u,a);this._listChangedDebounceTimers.set(e,p)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Xs=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}},SP=10,A1=13,gn=32;function Ef(t){}function Cc(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:e=Ef,onError:r=Ef,onRetry:n=Ef,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,p,f=!1;function h(_){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,_.charCodeAt(0)===239&&_.charCodeAt(1)===187&&_.charCodeAt(2)===191&&(_=_.slice(3))),i.length===0){let ge=y(_);ge!==""&&(i.push(ge),a=ge.length),m();return}if(_.indexOf(`
88
+ `)===-1&&_.indexOf("\r")===-1){i.push(_),a+=_.length,m();return}i.push(_);let P=i.join("");i.length=0,a=0;let z=y(P);z!==""&&(i.push(z),a=z.length),m()}function m(){s!==void 0&&(a+d.length<=s||(f=!0,i.length=0,a=0,u=void 0,d="",l=0,p=void 0,r(new Xs(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(_){let P=0;if(_.indexOf("\r")===-1){let z=_.indexOf(`
89
89
  `,P);for(;z!==-1;){if(P===z){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0,P=z+1,z=_.indexOf(`
90
- `,P);continue}let ge=_.charCodeAt(P);if(gP(_,P,ge)){let ye=_.charCodeAt(P+5)===mn?P+6:P+5,Ze=_.slice(ye,z);if(l===0&&_.charCodeAt(z+1)===mP){e({id:u,event:p,data:Ze}),u=void 0,d="",p=void 0,P=z+2,z=_.indexOf(`
90
+ `,P);continue}let ge=_.charCodeAt(P);if(wP(_,P,ge)){let ye=_.charCodeAt(P+5)===gn?P+6:P+5,Ze=_.slice(ye,z);if(l===0&&_.charCodeAt(z+1)===SP){e({id:u,event:p,data:Ze}),u=void 0,d="",p=void 0,P=z+2,z=_.indexOf(`
91
91
  `,P);continue}d=l===0?Ze:`${d}
92
- ${Ze}`,l++}else yP(_,P,ge)?p=_.slice(_.charCodeAt(P+6)===mn?P+7:P+6,z)||void 0:S(_,P,z);P=z+1,z=_.indexOf(`
92
+ ${Ze}`,l++}else bP(_,P,ge)?p=_.slice(_.charCodeAt(P+6)===gn?P+7:P+6,z)||void 0:S(_,P,z);P=z+1,z=_.indexOf(`
93
93
  `,P)}return _.slice(P)}for(;P<_.length;){let z=_.indexOf("\r",P),ge=_.indexOf(`
94
- `,P),ye=-1;if(z!==-1&&ge!==-1?ye=z<ge?z:ge:z!==-1?z===_.length-1?ye=-1:ye=z:ge!==-1&&(ye=ge),ye===-1)break;S(_,P,ye),P=ye+1,_.charCodeAt(P-1)===R1&&_.charCodeAt(P)===mP&&P++}return _.slice(P)}function S(_,P,z){if(P===z){b();return}let ge=_.charCodeAt(P);if(gP(_,P,ge)){let dr=_.charCodeAt(P+5)===mn?P+6:P+5,jh=_.slice(dr,z);d=l===0?jh:`${d}
95
- ${jh}`,l++;return}if(yP(_,P,ge)){p=_.slice(_.charCodeAt(P+6)===mn?P+7:P+6,z)||void 0;return}if(ge===105&&_.charCodeAt(P+1)===100&&_.charCodeAt(P+2)===58){let dr=_.slice(_.charCodeAt(P+3)===mn?P+4:P+3,z);u=dr.includes("\0")?void 0:dr;return}if(ge===58){if(o){let dr=_.slice(P,z);o(dr.slice(_.charCodeAt(P+1)===mn?2:1))}return}let ye=_.slice(P,z),Ze=ye.indexOf(":");if(Ze===-1){w(ye,"",ye);return}let To=ye.slice(0,Ze),Ri=ye.charCodeAt(Ze+1)===mn?2:1,Pi=ye.slice(Ze+Ri);w(To,Pi,ye)}function w(_,P,z){switch(_){case"event":p=P||void 0;break;case"data":d=l===0?P:`${d}
96
- ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new Ys(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:z}));break;default:r(new Ys(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:P,line:z}));break}}function b(){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0}function k(_={}){if(_.consume&&i.length>0){let P=i.join("");S(P,0,P.length)}c=!0,u=void 0,d="",l=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:k}}function gP(t,e,r){return r===100&&t.charCodeAt(e+1)===97&&t.charCodeAt(e+2)===116&&t.charCodeAt(e+3)===97&&t.charCodeAt(e+4)===58}function yP(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 xc=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 P1(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Ef(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Ef).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Ef(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 SP=t=>{throw TypeError(t)},Nf=(t,e,r)=>e.has(t)||SP("Cannot "+r),U=(t,e,r)=>(Nf(t,e,"read from private field"),r?r.call(t):e.get(t)),ke=(t,e,r)=>e.has(t)?SP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),me=(t,e,r,n)=>(Nf(t,e,"write to private field"),e.set(t,r),r),ar=(t,e,r)=>(Nf(t,e,"access private method"),r),rt,gn,go,Cc,kc,ei,_o,ti,Or,yo,So,vo,Xs,Mt,Tf,Af,$f,_P,Mf,If,Qs,zf,Of,yn=class extends EventTarget{constructor(e,r){var n,o;super(),ke(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ke(this,rt),ke(this,gn),ke(this,go),ke(this,Cc),ke(this,kc),ke(this,ei),ke(this,_o),ke(this,ti,null),ke(this,Or),ke(this,yo),ke(this,So,null),ke(this,vo,null),ke(this,Xs,null),ke(this,Af,async s=>{var i;U(this,yo).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){ar(this,Mt,Qs).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?me(this,go,new URL(s.url)):me(this,go,void 0),u!==200){ar(this,Mt,Qs).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ar(this,Mt,Qs).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(U(this,rt)===this.CLOSED)return;me(this,rt,this.OPEN);let l=new Event("open");if((i=U(this,Xs))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){ar(this,Mt,Qs).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,f=a.getReader(),h=!0;do{let{done:m,value:y}=await f.read();y&&U(this,yo).feed(p.decode(y,{stream:!m})),m&&(h=!1,U(this,yo).reset(),ar(this,Mt,zf).call(this))}while(h)}),ke(this,$f,s=>{me(this,Or,void 0),!(s.name==="AbortError"||s.type==="aborted")&&ar(this,Mt,zf).call(this,Ef(s))}),ke(this,Mf,s=>{typeof s.id=="string"&&me(this,ti,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:U(this,go)?U(this,go).origin:U(this,gn).origin,lastEventId:s.id||""});U(this,vo)&&(!s.event||s.event==="message")&&U(this,vo).call(this,i),this.dispatchEvent(i)}),ke(this,If,s=>{me(this,ei,s)}),ke(this,Of,()=>{me(this,_o,void 0),U(this,rt)===this.CONNECTING&&ar(this,Mt,Tf).call(this)});try{if(e instanceof URL)me(this,gn,e);else if(typeof e=="string")me(this,gn,new URL(e,C1()));else throw new Error("Invalid URL")}catch{throw P1("An invalid or illegal string was specified")}me(this,yo,Pc({onEvent:U(this,Mf),onRetry:U(this,If)})),me(this,rt,this.CONNECTING),me(this,ei,3e3),me(this,kc,(n=r?.fetch)!=null?n:globalThis.fetch),me(this,Cc,(o=r?.withCredentials)!=null?o:!1),ar(this,Mt,Tf).call(this)}get readyState(){return U(this,rt)}get url(){return U(this,gn).href}get withCredentials(){return U(this,Cc)}get onerror(){return U(this,So)}set onerror(e){me(this,So,e)}get onmessage(){return U(this,vo)}set onmessage(e){me(this,vo,e)}get onopen(){return U(this,Xs)}set onopen(e){me(this,Xs,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(){U(this,_o)&&clearTimeout(U(this,_o)),U(this,rt)!==this.CLOSED&&(U(this,Or)&&U(this,Or).abort(),me(this,rt,this.CLOSED),me(this,Or,void 0))}};rt=new WeakMap,gn=new WeakMap,go=new WeakMap,Cc=new WeakMap,kc=new WeakMap,ei=new WeakMap,_o=new WeakMap,ti=new WeakMap,Or=new WeakMap,yo=new WeakMap,So=new WeakMap,vo=new WeakMap,Xs=new WeakMap,Mt=new WeakSet,Tf=function(){me(this,rt,this.CONNECTING),me(this,Or,new AbortController),U(this,kc)(U(this,gn),ar(this,Mt,_P).call(this)).then(U(this,Af)).catch(U(this,$f))},Af=new WeakMap,$f=new WeakMap,_P=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...U(this,ti)?{"Last-Event-ID":U(this,ti)}:void 0},cache:"no-store",signal:(t=U(this,Or))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Mf=new WeakMap,If=new WeakMap,Qs=function(t,e){var r;U(this,rt)!==this.CLOSED&&me(this,rt,this.CLOSED);let n=new xc("error",{code:e,message:t});(r=U(this,So))==null||r.call(this,n),this.dispatchEvent(n)},zf=function(t,e){var r;if(U(this,rt)===this.CLOSED)return;me(this,rt,this.CONNECTING);let n=new xc("error",{code:e,message:t});(r=U(this,So))==null||r.call(this,n),this.dispatchEvent(n),me(this,_o,setTimeout(U(this,Of),U(this,ei)))},Of=new WeakMap,yn.CONNECTING=0,yn.OPEN=1,yn.CLOSED=2;function C1(){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 wo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Ec(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...wo(e.headers),...wo(n.headers)}:e.headers};return t(r,o)}:t}var Df;Df=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function x1(t){return(await Df).getRandomValues(new Uint8Array(t))}async function k1(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await x1(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function E1(t){return await k1(t)}async function T1(t){let e=await(await Df).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Lf(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await E1(t),r=await T1(e);return{code_verifier:e,code_challenge:r}}var ze=US().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:ew.custom,message:"URL must be parseable",fatal:!0}),ud}).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"}),bP=Pe({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:ne().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:ne().optional()}),jf=Pe({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:ne().optional()}),A1=Pe({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:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:ne().optional()}),RP=x({...A1.shape,...jf.pick({code_challenge_methods_supported:!0}).shape}),PP=x({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:Pa.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),CP=x({error:g(),error_description:g().optional(),error_uri:g().optional()}),wP=ze.optional().or(E("").transform(()=>{})),$1=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:wP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:wP,policy_uri:g().optional(),jwks_uri:ze.optional(),jwks:HS().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),M1=x({client_id:g(),client_secret:g().optional(),client_id_issued_at:W().optional(),client_secret_expires_at:W().optional()}).strip(),xP=$1.merge(M1),HJ=x({error:g(),error_description:g().optional()}).strip(),GJ=x({token:g(),token_type_hint:g().optional()}).strip();function kP(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function EP({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}},ri=class extends Se{};ri.errorCode="invalid_request";var vn=class extends Se{};vn.errorCode="invalid_client";var _n=class extends Se{};_n.errorCode="invalid_grant";var Sn=class extends Se{};Sn.errorCode="unauthorized_client";var ni=class extends Se{};ni.errorCode="unsupported_grant_type";var oi=class extends Se{};oi.errorCode="invalid_scope";var si=class extends Se{};si.errorCode="access_denied";var cr=class extends Se{};cr.errorCode="server_error";var ii=class extends Se{};ii.errorCode="temporarily_unavailable";var ai=class extends Se{};ai.errorCode="unsupported_response_type";var ci=class extends Se{};ci.errorCode="unsupported_token_type";var ui=class extends Se{};ui.errorCode="invalid_token";var di=class extends Se{};di.errorCode="method_not_allowed";var li=class extends Se{};li.errorCode="too_many_requests";var wn=class extends Se{};wn.errorCode="invalid_client_metadata";var pi=class extends Se{};pi.errorCode="insufficient_scope";var fi=class extends Se{};fi.errorCode="invalid_target";var TP={[ri.errorCode]:ri,[vn.errorCode]:vn,[_n.errorCode]:_n,[Sn.errorCode]:Sn,[ni.errorCode]:ni,[oi.errorCode]:oi,[si.errorCode]:si,[cr.errorCode]:cr,[ii.errorCode]:ii,[ai.errorCode]:ai,[ci.errorCode]:ci,[ui.errorCode]:ui,[di.errorCode]:di,[li.errorCode]:li,[wn.errorCode]:wn,[pi.errorCode]:pi,[fi.errorCode]:fi};var qe=class extends Error{constructor(e){super(e??"Unauthorized")}};function I1(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Uf="code",Ff="S256";function z1(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&I1(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 O1(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":N1(o,s,r);return;case"client_secret_post":D1(o,s,n);return;case"none":L1(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function N1(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 D1(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function L1(t,e){e.set("client_id",t)}async function $P(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=CP.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=TP[o]||cr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new cr(o)}}async function ur(t,e){try{return await qf(t,e)}catch(r){if(r instanceof vn||r instanceof Sn)return await t.invalidateCredentials?.("all"),await qf(t,e);if(r instanceof _n)return await t.invalidateCredentials?.("tokens"),await qf(t,e);throw r}}async function qf(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 IP(c,{fetchFn:s}),!a)try{a=await MP(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await Z1(e,{resourceMetadataUrl:d,fetchFn:s});c=b.authorizationServerUrl,u=b.authorizationServerMetadata,a=b.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await U1(e,t,a),p=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=u?.client_id_metadata_document_supported===!0,k=t.clientMetadataUrl;if(k&&!j1(k))throw new wn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(b&&k)f={client_id:k},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await J1(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:s});await t.saveClientInformation(P),f=P}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await K1(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let b=await W1(c,{metadata:u,clientInformation:f,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Se)||b instanceof cr))throw b}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:w}=await V1(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:p,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(S),"REDIRECT"}function j1(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function U1(t,e,r){let n=kP(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!EP({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 bo(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Hf(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Hf(t,"scope")||void 0,a=Hf(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Hf(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 MP(t,e,r=fetch){let n=await H1(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 bP.parse(await n.json())}async function Gf(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Gf(t,void 0,r):void 0;throw n}}function F1(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function AP(t,e,r=fetch){return await Gf(t,{"MCP-Protocol-Version":e},r)}function q1(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function H1(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??Jn,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=F1(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await AP(i,s,r);if(!n?.metadataUrl&&q1(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await AP(c,s,r)}return a}function G1(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 IP(t,{fetchFn:e=fetch,protocolVersion:r=Jn}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=G1(t);for(let{url:s,type:i}of o){let a=await Gf(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"?jf.parse(await a.json()):RP.parse(await a.json())}}}async function Z1(t,e){let r,n;try{r=await MP(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 IP(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function V1(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(Uf))throw new Error(`Incompatible auth server: does not support response type ${Uf}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(Ff))throw new Error(`Incompatible auth server: does not support code challenge method ${Ff}`)}else a=new URL("/authorize",t);let c=await Lf(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Uf),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",Ff),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 B1(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function zP(t,{metadata:e,tokenRequestParams:r,clientInformation:n,addClientAuthentication:o,resource:s,fetchFn:i}){let a=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),o)await o(c,r,a,e);else if(n){let d=e?.token_endpoint_auth_methods_supported??[],l=z1(n,d);O1(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await $P(u);return PP.parse(await u.json())}async function W1(t,{metadata:e,clientInformation:r,refreshToken:n,resource:o,addClientAuthentication:s,fetchFn:i}){let a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n}),c=await zP(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function K1(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=B1(o,u,t.redirectUrl)}let c=await t.clientInformation();return zP(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function J1(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 $P(i);return xP.parse(await i.json())}var hi=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Tc=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ec(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=wo(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 yn(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}=bo(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 hi(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=Cr.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await ur(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=bo(o);if(this._resourceMetadataUrl=i,this._scope=a,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var PC=Ci(bC(),1);import eh from"node:process";import{PassThrough as CU}from"node:stream";var RU=10*1024*1024,$c=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??RU}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 Cr.parse(JSON.parse(t))}function RC(t){return JSON.stringify(t)+`
98
- `}var xU=eh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Ic(){let t={};for(let e of xU){let r=eh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Mc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new $c({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new CU)}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,PC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Ic(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:eh.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=RC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var TC=Ci(EC(),1);function AC(t){if(t)try{return TC.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=Pc({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 OU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},It=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Oc=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Ec(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??OU}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=wo(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new It(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new zc({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await d.read();if(h)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let m=Cr.parse(JSON.parse(f.data));Qr(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await ur(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:fs(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=bo(a);if(this._resourceMetadataUrl=h,this._scope=m,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=bo(a);if(y==="insufficient_scope"){let S=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new It(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=S??void 0,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qe;return this.send(e)}}throw new It(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),lw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,l=a.headers.get("content-type"),p=AC(l);if(d)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(m=>Cr.parse(m)):[Cr.parse(f)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new It(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new It(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};function $C(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 DU={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 MC(t){return{...Ic(),...DU,...t??{}}}function IC(){return Ic()}var rh=class t extends Mc{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
94
+ `,P),ye=-1;if(z!==-1&&ge!==-1?ye=z<ge?z:ge:z!==-1?z===_.length-1?ye=-1:ye=z:ge!==-1&&(ye=ge),ye===-1)break;S(_,P,ye),P=ye+1,_.charCodeAt(P-1)===A1&&_.charCodeAt(P)===SP&&P++}return _.slice(P)}function S(_,P,z){if(P===z){b();return}let ge=_.charCodeAt(P);if(wP(_,P,ge)){let dr=_.charCodeAt(P+5)===gn?P+6:P+5,Uh=_.slice(dr,z);d=l===0?Uh:`${d}
95
+ ${Uh}`,l++;return}if(bP(_,P,ge)){p=_.slice(_.charCodeAt(P+6)===gn?P+7:P+6,z)||void 0;return}if(ge===105&&_.charCodeAt(P+1)===100&&_.charCodeAt(P+2)===58){let dr=_.slice(_.charCodeAt(P+3)===gn?P+4:P+3,z);u=dr.includes("\0")?void 0:dr;return}if(ge===58){if(o){let dr=_.slice(P,z);o(dr.slice(_.charCodeAt(P+1)===gn?2:1))}return}let ye=_.slice(P,z),Ze=ye.indexOf(":");if(Ze===-1){w(ye,"",ye);return}let Ao=ye.slice(0,Ze),Pi=ye.charCodeAt(Ze+1)===gn?2:1,Ci=ye.slice(Ze+Pi);w(Ao,Ci,ye)}function w(_,P,z){switch(_){case"event":p=P||void 0;break;case"data":d=l===0?P:`${d}
96
+ ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new Xs(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:z}));break;default:r(new Xs(`Unknown field "${_.length>20?`${_.slice(0,20)}\u2026`:_}"`,{type:"unknown-field",field:_,value:P,line:z}));break}}function b(){l>0&&e({id:u,event:p,data:d}),u=void 0,d="",l=0,p=void 0}function k(_={}){if(_.consume&&i.length>0){let P=i.join("");S(P,0,P.length)}c=!0,u=void 0,d="",l=0,p=void 0,i.length=0,a=0,f=!1}return{feed:h,reset:k}}function 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 kc=class extends Event{constructor(e,r){var n,o;super(e),this.code=(n=r?.code)!=null?n:void 0,this.message=(o=r?.message)!=null?o:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,r,n){return n(RP(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(RP(this),r)}};function $1(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Tf(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Tf).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Tf(t.cause)}`:t.message:`${t}`}function RP(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var CP=t=>{throw TypeError(t)},Df=(t,e,r)=>e.has(t)||CP("Cannot "+r),U=(t,e,r)=>(Df(t,e,"read from private field"),r?r.call(t):e.get(t)),ke=(t,e,r)=>e.has(t)?CP("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),me=(t,e,r,n)=>(Df(t,e,"write to private field"),e.set(t,r),r),ar=(t,e,r)=>(Df(t,e,"access private method"),r),rt,yn,yo,xc,Ec,ti,So,ri,Nr,vo,wo,_o,Qs,Mt,Af,$f,Mf,PP,If,zf,ei,Of,Nf,vn=class extends EventTarget{constructor(e,r){var n,o;super(),ke(this,Mt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ke(this,rt),ke(this,yn),ke(this,yo),ke(this,xc),ke(this,Ec),ke(this,ti),ke(this,So),ke(this,ri,null),ke(this,Nr),ke(this,vo),ke(this,wo,null),ke(this,_o,null),ke(this,Qs,null),ke(this,$f,async s=>{var i;U(this,vo).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){ar(this,Mt,ei).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?me(this,yo,new URL(s.url)):me(this,yo,void 0),u!==200){ar(this,Mt,ei).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ar(this,Mt,ei).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(U(this,rt)===this.CLOSED)return;me(this,rt,this.OPEN);let l=new Event("open");if((i=U(this,Qs))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){ar(this,Mt,ei).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let p=new TextDecoder,f=a.getReader(),h=!0;do{let{done:m,value:y}=await f.read();y&&U(this,vo).feed(p.decode(y,{stream:!m})),m&&(h=!1,U(this,vo).reset(),ar(this,Mt,Of).call(this))}while(h)}),ke(this,Mf,s=>{me(this,Nr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&ar(this,Mt,Of).call(this,Tf(s))}),ke(this,If,s=>{typeof s.id=="string"&&me(this,ri,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:U(this,yo)?U(this,yo).origin:U(this,yn).origin,lastEventId:s.id||""});U(this,_o)&&(!s.event||s.event==="message")&&U(this,_o).call(this,i),this.dispatchEvent(i)}),ke(this,zf,s=>{me(this,ti,s)}),ke(this,Nf,()=>{me(this,So,void 0),U(this,rt)===this.CONNECTING&&ar(this,Mt,Af).call(this)});try{if(e instanceof URL)me(this,yn,e);else if(typeof e=="string")me(this,yn,new URL(e,M1()));else throw new Error("Invalid URL")}catch{throw $1("An invalid or illegal string was specified")}me(this,vo,Cc({onEvent:U(this,If),onRetry:U(this,zf)})),me(this,rt,this.CONNECTING),me(this,ti,3e3),me(this,Ec,(n=r?.fetch)!=null?n:globalThis.fetch),me(this,xc,(o=r?.withCredentials)!=null?o:!1),ar(this,Mt,Af).call(this)}get readyState(){return U(this,rt)}get url(){return U(this,yn).href}get withCredentials(){return U(this,xc)}get onerror(){return U(this,wo)}set onerror(e){me(this,wo,e)}get onmessage(){return U(this,_o)}set onmessage(e){me(this,_o,e)}get onopen(){return U(this,Qs)}set onopen(e){me(this,Qs,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(){U(this,So)&&clearTimeout(U(this,So)),U(this,rt)!==this.CLOSED&&(U(this,Nr)&&U(this,Nr).abort(),me(this,rt,this.CLOSED),me(this,Nr,void 0))}};rt=new WeakMap,yn=new WeakMap,yo=new WeakMap,xc=new WeakMap,Ec=new WeakMap,ti=new WeakMap,So=new WeakMap,ri=new WeakMap,Nr=new WeakMap,vo=new WeakMap,wo=new WeakMap,_o=new WeakMap,Qs=new WeakMap,Mt=new WeakSet,Af=function(){me(this,rt,this.CONNECTING),me(this,Nr,new AbortController),U(this,Ec)(U(this,yn),ar(this,Mt,PP).call(this)).then(U(this,$f)).catch(U(this,Mf))},$f=new WeakMap,Mf=new WeakMap,PP=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...U(this,ri)?{"Last-Event-ID":U(this,ri)}:void 0},cache:"no-store",signal:(t=U(this,Nr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},If=new WeakMap,zf=new WeakMap,ei=function(t,e){var r;U(this,rt)!==this.CLOSED&&me(this,rt,this.CLOSED);let n=new kc("error",{code:e,message:t});(r=U(this,wo))==null||r.call(this,n),this.dispatchEvent(n)},Of=function(t,e){var r;if(U(this,rt)===this.CLOSED)return;me(this,rt,this.CONNECTING);let n=new kc("error",{code:e,message:t});(r=U(this,wo))==null||r.call(this,n),this.dispatchEvent(n),me(this,So,setTimeout(U(this,Nf),U(this,ti)))},Nf=new WeakMap,vn.CONNECTING=0,vn.OPEN=1,vn.CLOSED=2;function M1(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function bo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Tc(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...bo(e.headers),...bo(n.headers)}:e.headers};return t(r,o)}:t}var Lf;Lf=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function I1(t){return(await Lf).getRandomValues(new Uint8Array(t))}async function z1(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await I1(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function O1(t){return await z1(t)}async function N1(t){let e=await(await Lf).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function jf(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await O1(t),r=await N1(e);return{code_verifier:e,code_challenge:r}}var ze=ZS().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:sw.custom,message:"URL must be parseable",fatal:!0}),dd}).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"}),kP=Pe({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:ne().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:ne().optional()}),Uf=Pe({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:ne().optional()}),D1=Pe({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:ne().optional(),request_parameter_supported:ne().optional(),request_uri_parameter_supported:ne().optional(),require_request_uri_registration:ne().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:ne().optional()}),EP=x({...D1.shape,...Uf.pick({code_challenge_methods_supported:!0}).shape}),TP=x({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:Ca.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),AP=x({error:g(),error_description:g().optional(),error_uri:g().optional()}),xP=ze.optional().or(E("").transform(()=>{})),L1=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:xP,scope:g().optional(),contacts:C(g()).optional(),tos_uri:xP,policy_uri:g().optional(),jwks_uri:ze.optional(),jwks:WS().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),j1=x({client_id:g(),client_secret:g().optional(),client_id_issued_at:W().optional(),client_secret_expires_at:W().optional()}).strip(),$P=L1.merge(j1),QJ=x({error:g(),error_description:g().optional()}).strip(),e5=x({token:g(),token_type_hint:g().optional()}).strip();function MP(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function IP({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}},ni=class extends Se{};ni.errorCode="invalid_request";var _n=class extends Se{};_n.errorCode="invalid_client";var Sn=class extends Se{};Sn.errorCode="invalid_grant";var wn=class extends Se{};wn.errorCode="unauthorized_client";var oi=class extends Se{};oi.errorCode="unsupported_grant_type";var si=class extends Se{};si.errorCode="invalid_scope";var ii=class extends Se{};ii.errorCode="access_denied";var cr=class extends Se{};cr.errorCode="server_error";var ai=class extends Se{};ai.errorCode="temporarily_unavailable";var ci=class extends Se{};ci.errorCode="unsupported_response_type";var ui=class extends Se{};ui.errorCode="unsupported_token_type";var di=class extends Se{};di.errorCode="invalid_token";var li=class extends Se{};li.errorCode="method_not_allowed";var pi=class extends Se{};pi.errorCode="too_many_requests";var bn=class extends Se{};bn.errorCode="invalid_client_metadata";var fi=class extends Se{};fi.errorCode="insufficient_scope";var hi=class extends Se{};hi.errorCode="invalid_target";var zP={[ni.errorCode]:ni,[_n.errorCode]:_n,[Sn.errorCode]:Sn,[wn.errorCode]:wn,[oi.errorCode]:oi,[si.errorCode]:si,[ii.errorCode]:ii,[cr.errorCode]:cr,[ai.errorCode]:ai,[ci.errorCode]:ci,[ui.errorCode]:ui,[di.errorCode]:di,[li.errorCode]:li,[pi.errorCode]:pi,[bn.errorCode]:bn,[fi.errorCode]:fi,[hi.errorCode]:hi};var qe=class extends Error{constructor(e){super(e??"Unauthorized")}};function U1(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var Ff="code",qf="S256";function F1(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&U1(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 q1(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":H1(o,s,r);return;case"client_secret_post":G1(o,s,n);return;case"none":Z1(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function H1(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 G1(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Z1(t,e){e.set("client_id",t)}async function NP(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=AP.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=zP[o]||cr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new cr(o)}}async function ur(t,e){try{return await Hf(t,e)}catch(r){if(r instanceof _n||r instanceof wn)return await t.invalidateCredentials?.("all"),await Hf(t,e);if(r instanceof Sn)return await t.invalidateCredentials?.("tokens"),await Hf(t,e);throw r}}async function Hf(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 LP(c,{fetchFn:s}),!a)try{a=await DP(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let b=await X1(e,{resourceMetadataUrl:d,fetchFn:s});c=b.authorizationServerUrl,u=b.authorizationServerMetadata,a=b.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await V1(e,t,a),p=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let b=u?.client_id_metadata_document_supported===!0,k=t.clientMetadataUrl;if(k&&!B1(k))throw new bn(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${k}`);if(b&&k)f={client_id:k},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await nU(c,{metadata:u,clientMetadata:t.clientMetadata,scope:p,fetchFn:s});await t.saveClientInformation(P),f=P}}let h=!t.redirectUrl;if(r!==void 0||h){let b=await rU(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let b=await tU(c,{metadata:u,clientInformation:f,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Se)||b instanceof cr))throw b}let y=t.state?await t.state():void 0,{authorizationUrl:S,codeVerifier:w}=await Q1(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:p,resource:l});return await t.saveCodeVerifier(w),await t.redirectToAuthorization(S),"REDIRECT"}function B1(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function V1(t,e,r){let n=MP(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!IP({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}function Ro(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=Gf(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=Gf(t,"scope")||void 0,a=Gf(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function Gf(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 DP(t,e,r=fetch){let n=await J1(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 kP.parse(await n.json())}async function Zf(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?Zf(t,void 0,r):void 0;throw n}}function W1(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function OP(t,e,r=fetch){return await Zf(t,{"MCP-Protocol-Version":e},r)}function K1(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function J1(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??Yn,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=W1(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await OP(i,s,r);if(!n?.metadataUrl&&K1(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await OP(c,s,r)}return a}function Y1(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 LP(t,{fetchFn:e=fetch,protocolVersion:r=Yn}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Y1(t);for(let{url:s,type:i}of o){let a=await Zf(s,n,e);if(a){if(!a.ok){if(await a.body?.cancel(),a.status>=400&&a.status<500)continue;throw new Error(`HTTP ${a.status} trying to load ${i==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return i==="oauth"?Uf.parse(await a.json()):EP.parse(await a.json())}}}async function X1(t,e){let r,n;try{r=await DP(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 LP(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Q1(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(Ff))throw new Error(`Incompatible auth server: does not support response type ${Ff}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(qf))throw new Error(`Incompatible auth server: does not support code challenge method ${qf}`)}else a=new URL("/authorize",t);let c=await jf(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",Ff),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",qf),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 eU(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function jP(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=F1(n,d);q1(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await NP(u);return TP.parse(await u.json())}async function tU(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 jP(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function rU(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=eU(o,u,t.redirectUrl)}let c=await t.clientInformation();return jP(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function nU(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 NP(i);return $P.parse(await i.json())}var mi=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Ac=class{constructor(e,r){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=r?.eventSourceInit,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Tc(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=bo(this._requestInit?.headers);return new Headers({...e,...r})}_startOrAuth(){let e=this?._eventSourceInit?.fetch??this._fetch??fetch;return new Promise((r,n)=>{this._eventSource=new vn(this._url.href,{...this._eventSourceInit,fetch:async(o,s)=>{let i=await this._commonHeaders();i.set("Accept","text/event-stream");let a=await e(o,{...s,headers:i});if(a.status===401&&a.headers.has("www-authenticate")){let{resourceMetadataUrl:c,scope:u}=Ro(a);this._resourceMetadataUrl=c,this._scope=u}return a}}),this._abortController=new AbortController,this._eventSource.onerror=o=>{if(o.code===401&&this._authProvider){this._authThenStart().then(r,n);return}let s=new mi(o.code,o.message,o);n(s),this.onerror?.(s)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",o=>{let s=o;try{if(this._endpoint=new URL(s.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){n(i),this.onerror?.(i),this.close();return}r()}),this._eventSource.onmessage=o=>{let s=o,i;try{i=xr.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await ur(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=Ro(o);if(this._resourceMetadataUrl=i,this._scope=a,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var TC=xi(kC(),1);import th from"node:process";import{PassThrough as MU}from"node:stream";var AU=10*1024*1024,Mc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??AU}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),$U(r)}clear(){this._buffer=void 0}};function $U(t){return xr.parse(JSON.parse(t))}function EC(t){return JSON.stringify(t)+`
98
+ `}var IU=th.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function zc(){let t={};for(let e of IU){let r=th.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ic=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Mc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new MU)}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,TC.default)(this._serverParams.command,this._serverParams.args??[],{env:{...zc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:th.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=EC(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var zC=xi(IC(),1);function OC(t){if(t)try{return zC.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Oc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Cc({onEvent:a=>{i.enqueue(a)},onError(a){typeof e=="function"&&e(a),(e==="terminate"||a.type==="max-buffer-size-exceeded")&&i.error(a)},onRetry:r,onComment:n,maxBufferSize:o})},transform(i){s.feed(i)}})}};var qU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},It=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Nc=class{constructor(e,r){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=r?.requestInit,this._authProvider=r?.authProvider,this._fetch=r?.fetch,this._fetchWithInit=Tc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??qU}async _authThenStart(){if(!this._authProvider)throw new qe("No auth provider");let e;try{e=await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new qe;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=bo(this._requestInit?.headers);return new Headers({...e,...r})}async _startOrAuthSse(e){let{resumptionToken:r}=e;try{let n=await this._commonHeaders();n.set("Accept","text/event-stream"),r&&n.set("last-event-id",r);let o=await(this._fetch??fetch)(this._url,{method:"GET",headers:n,signal:this._abortController?.signal});if(!o.ok){if(await o.body?.cancel(),o.status===401&&this._authProvider)return await this._authThenStart();if(o.status===405)return;throw new It(o.status,`Failed to open SSE stream: ${o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(n){throw this.onerror?.(n),n}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let r=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,o=this._reconnectionOptions.maxReconnectionDelay;return Math.min(r*Math.pow(n,e),o)}_scheduleReconnection(e,r=0){let n=this._reconnectionOptions.maxRetries;if(r>=n){this.onerror?.(new Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let o=this._getNextReconnectionDelay(r);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(s=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(e,r+1)})},o)}_handleSseStream(e,r,n){if(!e)return;let{onresumptiontoken:o,replayMessageId:s}=r,i,a=!1,c=!1;(async()=>{try{let d=e.pipeThrough(new TextDecoderStream).pipeThrough(new Oc({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:h}=await d.read();if(h)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let m=xr.parse(JSON.parse(f.data));en(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new qe("No auth provider");if(await ur(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:hs(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new It(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=Ro(a);if(this._resourceMetadataUrl=h,this._scope=m,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qe;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=Ro(a);if(y==="insufficient_scope"){let S=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===S)throw new It(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=S??void 0,await ur(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qe;return this.send(e)}}throw new It(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),gw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let d=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,l=a.headers.get("content-type"),p=OC(l);if(d)if(p==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(p==="application/json"){let f=await a.json(),h=Array.isArray(f)?f.map(m=>xr.parse(m)):[xr.parse(f)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new It(-1,`Unexpected content type: ${l}`);else await a.body?.cancel()}catch(n){throw this.onerror?.(n),n}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),r={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,r);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new It(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};function NC(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 GU={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 DC(t){return{...zc(),...GU,...t??{}}}function LC(){return zc()}var nh=class t extends Ic{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
99
99
  `);this._lineBuffer=r.at(-1)??"",this._lineBuffer.length>t.MAX_LINE_BUFFER_CHARS&&(this._lineBuffer=this._lineBuffer.slice(-t.MAX_LINE_BUFFER_CHARS));for(let n of r.slice(0,-1))this.pushCapturedLine(`${n}
100
- `)}pushCapturedLine(e){this._captured.push(e),this._captured.length>t.MAX_CAPTURED_LINES&&this._captured.shift(),this._logHistory.push(e),this._logHistory.length>t.MAX_LOG_HISTORY&&this._logHistory.shift()}consumeStderr(){this._lineBuffer.length>0&&(this.pushCapturedLine(this._lineBuffer),this._lineBuffer="");let e=this._captured.join("");return this._captured=[],e}getLogHistory(){return[...this._logHistory]}};function zC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new rh(e)}var bn=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}},nh=new NU;function oh(t,e){return nh.run(t,e)}function LU(t){nh.getStore()?.onFailure?.(t)}function OC({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=nh.getStore(),c=new bn({status:i.status,transport:e,operation:a?.operation??"transport"});throw LU(c),c}}function NC(t,e){let r=OC({getHeaders:e.getHeaders,transport:"http"});return new Oc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function DC(t,e){let r=OC({getHeaders:e.getHeaders,transport:"sse"});return new Tc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function LC(){return new Rc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var jC=Ss,UC=xe;function _t(t){return t instanceof bn&&t.status===401||(t instanceof It||t instanceof hi)&&t.code===401}function FC(t){return t instanceof $&&t.code===M.MethodNotFound}function sh(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var jU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function qC(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return jU.some(r=>e.includes(r))}function HC(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function ih(t){return t instanceof bn&&t.transport==="http"&&t.status===404||t instanceof It&&t.code===404}var X=UU.child({prefix:"pi-mcp"});function FU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function qU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&FU(r,o)})}var HU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),GU=/^Node\.js v\d/,ZU=/^[\w$.]*error[\w$]*:/i,GC=400,VU=63e3,ZC=3,BU=/[\\/]lib[\\/]cli\.js/,WU="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.",JC=Symbol("mcpReinitReported");function KU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,JC,{value:!0,enumerable:!1,configurable:!0})}function JU(t){return typeof t=="object"&&t!==null&&t[JC]===!0}function YU(t){let e=t.filter(a=>!GU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>BU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return WU;let o=r.findIndex(a=>ZU.test(a)),i=(o===-1?r.slice(-ZC):r.slice(o,o+ZC)).join(" / ");return i.length>GC?`${i.slice(0,GC)}\u2026`:i}function XU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(HU,"").split(`
101
- `).map(s=>s.trim()).filter(s=>s.length>0),o=YU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var QU=6e5,eF=18e5,VC=2147483647,tF=3e4,BC=1e4,YC=[250,1e3,2e3],Rn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},mi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},rF=250,WC=3,nF=[200,500];function oF(t){for(let e of Object.values(t))if(ra(e))return!0;return!1}function XC(t){let e=new Set;for(let r of t.matchAll(Yo))e.add(na(r[0]));return[...e].sort()}function uh(t){return[...new Set(t)].sort()}function sF({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return uh([...e&&t?cd(t):[],...n&&r?XC(r):[]])}var Nc="${augmentToken}";function iF(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 aF(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var QC="(unknown uri)",dh="unknown",KC=/=+$/,cF=/\s+/g,uF=/[-_]/g,dF=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Pn(t,e){return typeof t=="string"?t:e}function ex(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function lF(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function pF(t){let e=t.replace(cF,"").replace(uF,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(KC,"");if(r.toString("base64").replace(KC,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function tx(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function fF(t){let e=tx(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Pn(e.uri,QC),n=Pn(e.mimeType,dh);if(typeof e.blob=="string"&&lF(n)){let s=pF(e.blob);if(s!==void 0)return s}let o=ex(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function hF(t){let e=Pn(t.type,"unknown");if(e==="resource")return fF(t);if(e==="audio"){let r=Pn(t.mimeType,dh),n=ex(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Pn(t.uri,QC),n=Pn(t.name,""),o=Pn(t.mimeType,dh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function mF(t){if(t.type!=="resource")return;let e=tx(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&dF.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function gF(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=mF(t);return e||{type:"text",text:hF(t)}}function yF(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(gF(n))}return e}function vF(t){return Tg(t,VU)}function _F(t,e){let r=yF(t);if(r.length===0){let o=vF(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 rx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),SF=new Set([502,503,504]),gi=YC.length+1,wF=2;function bF(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 RF(t){if(_t(t)||ih(t)||t instanceof Pt)return;let e=t?.cause?.code;if(typeof e=="string")return rx.has(e)?{totalAttempts:gi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:wF}:SF.has(r)?{totalAttempts:gi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:gi}:void 0}var PF=80,CF=10,xF=/[^a-zA-Z0-9_.()-]/g,kF=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Dc(t){return t.replace(xF,"_").slice(0,PF)||"unknown"}function EF(t){let e=bF(t);if(e!==void 0&&(/^\d{3}$/.test(e)||rx.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=kF.has(e)?e:"Error",n=EF(t);return n===void 0?r:`${r}(${n})`}function ah(t,e,r){return t instanceof Pt?new Pt(Dc(t.serverName),t.missingKeys.slice(0,CF).map(Dc)).message:t instanceof bn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function ch(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Dc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Lc=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=>id(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=ah(r,"connect",this._config.type),o=this._config.type==="stdio"&&!_t(r)?id(XU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=gi,r={available:!0};for(let n=1;n<=gi;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=RF(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=(YC[r-1]??0)+Math.floor(Math.random()*(rF+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Vr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return _t(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!se().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 Rn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=LC();this._client=s;let i;try{if(await oh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(jC,()=>{X.debug(`MCP server "${this.name}" sent tools/list_changed; refreshing tools`),this._refreshTools()});let a=await this._listToolsWithAuthRetry(e);if(this._disposed)return await this._closeFailedInitialization(s,n),o;this._tools=a.tools??[],this._status="success",this._lastError=void 0,this._emitState("connected"),this._wireLivenessHandlers(),this._startHeartbeat();let c=se();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&ot(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=ah(e,r,this._config.type)){if(e instanceof mi||e instanceof Rn)this._status="failed";else if(_t(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(_t(e)){this._status="auth_required";let o=se(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=ah(e,r,this._config.type);ad(ch(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=$C(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=MC(this._resolvedEnv??e.env);return zC({command:r.command,args:r.args,env:n,cwd:e.cwd})}case"http":return this._createHttpTransport(e.url,this._resolvedHeaders??e.headers??{});case"sse":return DC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=NC(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?oF(r):!1,o=e.type==="stdio"&&ra(e.command);if(!(n||o))return;let s=se();if(!Dg(s)){let a=sF({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new Pt(this.name,a)}let i=Ng(s);n&&r&&await this._resolveMapSecretRefs(r,i,e.type==="stdio"),o&&e.type==="stdio"&&await this._resolveCommandSecretRefs(e.command,i)}async _resolveMapSecretRefs(e,r,n){let o;try{o=await jg({configEnv:e,localEnv:n?IC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new Pt(this.name,cd(e),i)}let s=uh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new Pt(this.name,s);n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Ug(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new Pt(this.name,XC(e),s)}let o=uh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new Pt(this.name,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(Nc)))return;let o;if(iF(e.url)){let i=se().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Nc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Nc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${aF(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(Nc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=se();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=se(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Ve(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=se().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&$u(o)&&se().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Ho(o)&&se().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=se(),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:fr(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||!Ve(this._config,s.config)))try{if(a===e.token){i.commit(this.name,r),jr({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;jr({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 V?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof V)&&Iu(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&xi(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),xi(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await zu(e.token);if(!this._ownsRefresh(e))return{kind:"transient_failure"};this._refreshPersisting=!0;let s=await e.tokenStore.persistRefresh(this.name,o,r,n);if(!this._ownsRefresh(e))return await this._restoreAfterSupersededRefresh(e,o,r,s),{kind:"transient_failure"};e.tokenStore.commit(this.name,o),jr({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:ih(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),KU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Rn}async _withAuthRetry(e,r,n){let o=this._config,s=se(),i=fr(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),oh({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||!_t(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new mi;if(this._hostedCredentialProvenance!==void 0)throw new Rn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw _t(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=se();xi(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new Lc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Lc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},tF),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=se(),r=fr(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=WC&&n.outcome==="transient";i++)await Vr(nF[i-2]??0),n=await this._runProbe();let o=fr(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 ${WC} 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:BC})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":FC(e)||sh(e)?"alive":_t(e)?"authFailure":qC(e)?"transient":"inconclusive"}async _sendHeartbeat(){if(this._inFlightCalls.size===0||this._reinitializingPromise)return;let e=this._client;if(!(!e||this._disposed))try{await e.ping({timeout:BC})}catch(r){if(this._reinitializingPromise||this._disposed||sh(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 _t(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&&!_t(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=!qU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>VC)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${VC}.`);let s={timeout:this._config.timeoutMs??QU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??eF,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??{}},UC,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=_F(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 Rn||e instanceof mi)throw e;if(_t(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Dc(r),s=He(e),i=HC(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)||ad(ch(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),ch(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 nx=AF.child({prefix:"pi-mcp"}),$F=3,MF=6e4;function IF(t,e){let r=Date.now(),n=r-MF,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=$F?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function ox(t){Zr(t),ji(t)}async function zF(t,e,r){if(!IF(e,t)){nx.warn(`MCP server "${t}" automatic restart rate-limited`);return}nx.warn(`MCP server "${t}" wedged; recycling transport`),await Nr(t,e,r)}function Uc(t,e,r){if(OF(e)){ox(t);return}wu(t,r),Mn(e)&&ox(t)}function OF(t){return No()||t.toolSearchLatched}function Bt(t,e,r){return Zh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function lh(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 NF(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name);return o!==void 0&&s!==void 0&&i!==void 0&&i.revision===o.revision&&i.domain===o.domain&&e.oauthCredentialDomains.get(r.name)===o.domain&&ut(o.domain)===We(r.id)?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function ph(t){let{state:e,config:r,generation:n}=t;return new jc(r,NF({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function fh(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 hh(t,e,r){return t.configDesiredRevisions.get(e)===r}function sx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function mh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Bt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(TF,c)},t.onWedged=()=>{if(!Bt(t,e,r))return;let i=r.currentLoad?.latestPi??n;zF(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(!Bt(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(!Bt(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=()=>{Bt(t,e,r)&&t.status==="success"&&Uc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;bu(i,t,e),i!==n&&bu(n,t,e)}}async function ix(t,e,r,n){let o=setTimeout(()=>{Bt(t,e,r)&&J(n(),r)},ki);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Bt(t,e,r)&&J(n(),r)}}async function ax(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function Fc(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 DF(t){let{state:e,config:r,displaced:n,retirement:o}=t;fh(e,n.config),Io(e,r.name),n.beginDisposal?.();try{let s=Ve(n.config,r)?Promise.resolve():ct(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function LF(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=wt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function jF(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Bt(r,o,e)?a?.(n)===!1?(await LF({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Uc(c(),e,r),J(c(),e),r.status==="failed"?{status:"unavailable",config:n,error:new Error(r.lastError??`MCP server "${n.name}" failed`)}:{status:"installed",config:n,leaseRevision:i}):{status:"superseded",config:n}}function UF(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(!hh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=lh(e,r.name),l=ph({state:e,config:r,generation:d});return mh(l,d,e,o),Ai({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:jF({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function FF(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!hh(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=kn(a,s),p=Mo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>UF({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await DF({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await cu(p.retirement),h());return p.retirement?m():h()}async function St(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await FF({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)},ki);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function qF({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!sx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);fh(e,s),Io(e,t);let a=wt({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||!sx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=lh(e,t),u=ph({state:e,config:s,generation:c});if(mh(u,c,e,r),!Ai({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await ix(u,c,e,d),Bt(u,c,e)&&u.status==="success"&&Uc(d(),e,u),!0}function Nr(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 qF({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 HF(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;fh(e,n.config),Io(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Ve(n.config,o)?Promise.resolve():ct(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function cx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=An(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=Mo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await HF({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await cu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!hh(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=lh(e,t),h=ph({state:e,config:a,generation:f});mh(h,f,e,r),Ai({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await ix(h,f,e,s),Bt(h,f,e)&&h.status==="success"&&Uc(s(),e,h))}async function yi(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Nr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as GF}from"@hermes/logger";var gh=GF.child({prefix:"pi-mcp"}),ZF=1e6,VF=1e3,BF=/^\d+$/;function ux(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function Cn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(!(typeof e!="string"||!BF.test(e)||typeof r!="string"||r.length===0))return{revision:e.replace(/^0+(?=\d)/,""),domain:ux(r)}}function WF(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function KF(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 gh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";if(i?.kind==="blocked"||i?.kind==="domain"&&ut(r.domain)!==i.domain)return"reject";let a=n?.acceptedDomains?.get(t);if(a!==void 0&&ux(a)!==r.domain)return"reject";let c=WF(n?.acceptedRevisions,r.domain,s);if(c===void 0)return"apply";let u=mr(r.revision,c);return u>0||u===0&&a===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":u===0?"equal":"reject"}function JF(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 YF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function XF(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*VF+Math.floor(t.access_token_expires_at.nanos/ZF):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret}}}function qc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!YF(s)){gh.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=Cn(s),a=KF(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=XF(s);if(JF(t,o,c,i)){gh.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 eq=QF.child({prefix:"pi-mcp"});function tq(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 rq(t,e){let r=Object.values(t).filter(n=>{let o=Cn(n);return o!==void 0&&ut(o.domain)===`user:${e}`});return r.length===1?r[0]:void 0}async function dx(t){let{pi:e,state:r,update:n}=t,o=tq(r,n.configId),s=rq(n.credentials,n.configId);if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=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 p=Cn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Nr,l=t.report??J;await d(o.name,r,u).catch(p=>{eq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),Oe(r)}import{logger as pq}from"@hermes/logger";import{execFile as nq}from"node:child_process";import{logger as oq}from"@hermes/logger";var sq=5e3;function iq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function lx(t,e=sq){let r=oq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=iq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=nq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as aq}from"node:http";function Hc(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function px(t){let e=Hc(t.title),r=Hc(t.heading),n=Hc(t.message),o=t.details?Hc(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 jC(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new nh(e)}var Rn=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},oh=new HU;function sh(t,e){return oh.run(t,e)}function ZU(t){oh.getStore()?.onFailure?.(t)}function UC({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=oh.getStore(),c=new Rn({status:i.status,transport:e,operation:a?.operation??"transport"});throw ZU(c),c}}function FC(t,e){let r=UC({getHeaders:e.getHeaders,transport:"http"});return new Nc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function qC(t,e){let r=UC({getHeaders:e.getHeaders,transport:"sse"});return new Ac(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function HC(){return new Pc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var GC=ws,ZC=xe;function _t(t){return t instanceof Rn&&t.status===401||(t instanceof It||t instanceof mi)&&t.code===401}function BC(t){return t instanceof $&&t.code===M.MethodNotFound}function ih(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var BU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function VC(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return BU.some(r=>e.includes(r))}function WC(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function ah(t){return t instanceof Rn&&t.transport==="http"&&t.status===404||t instanceof It&&t.code===404}var X=VU.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 KU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&WU(r,o)})}var JU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),YU=/^Node\.js v\d/,XU=/^[\w$.]*error[\w$]*:/i,KC=400,QU=63e3,JC=3,eF=/[\\/]lib[\\/]cli\.js/,tF="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.",tx=Symbol("mcpReinitReported");function rF(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,tx,{value:!0,enumerable:!1,configurable:!0})}function nF(t){return typeof t=="object"&&t!==null&&t[tx]===!0}function oF(t){let e=t.filter(a=>!YU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>eF.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return tF;let o=r.findIndex(a=>XU.test(a)),i=(o===-1?r.slice(-JC):r.slice(o,o+JC)).join(" / ");return i.length>KC?`${i.slice(0,KC)}\u2026`:i}function sF(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(JU,"").split(`
101
+ `).map(s=>s.trim()).filter(s=>s.length>0),o=oF(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var iF=6e5,aF=18e5,YC=2147483647,cF=3e4,XC=1e4,rx=[250,1e3,2e3],Pn=class extends Error{constructor(){super("MCP OAuth refresh is temporarily unavailable"),this.name="RefreshUnavailableError"}},gi=class extends Error{retryable=!0;constructor(){super("MCP authentication refresh is pending in the backend; retry shortly"),this.name="BackendRefreshPendingError"}},uF=250,QC=3,dF=[200,500];function lF(t){for(let e of Object.values(t))if(na(e))return!0;return!1}function nx(t){let e=new Set;for(let r of t.matchAll(Xo))e.add(oa(r[0]));return[...e].sort()}function dh(t){return[...new Set(t)].sort()}function pF({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return dh([...e&&t?ud(t):[],...n&&r?nx(r):[]])}var Dc="${augmentToken}";function fF(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 hF(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var ox="(unknown uri)",lh="unknown",ex=/=+$/,mF=/\s+/g,gF=/[-_]/g,yF=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Cn(t,e){return typeof t=="string"?t:e}function sx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function vF(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function _F(t){let e=t.replace(mF,"").replace(gF,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(ex,"");if(r.toString("base64").replace(ex,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function ix(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function SF(t){let e=ix(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Cn(e.uri,ox),n=Cn(e.mimeType,lh);if(typeof e.blob=="string"&&vF(n)){let s=_F(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 wF(t){let e=Cn(t.type,"unknown");if(e==="resource")return SF(t);if(e==="audio"){let r=Cn(t.mimeType,lh),n=sx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Cn(t.uri,ox),n=Cn(t.name,""),o=Cn(t.mimeType,lh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function bF(t){if(t.type!=="resource")return;let e=ix(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&yF.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function RF(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=bF(t);return e||{type:"text",text:wF(t)}}function PF(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(RF(n))}return e}function CF(t){return zg(t,QU)}function xF(t,e){let r=PF(t);if(r.length===0){let o=CF(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 ax=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),kF=new Set([502,503,504]),yi=rx.length+1,EF=2;function TF(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 AF(t){if(_t(t)||ah(t)||t instanceof Pt)return;let e=t?.cause?.code;if(typeof e=="string")return ax.has(e)?{totalAttempts:yi}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:EF}:kF.has(r)?{totalAttempts:yi}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:yi}:void 0}var $F=80,MF=10,IF=/[^a-zA-Z0-9_.()-]/g,zF=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Lc(t){return t.replace(IF,"_").slice(0,$F)||"unknown"}function OF(t){let e=TF(t);if(e!==void 0&&(/^\d{3}$/.test(e)||ax.has(e)))return e}function He(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=zF.has(e)?e:"Error",n=OF(t);return n===void 0?r:`${r}(${n})`}function ch(t,e,r){return t instanceof Pt?new Pt(Lc(t.serverName),t.missingKeys.slice(0,MF).map(Lc)).message:t instanceof Rn?t.message:`MCP ${r} ${e} failed (${He(t)})`}function uh(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Lc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var jc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Uc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>ad(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${He(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=ch(r,"connect",this._config.type),o=this._config.type==="stdio"&&!_t(r)?ad(sF(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",He(r))}}async _connectWithRetries(){let e=yi,r={available:!0};for(let n=1;n<=yi;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=AF(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=(rx[r-1]??0)+Math.floor(Math.random()*(uF+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${He(e)}; retrying in ${s}ms`),await Vr(s)}async _attemptConnect(e){let r=this._config;(r.type==="http"||r.type==="sse")&&await this._maybeProactiveRefresh(),this._expandAugmentToken(),await this._resolveSecretRefs();let n=!1;for(;;)try{return await this._initializeFreshClient(e)}catch(o){if(this._disposed)return;if(!n&&e.available&&this._canRecoverInitialization(o)){if(n=!0,await this._recoverStartupAuthentication(o,e)==="disposed")return;continue}throw o}}_canRecoverInitialization(e){let r=this._config;return _t(e)&&(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&!!se().tokens.get(this.name)?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new Pn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=HC();this._client=s;let i;try{if(await sh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(GC,()=>{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=se();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&ot(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${He(n)})`)}}}_recordConnectFailure(e,r,n=ch(e,r,this._config.type)){if(e instanceof gi||e instanceof Pn)this._status="failed";else if(_t(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(_t(e)){this._status="auth_required";let o=se(),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);cd(uh(o,He(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=NC(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=DC(this._resolvedEnv??e.env);return jC({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 qC(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=FC(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?lF(r):!1,o=e.type==="stdio"&&na(e.command);if(!(n||o))return;let s=se();if(!qg(s)){let a=pF({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new Pt(this.name,a)}let i=Fg(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 Gg({configEnv:e,localEnv:n?LC():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${He(i)})`),new Pt(this.name,ud(e),i)}let s=dh([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new Pt(this.name,s);n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Zg(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${He(s)})`),new Pt(this.name,nx(e),s)}let o=dh([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new Pt(this.name,o);this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Dc)))return;let o;if(fF(e.url)){let i=se().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Dc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Dc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${hF(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Dc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=se();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=se(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!Be(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?{Authorization:`Bearer ${e.accessToken}`}:{}}async _maybeProactiveRefresh(){let e=se().tokens,{config:r}=this;(r.type==="http"||r.type==="sse")&&r.auth==="oauth"&&await e.ensureLoaded?.(this.name,hr(r));let o=this._usableToken();o&&Mu(o)&&se().shouldProactivelyRefreshTokens&&(o.refreshToken?await this._refreshTokenDeduped():Go(o)&&se().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=se(),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:fr(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),Ur({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;Ur({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)&&zu(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&ki(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${He(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),ki(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=hr(this._config),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await Ou(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),Ur({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:ah(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${He(s)})`),rF(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new Pn}async _withAuthRetry(e,r,n){let o=this._config,s=se(),i=fr(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),sh({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||!_t(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new gi;if(this._hostedCredentialProvenance!==void 0)throw new Pn;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let p=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let f=await this._refreshTokenDeduped();if(this._disposed)throw d;if(f.kind==="transient_failure"&&this._throwRefreshUnavailable(d,p,n?.preserveAuthErrorOnRefreshUnavailable===!0),f.kind==="terminal_failure")throw this._status="auth_required",d}try{let f=await c();return this._clearHostedAuthFailure(),f}catch(f){let h=a?.failure??f;throw _t(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=se();ki(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",He(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new jc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new jc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},cF),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=se(),r=fr(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=QC&&n.outcome==="transient";i++)await Vr(dF[i-2]??0),n=await this._runProbe();let o=fr(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 ${QC} 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:XC})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${He(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":BC(e)||ih(e)?"alive":_t(e)?"authFailure":VC(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:XC})}catch(r){if(this._reinitializingPromise||this._disposed||ih(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 _t(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&&!_t(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=!KU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${He(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${He(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>YC)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${YC}.`);let s={timeout:this._config.timeoutMs??iF,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??aF,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??{}},ZC,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=xF(d.content,d.structuredContent);return{isError:d.isError===!0,content:l.content,rawItemCount:l.rawItemCount}}catch(d){if(n?.aborted||d instanceof Error&&d.name==="AbortError")throw d;return this._reportAndThrowToolError(d,e)}finally{i&&!this._wedgeRecoveryOwners.has(i)&&(i.failure=void 0,this._inFlightCalls.delete(i))}}_reportAndThrowToolError(e,r){if(e instanceof Pn||e instanceof gi)throw e;if(_t(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Lc(r),s=He(e),i=WC(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 nF(e)||cd(uh(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),uh(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 cx=DF.child({prefix:"pi-mcp"}),LF=3,jF=6e4;function UF(t,e){let r=Date.now(),n=r-jF,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=LF?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function ux(t){Br(t),Ui(t)}async function FF(t,e,r){if(!UF(e,t)){cx.warn(`MCP server "${t}" automatic restart rate-limited`);return}cx.warn(`MCP server "${t}" wedged; recycling transport`),await Dr(t,e,r)}function Fc(t,e,r){if(qF(e)){ux(t);return}bu(t,r),In(e)&&ux(t)}function qF(t){return Do()||t.toolSearchLatched}function Vt(t,e,r){return Bh(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function ph(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 HF(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name);return o!==void 0&&s!==void 0&&i!==void 0&&i.revision===o.revision&&i.domain===o.domain&&e.oauthCredentialDomains.get(r.name)===o.domain&&ut(o.domain)===We(r.id)?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function fh(t){let{state:e,config:r,generation:n}=t;return new Uc(r,HF({state:e,config:r,hostGeneration:n}))}function Ge(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function hh(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 dx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function gh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Vt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(NF,c)},t.onWedged=()=>{if(!Vt(t,e,r))return;let i=r.currentLoad?.latestPi??n;FF(t.name,r,i)};let o=t.hostedCredentialProvenance,s=o?.kind==="accepted"&&o.hostedAccessTokenOnly===!0?{serverGeneration:o.hostGeneration,mcpConfigId:o.configId,credentialRevision:o.credentialRevision,credentialRevisionDomain:o.credentialRevisionDomain}:void 0;t.onAuthRefreshNeeded=()=>{if(!Vt(t,e,r)||!s)return;let i=JSON.stringify(s);r.statusFailureCategories.set(t.name,{category:"auth_refresh_needed",...s}),r.authRefreshNeededReportKeys.get(t.name)!==i&&(r.authRefreshNeededReportKeys.set(t.name,i),J(r.currentLoad?.latestPi??n,r))},t.onAuthRefreshCleared=()=>{if(!Vt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&ot(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Vt(t,e,r)&&t.status==="success"&&Fc(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Ru(i,t,e),i!==n&&Ru(n,t,e)}}async function lx(t,e,r,n){let o=setTimeout(()=>{Vt(t,e,r)&&J(n(),r)},Ei);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Vt(t,e,r)&&J(n(),r)}}async function px(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function qc(t,e){if(e.status!=="installed")return!1;let r=Z(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function GF(t){let{state:e,config:r,displaced:n,retirement:o}=t;hh(e,n.config),zo(e,r.name),n.beginDisposal?.();try{let s=Be(n.config,r)?Promise.resolve():ct(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function ZF(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=wt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),be({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function BF(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Vt(r,o,e)?a?.(n)===!1?(await ZF({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&Fc(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 VF(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 be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=ph(e,r.name),l=fh({state:e,config:r,generation:d});return gh(l,d,e,o),$i({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:BF({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(be({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function WF(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=En(a,s),p=Io({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return{status:"collision",config:a};let f=p.lease.revision,h=()=>VF({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:f,sourceOwnership:o,activePi:i}),m=async()=>(p.displacedHost&&p.retirement?await GF({state:r,config:a,displaced:p.displacedHost,retirement:p.retirement}):await uu(p.retirement),h());return p.retirement?m():h()}async function St(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ge(e,d.name)})).map(async d=>{try{let l=await WF({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Ei);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function KF({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!dx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);hh(e,s),zo(e,t);let a=wt({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||!dx(e,t,n))return be({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=ph(e,t),u=fh({state:e,config:s,generation:c});if(gh(u,c,e,r),!$i({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await lx(u,c,e,d),Vt(u,c,e)&&u.status==="success"&&Fc(d(),e,u),!0}function Dr(t,e,r){e.reconnects??=new Map,e.configRevisions??=new Map,e.reconnectDesiredGenerations??=new Map,e.statusFailureCategories??=new Map;let n=(e.reconnectDesiredGenerations.get(t)??0)+1;e.reconnectDesiredGenerations.set(t,n);let o=e.reconnects.get(t);if(o)return o;let s=(async()=>{let i=0,a=e.configRevisions.get(t)??0;do{let c=e.reconnectDesiredGenerations.get(t)??0;if((e.configRevisions.get(t)??0)!==a||!await KF({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 JF(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;hh(e,n.config),zo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Be(n.config,o)?Promise.resolve():ct(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function fx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=$n(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ge(e,t),u=e.servers.get(t),d=u?Q(e,t,u):Z(e,t),l={kind:"local",identity:a?.id??t},p=Io({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!p)return;if(u&&await JF({state:e,name:t,existing:u,config:a,retirement:p.retirement}),p.retirement&&await uu(p.retirement),Z(e,t)?.revision!==p.lease.revision||!mh(e,t,c)){be({state:e,name:t,owner:l,revision:p.lease.revision});return}if(e.configRevisions.set(t,c),!a){be({state:e,name:t,owner:l,revision:p.lease.revision}),J(s(),e);return}let f=ph(e,t),h=fh({state:e,config:a,generation:f});gh(h,f,e,r),$i({state:e,name:t,owner:l,revision:p.lease.revision,host:h})&&(await lx(h,f,e,s),Vt(h,f,e)&&h.status==="success"&&Fc(s(),e,h))}async function vi(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Dr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as YF}from"@hermes/logger";var yh=YF.child({prefix:"pi-mcp"}),XF=1e6,QF=1e3,eq=/^\d+$/;function hx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function xn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(!(typeof e!="string"||!eq.test(e)||typeof r!="string"||r.length===0))return{revision:e.replace(/^0+(?=\d)/,""),domain:hx(r)}}function tq(t,e,r){let n=t?.get(e),o=typeof r=="string"?t?.get(r):void 0;return n===void 0?o:o===void 0?n:mr(o,n)>0?o:n}function rq(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 yh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";if(i?.kind==="blocked"||i?.kind==="domain"&&ut(r.domain)!==i.domain)return"reject";let a=n?.acceptedDomains?.get(t);if(a!==void 0&&hx(a)!==r.domain)return"reject";let c=tq(n?.acceptedRevisions,r.domain,s);if(c===void 0)return"apply";let u=mr(r.revision,c);return u>0||u===0&&a===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":u===0?"equal":"reject"}function nq(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 oq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function sq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*QF+Math.floor(t.access_token_expires_at.nanos/XF):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret}}}function Hc(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!oq(s)){yh.warn(`Skipping MCP OAuth credentials for "${o}": entry is not an object with a non-empty access_token`),n.rejected.push(o);continue}let i=xn(s),a=rq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=sq(s);if(nq(t,o,c,i)){yh.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 aq=iq.child({prefix:"pi-mcp"});function cq(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 uq(t,e){let r=Object.values(t).filter(n=>{let o=xn(n);return o!==void 0&&ut(o.domain)===`user:${e}`});return r.length===1?r[0]:void 0}async function mx(t){let{pi:e,state:r,update:n}=t,o=cq(r,n.configId),s=uq(n.credentials,n.configId);if(!o||!s)return;let i=Z(r,o.name);if(i?.owner.identity!==`user:${n.configId}`||o.server.config.type==="stdio"||o.server.config.auth!=="oauth")return;r.shouldProactivelyRefreshTokens=!1;let a=o.server.getRefreshInFlight?.();if(a&&await Promise.resolve(a).catch(()=>{}),r.servers.get(o.name)!==o.server||Z(r,o.name)!==i)return;let c=Hc(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let p=xn(s);p&&(r.credentialRevisions.set(o.name,p),r.hostedCredentialOwnership.set(o.name,{...p,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Dr,l=t.report??J;await d(o.name,r,u).catch(p=>{aq.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${p instanceof Error?p.name:"non-Error"}`)}),l(u,r),Oe(r)}import{logger as _q}from"@hermes/logger";import{execFile as dq}from"node:child_process";import{logger as lq}from"@hermes/logger";var pq=5e3;function fq(t){switch(process.platform){case"darwin":return{file:"open",args:[t]};case"win32":return{file:"cmd",args:["/c","start","",t]};default:return{file:"xdg-open",args:[t]}}}function gx(t,e=pq){let r=lq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{o=new URL(t).protocol}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}if(o!=="http:"&&o!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}let{file:s,args:i}=fq(t),a=!1,c=null,u=setTimeout(()=>{if(!a){a=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{c?.kill()}catch(d){r.debug("Failed to kill browser-open child process",{error:d})}n(!1)}},e);c=dq(s,i,d=>{a||(a=!0,clearTimeout(u),d?(r.warn("Failed to open browser",{error:d}),n(!1)):n(!0))})})}import{createServer as hq}from"node:http";function Gc(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function yx(t){let e=Gc(t.title),r=Gc(t.heading),n=Gc(t.message),o=t.details?Gc(t.details):void 0,s=t.autoClose?"<script>setTimeout(() => window.close(), 2000);</script>":"";return`<!doctype html>
102
102
  <html lang="en">
103
103
  <head>
104
104
  <meta charset="utf-8" />
@@ -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 fx(t){return px({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Gc(t,e){return px({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var cq="127.0.0.1",gx="/callback",hx=3e3,mx=3010,uq="Authentication successful. You can close this window.",Zc={"Content-Type":"text/html; charset=utf-8"};function yx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function vx(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n,o;try{let s=new URL(r);n=s.searchParams.get("code")??void 0,o=s.searchParams.get("state")??void 0}catch{if(r.includes("code=")){let s=new URLSearchParams(r);n=s.get("code")??void 0,o=s.get("state")??void 0}else n=r}if(!n)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{code:n,state:o??e}}function dq(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==gx){e.writeHead(404,Zc),e.end(Gc("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){e.writeHead(400,Zc),e.end(Gc("Authentication did not complete.",`Error: ${i}`));let a=n.searchParams.get("error_description");r.onError(new Error(`Authentication did not complete: ${i}${a?`: ${a}`:""}`));return}if(!o||!s){e.writeHead(400,Zc),e.end(Gc("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Zc),e.end(fx(uq)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function lq(t){for(let e=hx;e<=mx;e++)if(await new Promise(n=>{let o=()=>{t.removeListener("listening",s),n(!1)},s=()=>{t.removeListener("error",o),n(!0)};t.once("error",o),t.once("listening",s),t.listen(e,cq)}))return e;throw new Error(`No free port in ${hx}-${mx} for the OAuth callback server`)}async function _x(){let t=!1,e,r,n=new Promise((i,a)=>{e=c=>{t||(t=!0,i(c))},r=c=>{t||(t=!0,a(c))}}),o=aq((i,a)=>{dq(i,a,{onSuccess:c=>e?.(c),onError:c=>r?.(c)})}),s=await lq(o);return{port:s,redirectUri:`http://localhost:${s}${gx}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>o.close()}}var wx=pq.child({prefix:"pi-mcp"}),fq=300*1e3,bx="MCP authentication was superseded";function hq(){return yx()?"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 xn(t){if(t.aborted)throw new Error("Authentication cancelled")}function Rx(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&&Px(t.credentialRevisions.get(e),r.credentialRevision)}function Px(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Sx(t,e,r){if(!Rx(t,e,r))throw new Error(bx)}async function mq(t,e,r,n,o,s){let i=t.servers.get(e),a=t.tokens,c=a.get(e),u=t.credentialRevisions.get(e);if(a!==r.tokenStore||!i||!c||!Ve(r.server.config,i.config))return;let d=i.config,l=hr(d);try{let p=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(p===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!Px(t.credentialRevisions.get(e),u))return;jr({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??s,t)}catch{wx.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function gq(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 yq(t,e,r){return new Promise((n,o)=>{let s=!1,i=()=>{clearTimeout(u),e.signal.removeEventListener("abort",c),t.cancelWait()},a=d=>{s||(s=!0,i(),d())},c=()=>a(()=>o(new Error("Authentication cancelled"))),u=setTimeout(()=>a(()=>o(new Error("Authentication timed out"))),fq);if(e.signal.aborted){a(()=>o(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",c),t.waitForCode().then(d=>{d&&a(()=>n(new URLSearchParams({code:d.code,state:d.state})))}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d))))),e.waitForManualCode().then(d=>{if(d)try{let l=vx(d,r);a(()=>n(new URLSearchParams({code:l.code,state:l.state})))}catch(l){let p=l instanceof Error?l.message:String(l);a(()=>o(new Error(`Could not read the pasted authorization code (${p}). Restart sign-in and paste the full redirect URL.`)))}}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d)))))})}async function Cx(t){let{serverName:e,state:r,pi:n,controller:o}=t,s=r.servers.get(e);if(!s)throw new Error(`Unknown MCP server "${e}"`);let i=s.config;if(i.type!=="http"&&i.type!=="sse")throw new Error(`MCP server "${e}" does not use OAuth authentication`);if(r.authenticating)throw new Error("Another MCP authentication is already in progress");r.authenticating=!0,r.authenticatingServerName=e;let a=++r.authenticationGeneration,c={authenticationGeneration:a,server:s,serverGeneration:r.serverGenerations.get(e)??0,installedConfigRevision:r.configRevisions.get(e)??0,desiredConfigRevision:r.configDesiredRevisions.get(e)??0,tokenStore:r.tokens,token:r.tokens.get(e),credentialRevision:r.credentialRevisions.get(e)},u=hr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Sx(r,e,c),xn(o.signal),d=await _x(),xn(o.signal);let p=new URL(i.url),f=await ed(p);xn(o.signal);let h=await td(f);xn(o.signal);let m=await rd({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});xn(o.signal);let y=await nd(p,m,h,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);xn(o.signal),o.onAuthUrl({url:y.authUri.toString(),instructions:hq()}),xn(o.signal),await lx(y.authUri.toString());let S=await yq(d,o,y.state),w=await od(S,y);Sx(r,e,c);let b=gq(w),k=await c.tokenStore.persistAuthenticated(e,b,u,l);if(!Rx(r,e,c))throw await mq(r,e,c,b,k,n),new Error(bx);c.tokenStore.commit(e,b),r.preservedCredentialIdentities?.delete(e),jr({state:r,name:e,revision:k}),r.tokens.clearAuthRequired(e),ot(r,e),await yi([e],r,n),J(r.currentLoad?.latestPi??n,r),wx.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as Iq}from"@augmentcode/auggie-v2";import{resolveTargetFiles as vq,SETTINGS_TARGET_ORDER as _q,SettingsManager as Sq,scopeToSettingsTarget as wq,settingsTargetToScope as yh}from"@augmentcode/auggie-v2";var bq=_q.map(t=>yh(t)),xx=(t,e)=>Sq.create(t,e);function kx(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 Ex(t,e,r){let n=xx(e,r);return bq.filter(o=>kx(n,o)?.[t])}function Tx(t){let e=t.map(n=>({target:wq(n),path:n,exists:!0})),r=vq({files:e});return"directTarget"in r?{scopes:t,direct:yh(r.directTarget)}:{scopes:r.files.map(n=>yh(n.target)),direct:null}}function Rq(t,e,r){let{servers:n}=An(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Ax(t,e,r,n,o){try{let s=xx(n,o);if(!kx(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:Rq(t,n,o)!==e}}function vh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function $x(t,e,r){return vh(t)}function Mx(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as Pq}from"@hermes/logger";var Sh=Pq.child({prefix:"pi-mcp"}),Ix="hermes:mcp:register-server-source";function Cq(t,e){return t.type==="stdio"?Dt(t,e):Nt(t,e)}function zx(t,e){return JSON.stringify(t)===JSON.stringify(e)}function xq(t,e){return{...t,disabled:e}}function kq(t){try{return t.getServers()}catch(e){return Sh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function Eq(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Ox(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 Tq(t,e,r,n){let o=new Map;if(!t)return o;for(let s of kq(t)){let i=e.servers.get(s.name),a=Cq(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=xq(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=Z(e,s.name),p=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,f=i!==void 0&&d===void 0&&n.has(s.name)&&zx(i.config,u);f&&(Q(e,s.name,i),Hh({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(p||f||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),Ox(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function Aq(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=Z(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){be({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=wt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=ct(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),be({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Nx(t,e){Ox(t,e)}function $q(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"){Nx(e,a);continue}u===o.get(a)&&n.has(a)&&zx(u.config,c)||(i.set(a,Ge(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function Mq(t,e,r){let n=r?.connect??St,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&Eq(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=Tq(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 Aq(a,u,e);let{reservedRevisions:d,toConnect:l}=$q({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Sh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let p=()=>e.currentLoad?.latestPi??t,f=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),S=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return S||Nx(e,h.name),S};try{await n(l,e,p(),f,d,"plugin");for(let h of l)f(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(p(),e),Oe(e)}}function _h(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>Mq(t,e,r)).catch(s=>{Sh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function Dx(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 Lx(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 zq(t,e){let n=Iq.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function jx(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(zq(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:vh(e)};if(gu(r.mcpConfigOverride).has(e))return{kind:"session"};if(pr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=Ex(e,n,o);if(i.length===0)return{kind:"blocked",message:$x(e,n,o)};let{scopes:a,direct:c}=Tx(i);return{kind:"local",scopes:a,direct:c}}async function Ux(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 Dx({name:e,disabled:r,state:n,pi:o});return}gu(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 St([a],n,o,void 0,void 0,i?.owner.kind),Oe(n)}async function Fx(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=Ax(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await cx(e,o,s,i,a),Oe(o),c.overridden?{notice:Mx(e)}:{}}import{Key as eH,matchesKey as tH,SpinnerTimer as rH,wrapTextWithAnsi as nH}from"@earendil-works/pi-tui";import{Key as Fq,matchesKey as qq}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as Oq,scopeToSettingsTarget as Nq}from"@augmentcode/auggie-v2";import{truncateToWidth as Dq,visibleWidth as qx}from"@earendil-works/pi-tui";var Lq=15,jq=2;function Hx(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 wh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Gx(t){return Math.max(bh(t),Lq)}function bh(t){return t.reduce((r,n)=>Math.max(r,qx(n)),0)+jq}function vi(t,e){let r=e-qx(t);return r>0?t+" ".repeat(r):t}function Zx(t,e){return Dq(t,Math.max(1,e),"\u2026")}function Vx(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 Uq(t,e){return Math.max(0,t-e)}function Rh(t,e,r){return Math.max(0,Math.min(t,Uq(e,r)))}function Bx(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 Wx(t,e){return String(t+1).padStart(String(e).length," ")}function Kx(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function Ph(t){return Oq(Nq(t))}function Vc(t){if(t.source==="plugin"&&t.disabled)return["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.isOAuth&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function Jx(){return{step:"serverList",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var Co=15;var Hq="k",Gq="j";function xo(t,e){return(t%e+e)%e}function nt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function Yx(t,e){return e.matches(t,"tui.select.up")||t===Hq?{kind:"up"}:e.matches(t,"tui.select.down")||t===Gq?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:qq(t,Fq.backspace)?{kind:"back"}:{kind:"ignore"}}function Zq(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=xo(nt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=xo(nt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[nt(r,t.selectedServer)];return o?.status==="auth_required"&&o.isOAuth?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function Vq(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Vc(n);switch(e.kind){case"up":return{state:{...t,actionIndex:xo(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:xo(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 Bq(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)]?.tools.length??0;switch(e.kind){case"up":return{state:{...t,toolIndex:Math.max(0,t.toolIndex-1)}};case"down":return{state:{...t,toolIndex:Math.min(Math.max(0,n-1),t.toolIndex+1)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function Wq(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)]?.logLines().length??0;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Rh(t.logScrollOffset-1,n,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Rh(t.logScrollOffset+1,n,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function Kq(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Bc(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function Jq(t,e){let r=t.targetScopes.length;if(r===0)return{state:Bc(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:xo(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:xo(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Bc(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Bc({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Bc(t,"serverActions")}}default:return{state:t}}}function Xx(t,e,r){switch(t.step){case"serverList":return Zq(t,e,r.snapshots);case"serverActions":return Vq(t,e,r);case"viewTools":return Bq(t,e,r);case"viewLogs":return Wq(t,e,r);case"pasteAuthCode":return Kq(t,e);case"selectTarget":return Jq(t,e);default:return{state:t}}}var Ch="\u2192 ",Wc=" ";function Yq(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 Qx(t,e,r){if(e.length===0)return[r.fg("muted","No MCP servers available")];let n=Gx(e.map(c=>c.name)),o=bh(["Source",...e.map(wh)]),s=nt(e,t.selectedServer),a=[Wc+vi(r.bold(r.fg("accent","Name")),n)+vi(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=Hx(u),p=r.fg(l.color,l.label)+(l.hint?r.fg("muted",l.hint):"");a.push((d?Ch:Wc)+vi(Yq(u,d,r),n)+vi(r.fg("muted",wh(u)),o)+p)}return a}var Xq={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 Qq(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 Xq[t]}function ek(t,e,r,n){let o=e[nt(e,t.selectedServer)];if(!o)return[r.fg("muted","No MCP servers available")];let s=o.transport==="stdio"?"Command: ":"URL: ",i=[r.fg("muted",Zx(s+o.connectionInfo,n))];o.source==="plugin"&&i.push(r.fg("muted","Source: plugin (toggles apply to this session only)")),i.push("");let a=Vc(o);for(let[c,u]of a.entries()){let d=c===t.actionIndex,l=Qq(u,o),p=u==="authenticate"?Kx(o.status):l.label,f=d?r.bold(r.fg("accent",p)):r.fg("text",p);i.push((d?Ch:Wc)+f+r.fg("muted",` - ${l.description}`))}return i}function tk(t,e,r){let n=e[nt(e,t.selectedServer)];if(!n)return[r.fg("muted","No tools available.")];if(n.disabled)return[r.fg("muted","Server is disabled; no tools are currently available.")];if(n.tools.length===0)return[r.fg("muted","No tools available.")];let o=n.tools.length,{start:s,end:i}=Vx(t.toolIndex,o,Co),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",`${Wx(c,o)} `)+l+(u.disabled?r.fg("muted"," (disabled)"):""))}return a}function rk(t,e,r){let o=e[nt(e,t.selectedServer)]?.logLines()??[];if(o.length===0)return[r.fg("muted","No logs available yet.")];let s=o.length,i=Bx(t.logScrollOffset,s,Co),a=[];s>Co&&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 nk(t,e,r){let n=e[nt(e,t.selectedServer)]?.name??"",o=[r.fg("muted",`Save the toggle for "${n}" to which settings file?`),""];for(let[s,i]of t.targetScopes.entries()){let a=s===t.targetIndex,c=a?r.bold(r.fg("accent",Ph(i))):r.fg("text",Ph(i));o.push((a?Ch:Wc)+c)}return o}function oH(t){return t.type==="stdio"?t.command:t.url}function sH(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
143
+ </html>`}function vx(t){return yx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function Zc(t,e){return yx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var mq="127.0.0.1",wx="/callback",_x=3e3,Sx=3010,gq="Authentication successful. You can close this window.",Bc={"Content-Type":"text/html; charset=utf-8"};function bx(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function Rx(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n,o;try{let s=new URL(r);n=s.searchParams.get("code")??void 0,o=s.searchParams.get("state")??void 0}catch{if(r.includes("code=")){let s=new URLSearchParams(r);n=s.get("code")??void 0,o=s.get("state")??void 0}else n=r}if(!n)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{code:n,state:o??e}}function yq(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==wx){e.writeHead(404,Bc),e.end(Zc("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){e.writeHead(400,Bc),e.end(Zc("Authentication did not complete.",`Error: ${i}`));let a=n.searchParams.get("error_description");r.onError(new Error(`Authentication did not complete: ${i}${a?`: ${a}`:""}`));return}if(!o||!s){e.writeHead(400,Bc),e.end(Zc("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,Bc),e.end(vx(gq)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function vq(t){for(let e=_x;e<=Sx;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,mq)}))return e;throw new Error(`No free port in ${_x}-${Sx} for the OAuth callback server`)}async function Px(){let t=!1,e,r,n=new Promise((i,a)=>{e=c=>{t||(t=!0,i(c))},r=c=>{t||(t=!0,a(c))}}),o=hq((i,a)=>{yq(i,a,{onSuccess:c=>e?.(c),onError:c=>r?.(c)})}),s=await vq(o);return{port:s,redirectUri:`http://localhost:${s}${wx}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>o.close()}}var xx=_q.child({prefix:"pi-mcp"}),Sq=300*1e3,kx="MCP authentication was superseded";function wq(){return bx()?"You appear to be on a remote machine. Open the URL in a local browser, then paste the final redirect URL or code below.":"Complete sign-in in your browser. If it doesn't open, paste the final redirect URL or code below."}function kn(t){if(t.aborted)throw new Error("Authentication cancelled")}function Ex(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&&Tx(t.credentialRevisions.get(e),r.credentialRevision)}function Tx(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function Cx(t,e,r){if(!Ex(t,e,r))throw new Error(kx)}async function bq(t,e,r,n,o,s){let i=t.servers.get(e),a=t.tokens,c=a.get(e),u=t.credentialRevisions.get(e);if(a!==r.tokenStore||!i||!c||!Be(r.server.config,i.config))return;let d=i.config,l=hr(d);try{let p=await a.restoreAfterSupersededAuthentication(e,n,c,l,o);if(p===void 0||t.tokens!==a||t.servers.get(e)?.config!==d||a.get(e)!==c||!Tx(t.credentialRevisions.get(e),u))return;Ur({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??s,t)}catch{xx.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function Rq(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 Pq(t,e,r){return new Promise((n,o)=>{let s=!1,i=()=>{clearTimeout(u),e.signal.removeEventListener("abort",c),t.cancelWait()},a=d=>{s||(s=!0,i(),d())},c=()=>a(()=>o(new Error("Authentication cancelled"))),u=setTimeout(()=>a(()=>o(new Error("Authentication timed out"))),Sq);if(e.signal.aborted){a(()=>o(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",c),t.waitForCode().then(d=>{d&&a(()=>n(new URLSearchParams({code:d.code,state:d.state})))}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d))))),e.waitForManualCode().then(d=>{if(d)try{let l=Rx(d,r);a(()=>n(new URLSearchParams({code:l.code,state:l.state})))}catch(l){let p=l instanceof Error?l.message:String(l);a(()=>o(new Error(`Could not read the pasted authorization code (${p}). Restart sign-in and paste the full redirect URL.`)))}}).catch(d=>a(()=>o(d instanceof Error?d:new Error(String(d)))))})}async function Ax(t){let{serverName:e,state:r,pi:n,controller:o}=t,s=r.servers.get(e);if(!s)throw new Error(`Unknown MCP server "${e}"`);let i=s.config;if(i.type!=="http"&&i.type!=="sse")throw new Error(`MCP server "${e}" does not use OAuth authentication`);if(r.authenticating)throw new Error("Another MCP authentication is already in progress");r.authenticating=!0,r.authenticatingServerName=e;let a=++r.authenticationGeneration,c={authenticationGeneration:a,server:s,serverGeneration:r.serverGenerations.get(e)??0,installedConfigRevision:r.configRevisions.get(e)??0,desiredConfigRevision:r.configDesiredRevisions.get(e)??0,tokenStore:r.tokens,token:r.tokens.get(e),credentialRevision:r.credentialRevisions.get(e)},u=hr(i),d;try{let l=await c.tokenStore.captureAuthenticatedIdentityVersion(u);Cx(r,e,c),kn(o.signal),d=await Px(),kn(o.signal);let p=new URL(i.url),f=await td(p);kn(o.signal);let h=await rd(f);kn(o.signal);let m=await nd({config:{},serverMetadata:h,redirectUris:[d.redirectUri]});kn(o.signal);let y=await od(p,m,h,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);kn(o.signal),o.onAuthUrl({url:y.authUri.toString(),instructions:wq()}),kn(o.signal),await gx(y.authUri.toString());let S=await Pq(d,o,y.state),w=await sd(S,y);Cx(r,e,c);let b=Rq(w),k=await c.tokenStore.persistAuthenticated(e,b,u,l);if(!Ex(r,e,c))throw await bq(r,e,c,b,k,n),new Error(kx);c.tokenStore.commit(e,b),r.preservedCredentialIdentities?.delete(e),Ur({state:r,name:e,revision:k}),r.tokens.clearAuthRequired(e),ot(r,e),await vi([e],r,n),J(r.currentLoad?.latestPi??n,r),xx.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as Uq}from"@augmentcode/auggie-v2";import{resolveTargetFiles as Cq,SETTINGS_TARGET_ORDER as xq,SettingsManager as kq,scopeToSettingsTarget as Eq,settingsTargetToScope as vh}from"@augmentcode/auggie-v2";var Tq=xq.map(t=>vh(t)),$x=(t,e)=>kq.create(t,e);function Mx(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 Ix(t,e,r){let n=$x(e,r);return Tq.filter(o=>Mx(n,o)?.[t])}function zx(t){let e=t.map(n=>({target:Eq(n),path:n,exists:!0})),r=Cq({files:e});return"directTarget"in r?{scopes:t,direct:vh(r.directTarget)}:{scopes:r.files.map(n=>vh(n.target)),direct:null}}function Aq(t,e,r){let{servers:n}=$n(e,r);return n.find(o=>o.name===t)?.disabled===!0}function Ox(t,e,r,n,o){try{let s=$x(n,o);if(!Mx(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:Aq(t,n,o)!==e}}function _h(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function Nx(t,e,r){return _h(t)}function Dx(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as $q}from"@hermes/logger";var wh=$q.child({prefix:"pi-mcp"}),Lx="hermes:mcp:register-server-source";function Mq(t,e){return t.type==="stdio"?Dt(t,e):Nt(t,e)}function jx(t,e){return JSON.stringify(t)===JSON.stringify(e)}function Iq(t,e){return{...t,disabled:e}}function zq(t){try{return t.getServers()}catch(e){return wh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function Oq(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function Ux(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 Nq(t,e,r,n){let o=new Map;if(!t)return o;for(let s of zq(t)){let i=e.servers.get(s.name),a=Mq(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=Iq(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=Z(e,s.name),p=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,f=i!==void 0&&d===void 0&&n.has(s.name)&&jx(i.config,u);f&&(Q(e,s.name,i),Gh({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(p||f||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),Ux(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function Dq(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=Z(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){be({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=wt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=ct(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),be({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Fx(t,e){Ux(t,e)}function Lq(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"){Fx(e,a);continue}u===o.get(a)&&n.has(a)&&jx(u.config,c)||(i.set(a,Ge(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function jq(t,e,r){let n=r?.connect??St,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&Oq(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=Nq(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 Dq(a,u,e);let{reservedRevisions:d,toConnect:l}=Lq({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;wh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let p=()=>e.currentLoad?.latestPi??t,f=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=Z(e,h.name),S=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return S||Fx(e,h.name),S};try{await n(l,e,p(),f,d,"plugin");for(let h of l)f(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(p(),e),Oe(e)}}function Sh(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>jq(t,e,r)).catch(s=>{wh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function qx(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),Sh(o.currentLoad?.latestPi??s,o,e))}function Hx(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Sh(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Sh(e.currentLoad?.latestPi??t,e))})}}function Fq(t,e){let n=Uq.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function Gx(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(Fq(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:_h(e)};if(yu(r.mcpConfigOverride).has(e))return{kind:"session"};if(pr(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=Ix(e,n,o);if(i.length===0)return{kind:"blocked",message:Nx(e,n,o)};let{scopes:a,direct:c}=zx(i);return{kind:"local",scopes:a,direct:c}}async function Zx(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 qx({name:e,disabled:r,state:n,pi:o});return}yu(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),s.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...s.config,disabled:r};await St([a],n,o,void 0,void 0,i?.owner.kind),Oe(n)}async function Bx(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=Ox(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await fx(e,o,s,i,a),Oe(o),c.overridden?{notice:Dx(e)}:{}}import{Key as aH,matchesKey as cH,SpinnerTimer as uH,wrapTextWithAnsi as dH}from"@earendil-works/pi-tui";import{Key as Wq,matchesKey as Kq}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as qq,scopeToSettingsTarget as Hq}from"@augmentcode/auggie-v2";import{truncateToWidth as Gq,visibleWidth as Vx}from"@earendil-works/pi-tui";var Zq=15,Bq=2;function Wx(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 bh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Kx(t){return Math.max(Rh(t),Zq)}function Rh(t){return t.reduce((r,n)=>Math.max(r,Vx(n)),0)+Bq}function _i(t,e){let r=e-Vx(t);return r>0?t+" ".repeat(r):t}function Jx(t,e){return Gq(t,Math.max(1,e),"\u2026")}function Yx(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 Vq(t,e){return Math.max(0,t-e)}function Ph(t,e,r){return Math.max(0,Math.min(t,Vq(e,r)))}function Xx(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 Qx(t,e){return String(t+1).padStart(String(e).length," ")}function ek(t){return t==="auth_required"?"Reauthenticate":"Authenticate"}function Ch(t){return qq(Hq(t))}function Vc(t){if(t.source==="plugin"&&t.disabled)return["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.isOAuth&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function tk(){return{step:"serverList",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var xo=15;var Jq="k",Yq="j";function ko(t,e){return(t%e+e)%e}function nt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function rk(t,e){return e.matches(t,"tui.select.up")||t===Jq?{kind:"up"}:e.matches(t,"tui.select.down")||t===Yq?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:Kq(t,Wq.backspace)?{kind:"back"}:{kind:"ignore"}}function Xq(t,e,r){let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=ko(nt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=ko(nt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[nt(r,t.selectedServer)];return o?.status==="auth_required"&&o.isOAuth?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function Qq(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=Vc(n);switch(e.kind){case"up":return{state:{...t,actionIndex:ko(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:ko(t.actionIndex+1,o.length)}};case"cancel":case"back":return{state:{...t,step:"serverList"}};case"confirm":{let s=o[t.actionIndex];return s==="viewTools"?{state:{...t,step:"viewTools",toolIndex:0}}:s==="viewLogs"?{state:{...t,step:"viewLogs",logScrollOffset:0}}:s==="authenticate"?{state:t,effect:{kind:"authenticate",server:n.name}}:s==="toggle"?{state:t,effect:{kind:"toggle",server:n.name,disable:!n.disabled}}:{state:t,effect:{kind:"reconnect",server:n.name}}}default:return{state:t}}}function eH(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)]?.tools.length??0;switch(e.kind){case"up":return{state:{...t,toolIndex:Math.max(0,t.toolIndex-1)}};case"down":return{state:{...t,toolIndex:Math.min(Math.max(0,n-1),t.toolIndex+1)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function tH(t,e,r){let n=r.snapshots[nt(r.snapshots,t.selectedServer)]?.logLines().length??0;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Ph(t.logScrollOffset-1,n,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Ph(t.logScrollOffset+1,n,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function rH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function Wc(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function nH(t,e){let r=t.targetScopes.length;if(r===0)return{state:Wc(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:ko(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:ko(t.targetIndex+1,r)}};case"cancel":case"back":return{state:Wc(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:Wc({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:Wc(t,"serverActions")}}default:return{state:t}}}function nk(t,e,r){switch(t.step){case"serverList":return Xq(t,e,r.snapshots);case"serverActions":return Qq(t,e,r);case"viewTools":return eH(t,e,r);case"viewLogs":return tH(t,e,r);case"pasteAuthCode":return rH(t,e);case"selectTarget":return nH(t,e);default:return{state:t}}}var xh="\u2192 ",Kc=" ";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 ok(t,e,r){if(e.length===0)return[r.fg("muted","No MCP servers available")];let n=Kx(e.map(c=>c.name)),o=Rh(["Source",...e.map(bh)]),s=nt(e,t.selectedServer),a=[Kc+_i(r.bold(r.fg("accent","Name")),n)+_i(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=Wx(u),p=r.fg(l.color,l.label)+(l.hint?r.fg("muted",l.hint):"");a.push((d?xh:Kc)+_i(oH(u,d,r),n)+_i(r.fg("muted",bh(u)),o)+p)}return a}var sH={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 iH(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 sH[t]}function sk(t,e,r,n){let o=e[nt(e,t.selectedServer)];if(!o)return[r.fg("muted","No MCP servers available")];let s=o.transport==="stdio"?"Command: ":"URL: ",i=[r.fg("muted",Jx(s+o.connectionInfo,n))];o.source==="plugin"&&i.push(r.fg("muted","Source: plugin (toggles apply to this session only)")),i.push("");let a=Vc(o);for(let[c,u]of a.entries()){let d=c===t.actionIndex,l=iH(u,o),p=u==="authenticate"?ek(o.status):l.label,f=d?r.bold(r.fg("accent",p)):r.fg("text",p);i.push((d?xh:Kc)+f+r.fg("muted",` - ${l.description}`))}return i}function ik(t,e,r){let n=e[nt(e,t.selectedServer)];if(!n)return[r.fg("muted","No tools available.")];if(n.disabled)return[r.fg("muted","Server is disabled; no tools are currently available.")];if(n.tools.length===0)return[r.fg("muted","No tools available.")];let o=n.tools.length,{start:s,end:i}=Yx(t.toolIndex,o,xo),a=[];for(let c=s;c<i;c++){let u=n.tools[c];if(!u)continue;let l=c===t.toolIndex?r.bold(r.fg("accent",u.name)):r.fg("text",u.name);a.push(r.fg("muted",`${Qx(c,o)} `)+l+(u.disabled?r.fg("muted"," (disabled)"):""))}return a}function ak(t,e,r){let o=e[nt(e,t.selectedServer)]?.logLines()??[];if(o.length===0)return[r.fg("muted","No logs available yet.")];let s=o.length,i=Xx(t.logScrollOffset,s,xo),a=[];s>xo&&a.push(r.fg("muted",i.rangeLabel)),i.aboveCount>0&&a.push(r.fg("dim",`\u2191 ${i.aboveCount} more`));for(let c of o.slice(i.start,i.end))a.push(r.fg("text",c));return i.belowCount>0&&a.push(r.fg("dim",`\u2193 ${i.belowCount} more`)),a}function ck(t,e,r){let n=e[nt(e,t.selectedServer)]?.name??"",o=[r.fg("muted",`Save the toggle for "${n}" to which settings file?`),""];for(let[s,i]of t.targetScopes.entries()){let a=s===t.targetIndex,c=a?r.bold(r.fg("accent",Ch(i))):r.fg("text",Ch(i));o.push((a?xh:Kc)+c)}return o}function lH(t){return t.type==="stdio"?t.command:t.url}function pH(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 ok(t){return t.disabled?2:t.status==="auth_required"?0:1}function iH(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:pr(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:oH(r.config),logLines:()=>sH(r)});return e.sort((r,n)=>ok(r)-ok(n)),e}function aH(t,e){let r=e[nt(e,t.selectedServer)]?.name??"";switch(t.step){case"serverActions":return`MCP Servers \u203A ${r}`;case"viewTools":return`MCP Servers \u203A ${r} \u203A Tools`;case"viewLogs":return`MCP Servers \u203A ${r} \u203A Logs`;case"selectTarget":return`MCP Servers \u203A ${r} \u203A Settings file`;default:return"MCP Servers"}}function cH(t){switch(t){case"serverList":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function uH(t,e,r,n){switch(t.step){case"serverActions":return ek(t,e,r,n);case"viewTools":return tk(t,e,r);case"viewLogs":return rk(t,e,r);case"selectTarget":return nk(t,e,r);default:return Qx(t,e,r)}}function dH(t,e,r,n){let o=r.bold(r.fg("accent",aH(t,e))),s=uH(t,e,r,n);return[o,"",...s,"",r.fg("muted",cH(t.step))]}function lH(t,e,r,n){let o=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),s=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[o,"",s]}function pH(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function fH(t,e,r){let n=i=>i.flatMap(a=>nH(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 hH(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function sk(t){return t?"Disabling":"Enabling"}function ik(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var xh=class{state=Jx();config;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;authInPaste=!1;authPasteBuffer="";authDone;component;constructor(e){this.config=e,this.component={render:r=>this.render(r),handleInput:r=>this.dispatch(r),invalidate:()=>{}}}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){return this.busy?lH(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme):this.authenticating?fH({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,e):dH(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=Yx(e,this.config.keybindings),o=Xx(this.state,n,{snapshots:r,windowSize:Co});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,sk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(ik(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,sk(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(ik(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new rH(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=pH();let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>this.manualCode?this.manualCode.promise:Promise.resolve(null),signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();n&&this.manualCode?.resolve(n);return}if(tH(e,eH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),this.authInPaste){this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n!==-1){let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}return}hH(e)&&(this.state={...this.state,authInput:this.state.authInput+e},this.config.tui.requestRender())}exitAuth(){this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode=void 0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function ak(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new xh({tui:s,theme:i,keybindings:a,snapshots:()=>iH(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Eh=["list"];function ck(t){let{name:e,status:r}=t,n;switch(r){case"success":{let o=t.tools.length;n=o>0?` \u2705 ${e} (${o} tool${o===1?"":"s"})`:` \u2705 ${e} (ready)`;break}case"failed":n=` \u274C ${e} (failed)`;break;case"auth_required":n=` \u{1F510} ${e} (auth required)`;break;case"disabled":n=` \u26AA ${e} (disabled)`;break;default:n=` \u23F3 ${e} (initializing...)`;break}return r==="failed"&&t.lastError?`${n}
146
- error: ${t.lastError}`:n}function mH(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var gH="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function kh(t,e){return e.length>0?[t,...e]:null}function yH(t){let e=[],r=[];for(let o of t.servers.values())(pr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[kh("MCP Server Status:",e.map(ck)),kh("Plugin MCP servers:",r.map(ck)),kh("Diagnostics:",t.diagnostics.map(mH))];return t.servers.size===0&&n.unshift([gH]),n.filter(o=>o!==null).map(o=>o.join(`
145
+ `)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function uk(t){return t.disabled?2:t.status==="auth_required"?0:1}function fH(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:pr(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:lH(r.config),logLines:()=>pH(r)});return e.sort((r,n)=>uk(r)-uk(n)),e}function hH(t,e){let r=e[nt(e,t.selectedServer)]?.name??"";switch(t.step){case"serverActions":return`MCP Servers \u203A ${r}`;case"viewTools":return`MCP Servers \u203A ${r} \u203A Tools`;case"viewLogs":return`MCP Servers \u203A ${r} \u203A Logs`;case"selectTarget":return`MCP Servers \u203A ${r} \u203A Settings file`;default:return"MCP Servers"}}function mH(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 gH(t,e,r,n){switch(t.step){case"serverActions":return sk(t,e,r,n);case"viewTools":return ik(t,e,r);case"viewLogs":return ak(t,e,r);case"selectTarget":return ck(t,e,r);default:return ok(t,e,r)}}function yH(t,e,r,n){let o=r.bold(r.fg("accent",hH(t,e))),s=gH(t,e,r,n);return[o,"",...s,"",r.fg("muted",mH(t.step))]}function vH(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 _H(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function SH(t,e,r){let n=i=>i.flatMap(a=>dH(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 wH(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function dk(t){return t?"Disabling":"Enabling"}function lk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var kh=class{state=tk();config;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;authInPaste=!1;authPasteBuffer="";authDone;component;constructor(e){this.config=e,this.component={render:r=>this.render(r),handleInput:r=>this.dispatch(r),invalidate:()=>{}}}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){return this.busy?vH(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme):this.authenticating?SH({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,e):yH(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=rk(e,this.config.keybindings),o=nk(this.state,n,{snapshots:r,windowSize:xo});this.state=o.state,o.effect&&this.runEffect(o.effect),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,dk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(lk(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,dk(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(lk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new uH(()=>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=_H();let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>this.manualCode?this.manualCode.promise:Promise.resolve(null),signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();n&&this.manualCode?.resolve(n);return}if(cH(e,aH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),this.authInPaste){this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n!==-1){let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}return}wH(e)&&(this.state={...this.state,authInput:this.state.authInput+e},this.config.tui.requestRender())}exitAuth(){this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode=void 0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:"serverList",actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function pk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new kh({tui:s,theme:i,keybindings:a,snapshots:()=>fH(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var Th=["list"];function fk(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 bH(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var RH="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function Eh(t,e){return e.length>0?[t,...e]:null}function PH(t){let e=[],r=[];for(let o of t.servers.values())(pr(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[Eh("MCP Server Status:",e.map(fk)),Eh("Plugin MCP servers:",r.map(fk)),Eh("Diagnostics:",t.diagnostics.map(bH))];return t.servers.size===0&&n.unshift([RH]),n.filter(o=>o!==null).map(o=>o.join(`
147
147
  `)).join(`
148
148
 
149
- `)}function vH(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Eh.includes(e))return e}async function _H(t,e,r){if(e.servers.size===0){t.ui.notify("MCP servers are not available","warning");return}if(e.reconnecting){t.ui.notify("MCP servers are already restarting...","warning");return}t.ui.notify("Restarting MCP servers...","info");let n=yi([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function uk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Eh.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 ak(n,e,i=>yi([i],e,t),{classify:i=>jx({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>Ux({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Fx({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)=>Cx({serverName:i,state:e,pi:t,controller:a}));return}let s=vH(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Eh.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(yH(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await _H(n,e,t)}})}import{logger as SH}from"@hermes/logger";var dk=SH.child({prefix:"pi-mcp"}),Th="augment:feature-flags";function wH(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 lk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Th,r=>{let n=wH(r);if(n===void 0){dk.warn(`${Th} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,dk.debug(`Received feature-flag snapshot via ${Th} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as bH}from"@hermes/logger";var Kc=bH.child({prefix:"pi-mcp"}),Ah="augment:mcp-attach-result";function pk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(Ah,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){Kc.warn(`${Ah} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){Kc.debug(`${Ah}: 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 Jc(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 _m(r);o.ok?(e.mcpCatalog=o.entries,Kc.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,Kc.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),Mn(e)&&Zr(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as RH}from"@hermes/logger";var _i=RH.child({prefix:"pi-mcp"}),fk=300*1e3,$h=600*1e3;function PH(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&&(Ho(o,e)||o.expiresAt>e+$h||(_i.debug(`Background refresh: token for MCP server "${r.name}" expires within ${$h}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(()=>{PH(t)},fk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,_i.debug(`Started background MCP OAuth refresh loop (interval ${fk}ms, buffer ${$h}ms)`)}function mk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,_i.debug("Stopped background MCP OAuth refresh loop"))}import{logger as LH}from"@hermes/logger";function CH(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Do.OAUTH:return"oauth";case Do.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 xH(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case qr.CLI:return"cli";case qr.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 Yc(t){if(t==null)return;if(t.length===0)return[];let e=t.map(xH).filter(r=>r!==void 0);return e.length===0?void 0:e}function Xc(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=CH(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=En(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Tn(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Rt?i.message:String(i)}}}function kH(t){let e=t.config?.auth_type;return e===Do.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function EH(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 Mh(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 TH(t,e,r){if(r!==void 0&&t.added_by===r)return Yc(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?Yc(n):[]}function AH(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let f=Mh(e,r,()=>!0);return{selected:[],filteredOutIds:f.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let f=new Set(s),h=Mh(e,r,()=>!0),m=new Set(h.map(b=>b.id)),y=h.filter(b=>f.has(b.id)),S=h.filter(b=>!f.has(b.id)).map(b=>b.id),w=s.filter(b=>!m.has(b));return{selected:y,filteredOutIds:S,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let f of e)a.has(f.id)||c.push(f.id);let u=Mh(e,r,f=>a.has(f)),d=new Set(r.map(f=>f.id)),l=[],p=[];for(let f of u){let m=!d.has(f.id)&&a.has(f.id)?TH(f,o,i):Yc(f.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(f):(c.push(f.id),f.config?.name&&p.push(f.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:p}}function $H(t){return t==null?qr.CLOUD_AGENT:void 0}function MH(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 IH(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Dt(t,n):Nt(t,n)}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${s}`}}}}function zH(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=Xc(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){let d=n.has(c.name)?`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`;return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:d}}}let u=IH(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 OH(t){let e=[],r=[],n=[];for(let o of t)kH(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 NH(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=EH(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}async function Qc(t){let e=t.client??new Fi(t.creds),{tenant:r,user:n,diagnostics:o}=await $m(e,$H(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=AH({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=OH(a),p=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...MH(u));let f=[],h=new Set(t.localServerNames),m=[...p.filter(w=>i.has(w.id)),...p.filter(w=>!i.has(w.id))];for(let w of m){let b=zH({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:h,workspaceRoot:t.workspaceRoot});b.kind!=="connected"&&b.diagnostic&&o.push(b.diagnostic),b.kind==="connected"?f.push(b.server):b.kind==="retained"&&d.push(b.name)}let y=NH(f);d.push(...y.droppedNames),o.push(...y.diagnostics);let S=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&S.set(w.id,w.config.name);return{servers:y.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:S}}import{logger as DH}from"@hermes/logger";var ko=DH.child({prefix:"pi-mcp"});function gk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){ko.warn("Embedded MCP config is missing an id; ignoring");return}let n=Xc(r,"tenant");if(!n.ok){ko.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Dt(n.server,o):Nt(n.server,o)}catch(s){ko.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function yk(t,e){let r;try{r=JSON.parse(t)}catch(n){ko.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return gk(r,e)}function eu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){ko.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){ko.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=gk(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=LH.child({prefix:"pi-mcp"});function jH(t,e,r){t.dynamicallyAddedConfigIds.add(e),t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.sessionRemovedConfigIds.delete(e);for(let n of r)n.id!==void 0&&(t.registryConfigNamesById.set(n.id,n.name),t.registryCredentialConfigsById.set(n.id,{...n}))}function Wt(t){Be({state:t.state,domain:We(t.configId),epoch:t.intentEpoch})}function UH(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 _k(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 Si(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Wt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(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 FH(t,e){return e.flatMap(r=>Fc(t,r)?[r.config]:[])}function qH(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function HH(t,e){let r=qH(e);if(r){if(Si(t,r.error),r.error instanceof bt)throw r.error;return}let n=FH(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){jH(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 Sk(t,e){try{HH(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function GH(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 ZH(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await Oo(t.state,t.configId),t.superseded()){Wt(t);return}if(GH(t,e)){Wt(t);return}try{if(!await Fr({state:t.state,config:e,pi:t.activePi})){Wt(t);return}}catch(r){throw Si(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);Sk(t,r??[])}catch(r){if(Si(t,r),r instanceof bt)throw r}}async function VH(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Wt(t),zt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){_k(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),Wt(t);return}if(await Oo(r,n),o()){Wt(t);return}try{if((await Promise.all(e.servers.map(c=>Fr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Wt(t);return}}catch(a){throw Si(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()){Wt(t);return}_k(r,e),Sk(t,i??[])}function BH(t,e){if(typeof e=="string")return yk(e,t.workspaceRoot??process.cwd())}function wk(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(!Oi({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=$i({state:r,domain:We(i),forceNew:!0}),c=UH(r),u=r.currentLoad?.latestPi??e,d=r.registryGeneration;r.liveEditGenerations??=new Map;let l=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,l);let p=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,f={state:r,configId:i,activePi:u,connect:o?.connect??St,report:o?.report??J,intentEpoch:a.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>vk(r,i)},h=BH(r,s?.embeddedConfig),m;if(h)m=ZH(f,h);else{let y=r.credentials;y?m=(o?.discover??Qc)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(w=>VH(f,w)).catch(w=>{if(!(w instanceof bt)){Si(f,w);return}throw w}):(zt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Wt(f),m=Promise.resolve())}return Ni({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>vk(r,i)})}import{logger as WH}from"@hermes/logger";var Kt=WH.child({prefix:"pi-mcp"});function Rk(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function Pk(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?wt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ge(e,r),"retiring"):void 0:(be({state:e,name:r,owner:n.owner,revision:n.revision}),Ge(e,r),"released");let c=a.get(r),u=Mo({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return s&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ge(e,r),leaseRevision:u.lease.revision}}function KH(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=Pk({state:e,name:r,lease:c,host:n,isDeselected:Rk({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:s});if(d===void 0)return;d!=="released"&&d!=="retiring"&&i.set(r,d);let l=Z(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&be({state:e,name:r,owner:c.owner,revision:c.revision})},p=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:p}}),p})}function JH(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=Pk({state:e,name:r,lease:n,isDeselected:Rk({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function YH(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=KH({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||JH({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function Ck(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let p=t.registryConfigNamesById.get(l);return p===void 0?[]:[p]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,p]of t.registryCredentialConfigs){let f=i.get(l);if(f===void 0&&p.id!==void 0&&n.has(p.id)&&!u.has(p.id)){i.set(l,p);continue}let h=p.id===void 0?c.has(l):a.has(p.id);f===void 0&&!h&&s.push(ct(t,l,p.id,p))}try{await Promise.all(s)}catch(l){let p=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new bt(p)}let d=new Map;for(let[l,p]of i){let f=t.registryCredentialConfigs.get(l);f&&(d.set(l,{...f}),Ve(f,p)&&p.id!==void 0&&t.registryCredentialConfigsById.set(p.id,{...p}))}t.registryCredentialConfigs=d}function XH(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:p}]of t.allConfigsById)n&&!n.has(l)||u.has(p)||d.has(p)||(d.add(p),a.push(p));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function QH(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return eu(n,e.workspaceRoot??process.cwd())}async function eG(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),s=[],i=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(We(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(ct(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new bt(c)}}function tG(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 rG(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function nG(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 oG(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 Ck(e,r.servers,n,s,o!==void 0)}async function xk(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():Oo(t,r.id)))}async function bk(t){return await xk(t.state,t.result),t.state.registryGeneration===t.generation&&await oG(t),t.result}function sG(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Kt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=XH(n,r,s);return bk({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=>bk({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function iG(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Kt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Kt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function aG(t){let{state:e,result:r}=t,n=r.servers.map(s=>{let i=e.sessionRegistryDisabledOverrides.get(s.name);return i===void 0?s:{...s,disabled:i}}),o=new Set([...n.map(s=>s.name),...r.retainedNames??[]]);for(let s of e.sessionRegistryDisabledOverrides.keys())o.has(s)||e.sessionRegistryDisabledOverrides.delete(s);return n}function cG(t){let{state:e,generation:r}=t;return n=>{if(e.registryGeneration!==r||n.id===void 0)return e.registryGeneration===r;let o=e.missingHostRemovalFences.get(n.id);return!e.sessionRemovedConfigIds.has(n.id)&&o?.registryGeneration!==r}}function Ih(t){let{state:e,result:r,selection:n,slotReservations:o}=t,s=new Set([...r.servers.map(i=>i.name),...r.retainedNames??[],...(n??[]).flatMap(i=>{let a=e.registryConfigNamesById.get(i);return a?[a]:[]})]);for(let[i,a]of o){if(s.has(i))continue;let c=Z(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&be({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function uG(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){Ih({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),Kt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await xk(e,r),e.registryGeneration!==o)return;let c=cG({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>Fr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;iG({state:e,result:r,selection:n}),Ih({state:e,result:r,selection:n,slotReservations:a});let l=aG({state:e,result:{...r,servers:u}});if(l.length===0)return;let p=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):Z(e,m.name))?.owner.kind==="local")return Kt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let w=a.get(m.name)?.configRevision;if(w===void 0)return!0;let b=e.configDesiredRevisions.get(m.name);return b!==w?(Kt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${w} to ${b} by a concurrent operation`),!1):!0});if(p.length===0)return;Kt.info(`Registry discovery: connecting ${p.length} server(s)`);let h=(await s(p,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error))}async function dG(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Kt.warn(i),e.registryGeneration===n&&(await Ck(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function lG(t,e){for(let r of e??[]){let n=We(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Be({state:t,domain:n,epoch:o?.epoch})}}async function pG(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await uG({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),Ih({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 bt)throw lG(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 dG({...t.resultArgs,error:r})}}function kk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??Qc,i=o?.connect??St,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Kt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&tm(r,new Set(a.configIds.map(We)));let c=QH({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Kt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let S of a.configIds??[])Be({state:r,domain:We(S)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=eG({state:r,previousSelectedIds:d,configIds:a.configIds}),p=tG({parsedEmbedded:c,configIds:a.configIds}),f=++r.registryGeneration,h=Promise.all([YH(r,a.configIds,p),l]).then(([S])=>S);rG(r);let m=a.configIds?[...a.configIds]:void 0,y=sG({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:nG(r),previousSelectedIds:d,selection:m,generation:f,discover:s});return y?pG({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:f,connect:i,pi:e}}):Promise.resolve()}import{logger as fG}from"@hermes/logger";var Dr=fG.child({prefix:"pi-mcp"});function hG(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 mG(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function $k(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function gG(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function Ek(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&&(gG({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 Mk(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function Tk(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 Ik(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function yG(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?kn(n):void 0;if(s===void 0){Ge(e,r);return}let a=s.host===void 0&&s.owner.kind==="registry"&&i?.kind==="registry"&&s.owner.identity===i.identity,c=o?.incumbent.owner.kind==="registry"&&i?.kind==="registry"&&o.incumbent.owner.identity===i.identity;if(!a&&!c)return;(o?.settled&&s.retirement===o?Gh({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):be({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(Ik(e,r),Ge(e,r))}async function zh(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Dr.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=kn(i),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,p=e.configDesiredRevisions.get(a),f=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ge(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=Z(e,a)?.retirement===d?d:void 0,S=y?.result;if(d&&S?.status==="failed"&&S.transportDisposed!==!0){let w=S.error instanceof Error?S.error:new Error(String(S.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Dr.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await zo(e,a,r,i)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(p===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,p),f===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,f));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw Dr.warn(b),e.diagnostics.push({server:a,message:b}),w}$k({state:e,configId:r,fence:s})&&(Mk(e,r),yG({state:e,name:a,config:i,retirement:y})),Dr.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 Ak(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)}`;Dr.warn(s),e.diagnostics.push({server:r,message:s})}async function vG(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(Ak({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([zo(e,r,n,o.config)]);return Ak({state:e,name:r,operation:"detach",result:i}),i.status==="fulfilled"?{removed:!0,failure:void 0,transportDisposed:!0}:{removed:!1,failure:i.reason,transportDisposed:!0}}async function _G(t){let{state:e,configId:r,name:n,pi:o,report:s,sourceFence:i}=t,a=e.servers.get(n),c=a?Q(e,n,a):Z(e,n);if(!a||!c||c.owner.kind!=="registry"||c.host!==a)return;e.registryConfigNamesById.set(r,n),e.registryCredentialConfigsById.set(r,{...a.config});let u=e.configDesiredRevisions.get(n),d=e.configDesiredSources.get(n),l=Ge(e,n),p=wt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!p)return;a.beginDisposal?.(),Dr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let f=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await vG({state:e,name:n,configId:r,server:a});if(h&&$k({state:e,configId:r,fence:i})?Mk(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),we({state:e,name:n,retirement:p,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&be({state:e,name:n,owner:c.owner,revision:c.revision})&&Ik(e,n),s(f,e),!h)throw m}function zk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Dr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Oi({state:r,configId:i,generation:s?.attachmentGeneration}))return Dr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Ni({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=Tk(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,p=r.missingHostRemovals.get(i),f=p?.registryGeneration===r.registryGeneration&&p?.liveEditGeneration===r.liveEditGenerations.get(i);if(f&&l===void 0)return a(p.promise);if(f&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(Ek({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>zh({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=hG(r,i);if(u===void 0&&d===void 0)return a(zh({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=mG({state:r,configId:i,liveEditGeneration:h});return a(Ek({state:r,configId:i,fence:m,operation:()=>{let y=Tk(r,i);return y===void 0?zh({state:r,configId:i,pi:e,report:c,sourceFence:m}):_G({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as SG}from"@hermes/logger";var wi=SG.child({prefix:"pi-mcp"}),Ok=3,Nk=6e4,wG=1e3,bG=8e3;function Oh(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Nr,i=o?.now??Date.now,a=o?.sleep??Vr,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return wi.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return wi.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),p=r.mcpRestartState.get(d),f=p&&l-p.lastRestart<Nk?p.count+1:1,h=r.currentLoad?.latestPi??e;if(f>Ok)return wi.warn(`augment:mcp-restart-server: ${d} exceeded ${Ok} restarts within ${Nk}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:f,lastRestart:l});let m=Math.min(wG*2**(f-1),bG);return(f>1?a(m):Promise.resolve()).then(()=>(wi.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(S=>{let w=`Live MCP restart-server failed for ${d}: ${S instanceof Error?S.message:String(S)}`;wi.warn(w),r.diagnostics.push({server:d,message:w})}).then(()=>{c(h,r)})}import{logger as RG}from"@hermes/logger";var bi=RG.child({prefix:"pi-mcp"}),PG=/^\d+$/,Nh=1,Dk="AUGMENT_ACTIVE_SPACE_ID",CG="augment-mcp-access-token-";function tu(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function Lk(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 ru=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??Cu}lookupBody(e){let r={name:e};return!e.startsWith(CG)&&Object.hasOwn(process.env,Dk)&&(r.active_space_id=process.env[Dk]??""),r}getSecret(e){let r=tu(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 Br(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=tu(e),i=(await this._callUpsert({name:o,value:r,scope:Nh,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!PG.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),bi.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await Br(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=tu(e);this.cache.delete(r),await this._callDelete({name:r,scope:Nh}),bi.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>Jt?`${o.slice(0,Jt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Jt?`${o.slice(0,Jt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=tu(e);try{let n=await Br(()=>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===Nh||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:Lk(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof dt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&bi.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await Br(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:Lk(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof dt&&o.statusCode===404)return bi.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return bi.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>Jt?`${s.slice(0,Jt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}};function Dh(t){return{latestPi:t}}import{randomUUID as xG}from"node:crypto";import{setToolSource as kG}from"@augmentcode/auggie-v2";import{logger as EG}from"@hermes/logger";import{Type as TG}from"@sinclair/typebox";var Uk=EG.child({prefix:"pi-mcp"}),nu="attach-mcp-server",AG="augment:mcp-attach-request",$G=15e3,MG={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 IG(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[];return o.find(s=>s.id===r)??o.find(s=>s.name.toLowerCase()===n)}function zG(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},$G);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function jk(t){let e=Lo(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function OG(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return Re(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return Re(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.`)}function NG(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return Re(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,Re("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return Re(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return Re(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return Re(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return Re(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.`);case"NO_ACTIVE_VM":return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return Re(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function DG(t,e,r){if(e.mcpAttachDisabled)return Re("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${nu} requires a string "config_id" parameter. ${jk(e)}`);let o=IG(e,n);if(!o)return Re(`No MCP server matching "${n}" is available to attach. ${jk(e)}`);let s=OG({entry:o,state:e});if(s!==void 0)return s;if(Ru(e,o))return Re(`MCP server "${o.name}" is already attached to this session. Use find-tool to discover its tools.`);if(o.state!=="available"&&o.state!=="opt_in_required")return Re(`MCP server "${o.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let i=xG();Uk.info(`attach-mcp-server: requesting attach of "${o.name}" (config=${o.id} request=${i})`);let a=zG(e,i);t.events.emit(AG,{configId:o.id,requestId:i});let c=await a;return NG({entry:o,result:c,state:e})}function Lh(t,e){let r={name:nu,label:nu,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:TG.Unsafe(MG),execute:(n,o)=>DG(t,e,o)};kG(nu,"mcp"),t.registerTool(r),Uk.debug("Registered attach-mcp-server tool")}import{logger as LG}from"@hermes/logger";var Eo=LG.child({prefix:"pi-mcp"});async function jG(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=wt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ge(t,r);let i=ct(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),be({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function UG(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),Eo.warn(r.message))}function FG(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"}),Eo.warn(a);return}try{let a=Tn(r,n);return{...a.type==="stdio"?Dt(a,i):Nt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Rt?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"}),Eo.warn(c);return}}function qG(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=FG({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function HG(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function Fk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??St,i=n;if(!i||typeof i!="object"||Array.isArray(i))return Eo.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&&HG(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=jG(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;UG(r,i.diagnostics);let{servers:l,blockedNames:p}=qG(r,i);return u=p,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=p),!1):(Eo.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(f=>{let h=f?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(f??[]).some(y=>y.config===m&&Fc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let p=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;Eo.warn(p),r.vfsGeneration===c&&r.diagnostics.push({message:p,origin:"vfs"})})}var at=GG.child({prefix:"pi-mcp"}),Zk="augment:mcp-oauth-credentials",qk="augment:mcp-header-secrets",Hk="augment:credentials",ZG="augment:mcp-config-ids",Gk="augment:mcp-configs",VG="augment:mcp-vfs-servers",BG="augment:mcp-add-server",WG="augment:mcp-restart-server",KG="augment:mcp-remove-server";function JG(t){if(!t.secretsClient||t.tokens instanceof qo)return;let e=t.tokens;t.tokens=new qo(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),at.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function YG(t){if(!t||typeof t!="object"){at.warn(`${Zk} 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 XG(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){dx({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=sZ({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)){Oh({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";at.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function QG(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(Zk,r=>{let n=YG(r);n&&XG({pi:t,state:e,payload:n})}))}function eZ(t){let{state:e,name:r,revision:n}=t,o=ut(n.domain);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id;return s===void 0&&i===void 0?a?.config.registrySource!==void 0&&c!==void 0&&We(c)===o:s?.kind==="domain"&&s.domain===o||i===n.domain}function tZ(t){let{state:e,domain:r}=t,n=ut(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function rZ(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=Cn(i);if(a===void 0){o[s]=i;continue}if(tZ({state:e,domain:a.domain})){rm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(eZ({state:e,name:s,revision:a})){o[s]=i;continue}em({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function nZ(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=Cn(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 oZ(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"&&Nr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Oe(r)})}}function sZ(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=rZ({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 nZ({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(at.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),oZ({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function iZ(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(qk,r=>{if(!r||typeof r!="object"||Array.isArray(r)){at.warn(`${qk} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);Og(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}))}function aZ(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(Hk,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){at.warn(`${Hk} 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 ru(e.credentials),JG(e)}),t.events.on(ZG,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,Lh(e.currentLoad?.latestPi??t,e)),kk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{at.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;Oe(e),Jc(n,e)})}))}function cZ(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(Gk,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){at.warn(`${Gk} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=eu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&Fr({state:e,config:i,pi:t}).catch(a=>{at.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}at.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function uZ(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(VG,r=>{Fk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Oe(e)})}))}function dZ(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(BG,r=>{wk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{at.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;Oe(e),Jc(n,e)})}))}function lZ(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(WG,r=>{Oh({pi:t,state:e,data:r}).then(()=>{Oe(e)})}))}function pZ(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(KG,r=>{zk({pi:t,state:e,data:r}).catch(n=>{at.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Oe(e),Jc(n,e)})}))}function IY(t){return Ig(t)}function zY(t){let e=se();e.currentLoad=Dh(t);let r=!1;uk(t,e),QG(t,e),iZ(t,e),aZ(t,e),cZ(t,e),uZ(t,e),dZ(t,e),lZ(t,e),pZ(t,e),lk(t,e),pk(t,e),e.mcpAttachCloudSignaled&&Lh(t,e),t.on("session_start",(n,o)=>{e.currentLoad=Dh(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)Mn(e)?(Zr(t),ji(t)):mm(t,e),Oe(e);else{e.connectStarted=!0,No()&&Zr(t);let{servers:i,diagnostics:a}=An(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),at.warn(c.message);St(i,e,t).then(()=>ax(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Oe(e)})}r||(r=!0,t.events.emit(Ix,Lx(t,e)))}),t.on("session_shutdown",()=>{mk(e)})}export{zY as default,IY as setMcpErrorReporter};
149
+ `)}function CH(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(Th.includes(e))return e}async function xH(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=vi([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function hk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return Th.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 pk(n,e,i=>vi([i],e,t),{classify:i=>Gx({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>Zx({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Bx({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)=>Ax({serverName:i,state:e,pi:t,controller:a}));return}let s=CH(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${Th.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(PH(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await xH(n,e,t)}})}import{logger as kH}from"@hermes/logger";var mk=kH.child({prefix:"pi-mcp"}),Ah="augment:feature-flags";function EH(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 gk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(Ah,r=>{let n=EH(r);if(n===void 0){mk.warn(`${Ah} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,mk.debug(`Received feature-flag snapshot via ${Ah} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as TH}from"@hermes/logger";var Jc=TH.child({prefix:"pi-mcp"}),$h="augment:mcp-attach-result";function yk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on($h,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){Jc.warn(`${$h} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){Jc.debug(`${$h}: no pending resolver for request ${o} (already timed out?)`);return}let i={...typeof n?.status=="string"?{status:n.status}:{},...typeof n?.error=="string"?{error:n.error}:{}};s(i)}))}function Yc(t,e){if(!e.mcpAttachCloudSignaled||e.mcpAttachDisabled||!e.credentials)return Promise.resolve();if(e.catalogRefreshInFlight)return e.catalogRefreshInFlight;let r=e.credentials,n=(async()=>{let o=await Pm(r);o.ok?(e.mcpCatalog=o.entries,Jc.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,Jc.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),In(e)&&Br(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as AH}from"@hermes/logger";var Si=AH.child({prefix:"pi-mcp"}),vk=300*1e3,Mh=600*1e3;function $H(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&&(Go(o,e)||o.expiresAt>e+Mh||(Si.debug(`Background refresh: token for MCP server "${r.name}" expires within ${Mh}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&Si.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{Si.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function _k(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{$H(t)},vk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,Si.debug(`Started background MCP OAuth refresh loop (interval ${vk}ms, buffer ${Mh}ms)`)}function Sk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,Si.debug("Stopped background MCP OAuth refresh loop"))}import{logger as ZH}from"@hermes/logger";function MH(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Lo.OAUTH:return"oauth";case Lo.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 IH(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case Hr.CLI:return"cli";case Hr.CLOUD_AGENT:return"cloud_agent";default:return}switch(t){case"MCP_PRODUCT_TYPE_CLI":return"cli";case"MCP_PRODUCT_TYPE_CLOUD_AGENT":return"cloud_agent";default:return}}function Xc(t){if(t==null)return;if(t.length===0)return[];let e=t.map(IH).filter(r=>r!==void 0);return e.length===0?void 0:e}function Qc(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=MH(r.auth_type),o={name:r.name,type:r.type==="http"||r.type==="sse"||r.type==="stdio"?r.type:void 0,disabled:r.disabled,command:r.command,args:r.args,env:r.env,url:r.url,auth:n==="oauth"?"oauth":void 0,timeoutMs:r.timeout_ms,useShellInterpolation:r.use_shell_interpolation},s=Tn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...An(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof Rt?i.message:String(i)}}}function zH(t){let e=t.config?.auth_type;return e===Lo.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function OH(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 Ih(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 NH(t,e,r){if(r!==void 0&&t.added_by===r)return Xc(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?Xc(n):[]}function DH(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let f=Ih(e,r,()=>!0);return{selected:[],filteredOutIds:f.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let f=new Set(s),h=Ih(e,r,()=>!0),m=new Set(h.map(b=>b.id)),y=h.filter(b=>f.has(b.id)),S=h.filter(b=>!f.has(b.id)).map(b=>b.id),w=s.filter(b=>!m.has(b));return{selected:y,filteredOutIds:S,missingIds:w,retainedNames:[]}}let a=new Set(n),c=[];for(let f of e)a.has(f.id)||c.push(f.id);let u=Ih(e,r,f=>a.has(f)),d=new Set(r.map(f=>f.id)),l=[],p=[];for(let f of u){let m=!d.has(f.id)&&a.has(f.id)?NH(f,o,i):Xc(f.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(f):(c.push(f.id),f.config?.name&&p.push(f.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:p}}function LH(t){return t==null?Hr.CLOUD_AGENT:void 0}function jH(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 UH(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Dt(t,n):Nt(t,n)}}catch(o){let s=o instanceof Error?o.message:String(o);return{ok:!1,diagnostic:{server:t.name,message:`Skipped registry MCP server "${t.name}" (id=${e}, ${r}): ${s}`}}}}function FH(t){let{payload:e,userIds:r,localServerNames:n,seenNames:o,workspaceRoot:s}=t;if(e.config?.disabled)return e.config.name?{kind:"retained",name:e.config.name}:{kind:"dropped"};let i=r.has(e.id)?"user":"tenant",a=Qc(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){let d=n.has(c.name)?`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`;return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:d}}}let u=UH(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 qH(t){let e=[],r=[],n=[];for(let o of t)zH(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 HH(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=OH(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}async function eu(t){let e=t.client??new qi(t.creds),{tenant:r,user:n,diagnostics:o}=await Nm(e,LH(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=DH({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=qH(a),p=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...jH(u));let f=[],h=new Set(t.localServerNames),m=[...p.filter(w=>i.has(w.id)),...p.filter(w=>!i.has(w.id))];for(let w of m){let b=FH({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:h,workspaceRoot:t.workspaceRoot});b.kind!=="connected"&&b.diagnostic&&o.push(b.diagnostic),b.kind==="connected"?f.push(b.server):b.kind==="retained"&&d.push(b.name)}let y=HH(f);d.push(...y.droppedNames),o.push(...y.diagnostics);let S=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&S.set(w.id,w.config.name);return{servers:y.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:S}}import{logger as GH}from"@hermes/logger";var Eo=GH.child({prefix:"pi-mcp"});function wk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Eo.warn("Embedded MCP config is missing an id; ignoring");return}let n=Qc(r,"tenant");if(!n.ok){Eo.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Dt(n.server,o):Nt(n.server,o)}catch(s){Eo.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function bk(t,e){let r;try{r=JSON.parse(t)}catch(n){Eo.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return wk(r,e)}function tu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Eo.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Eo.warn("Embedded MCP configs payload is not an array; ignoring");return}let n=[],o=new Map,s=!1;for(let i of r){let a=i,c=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 zt=ZH.child({prefix:"pi-mcp"});function BH(t,e,r){t.dynamicallyAddedConfigIds.add(e),t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.sessionRemovedConfigIds.delete(e);for(let n of r)n.id!==void 0&&(t.registryConfigNamesById.set(n.id,n.name),t.registryCredentialConfigsById.set(n.id,{...n}))}function Wt(t){Ve({state:t.state,domain:We(t.configId),epoch:t.intentEpoch})}function VH(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 Rk(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function Pk(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 wi(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;Wt(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(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 WH(t,e){return e.flatMap(r=>qc(t,r)?[r.config]:[])}function KH(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function JH(t,e){let r=KH(e);if(r){if(wi(t,r.error),r.error instanceof bt)throw r.error;return}let n=WH(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){BH(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 Ck(t,e){try{JH(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function YH(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 XH(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await No(t.state,t.configId),t.superseded()){Wt(t);return}if(YH(t,e)){Wt(t);return}try{if(!await qr({state:t.state,config:e,pi:t.activePi})){Wt(t);return}}catch(r){throw wi(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);Ck(t,r??[])}catch(r){if(wi(t,r),r instanceof bt)throw r}}async function QH(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){Wt(t),zt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){Pk(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),Wt(t);return}if(await No(r,n),o()){Wt(t);return}try{if((await Promise.all(e.servers.map(c=>qr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){Wt(t);return}}catch(a){throw wi(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()){Wt(t);return}Pk(r,e),Ck(t,i??[])}function eG(t,e){if(typeof e=="string")return bk(e,t.workspaceRoot??process.cwd())}function xk(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(!Ni({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=Mi({state:r,domain:We(i),forceNew:!0}),c=VH(r),u=r.currentLoad?.latestPi??e,d=r.registryGeneration;r.liveEditGenerations??=new Map;let l=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,l);let p=()=>r.registryGeneration!==d||r.liveEditGenerations.get(i)!==l,f={state:r,configId:i,activePi:u,connect:o?.connect??St,report:o?.report??J,intentEpoch:a.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>Rk(r,i)},h=eG(r,s?.embeddedConfig),m;if(h)m=XH(f,h);else{let y=r.credentials;y?m=(o?.discover??eu)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:c}).then(w=>QH(f,w)).catch(w=>{if(!(w instanceof bt)){wi(f,w);return}throw w}):(zt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),Wt(f),m=Promise.resolve())}return Di({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>Rk(r,i)})}import{logger as tG}from"@hermes/logger";var Kt=tG.child({prefix:"pi-mcp"});function Ek(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function Tk(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?wt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ge(e,r),"retiring"):void 0:(be({state:e,name:r,owner:n.owner,revision:n.revision}),Ge(e,r),"released");let c=a.get(r),u=Io({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return s&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ge(e,r),leaseRevision:u.lease.revision}}function rG(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=Tk({state:e,name:r,lease:c,host:n,isDeselected:Ek({selectedIds:o,config:n.config}),selectionIsEmpty:o?.size===0,replacementOwners:s});if(d===void 0)return;d!=="released"&&d!=="retiring"&&i.set(r,d);let l=Z(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&be({state:e,name:r,owner:c.owner,revision:c.revision})},p=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:p}}),p})}function nG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=Tk({state:e,name:r,lease:n,isDeselected:Ek({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=rG({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||nG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function Ak(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let p=t.registryConfigNamesById.get(l);return p===void 0?[]:[p]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,p]of t.registryCredentialConfigs){let f=i.get(l);if(f===void 0&&p.id!==void 0&&n.has(p.id)&&!u.has(p.id)){i.set(l,p);continue}let h=p.id===void 0?c.has(l):a.has(p.id);f===void 0&&!h&&s.push(ct(t,l,p.id,p))}try{await Promise.all(s)}catch(l){let p=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new bt(p)}let d=new Map;for(let[l,p]of i){let f=t.registryCredentialConfigs.get(l);f&&(d.set(l,{...f}),Be(f,p)&&p.id!==void 0&&t.registryCredentialConfigsById.set(p.id,{...p}))}t.registryCredentialConfigs=d}function sG(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:p}]of t.allConfigsById)n&&!n.has(l)||u.has(p)||d.has(p)||(d.add(p),a.push(p));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function iG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return tu(n,e.workspaceRoot??process.cwd())}async function aG(t){let{state:e,previousSelectedIds:r,configIds:n}=t;if(!n)return;let o=new Set(n),s=[],i=[];for(let a of r){if(o.has(a))continue;let c=e.registryConfigNamesById.get(a),u=[...o].some(d=>e.registryCredentialIntents.get(We(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(ct(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new bt(c)}}function cG(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 uG(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function dG(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 lG(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 Ak(e,r.servers,n,s,o!==void 0)}async function $k(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():No(t,r.id)))}async function kk(t){return await $k(t.state,t.result),t.state.registryGeneration===t.generation&&await lG(t),t.result}function pG(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){Kt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=sG(n,r,s);return kk({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=>kk({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function fG(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),Kt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&Kt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function hG(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 mG(t){let{state:e,generation:r}=t;return n=>{if(e.registryGeneration!==r||n.id===void 0)return e.registryGeneration===r;let o=e.missingHostRemovalFences.get(n.id);return!e.sessionRemovedConfigIds.has(n.id)&&o?.registryGeneration!==r}}function zh(t){let{state:e,result:r,selection:n,slotReservations:o}=t,s=new Set([...r.servers.map(i=>i.name),...r.retainedNames??[],...(n??[]).flatMap(i=>{let a=e.registryConfigNamesById.get(i);return a?[a]:[]})]);for(let[i,a]of o){if(s.has(i))continue;let c=Z(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&be({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function gG(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){zh({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),Kt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await $k(e,r),e.registryGeneration!==o)return;let c=mG({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>qr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;fG({state:e,result:r,selection:n}),zh({state:e,result:r,selection:n,slotReservations:a});let l=hG({state:e,result:{...r,servers:u}});if(l.length===0)return;let p=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):Z(e,m.name))?.owner.kind==="local")return Kt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let w=a.get(m.name)?.configRevision;if(w===void 0)return!0;let b=e.configDesiredRevisions.get(m.name);return b!==w?(Kt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${w} to ${b} by a concurrent operation`),!1):!0});if(p.length===0)return;Kt.info(`Registry discovery: connecting ${p.length} server(s)`);let h=(await s(p,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error))}async function yG(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;Kt.warn(i),e.registryGeneration===n&&(await Ak(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function vG(t,e){for(let r of e??[]){let n=We(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),Ve({state:t,domain:n,epoch:o?.epoch})}}async function _G(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await gG({...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 bt)throw vG(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 yG({...t.resultArgs,error:r})}}function Mk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??eu,i=o?.connect??St,a=n;if(!a||typeof a!="object"||Array.isArray(a))return Kt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&rm(r,new Set(a.configIds.map(We)));let c=iG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){Kt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let S of a.configIds??[])Ve({state:r,domain:We(S)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=aG({state:r,previousSelectedIds:d,configIds:a.configIds}),p=cG({parsedEmbedded:c,configIds:a.configIds}),f=++r.registryGeneration,h=Promise.all([oG(r,a.configIds,p),l]).then(([S])=>S);uG(r);let m=a.configIds?[...a.configIds]:void 0,y=pG({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:dG(r),previousSelectedIds:d,selection:m,generation:f,discover:s});return y?_G({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:f,connect:i,pi:e}}):Promise.resolve()}import{logger as SG}from"@hermes/logger";var Lr=SG.child({prefix:"pi-mcp"});function wG(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 bG(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function Nk(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function RG(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function Ik(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&&(RG({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 Dk(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function zk(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 Lk(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function PG(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=Z(e,r),i=n?En(n):void 0;if(s===void 0){Ge(e,r);return}let a=s.host===void 0&&s.owner.kind==="registry"&&i?.kind==="registry"&&s.owner.identity===i.identity,c=o?.incumbent.owner.kind==="registry"&&i?.kind==="registry"&&o.incumbent.owner.identity===i.identity;if(!a&&!c)return;(o?.settled&&s.retirement===o?Zh({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):be({state:e,name:r,owner:s.owner,revision:s.revision}))&&Z(e,r)===void 0&&(Lk(e,r),Ge(e,r))}async function Oh(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let w=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Lr.warn(w),e.diagnostics.push({message:w,origin:"registry"}),new Error(w)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=Z(e,a),u=En(i),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,p=e.configDesiredRevisions.get(a),f=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ge(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=Z(e,a)?.retirement===d?d:void 0,S=y?.result;if(d&&S?.status==="failed"&&S.transportDisposed!==!0){let w=S.error instanceof Error?S.error:new Error(String(S.error)),b=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Lr.warn(b),e.diagnostics.push({server:a,message:b}),w}try{await Oo(e,a,r,i)}catch(w){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(p===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,p),f===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,f));let b=`Live MCP remove-server failed to detach ${a}: ${w instanceof Error?w.message:String(w)}`;throw Lr.warn(b),e.diagnostics.push({server:a,message:b}),w}Nk({state:e,configId:r,fence:s})&&(Dk(e,r),PG({state:e,name:a,config:i,retirement:y})),Lr.info(`Live MCP remove-server: config id ${r} resolved to no live server (already removed or unknown id)`),o(e.currentLoad?.latestPi??n,e)}function Ok(t){let{state:e,name:r,operation:n,result:o}=t;if(o.status!=="rejected")return;let s=`Live MCP remove-server failed to ${n} ${r}: ${o.reason instanceof Error?o.reason.message:String(o.reason)}`;Lr.warn(s),e.diagnostics.push({server:r,message:s})}async function CG(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(Ok({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Oo(e,r,n,o.config)]);return Ok({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 xG(t){let{state:e,configId:r,name:n,pi:o,report:s,sourceFence:i}=t,a=e.servers.get(n),c=a?Q(e,n,a):Z(e,n);if(!a||!c||c.owner.kind!=="registry"||c.host!==a)return;e.registryConfigNamesById.set(r,n),e.registryCredentialConfigsById.set(r,{...a.config});let u=e.configDesiredRevisions.get(n),d=e.configDesiredSources.get(n),l=Ge(e,n),p=wt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!p)return;a.beginDisposal?.(),Lr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let f=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await CG({state:e,name:n,configId:r,server:a});if(h&&Nk({state:e,configId:r,fence:i})?Dk(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),we({state:e,name:n,retirement:p,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&be({state:e,name:n,owner:c.owner,revision:c.revision})&&Lk(e,n),s(f,e),!h)throw m}function jk(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Lr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Ni({state:r,configId:i,generation:s?.attachmentGeneration}))return Lr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Di({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=zk(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?Z(r,d.name)?.retirement:void 0,p=r.missingHostRemovals.get(i),f=p?.registryGeneration===r.registryGeneration&&p?.liveEditGeneration===r.liveEditGenerations.get(i);if(f&&l===void 0)return a(p.promise);if(f&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(Ik({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>Oh({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=wG(r,i);if(u===void 0&&d===void 0)return a(Oh({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=bG({state:r,configId:i,liveEditGeneration:h});return a(Ik({state:r,configId:i,fence:m,operation:()=>{let y=zk(r,i);return y===void 0?Oh({state:r,configId:i,pi:e,report:c,sourceFence:m}):xG({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as kG}from"@hermes/logger";var bi=kG.child({prefix:"pi-mcp"}),Uk=3,Fk=6e4,EG=1e3,TG=8e3;function Nh(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Dr,i=o?.now??Date.now,a=o?.sleep??Vr,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return bi.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return bi.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),p=r.mcpRestartState.get(d),f=p&&l-p.lastRestart<Fk?p.count+1:1,h=r.currentLoad?.latestPi??e;if(f>Uk)return bi.warn(`augment:mcp-restart-server: ${d} exceeded ${Uk} restarts within ${Fk}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:f,lastRestart:l});let m=Math.min(EG*2**(f-1),TG);return(f>1?a(m):Promise.resolve()).then(()=>(bi.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(S=>{let w=`Live MCP restart-server failed for ${d}: ${S instanceof Error?S.message:String(S)}`;bi.warn(w),r.diagnostics.push({server:d,message:w})}).then(()=>{c(h,r)})}import{logger as AG}from"@hermes/logger";var Ri=AG.child({prefix:"pi-mcp"}),$G=/^\d+$/,Dh=1,qk="AUGMENT_ACTIVE_SPACE_ID",MG="augment-mcp-access-token-";function ru(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function Hk(t,e){return e?.["augment:encoding"]!=="base64"?t:/^[A-Za-z0-9+/]*={0,2}$/.test(t)&&t.length%4===0?Buffer.from(t,"base64").toString("utf-8"):t}var nu=class{apiKey;apiUrl;userAgent;fetchImpl;timeoutMs;cache=new Map;inflight=new Map;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??xu}lookupBody(e){let r={name:e};return!e.startsWith(MG)&&Object.hasOwn(process.env,qk)&&(r.active_space_id=process.env[qk]??""),r}getSecret(e){let r=ru(e),n=this.inflight.get(r);if(n)return n;let o=this._resolve(r).finally(()=>{this.inflight.delete(r)});return this.inflight.set(r,o),o}upsertUserSecret(e,r,n){return Wr(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=ru(e),i=(await this._callUpsert({name:o,value:r,scope:Dh,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!$G.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),Ri.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await Wr(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=ru(e);this.cache.delete(r),await this._callDelete({name:r,scope:Dh}),Ri.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>Jt?`${o.slice(0,Jt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>Jt?`${o.slice(0,Jt)}\u2026[truncated]`:o;throw new dt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=ru(e);try{let n=await Wr(()=>this._callApi("/mcp-secrets/get",this.lookupBody(r))),o=n.secret?.value,s=n.secret?.version;if(o===void 0||s===void 0)return;let i=n.secret?.scope===Dh||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:Hk(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof dt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&Ri.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await Wr(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:Hk(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof dt&&o.statusCode===404)return Ri.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Ri.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>Jt?`${s.slice(0,Jt)}\u2026[truncated]`:s;throw new dt(o.status,o.statusText,i)}return await o.json()}};function Lh(t){return{latestPi:t}}import{randomUUID as IG}from"node:crypto";import{setToolSource as zG}from"@augmentcode/auggie-v2";import{logger as OG}from"@hermes/logger";import{Type as NG}from"@sinclair/typebox";var Zk=OG.child({prefix:"pi-mcp"}),ou="attach-mcp-server",DG="augment:mcp-attach-request",LG=15e3,jG={type:"object",properties:{config_id:{type:"string",description:"Id (or name) of the MCP server to attach, as listed among the available unattached servers in find-tool's description."}},required:["config_id"]};function UG(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[];return o.find(s=>s.id===r)??o.find(s=>s.name.toLowerCase()===n)}function FG(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},LG);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function Gk(t){let e=jo(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function qG(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return Re(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return Re(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.`)}function HG(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return Re(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,Re("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return Re(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return Re(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return Re(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return Re(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.`);case"NO_ACTIVE_VM":return Re(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return Re(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function GG(t,e,r){if(e.mcpAttachDisabled)return Re("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${ou} requires a string "config_id" parameter. ${Gk(e)}`);let o=UG(e,n);if(!o)return Re(`No MCP server matching "${n}" is available to attach. ${Gk(e)}`);let s=qG({entry:o,state:e});if(s!==void 0)return s;if(Pu(e,o))return Re(`MCP server "${o.name}" is already attached to this session. Use find-tool to discover its tools.`);if(o.state!=="available"&&o.state!=="opt_in_required")return Re(`MCP server "${o.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let i=IG();Zk.info(`attach-mcp-server: requesting attach of "${o.name}" (config=${o.id} request=${i})`);let a=FG(e,i);t.events.emit(DG,{configId:o.id,requestId:i});let c=await a;return HG({entry:o,result:c,state:e})}function jh(t,e){let r={name:ou,label:ou,description:"Attach an available MCP server to this session so its tools become usable. Only servers listed as available-but-not-attached in find-tool's description can be attached. Call this tool immediately when the user's request needs one of those servers; it attaches directly without requiring user approval.",parameters:NG.Unsafe(jG),execute:(n,o)=>GG(t,e,o)};zG(ou,"mcp"),t.registerTool(r),gr(r),Zk.debug("Registered attach-mcp-server tool")}import{logger as ZG}from"@hermes/logger";var To=ZG.child({prefix:"pi-mcp"});async function BG(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=wt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ge(t,r);let i=ct(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),be({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function VG(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),To.warn(r.message))}function WG(t){let{state:e,name:r,stored:n,higherPriorityNames:o,blockedNames:s,workspaceRoot:i}=t;if(o.has(r)){s.add(r);let a=`VFS MCP server "${r}" ignored: a higher-priority server with the same name takes precedence`;e.diagnostics.push({server:r,message:a,origin:"vfs"}),To.warn(a);return}try{let a=An(r,n);return{...a.type==="stdio"?Dt(a,i):Nt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof Rt?a.message:`Failed to normalize VFS MCP server "${r}": ${a instanceof Error?a.message:String(a)}`;e.diagnostics.push({server:r,message:c,origin:"vfs"}),To.warn(c);return}}function KG(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=WG({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function JG(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function Bk(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??St,i=n;if(!i||typeof i!="object"||Array.isArray(i))return To.warn("augment:mcp-vfs-servers payload is not an object"),Promise.resolve();let a=typeof i.signature=="string"?i.signature:void 0;if(a!==void 0&&a===r.lastSuccessfulVfsMcpSignature&&JG(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=BG(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;VG(r,i.diagnostics);let{servers:l,blockedNames:p}=KG(r,i);return u=p,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=p),!1):(To.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(f=>{let h=f?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(f??[]).some(y=>y.config===m&&qc(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let p=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;To.warn(p),r.vfsGeneration===c&&r.diagnostics.push({message:p,origin:"vfs"})})}var at=YG.child({prefix:"pi-mcp"}),Jk="augment:mcp-oauth-credentials",Vk="augment:mcp-header-secrets",Wk="augment:credentials",XG="augment:mcp-config-ids",Kk="augment:mcp-configs",QG="augment:mcp-vfs-servers",eZ="augment:mcp-add-server",tZ="augment:mcp-restart-server",rZ="augment:mcp-remove-server";function nZ(t){if(!t.secretsClient||t.tokens instanceof Ho)return;let e=t.tokens;t.tokens=new Ho(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),at.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function oZ(t){if(!t||typeof t!="object"){at.warn(`${Jk} 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 sZ(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){mx({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=pZ({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)){Nh({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";at.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function iZ(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(Jk,r=>{let n=oZ(r);n&&sZ({pi:t,state:e,payload:n})}))}function aZ(t){let{state:e,name:r,revision:n}=t,o=ut(n.domain);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id;return s===void 0&&i===void 0?a?.config.registrySource!==void 0&&c!==void 0&&We(c)===o:s?.kind==="domain"&&s.domain===o||i===n.domain}function cZ(t){let{state:e,domain:r}=t,n=ut(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=xn(i);if(a===void 0){o[s]=i;continue}if(cZ({state:e,domain:a.domain})){nm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(aZ({state:e,name:s,revision:a})){o[s]=i;continue}tm({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function dZ(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=xn(s);i===void 0?(e.credentialRevisions.delete(o),e.hostedCredentialOwnership.delete(o)):(e.credentialRevisions.set(o,i),e.hostedCredentialOwnership.set(o,{...i,accessTokenOnly:s?.refresh_token===void 0})),e.statusFailureCategories.delete(o),e.authRefreshNeededReportKeys.delete(o),e.tokens.clearAuthRequired(o)}}function lZ(t){let{pi:e,state:r,seeded:n,suppressReconnect:o}=t;if(o)return;let s=r.currentLoad?.latestPi??e;for(let i of n){let a=r.servers.get(i),c=r.expectedCredentialDomains.get(i),u=Z(r,i),d=c?.kind!=="domain"||u?.owner.kind==="registry"&&u.owner.identity===c.domain;a&&d&&a.config.type!=="stdio"&&a.config.auth==="oauth"&&Dr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Oe(r)})}}function pZ(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=Hc(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return dZ({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(at.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),lZ({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function fZ(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(Vk,r=>{if(!r||typeof r!="object"||Array.isArray(r)){at.warn(`${Vk} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);Ug(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}))}function hZ(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(Wk,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){at.warn(`${Wk} payload missing apiKey or apiUrl`);return}e.credentials={apiKey:n.apiKey,apiUrl:n.apiUrl,...typeof n.userAgent=="string"?{userAgent:n.userAgent}:{},...typeof n.userId=="string"?{userId:n.userId}:{}},e.secretsClient=new nu(e.credentials),nZ(e)}),t.events.on(XG,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,jh(e.currentLoad?.latestPi??t,e)),Mk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{at.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;Oe(e),Yc(n,e)})}))}function mZ(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(Kk,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){at.warn(`${Kk} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=tu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&qr({state:e,config:i,pi:t}).catch(a=>{at.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}at.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function gZ(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(QG,r=>{Bk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Oe(e)})}))}function yZ(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(eZ,r=>{xk({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{at.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;Oe(e),Yc(n,e)})}))}function vZ(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(tZ,r=>{Nh({pi:t,state:e,data:r}).then(()=>{Oe(e)})}))}function _Z(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(rZ,r=>{jk({pi:t,state:e,data:r}).catch(n=>{at.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Oe(e),Yc(n,e)})}))}function ZY(t){return Lg(t)}var Yk=t=>{let e=se();e.currentLoad=Lh(t);let r=!1;hk(t,e),iZ(t,e),fZ(t,e),hZ(t,e),mZ(t,e),gZ(t,e),yZ(t,e),vZ(t,e),_Z(t,e),gk(t,e),yk(t,e),e.mcpAttachCloudSignaled&&jh(t,e),t.on("session_start",(n,o)=>{e.currentLoad=Lh(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,_k(e),e.connectStarted)In(e)?(Br(t),Ui(t)):Sm(t,e),Oe(e);else{e.connectStarted=!0,Do()&&Br(t);let{servers:i,diagnostics:a}=$n(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),at.warn(c.message);St(i,e,t).then(()=>px(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Oe(e)})}r||(r=!0,t.events.emit(Lx,Hx(t,e)))}),t.on("session_shutdown",()=>{Sk(e)})};gm(Yk);var BY=Yk;export{BY as default,ZY as setMcpErrorReporter};
150
150
  /*! Bundled license information:
151
151
 
152
152
  content-type/index.js: