@augmentcode/auggie 1.2.0-prerelease.202609081516 → 1.2.0-prerelease.202609090942

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 $E=Object.create;var bu=Object.defineProperty;var ME=Object.getOwnPropertyDescriptor;var IE=Object.getOwnPropertyNames;var OE=Object.getPrototypeOf,zE=Object.prototype.hasOwnProperty;var vr=(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}},Ru=(t,e)=>{for(var r in e)bu(t,r,{get:e[r],enumerable:!0})},NE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of IE(e))!zE.call(t,o)&&o!==r&&bu(t,o,{get:()=>e[o],enumerable:!(n=ME(e,o))||n.enumerable});return t};var ji=(t,e,r)=>(r=t!=null?$E(OE(t)):{},NE(e||!t||!t.__esModule?bu(r,"default",{value:t,enumerable:!0}):r,t));var Us=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 js=class{};K._CodeOrName=js;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var gn=class extends js{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=gn;var yt=class extends js{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 gn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=yt;K.nil=new yt("");function ob(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rf(r,e[n]),r.push(t[++n]);return new yt(r)}K._=ob;var tf=new yt("+");function sb(t,...e){let r=[Fs(t[0])],n=0;for(;n<e.length;)r.push(tf),rf(r,e[n]),r.push(tf,Fs(t[++n]));return fz(r),new yt(r)}K.str=sb;function rf(t,e){e instanceof yt?t.push(...e._items):e instanceof gn?t.push(e):t.push(mz(e))}K.addCodeArg=rf;function fz(t){let e=1;for(;e<t.length-1;){if(t[e]===tf){let r=pz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function pz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof gn||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 gn))return`"${t}${e.slice(1)}`}function hz(t,e){return e.emptyStr()?t:t.emptyStr()?e:sb`${t}${e}`}K.strConcat=hz;function mz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Fs(Array.isArray(t)?t.join(","):t)}function gz(t){return new yt(Fs(t))}K.stringify=gz;function Fs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Fs;function yz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new yt(`.${t}`):ob`[${t}]`}K.getProperty=yz;function vz(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=vz;function _z(t){return new yt(t.toString())}K.regexpCode=_z});var sf=R(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ValueScope=Ye.ValueScopeName=Ye.Scope=Ye.varKinds=Ye.UsedValueState=void 0;var Je=Us(),nf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Xa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Xa||(Ye.UsedValueState=Xa={}));Ye.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var Qa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.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}}};Ye.Scope=Qa;var ec=class extends Je.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(r)}[${n}]`}};Ye.ValueScopeName=ec;var Sz=(0,Je._)`\n`,of=class extends Qa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Sz:Je.nil}}get(){return this._scope}name(e){return new ec(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix: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,Je._)`${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=Je.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,Xa.Started);let d=r(u);if(d){let l=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const;s=(0,Je._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Je._)`${s}${d}${this.opts._n}`;else throw new nf(u);c.set(u,Xa.Completed)})}return s}};Ye.ValueScope=of});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=Us(),$t=sf(),Dr=Us();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Dr.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Dr.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Dr.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Dr.Name}});var oc=sf();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return oc.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return oc.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return oc.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return oc.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 cr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},af=class extends cr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.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=ho(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},tc=class extends cr{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=ho(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return nc(e,this.rhs)}},cf=class extends tc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},uf=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},df=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},lf=class extends cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ff=class extends cr{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=ho(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},qs=class extends cr{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)||(wz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_n(e,r.names),{})}},ur=class extends qs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},pf=class extends qs{},po=class extends ur{};po.kind="else";var yn=class t extends ur{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 po(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ib(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=ho(this.condition,e,r),this}get names(){let e=super.names;return nc(e,this.condition),this.else&&_n(e,this.else.names),e}};yn.kind="if";var vn=class extends ur{};vn.kind="for";var hf=class extends vn{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=ho(this.iteration,e,r),this}get names(){return _n(super.names,this.iteration.names)}},mf=class extends vn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.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=nc(super.names,this.from);return nc(e,this.to)}},rc=class extends vn{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=ho(this.iterable,e,r),this}get names(){return _n(super.names,this.iterable.names)}},Hs=class extends ur{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)}};Hs.kind="func";var Gs=class extends qs{render(e){return"return "+super.render(e)}};Gs.kind="return";var gf=class extends ur{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&&_n(e,this.catch.names),this.finally&&_n(e,this.finally.names),e}},Zs=class extends ur{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Zs.kind="catch";var Ws=class extends ur{render(e){return"finally"+super.render(e)}};Ws.kind="finally";var yf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new pf]}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 af(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new tc(e,r,n))}add(e,r){return this._leafNode(new cf(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new ff(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 yn(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 yn(e))}else(){return this._elseNode(new po)}endIf(){return this._endBlockNode(yn,po)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new hf(e),r)}forRange(e,r,n,o,s=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new mf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.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 rc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.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 rc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vn)}label(e){return this._leafNode(new uf(e))}break(e){return this._leafNode(new df(e))}return(e){let r=new Gs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Gs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new gf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Zs(s),r(s)}return n&&(this._currNode=o.finally=new Ws,this.code(n)),this._endBlockNode(Zs,Ws)}throw(e){return this._leafNode(new lf(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 Hs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Hs)}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 yn))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=yf;function _n(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function nc(t,e){return e instanceof q._CodeOrName?_n(t,e.names):t}function ho(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 wz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ib(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${vf(t)}`}L.not=ib;var bz=ab(L.operators.AND);function Rz(...t){return t.reduce(bz)}L.and=Rz;var Pz=ab(L.operators.OR);function Cz(...t){return t.reduce(Pz)}L.or=Cz;function ab(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${vf(e)} ${t} ${vf(r)}`}function vf(t){return t instanceof q.Name?t:(0,q._)`(${t})`}});var G=R(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var se=D(),xz=Us();function kz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=kz;function Ez(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(db(t,e),!lb(e,t.self.RULES.all))}j.alwaysValidSchema=Ez;function db(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]||hb(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=db;function lb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=lb;function Tz(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=Tz;function Az({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${t}${e}${(0,se.getProperty)(n)}`}j.schemaRefOrVal=Az;function $z(t){return fb(decodeURIComponent(t))}j.unescapeFragment=$z;function Mz(t){return encodeURIComponent(Sf(t))}j.escapeFragment=Mz;function Sf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Sf;function fb(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=fb;function Iz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=Iz;function cb({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?t(o,s,i):e(o,s,i),i):s instanceof se.Name?(e(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}j.mergeEvaluated={props:cb({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,se._)`${r} || {}`),wf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:pb}),items:cb({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function pb(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&wf(t,r,e),r}j.evaluatedPropsToName=pb;function wf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}j.setEvaluated=wf;var ub={};function Oz(t,e){return t.scopeValue("func",{ref:e,code:ub[e.code]||(ub[e.code]=new xz._Code(e.code))})}j.useFunc=Oz;var _f;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_f||(j.Type=_f={}));function zz(t,e,r){if(t instanceof se.Name){let n=e===_f.Num;return r?n?(0,se._)`"[" + ${t} + "]"`:(0,se._)`"['" + ${t} + "']"`:n?(0,se._)`"/" + ${t}`:(0,se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(t).toString():"/"+Sf(t)}j.getErrorPath=zz;function hb(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=hb});var dr=R(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var De=D(),Nz={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};bf.default=Nz});var Bs=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var Z=D(),sc=G(),Ue=dr();Le.keywordError={message:({keyword:t})=>(0,Z.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Z.str)`"${t}" keyword must be ${e} ($data)`:(0,Z.str)`"${t}" keyword is invalid ($data)`};function Dz(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=yb(t,e,r);n??(i||a)?mb(s,c):gb(o,(0,Z._)`[${c}]`)}Le.reportError=Dz;function Lz(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=yb(t,e,r);mb(o,a),s||i||gb(n,Ue.default.vErrors)}Le.reportExtraError=Lz;function jz(t,e){t.assign(Ue.default.errors,e),t.if((0,Z._)`${Ue.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Z._)`${Ue.default.vErrors}.length`,e),()=>t.assign(Ue.default.vErrors,null)))}Le.resetErrorsCount=jz;function Fz({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,Z._)`${Ue.default.vErrors}[${a}]`),t.if((0,Z._)`${i}.instancePath === undefined`,()=>t.assign((0,Z._)`${i}.instancePath`,(0,Z.strConcat)(Ue.default.instancePath,s.errorPath))),t.assign((0,Z._)`${i}.schemaPath`,(0,Z.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Z._)`${i}.schema`,r),t.assign((0,Z._)`${i}.data`,n))})}Le.extendErrors=Fz;function mb(t,e){let r=t.const("err",e);t.if((0,Z._)`${Ue.default.vErrors} === null`,()=>t.assign(Ue.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${Ue.default.vErrors}.push(${r})`),t.code((0,Z._)`${Ue.default.errors}++`)}function gb(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Z._)`new ${t.ValidationError}(${e})`):(r.assign((0,Z._)`${n}.errors`,e),r.return(!1))}var Sn={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function yb(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Z._)`{}`:Uz(t,e,r)}function Uz(t,e,r={}){let{gen:n,it:o}=t,s=[qz(o,r),Hz(t,r)];return Gz(t,e,s),n.object(...s)}function qz({errorPath:t},{instancePath:e}){let r=e?(0,Z.str)`${t}${(0,sc.getErrorPath)(e,sc.Type.Str)}`:t;return[Ue.default.instancePath,(0,Z.strConcat)(Ue.default.instancePath,r)]}function Hz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Z.str)`${e}/${t}`;return r&&(o=(0,Z.str)`${o}${(0,sc.getErrorPath)(r,sc.Type.Str)}`),[Sn.schemaPath,o]}function Gz(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([Sn.keyword,o],[Sn.params,typeof e=="function"?e(t):e||(0,Z._)`{}`]),c.messages&&n.push([Sn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Sn.schema,i],[Sn.parentSchema,(0,Z._)`${d}${l}`],[Ue.default.data,s]),u&&n.push([Sn.propertyName,u])}});var _b=R(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.boolOrEmptySchema=mo.topBoolOrEmptySchema=void 0;var Zz=Bs(),Wz=D(),Bz=dr(),Vz={message:"boolean schema is false"};function Kz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?vb(t,!1):typeof r=="object"&&r.$async===!0?e.return(Bz.default.data):(e.assign((0,Wz._)`${n}.errors`,null),e.return(!0))}mo.topBoolOrEmptySchema=Kz;function Jz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),vb(t)):r.var(e,!0)}mo.boolOrEmptySchema=Jz;function vb(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,Zz.reportError)(o,Vz,void 0,e)}});var Rf=R(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.getRules=go.isJSONType=void 0;var Yz=["string","number","integer","boolean","null","object","array"],Xz=new Set(Yz);function Qz(t){return typeof t=="string"&&Xz.has(t)}go.isJSONType=Qz;function eN(){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:{}}}go.getRules=eN});var Pf=R(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.shouldUseRule=Lr.shouldUseGroup=Lr.schemaHasRulesForType=void 0;function tN({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Sb(t,n)}Lr.schemaHasRulesForType=tN;function Sb(t,e){return e.rules.some(r=>wb(t,r))}Lr.shouldUseGroup=Sb;function wb(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))}Lr.shouldUseRule=wb});var Vs=R(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var rN=Rf(),nN=Pf(),oN=Bs(),N=D(),bb=G(),yo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(yo||(je.DataType=yo={}));function sN(t){let e=Rb(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}je.getSchemaTypes=sN;function Rb(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(rN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=Rb;function iN(t,e){let{gen:r,data:n,opts:o}=t,s=aN(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,nN.schemaHasRulesForType)(t,e[0]));if(i){let a=xf(e,n,o.strictNumbers,yo.Wrong);r.if(a,()=>{s.length?cN(t,e,s):kf(t)})}return i}je.coerceAndCheckDataType=iN;var Pb=new Set(["string","number","integer","boolean","null"]);function aN(t,e){return e?t.filter(r=>Pb.has(r)||e==="array"&&r==="array"):[]}function cN(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(xf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(Pb.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),kf(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),uN(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 OE=Object.create;var bu=Object.defineProperty;var zE=Object.getOwnPropertyDescriptor;var NE=Object.getOwnPropertyNames;var DE=Object.getPrototypeOf,LE=Object.prototype.hasOwnProperty;var vr=(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}},Ru=(t,e)=>{for(var r in e)bu(t,r,{get:e[r],enumerable:!0})},jE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of NE(e))!LE.call(t,o)&&o!==r&&bu(t,o,{get:()=>e[o],enumerable:!(n=zE(e,o))||n.enumerable});return t};var ji=(t,e,r)=>(r=t!=null?OE(DE(t)):{},jE(e||!t||!t.__esModule?bu(r,"default",{value:t,enumerable:!0}):r,t));var Us=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 js=class{};K._CodeOrName=js;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var gn=class extends js{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=gn;var yt=class extends js{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 gn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=yt;K.nil=new yt("");function ab(t,...e){let r=[t[0]],n=0;for(;n<e.length;)rf(r,e[n]),r.push(t[++n]);return new yt(r)}K._=ab;var tf=new yt("+");function cb(t,...e){let r=[Fs(t[0])],n=0;for(;n<e.length;)r.push(tf),rf(r,e[n]),r.push(tf,Fs(t[++n]));return _z(r),new yt(r)}K.str=cb;function rf(t,e){e instanceof yt?t.push(...e._items):e instanceof gn?t.push(e):t.push(bz(e))}K.addCodeArg=rf;function _z(t){let e=1;for(;e<t.length-1;){if(t[e]===tf){let r=Sz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Sz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof gn||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 gn))return`"${t}${e.slice(1)}`}function wz(t,e){return e.emptyStr()?t:t.emptyStr()?e:cb`${t}${e}`}K.strConcat=wz;function bz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Fs(Array.isArray(t)?t.join(","):t)}function Rz(t){return new yt(Fs(t))}K.stringify=Rz;function Fs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}K.safeStringify=Fs;function Pz(t){return typeof t=="string"&&K.IDENTIFIER.test(t)?new yt(`.${t}`):ab`[${t}]`}K.getProperty=Pz;function Cz(t){if(typeof t=="string"&&K.IDENTIFIER.test(t))return new yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}K.getEsmExportName=Cz;function xz(t){return new yt(t.toString())}K.regexpCode=xz});var sf=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Us(),nf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Xa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Xa||(Xe.UsedValueState=Xa={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Qa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=Qa;var ec=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=ec;var kz=(0,Ye._)`\n`,of=class extends Qa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?kz:Ye.nil}}get(){return this._scope}name(e){return new ec(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let d=a.get(i);if(d)return d}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Xa.Started);let d=r(u);if(d){let l=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${l} ${u} = ${d};${this.opts._n}`}else if(d=o?.(u))s=(0,Ye._)`${s}${d}${this.opts._n}`;else throw new nf(u);c.set(u,Xa.Completed)})}return s}};Xe.ValueScope=of});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=Us(),$t=sf(),Dr=Us();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return Dr._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return Dr.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return Dr.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return Dr.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return Dr.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return Dr.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return Dr.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return Dr.Name}});var oc=sf();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return oc.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return oc.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return oc.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return oc.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 cr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},af=class extends cr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.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=ho(this.rhs,e,r)),this}get names(){return this.rhs instanceof q._CodeOrName?this.rhs.names:{}}},tc=class extends cr{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=ho(this.rhs,e,r),this}get names(){let e=this.lhs instanceof q.Name?{}:{...this.lhs.names};return nc(e,this.rhs)}},cf=class extends tc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},uf=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},df=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},lf=class extends cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ff=class extends cr{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=ho(this.code,e,r),this}get names(){return this.code instanceof q._CodeOrName?this.code.names:{}}},qs=class extends cr{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)||(Ez(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_n(e,r.names),{})}},ur=class extends qs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},pf=class extends qs{},po=class extends ur{};po.kind="else";var yn=class t extends ur{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 po(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ub(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=ho(this.condition,e,r),this}get names(){let e=super.names;return nc(e,this.condition),this.else&&_n(e,this.else.names),e}};yn.kind="if";var vn=class extends ur{};vn.kind="for";var hf=class extends vn{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=ho(this.iteration,e,r),this}get names(){return _n(super.names,this.iteration.names)}},mf=class extends vn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.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=nc(super.names,this.from);return nc(e,this.to)}},rc=class extends vn{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=ho(this.iterable,e,r),this}get names(){return _n(super.names,this.iterable.names)}},Hs=class extends ur{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)}};Hs.kind="func";var Gs=class extends qs{render(e){return"return "+super.render(e)}};Gs.kind="return";var gf=class extends ur{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&&_n(e,this.catch.names),this.finally&&_n(e,this.finally.names),e}},Zs=class extends ur{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Zs.kind="catch";var Ws=class extends ur{render(e){return"finally"+super.render(e)}};Ws.kind="finally";var yf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new pf]}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 af(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new tc(e,r,n))}add(e,r){return this._leafNode(new cf(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==q.nil&&this._leafNode(new ff(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 yn(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 yn(e))}else(){return this._elseNode(new po)}endIf(){return this._endBlockNode(yn,po)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new hf(e),r)}forRange(e,r,n,o,s=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new mf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.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 rc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.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 rc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(vn)}label(e){return this._leafNode(new uf(e))}break(e){return this._leafNode(new df(e))}return(e){let r=new Gs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Gs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new gf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Zs(s),r(s)}return n&&(this._currNode=o.finally=new Ws,this.code(n)),this._endBlockNode(Zs,Ws)}throw(e){return this._leafNode(new lf(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 Hs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Hs)}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 yn))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=yf;function _n(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function nc(t,e){return e instanceof q._CodeOrName?_n(t,e.names):t}function ho(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 Ez(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ub(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,q._)`!${vf(t)}`}L.not=ub;var Tz=db(L.operators.AND);function Az(...t){return t.reduce(Tz)}L.and=Az;var $z=db(L.operators.OR);function Mz(...t){return t.reduce($z)}L.or=Mz;function db(t){return(e,r)=>e===q.nil?r:r===q.nil?e:(0,q._)`${vf(e)} ${t} ${vf(r)}`}function vf(t){return t instanceof q.Name?t:(0,q._)`(${t})`}});var G=R(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.checkStrictMode=j.getErrorPath=j.Type=j.useFunc=j.setEvaluated=j.evaluatedPropsToName=j.mergeEvaluated=j.eachItem=j.unescapeJsonPointer=j.escapeJsonPointer=j.escapeFragment=j.unescapeFragment=j.schemaRefOrVal=j.schemaHasRulesButRef=j.schemaHasRules=j.checkUnknownRules=j.alwaysValidSchema=j.toHash=void 0;var se=D(),Iz=Us();function Oz(t){let e={};for(let r of t)e[r]=!0;return e}j.toHash=Oz;function zz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pb(t,e),!hb(e,t.self.RULES.all))}j.alwaysValidSchema=zz;function pb(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]||yb(t,`unknown keyword: "${s}"`)}j.checkUnknownRules=pb;function hb(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}j.schemaHasRules=hb;function Nz(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=Nz;function Dz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${t}${e}${(0,se.getProperty)(n)}`}j.schemaRefOrVal=Dz;function Lz(t){return mb(decodeURIComponent(t))}j.unescapeFragment=Lz;function jz(t){return encodeURIComponent(Sf(t))}j.escapeFragment=jz;function Sf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}j.escapeJsonPointer=Sf;function mb(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}j.unescapeJsonPointer=mb;function Fz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}j.eachItem=Fz;function lb({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof se.Name?(s instanceof se.Name?t(o,s,i):e(o,s,i),i):s instanceof se.Name?(e(o,i,s),s):r(s,i);return a===se.Name&&!(c instanceof se.Name)?n(o,c):c}}j.mergeEvaluated={props:lb({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,se._)`${r} || {}`),wf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:gb}),items:lb({mergeNames:(t,e,r)=>t.if((0,se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function gb(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,se._)`{}`);return e!==void 0&&wf(t,r,e),r}j.evaluatedPropsToName=gb;function wf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,se._)`${e}${(0,se.getProperty)(n)}`,!0))}j.setEvaluated=wf;var fb={};function Uz(t,e){return t.scopeValue("func",{ref:e,code:fb[e.code]||(fb[e.code]=new Iz._Code(e.code))})}j.useFunc=Uz;var _f;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(_f||(j.Type=_f={}));function qz(t,e,r){if(t instanceof se.Name){let n=e===_f.Num;return r?n?(0,se._)`"[" + ${t} + "]"`:(0,se._)`"['" + ${t} + "']"`:n?(0,se._)`"/" + ${t}`:(0,se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(t).toString():"/"+Sf(t)}j.getErrorPath=qz;function yb(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=yb});var dr=R(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var De=D(),Hz={data:new De.Name("data"),valCxt:new De.Name("valCxt"),instancePath:new De.Name("instancePath"),parentData:new De.Name("parentData"),parentDataProperty:new De.Name("parentDataProperty"),rootData:new De.Name("rootData"),dynamicAnchors:new De.Name("dynamicAnchors"),vErrors:new De.Name("vErrors"),errors:new De.Name("errors"),this:new De.Name("this"),self:new De.Name("self"),scope:new De.Name("scope"),json:new De.Name("json"),jsonPos:new De.Name("jsonPos"),jsonLen:new De.Name("jsonLen"),jsonPart:new De.Name("jsonPart")};bf.default=Hz});var Bs=R(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var Z=D(),sc=G(),qe=dr();Le.keywordError={message:({keyword:t})=>(0,Z.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,Z.str)`"${t}" keyword must be ${e} ($data)`:(0,Z.str)`"${t}" keyword is invalid ($data)`};function Gz(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Sb(t,e,r);n??(i||a)?vb(s,c):_b(o,(0,Z._)`[${c}]`)}Le.reportError=Gz;function Zz(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Sb(t,e,r);vb(o,a),s||i||_b(n,qe.default.vErrors)}Le.reportExtraError=Zz;function Wz(t,e){t.assign(qe.default.errors,e),t.if((0,Z._)`${qe.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Z._)`${qe.default.vErrors}.length`,e),()=>t.assign(qe.default.vErrors,null)))}Le.resetErrorsCount=Wz;function Bz({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,qe.default.errors,a=>{t.const(i,(0,Z._)`${qe.default.vErrors}[${a}]`),t.if((0,Z._)`${i}.instancePath === undefined`,()=>t.assign((0,Z._)`${i}.instancePath`,(0,Z.strConcat)(qe.default.instancePath,s.errorPath))),t.assign((0,Z._)`${i}.schemaPath`,(0,Z.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,Z._)`${i}.schema`,r),t.assign((0,Z._)`${i}.data`,n))})}Le.extendErrors=Bz;function vb(t,e){let r=t.const("err",e);t.if((0,Z._)`${qe.default.vErrors} === null`,()=>t.assign(qe.default.vErrors,(0,Z._)`[${r}]`),(0,Z._)`${qe.default.vErrors}.push(${r})`),t.code((0,Z._)`${qe.default.errors}++`)}function _b(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,Z._)`new ${t.ValidationError}(${e})`):(r.assign((0,Z._)`${n}.errors`,e),r.return(!1))}var Sn={keyword:new Z.Name("keyword"),schemaPath:new Z.Name("schemaPath"),params:new Z.Name("params"),propertyName:new Z.Name("propertyName"),message:new Z.Name("message"),schema:new Z.Name("schema"),parentSchema:new Z.Name("parentSchema")};function Sb(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Z._)`{}`:Vz(t,e,r)}function Vz(t,e,r={}){let{gen:n,it:o}=t,s=[Kz(o,r),Jz(t,r)];return Yz(t,e,s),n.object(...s)}function Kz({errorPath:t},{instancePath:e}){let r=e?(0,Z.str)`${t}${(0,sc.getErrorPath)(e,sc.Type.Str)}`:t;return[qe.default.instancePath,(0,Z.strConcat)(qe.default.instancePath,r)]}function Jz({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,Z.str)`${e}/${t}`;return r&&(o=(0,Z.str)`${o}${(0,sc.getErrorPath)(r,sc.Type.Str)}`),[Sn.schemaPath,o]}function Yz(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([Sn.keyword,o],[Sn.params,typeof e=="function"?e(t):e||(0,Z._)`{}`]),c.messages&&n.push([Sn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Sn.schema,i],[Sn.parentSchema,(0,Z._)`${d}${l}`],[qe.default.data,s]),u&&n.push([Sn.propertyName,u])}});var bb=R(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.boolOrEmptySchema=mo.topBoolOrEmptySchema=void 0;var Xz=Bs(),Qz=D(),eN=dr(),tN={message:"boolean schema is false"};function rN(t){let{gen:e,schema:r,validateName:n}=t;r===!1?wb(t,!1):typeof r=="object"&&r.$async===!0?e.return(eN.default.data):(e.assign((0,Qz._)`${n}.errors`,null),e.return(!0))}mo.topBoolOrEmptySchema=rN;function nN(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),wb(t)):r.var(e,!0)}mo.boolOrEmptySchema=nN;function wb(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,Xz.reportError)(o,tN,void 0,e)}});var Rf=R(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.getRules=go.isJSONType=void 0;var oN=["string","number","integer","boolean","null","object","array"],sN=new Set(oN);function iN(t){return typeof t=="string"&&sN.has(t)}go.isJSONType=iN;function aN(){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:{}}}go.getRules=aN});var Pf=R(Lr=>{"use strict";Object.defineProperty(Lr,"__esModule",{value:!0});Lr.shouldUseRule=Lr.shouldUseGroup=Lr.schemaHasRulesForType=void 0;function cN({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rb(t,n)}Lr.schemaHasRulesForType=cN;function Rb(t,e){return e.rules.some(r=>Pb(t,r))}Lr.shouldUseGroup=Rb;function Pb(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))}Lr.shouldUseRule=Pb});var Vs=R(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.reportTypeError=je.checkDataTypes=je.checkDataType=je.coerceAndCheckDataType=je.getJSONTypes=je.getSchemaTypes=je.DataType=void 0;var uN=Rf(),dN=Pf(),lN=Bs(),N=D(),Cb=G(),yo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(yo||(je.DataType=yo={}));function fN(t){let e=xb(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}je.getSchemaTypes=fN;function xb(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(uN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}je.getJSONTypes=xb;function pN(t,e){let{gen:r,data:n,opts:o}=t,s=hN(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,dN.schemaHasRulesForType)(t,e[0]));if(i){let a=xf(e,n,o.strictNumbers,yo.Wrong);r.if(a,()=>{s.length?mN(t,e,s):kf(t)})}return i}je.coerceAndCheckDataType=pN;var kb=new Set(["string","number","integer","boolean","null"]);function hN(t,e){return e?t.filter(r=>kb.has(r)||e==="array"&&r==="array"):[]}function mN(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(xf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(kb.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),kf(t),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),gN(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 uN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function Cf(t,e,r,n=yo.Correct){let o=n===yo.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===yo.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}je.checkDataType=Cf;function xf(t,e,r,n){if(t.length===1)return Cf(t[0],e,r,n);let o,s=(0,bb.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,Cf(i,e,r,n));return o}je.checkDataTypes=xf;var dN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function kf(t){let e=lN(t);(0,oN.reportError)(e,dN)}je.reportTypeError=kf;function lN(t){let{gen:e,data:r,schema:n}=t,o=(0,bb.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var xb=R(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.assignDefaults=void 0;var vo=D(),fN=G();function pN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Cb(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Cb(t,s,o.default))}ic.assignDefaults=pN;function Cb(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vo._)`${s}${(0,vo.getProperty)(e)}`;if(o){(0,fN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vo._)`${a} = ${(0,vo.stringify)(r)}`)}});var vt=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 de=D(),Ef=G(),jr=dr(),hN=G();function mN(t,e){let{gen:r,data:n,it:o}=t;r.if(Af(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}te.checkReportMissingProp=mN;function gN({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(Af(t,e,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}te.checkMissingProp=gN;function yN(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=yN;function kb(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=kb;function Tf(t,e,r){return(0,de._)`${kb(t)}.call(${e}, ${r})`}te.isOwnProperty=Tf;function vN(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Tf(t,e,r)}`:o}te.propertyInData=vN;function Af(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Tf(t,e,r))):o}te.noPropertyInData=Af;function Eb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=Eb;function _N(t,e){return Eb(e).filter(r=>!(0,Ef.alwaysValidSchema)(t,e[r]))}te.schemaProperties=_N;function SN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[jr.default.instancePath,(0,de.strConcat)(jr.default.instancePath,s)],[jr.default.parentData,i.parentData],[jr.default.parentDataProperty,i.parentDataProperty],[jr.default.rootData,jr.default.rootData]];i.opts.dynamicRef&&l.push([jr.default.dynamicAnchors,jr.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}te.callValidateCode=SN;var wN=(0,de._)`new RegExp`;function bN({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,de._)`${o.code==="new RegExp"?wN:(0,hN.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=bN;function RN(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ef.Type.Num},s),e.if((0,de.not)(s),a)})}}te.validateArray=RN;function PN(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,Ef.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,de._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=PN});var $b=R(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.validateKeywordUsage=Vt.validSchemaType=Vt.funcKeywordCode=Vt.macroKeywordCode=void 0;var qe=D(),wn=dr(),CN=vt(),xN=Bs();function kN(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ab(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:qe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Vt.macroKeywordCode=kN;function EN(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;AN(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=Ab(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&Tb(t),y(()=>t.error());else{let v=e.async?p():h();e.modifying&&Tb(t),y(()=>TN(t,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,qe._)`await `),b=>n.assign(l,!1).if((0,qe._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,qe._)`${b}.errors`),()=>n.throw(b))),v}function h(){let v=(0,qe._)`${d}.errors`;return n.assign(v,null),m(qe.nil),v}function m(v=e.async?(0,qe._)`await `:qe.nil){let b=c.opts.passContext?wn.default.this:wn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,qe._)`${v}${(0,CN.callValidateCode)(t,d,b,w)}`,e.modifying)}function y(v){var b;n.if((0,qe.not)((b=e.valid)!==null&&b!==void 0?b:l),v)}}Vt.funcKeywordCode=EN;function Tb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,qe._)`${n.parentData}[${n.parentDataProperty}]`))}function TN(t,e){let{gen:r}=t;r.if((0,qe._)`Array.isArray(${e})`,()=>{r.assign(wn.default.vErrors,(0,qe._)`${wn.default.vErrors} === null ? ${e} : ${wn.default.vErrors}.concat(${e})`).assign(wn.default.errors,(0,qe._)`${wn.default.vErrors}.length`),(0,xN.extendErrors)(t)},()=>t.error())}function AN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ab(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,qe.stringify)(r)})}function $N(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")}Vt.validSchemaType=$N;function MN({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)}}Vt.validateKeywordUsage=MN});var Ib=R(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.extendSubschemaMode=Fr.extendSubschemaData=Fr.getSubschema=void 0;var Kt=D(),Mb=G();function IN(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,Kt._)`${t.schemaPath}${(0,Kt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Kt._)`${t.schemaPath}${(0,Kt.getProperty)(e)}${(0,Kt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Mb.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Fr.getSubschema=IN;function ON(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=a.let("data",(0,Kt._)`${e.data}${(0,Kt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Kt.str)`${u}${(0,Mb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Kt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Kt.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]}}Fr.extendSubschemaData=ON;function zN(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}Fr.extendSubschemaMode=zN});var $f=R((MJ,Ob)=>{"use strict";Ob.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 Nb=R((IJ,zb)=>{"use strict";var Ur=zb.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(){};ac(e,n,o,t,"",t)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.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 ac(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 Ur.arrayKeywords)for(var f=0;f<l.length;f++)ac(t,e,r,l[f],o+"/"+d+"/"+f,s,o,d,n,f)}else if(d in Ur.propsKeywords){if(l&&typeof l=="object")for(var p in l)ac(t,e,r,l[p],o+"/"+d+"/"+NN(p),s,o,d,n,p)}else(d in Ur.keywords||t.allKeys&&!(d in Ur.skipKeywords))&&ac(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function NN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ks=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var DN=G(),LN=$f(),jN=Nb(),FN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function UN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Mf(t):e?Db(t)<=e:!1}Xe.inlineRef=UN;var qN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Mf(t){for(let e in t){if(qN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Mf)||typeof r=="object"&&Mf(r))return!0}return!1}function Db(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!FN.has(r)&&(typeof t[r]=="object"&&(0,DN.eachItem)(t[r],n=>e+=Db(n)),e===1/0))return 1/0}return e}function Lb(t,e="",r){r!==!1&&(e=_o(e));let n=t.parse(e);return jb(t,n)}Xe.getFullPath=Lb;function jb(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=jb;var HN=/#\/?$/;function _o(t){return t?t.replace(HN,""):""}Xe.normalizeId=_o;function GN(t,e,r){return r=_o(r),t.resolve(e,r)}Xe.resolveUrl=GN;var ZN=/^[a-z_][-a-z0-9._]*$/i;function WN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=_o(t[r]||e),s={"":o},i=Lb(n,o,!1),a={},c=new Set;return jN(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let m=i+f,y=s[h];typeof l[r]=="string"&&(y=v.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),s[f]=y;function v(w){let x=this.opts.uriResolver.resolve;if(w=_o(y?x(y,w):w),c.has(w))throw d(w);c.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,w):w!==_o(m)&&(w[0]==="#"?(u(l,a[w],w),a[w]=l):this.refs[w]=m),w}function b(w){if(typeof w=="string"){if(!ZN.test(w))throw new Error(`invalid anchor "${w}"`);v.call(this,`#${w}`)}}}),a;function u(l,f,p){if(f!==void 0&&!LN(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Xe.getSchemaRefs=WN});var Xs=R(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getData=qr.KeywordCxt=qr.validateFunctionCode=void 0;var Gb=_b(),Fb=Vs(),Of=Pf(),cc=Vs(),BN=xb(),Ys=$b(),If=Ib(),T=D(),z=dr(),VN=Ks(),lr=G(),Js=Bs();function KN(t){if(Bb(t)&&(Vb(t),Wb(t))){XN(t);return}Zb(t,()=>(0,Gb.topBoolOrEmptySchema)(t))}qr.validateFunctionCode=KN;function Zb({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Ub(r,o)}`),YN(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${JN(o)}`,n.$async,()=>t.code(Ub(r,o)).code(s))}function JN(t){return(0,T._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,T._)`, ${z.default.dynamicAnchors}={}`:T.nil}}={}`}function YN(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,T._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,T._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,T._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,T._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,T._)`""`),t.var(z.default.parentData,(0,T._)`undefined`),t.var(z.default.parentDataProperty,(0,T._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`{}`)})}function XN(t){let{schema:e,opts:r,gen:n}=t;Zb(t,()=>{r.$comment&&e.$comment&&Jb(t),nD(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&QN(t),Kb(t),iD(t)})}function QN(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 Ub(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 eD(t,e){if(Bb(t)&&(Vb(t),Wb(t))){tD(t,e);return}(0,Gb.boolOrEmptySchema)(t,e)}function Wb({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Bb(t){return typeof t.schema!="boolean"}function tD(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Jb(t),oD(t),sD(t);let s=n.const("_errs",z.default.errors);Kb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function Vb(t){(0,lr.checkUnknownRules)(t),rD(t)}function Kb(t,e){if(t.opts.jtd)return qb(t,[],!1,e);let r=(0,Fb.getSchemaTypes)(t.schema),n=(0,Fb.coerceAndCheckDataType)(t,r);qb(t,r,!n,e)}function rD(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,lr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function nD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,lr.checkStrictMode)(t,"default is ignored in the schema root")}function oD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,VN.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function sD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Jb({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function iD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,T._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,z.default.vErrors),s.unevaluated&&aD(t),e.return((0,T._)`${z.default.errors} === 0`))}function aD({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 qb(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,lr.schemaHasRulesButRef)(s,d))){o.block(()=>Xb(t,"$ref",d.all.$ref.definition));return}c.jtd||cD(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Of.shouldUseGroup)(s,f)&&(f.type?(o.if((0,cc.checkDataType)(f.type,i,c.strictNumbers)),Hb(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,cc.reportTypeError)(t)),o.endIf()):Hb(t,f),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function Hb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,BN.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Of.shouldUseRule)(n,s)&&Xb(t,s.keyword,s.definition,e.type)})}function cD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(uD(t,e),t.opts.allowUnionTypes||dD(t,e),lD(t,t.dataTypes))}function uD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Yb(t.dataTypes,r)||zf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),pD(t,e)}}function dD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zf(t,"use allowUnionTypes to allow union type keyword")}function lD(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Of.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>fD(e,i))&&zf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fD(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Yb(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function pD(t,e){let r=[];for(let n of t.dataTypes)Yb(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,lr.checkStrictMode)(t,e,t.opts.strictTypes)}var uc=class{constructor(e,r,n){if((0,Ys.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,lr.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",Qb(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",z.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Js.reportExtraError:Js.reportError)(this,this.def.error,r)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,cc.checkDataTypes)(c,r,s.opts.strictNumbers,cc.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,If.getSubschema)(this.it,e);(0,If.extendSubschemaData)(n,this.it,e),(0,If.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return eD(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=lr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=lr.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}};qr.KeywordCxt=uc;function Xb(t,e,r,n){let o=new uc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ys.funcKeywordCode)(o,r):"macro"in r?(0,Ys.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ys.funcKeywordCode)(o,r)}var hD=/^\/(?:[^~]|~0|~1)*$/,mD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qb(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!hD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=mD.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,lr.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}qr.getData=Qb});var dc=R(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Nf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Df.default=Nf});var Qs=R(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Lf=Ks(),jf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lf.resolveUrl)(e,r,n),this.missingSchema=(0,Lf.normalizeId)((0,Lf.getFullPath)(e,this.missingRef))}};Ff.default=jf});var fc=R(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;var Mt=D(),gD=dc(),bn=dr(),It=Ks(),eR=G(),yD=Xs(),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,It.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_t.SchemaEnv=So;function qf(t){let e=tR.call(this,t);if(e)return e;let r=(0,It.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Mt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:gD.default,code:(0,Mt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:bn.default.data,parentData:bn.default.parentData,parentDataProperty:bn.default.parentDataProperty,dataNames:[bn.default.data],dataPathArr:[Mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Mt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Mt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Mt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,yD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(bn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${bn.default.self}`,`${bn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;p.evaluated={props:h instanceof Mt.Name?void 0:h,items:m instanceof Mt.Name?void 0:m,dynamicProps:h instanceof Mt.Name,dynamicItems:m instanceof Mt.Name},p.source&&(p.source.evaluated=(0,Mt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}_t.compileSchema=qf;function vD(t,e,r){var n;r=(0,It.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=wD.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]=_D.call(this,s)}_t.resolveRef=vD;function _D(t){return(0,It.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qf.call(this,t)}function tR(t){for(let e of this._compilations)if(SD(e,t))return e}_t.getCompilingSchema=tR;function SD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function wD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||lc.call(this,t,e)}function lc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,It._getFullPath)(this.opts.uriResolver,r),o=(0,It.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Uf.call(this,r,t);let s=(0,It.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=lc.call(this,t,i);return typeof a?.schema!="object"?void 0:Uf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||qf.call(this,i),s===(0,It.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,It.resolveUrl)(this.opts.uriResolver,o,u)),new So({schema:a,schemaId:c,root:t,baseId:o})}return Uf.call(this,r,i)}}_t.resolveSchema=lc;var bD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Uf(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,eR.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!bD.has(a)&&u&&(e=(0,It.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,eR.schemaHasRulesButRef)(r,this.RULES)){let a=(0,It.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=lc.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 rR=R((jJ,RD)=>{RD.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 Zf=R((FJ,cR)=>{"use strict";var PD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),oR=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),Hf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sR=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),CD=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Gf(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 xD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function nR(t){return t.length=0,!0}function kD(t,e,r){if(t.length){let n=Gf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function ED(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=kD;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=nR}else{o.push(u);continue}}return o.length&&(a===nR?r.zone=o.join(""):i?n.push(o.join("")):n.push(Gf(o))),r.address=n.join(""),r}function iR(t){if(TD(t,":")<2)return{host:t,isIPV6:!1};let e=ED(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 TD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function AD(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 $D={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},MD=/[@/?#:]/g,ID=/[@/?#]/g;function aR(t,e){let r=e?ID:MD;return r.lastIndex=0,t.replace(r,n=>$D[n])}function OD(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(Hf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&sR(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function zD(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(Hf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&sR(s)?e+=s:e+="%"+o,r+=2;continue}}CD(t[r])?e+=t[r]:e+=escape(t[r])}return e}function ND(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(Hf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function DD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!oR(r)){let n=iR(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=aR(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}cR.exports={nonSimpleDomain:xD,recomposeAuthority:DD,reescapeHostDelimiters:aR,normalizePercentEncoding:OD,normalizePathEncoding:zD,escapePreservingEscapes:ND,removeDotSegments:AD,isIPv4:oR,isUUID:PD,normalizeIPv6:iR,stringArrayToHexStripped:Gf}});var pR=R((UJ,fR)=>{"use strict";var{isUUID:LD}=Zf(),jD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,FD=["http","https","ws","wss","urn","urn:uuid"];function UD(t){return FD.indexOf(t)!==-1}function Wf(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 uR(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function dR(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 qD(t){return t.secure=Wf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function HD(t){if((t.port===(Wf(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 GD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(jD);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=Bf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function ZD(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=Bf(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 WD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!LD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var lR={scheme:"http",domainHost:!0,parse:uR,serialize:dR},VD={scheme:"https",domainHost:lR.domainHost,parse:uR,serialize:dR},pc={scheme:"ws",domainHost:!0,parse:qD,serialize:HD},KD={scheme:"wss",domainHost:pc.domainHost,parse:pc.parse,serialize:pc.serialize},JD={scheme:"urn",parse:GD,serialize:ZD,skipNormalize:!0},YD={scheme:"urn:uuid",parse:WD,serialize:BD,skipNormalize:!0},hc={http:lR,https:VD,ws:pc,wss:KD,urn:JD,"urn:uuid":YD};Object.setPrototypeOf(hc,null);function Bf(t){return t&&(hc[t]||hc[t.toLowerCase()])||void 0}fR.exports={wsIsSecure:Wf,SCHEMES:hc,isValidSchemeName:UD,getSchemeHandler:Bf}});var vR=R((qJ,yc)=>{"use strict";var{normalizeIPv6:XD,removeDotSegments:ei,recomposeAuthority:QD,normalizePercentEncoding:eL,normalizePathEncoding:tL,escapePreservingEscapes:rL,reescapeHostDelimiters:nL,isIPv4:oL,nonSimpleDomain:sL}=Zf(),{SCHEMES:iL,getSchemeHandler:mR}=pR();function aL(t,e){return typeof t=="string"?t=hL(t,e):typeof t=="object"&&(t=gc(Rn(t,e),e)),t}function cL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=mc(t,n),{parsed:i,malformedAuthorityOrPort:a}=mc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=gR(o,i,n,!0);return n.skipEscape=!0,Rn(c,n)}function gR(t,e,r,n){let o={};return n||(t=gc(Rn(t,r),r),e=gc(Rn(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=ei(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=ei(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ei(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=ei(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 uL(t,e,r){let n=hR(t,r),o=hR(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Rn(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=mR(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=eL(r.path):(r.path=rL(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=QD(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=ei(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 dL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,lL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,fL=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function pL(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 mc(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(lL);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(fL);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(dL);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=pL(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(oL(n.host)===!1){let f=XD(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=mR(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&sL(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=nL(unescape(n.host),s))),n.path&&(n.path=tL(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 gc(t,e){return mc(t,e).parsed}function hL(t,e){return yR(t,e).normalized}function yR(t,e){let{parsed:r,malformedAuthorityOrPort:n}=mc(t,e);return{normalized:n?t:Rn(r,e),malformedAuthorityOrPort:n}}function hR(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=yR(t,e);return n?void 0:r}if(typeof t=="object")return Rn(t,e)}var Vf={SCHEMES:iL,normalize:aL,resolve:cL,resolveComponent:gR,equal:uL,serialize:Rn,parse:gc};yc.exports=Vf;yc.exports.default=Vf;yc.exports.fastUri=Vf});var SR=R(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var _R=vR();_R.code='require("ajv/dist/runtime/uri").default';Kf.default=_R});var ER=R(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var mL=Xs();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return mL.KeywordCxt}});var wo=D();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return wo._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return wo.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return wo.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return wo.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return wo.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return wo.CodeGen}});var gL=dc(),CR=Qs(),yL=Rf(),ti=fc(),vL=D(),ri=Ks(),vc=Vs(),Yf=G(),wR=rR(),_L=SR(),xR=(t,e)=>new RegExp(t,e);xR.code="new RegExp";var SL=["removeAdditional","useDefaults","coerceTypes"],wL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bL={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."},RL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},bR=200;function PL(t){var e,r,n,o,s,i,a,c,u,d,l,f,p,h,m,y,v,b,w,x,S,P,I,re,fe;let Re=t.strict,Kr=(e=t.code)===null||e===void 0?void 0:e.optimize,Jr=Kr===!0||Kr===void 0?1:Kr||0,ct=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:xR,yr=(o=t.uriResolver)!==null&&o!==void 0?o:_L.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:Re)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Jr,regExp:ct}:{optimize:Jr,regExp:ct},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:bR,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:bR,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(re=t.unicodeRegExp)!==null&&re!==void 0?re:!0,int32range:(fe=t.int32range)!==null&&fe!==void 0?fe:!0,uriResolver:yr}}var ni=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,...PL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new vL.ValueScope({scope:{},prefixes:wL,es5:r,lines:n}),this.logger=AL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yL.getRules)(),RR.call(this,bL,e,"NOT SUPPORTED"),RR.call(this,RL,e,"DEPRECATED","warn"),this._metaOpts=EL.call(this),e.formats&&xL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&kL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),CL.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=wR;n==="id"&&(o={...wR},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||i.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof CR.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ri.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=PR.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ti.SchemaEnv({schema:{},schemaId:n});if(r=ti.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=PR.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,ri.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(ML.call(this,n,r),!r)return(0,Yf.eachItem)(n,s=>Jf.call(this,s)),this;OL.call(this,r);let o={...r,type:(0,vc.getJSONTypes)(r.type),schemaType:(0,vc.getJSONTypes)(r.schemaType)};return(0,Yf.eachItem)(n,o.type.length===0?s=>Jf.call(this,s,o):s=>o.type.forEach(i=>Jf.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]=kR(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,ri.normalizeId)(i||n);let u=ri.getSchemaRefs.call(this,e,n);return c=new ti.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):ti.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{ti.compileSchema.call(this,e)}finally{this.opts=r}}};ni.ValidationError=gL.default;ni.MissingRefError=CR.default;Oe.default=ni;function RR(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 PR(t){return t=(0,ri.normalizeId)(t),this.schemas[t]||this.refs[t]}function CL(){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 xL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function kL(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 EL(){let t={...this.opts};for(let e of SL)delete t[e];return t}var TL={log(){},warn(){},error(){}};function AL(t){if(t===!1)return TL;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 $L=/^[a-z_$][a-z0-9_$:-]*$/i;function ML(t,e){let{RULES:r}=this;if((0,Yf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!$L.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 Jf(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,vc.getJSONTypes)(e.type),schemaType:(0,vc.getJSONTypes)(e.schemaType)}};e.before?IL.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 IL(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 OL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=kR(e)),t.validateSchema=this.compile(e,!0))}var zL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function kR(t){return{anyOf:[t,zL]}}});var TR=R(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var NL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xf.default=NL});var IR=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.callRef=Pn.getValidate=void 0;var DL=Qs(),AR=vt(),Qe=D(),bo=dr(),$R=fc(),_c=G(),LL={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=$R.resolveRef.call(c,u,o,r);if(d===void 0)throw new DL.default(n.opts.uriResolver,o,r);if(d instanceof $R.SchemaEnv)return f(d);return p(d);function l(){if(s===u)return Sc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return Sc(t,(0,Qe._)`${h}.validate`,u,u.$async)}function f(h){let m=MR(t,h);Sc(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,Qe.stringify)(h)}:{ref:h}),y=e.name("valid"),v=t.subschema({schema:h,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function MR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Pn.getValidate=MR;function Sc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?bo.default.this:Qe.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,Qe._)`await ${(0,AR.callValidateCode)(t,e,u)}`),p(e),i||o.assign(h,!0)},m=>{o.if((0,Qe._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,AR.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let m=(0,Qe._)`${h}.errors`;o.assign(bo.default.vErrors,(0,Qe._)`${bo.default.vErrors} === null ? ${m} : ${bo.default.vErrors}.concat(${m})`),o.assign(bo.default.errors,(0,Qe._)`${bo.default.vErrors}.length`)}function p(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=_c.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Qe._)`${h}.evaluated.props`);s.props=_c.mergeEvaluated.props(o,v,s.props,Qe.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=_c.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Qe._)`${h}.evaluated.items`);s.items=_c.mergeEvaluated.items(o,v,s.items,Qe.Name)}}}Pn.callRef=Sc;Pn.default=LL});var OR=R(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var jL=TR(),FL=IR(),UL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jL.default,FL.default];Qf.default=UL});var zR=R(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var wc=D(),Hr=wc.operators,bc={maximum:{okStr:"<=",ok:Hr.LTE,fail:Hr.GT},minimum:{okStr:">=",ok:Hr.GTE,fail:Hr.LT},exclusiveMaximum:{okStr:"<",ok:Hr.LT,fail:Hr.GTE},exclusiveMinimum:{okStr:">",ok:Hr.GT,fail:Hr.LTE}},qL={message:({keyword:t,schemaCode:e})=>(0,wc.str)`must be ${bc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wc._)`{comparison: ${bc[t].okStr}, limit: ${e}}`},HL={keyword:Object.keys(bc),type:"number",schemaType:"number",$data:!0,error:qL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,wc._)`${r} ${bc[e].fail} ${n} || isNaN(${r})`)}};ep.default=HL});var NR=R(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var oi=D(),GL={message:({schemaCode:t})=>(0,oi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,oi._)`{multipleOf: ${t}}`},ZL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,oi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,oi._)`${i} !== parseInt(${i})`;t.fail$data((0,oi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};tp.default=ZL});var LR=R(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});function DR(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}rp.default=DR;DR.code='require("ajv/dist/runtime/ucs2length").default'});var jR=R(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var Cn=D(),WL=G(),BL=LR(),VL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Cn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Cn._)`{limit: ${t}}`},KL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VL,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Cn.operators.GT:Cn.operators.LT,i=o.opts.unicode===!1?(0,Cn._)`${r}.length`:(0,Cn._)`${(0,WL.useFunc)(t.gen,BL.default)}(${r})`;t.fail$data((0,Cn._)`${i} ${s} ${n}`)}};np.default=KL});var FR=R(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var JL=vt(),YL=G(),Ro=D(),XL={message:({schemaCode:t})=>(0,Ro.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ro._)`{pattern: ${t}}`},QL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XL,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,Ro._)`new RegExp`:(0,YL.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Ro._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ro._)`!${d}`)}else{let c=(0,JL.usePattern)(t,o);t.fail$data((0,Ro._)`!${c}.test(${r})`)}}};op.default=QL});var UR=R(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var si=D(),ej={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,si.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,si._)`{limit: ${t}}`},tj={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ej,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?si.operators.GT:si.operators.LT;t.fail$data((0,si._)`Object.keys(${r}).length ${o} ${n}`)}};sp.default=tj});var qR=R(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var ii=vt(),ai=D(),rj=G(),nj={message:({params:{missingProperty:t}})=>(0,ai.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ai._)`{missingProperty: ${t}}`},oj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:nj,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,rj.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ai.nil,l);else for(let p of r)(0,ii.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,ii.checkMissingProp)(t,r,p)),(0,ii.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,ii.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,ii.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ai.not)(h),()=>{t.error(),e.break()})},ai.nil)}}};ip.default=oj});var HR=R(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var ci=D(),sj={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ci.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ci._)`{limit: ${t}}`},ij={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:sj,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ci.operators.GT:ci.operators.LT;t.fail$data((0,ci._)`${r}.length ${o} ${n}`)}};ap.default=ij});var Rc=R(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var GR=$f();GR.code='require("ajv/dist/runtime/equal").default';cp.default=GR});var ZR=R(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var up=Vs(),ze=D(),aj=G(),cj=Rc(),uj={message:({params:{i:t,j:e}})=>(0,ze.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ze._)`{i: ${t}, j: ${e}}`},dj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:uj,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,ze._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,ze._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,ze._)`${h} > 1`,()=>(l()?f:p)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),v=(0,up.checkDataTypes)(u,y,a.opts.strictNumbers,up.DataType.Wrong),b=e.const("indices",(0,ze._)`{}`);e.for((0,ze._)`;${h}--;`,()=>{e.let(y,(0,ze._)`${r}[${h}]`),e.if(v,(0,ze._)`continue`),u.length>1&&e.if((0,ze._)`typeof ${y} == "string"`,(0,ze._)`${y} += "_"`),e.if((0,ze._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,ze._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,ze._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,aj.useFunc)(e,cj.default),v=e.name("outer");e.label(v).for((0,ze._)`;${h}--;`,()=>e.for((0,ze._)`${m} = ${h}; ${m}--;`,()=>e.if((0,ze._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};dp.default=dj});var WR=R(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var lp=D(),lj=G(),fj=Rc(),pj={message:"must be equal to constant",params:({schemaCode:t})=>(0,lp._)`{allowedValue: ${t}}`},hj={keyword:"const",$data:!0,error:pj,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,lp._)`!${(0,lj.useFunc)(e,fj.default)}(${r}, ${o})`):t.fail((0,lp._)`${s} !== ${r}`)}};fp.default=hj});var BR=R(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var ui=D(),mj=G(),gj=Rc(),yj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ui._)`{allowedValues: ${t}}`},vj={keyword:"enum",schemaType:"array",$data:!0,error:yj,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,mj.useFunc)(e,gj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,ui.or)(...o.map((h,m)=>f(p,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,ui._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=o[h];return typeof m=="object"&&m!==null?(0,ui._)`${u()}(${r}, ${p}[${h}])`:(0,ui._)`${r} === ${m}`}}};pp.default=vj});var VR=R(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var _j=zR(),Sj=NR(),wj=jR(),bj=FR(),Rj=UR(),Pj=qR(),Cj=HR(),xj=ZR(),kj=WR(),Ej=BR(),Tj=[_j.default,Sj.default,wj.default,bj.default,Rj.default,Pj.default,Cj.default,xj.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},kj.default,Ej.default];hp.default=Tj});var gp=R(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var xn=D(),mp=G(),Aj={message:({params:{len:t}})=>(0,xn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xn._)`{limit: ${t}}`},$j={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Aj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}KR(t,n)}};function KR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,xn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,xn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,xn._)`${a} <= ${e.length}`);r.if((0,xn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:mp.Type.Num},u),i.allErrors||r.if((0,xn.not)(u),()=>r.break())})}}di.validateAdditionalItems=KR;di.default=$j});var yp=R(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.validateTuple=void 0;var JR=D(),Pc=G(),Mj=vt(),Ij={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return YR(t,"additionalItems",e);r.items=!0,!(0,Pc.alwaysValidSchema)(r,e)&&t.ok((0,Mj.validateArray)(t))}};function YR(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=Pc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,JR._)`${s}.length`);r.forEach((l,f)=>{(0,Pc.alwaysValidSchema)(a,l)||(n.if((0,JR._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Pc.checkStrictMode)(a,y,f.strictTuples)}}}li.validateTuple=YR;li.default=Ij});var XR=R(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var Oj=yp(),zj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Oj.validateTuple)(t,"items")};vp.default=zj});var eP=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var QR=D(),Nj=G(),Dj=vt(),Lj=gp(),jj={message:({params:{len:t}})=>(0,QR.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,QR._)`{limit: ${t}}`},Fj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:jj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,Nj.alwaysValidSchema)(n,e)&&(o?(0,Lj.validateAdditionalItems)(t,o):t.ok((0,Dj.validateArray)(t)))}};_p.default=Fj});var tP=R(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});var St=D(),Cc=G(),Uj={message:({params:{min:t,max:e}})=>e===void 0?(0,St.str)`must contain at least ${t} valid item(s)`:(0,St.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,St._)`{minContains: ${t}}`:(0,St._)`{minContains: ${t}, maxContains: ${e}}`},qj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Uj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,St._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Cc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Cc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Cc.alwaysValidSchema)(s,r)){let m=(0,St._)`${d} >= ${i}`;a!==void 0&&(m=(0,St._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?p(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,St._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Cc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,St._)`${m}++`),a===void 0?e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,St._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};Sp.default=qj});var oP=R(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.validateSchemaDeps=Jt.validatePropertyDeps=Jt.error=void 0;var wp=D(),Hj=G(),fi=vt();Jt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,wp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,wp._)`{property: ${t},
5
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function gN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,N._)`${e} !== undefined`,()=>t.assign((0,N._)`${e}[${r}]`,n))}function Cf(t,e,r,n=yo.Correct){let o=n===yo.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===yo.Correct?s:(0,N.not)(s);function i(a=N.nil){return(0,N.and)((0,N._)`typeof ${e} == "number"`,a,r?(0,N._)`isFinite(${e})`:N.nil)}}je.checkDataType=Cf;function xf(t,e,r,n){if(t.length===1)return Cf(t[0],e,r,n);let o,s=(0,Cb.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,Cf(i,e,r,n));return o}je.checkDataTypes=xf;var yN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,N._)`{type: ${t}}`:(0,N._)`{type: ${e}}`};function kf(t){let e=vN(t);(0,lN.reportError)(e,yN)}je.reportTypeError=kf;function vN(t){let{gen:e,data:r,schema:n}=t,o=(0,Cb.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Tb=R(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});ic.assignDefaults=void 0;var vo=D(),_N=G();function SN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Eb(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Eb(t,s,o.default))}ic.assignDefaults=SN;function Eb(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,vo._)`${s}${(0,vo.getProperty)(e)}`;if(o){(0,_N.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vo._)`${a} = ${(0,vo.stringify)(r)}`)}});var vt=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 de=D(),Ef=G(),jr=dr(),wN=G();function bN(t,e){let{gen:r,data:n,it:o}=t;r.if(Af(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,de._)`${e}`},!0),t.error()})}te.checkReportMissingProp=bN;function RN({gen:t,data:e,it:{opts:r}},n,o){return(0,de.or)(...n.map(s=>(0,de.and)(Af(t,e,s,r.ownProperties),(0,de._)`${o} = ${s}`)))}te.checkMissingProp=RN;function PN(t,e){t.setParams({missingProperty:e},!0),t.error()}te.reportMissingProp=PN;function Ab(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,de._)`Object.prototype.hasOwnProperty`})}te.hasPropFunc=Ab;function Tf(t,e,r){return(0,de._)`${Ab(t)}.call(${e}, ${r})`}te.isOwnProperty=Tf;function CN(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} !== undefined`;return n?(0,de._)`${o} && ${Tf(t,e,r)}`:o}te.propertyInData=CN;function Af(t,e,r,n){let o=(0,de._)`${e}${(0,de.getProperty)(r)} === undefined`;return n?(0,de.or)(o,(0,de.not)(Tf(t,e,r))):o}te.noPropertyInData=Af;function $b(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}te.allSchemaProperties=$b;function xN(t,e){return $b(e).filter(r=>!(0,Ef.alwaysValidSchema)(t,e[r]))}te.schemaProperties=xN;function kN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let d=u?(0,de._)`${t}, ${e}, ${n}${o}`:e,l=[[jr.default.instancePath,(0,de.strConcat)(jr.default.instancePath,s)],[jr.default.parentData,i.parentData],[jr.default.parentDataProperty,i.parentDataProperty],[jr.default.rootData,jr.default.rootData]];i.opts.dynamicRef&&l.push([jr.default.dynamicAnchors,jr.default.dynamicAnchors]);let f=(0,de._)`${d}, ${r.object(...l)}`;return c!==de.nil?(0,de._)`${a}.call(${c}, ${f})`:(0,de._)`${a}(${f})`}te.callValidateCode=kN;var EN=(0,de._)`new RegExp`;function TN({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,de._)`${o.code==="new RegExp"?EN:(0,wN.useFunc)(t,o)}(${r}, ${n})`})}te.usePattern=TN;function AN(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,de._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ef.Type.Num},s),e.if((0,de.not)(s),a)})}}te.validateArray=AN;function $N(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,Ef.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,de._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,de.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}te.validateUnion=$N});var Ob=R(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.validateKeywordUsage=Vt.validSchemaType=Vt.funcKeywordCode=Vt.macroKeywordCode=void 0;var He=D(),wn=dr(),MN=vt(),IN=Bs();function ON(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ib(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:He.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Vt.macroKeywordCode=ON;function zN(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;DN(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,d=Ib(n,o,u),l=n.let("valid");t.block$data(l,f),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function f(){if(e.errors===!1)m(),e.modifying&&Mb(t),y(()=>t.error());else{let v=e.async?p():h();e.modifying&&Mb(t),y(()=>NN(t,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>m((0,He._)`await `),b=>n.assign(l,!1).if((0,He._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,He._)`${b}.errors`),()=>n.throw(b))),v}function h(){let v=(0,He._)`${d}.errors`;return n.assign(v,null),m(He.nil),v}function m(v=e.async?(0,He._)`await `:He.nil){let b=c.opts.passContext?wn.default.this:wn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,He._)`${v}${(0,MN.callValidateCode)(t,d,b,w)}`,e.modifying)}function y(v){var b;n.if((0,He.not)((b=e.valid)!==null&&b!==void 0?b:l),v)}}Vt.funcKeywordCode=zN;function Mb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,He._)`${n.parentData}[${n.parentDataProperty}]`))}function NN(t,e){let{gen:r}=t;r.if((0,He._)`Array.isArray(${e})`,()=>{r.assign(wn.default.vErrors,(0,He._)`${wn.default.vErrors} === null ? ${e} : ${wn.default.vErrors}.concat(${e})`).assign(wn.default.errors,(0,He._)`${wn.default.vErrors}.length`),(0,IN.extendErrors)(t)},()=>t.error())}function DN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ib(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,He.stringify)(r)})}function LN(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")}Vt.validSchemaType=LN;function jN({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)}}Vt.validateKeywordUsage=jN});var Nb=R(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.extendSubschemaMode=Fr.extendSubschemaData=Fr.getSubschema=void 0;var Kt=D(),zb=G();function FN(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,Kt._)`${t.schemaPath}${(0,Kt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Kt._)`${t.schemaPath}${(0,Kt.getProperty)(e)}${(0,Kt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,zb.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')}Fr.getSubschema=FN;function UN(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:d,opts:l}=e,f=a.let("data",(0,Kt._)`${e.data}${(0,Kt.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Kt.str)`${u}${(0,zb.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Kt._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Kt.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]}}Fr.extendSubschemaData=UN;function qN(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}Fr.extendSubschemaMode=qN});var $f=R((jJ,Db)=>{"use strict";Db.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 jb=R((FJ,Lb)=>{"use strict";var Ur=Lb.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(){};ac(e,n,o,t,"",t)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.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 ac(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 Ur.arrayKeywords)for(var f=0;f<l.length;f++)ac(t,e,r,l[f],o+"/"+d+"/"+f,s,o,d,n,f)}else if(d in Ur.propsKeywords){if(l&&typeof l=="object")for(var p in l)ac(t,e,r,l[p],o+"/"+d+"/"+HN(p),s,o,d,n,p)}else(d in Ur.keywords||t.allKeys&&!(d in Ur.skipKeywords))&&ac(t,e,r,l,o+"/"+d,s,o,d,n)}r(n,o,s,i,a,c,u)}}function HN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ks=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.getSchemaRefs=Qe.resolveUrl=Qe.normalizeId=Qe._getFullPath=Qe.getFullPath=Qe.inlineRef=void 0;var GN=G(),ZN=$f(),WN=jb(),BN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function VN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Mf(t):e?Fb(t)<=e:!1}Qe.inlineRef=VN;var KN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Mf(t){for(let e in t){if(KN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Mf)||typeof r=="object"&&Mf(r))return!0}return!1}function Fb(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!BN.has(r)&&(typeof t[r]=="object"&&(0,GN.eachItem)(t[r],n=>e+=Fb(n)),e===1/0))return 1/0}return e}function Ub(t,e="",r){r!==!1&&(e=_o(e));let n=t.parse(e);return qb(t,n)}Qe.getFullPath=Ub;function qb(t,e){return t.serialize(e).split("#")[0]+"#"}Qe._getFullPath=qb;var JN=/#\/?$/;function _o(t){return t?t.replace(JN,""):""}Qe.normalizeId=_o;function YN(t,e,r){return r=_o(r),t.resolve(e,r)}Qe.resolveUrl=YN;var XN=/^[a-z_][-a-z0-9._]*$/i;function QN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=_o(t[r]||e),s={"":o},i=Ub(n,o,!1),a={},c=new Set;return WN(t,{allKeys:!0},(l,f,p,h)=>{if(h===void 0)return;let m=i+f,y=s[h];typeof l[r]=="string"&&(y=v.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),s[f]=y;function v(w){let x=this.opts.uriResolver.resolve;if(w=_o(y?x(y,w):w),c.has(w))throw d(w);c.add(w);let S=this.refs[w];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(l,S.schema,w):w!==_o(m)&&(w[0]==="#"?(u(l,a[w],w),a[w]=l):this.refs[w]=m),w}function b(w){if(typeof w=="string"){if(!XN.test(w))throw new Error(`invalid anchor "${w}"`);v.call(this,`#${w}`)}}}),a;function u(l,f,p){if(f!==void 0&&!ZN(l,f))throw d(p)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Qe.getSchemaRefs=QN});var Xs=R(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.getData=qr.KeywordCxt=qr.validateFunctionCode=void 0;var Bb=bb(),Hb=Vs(),Of=Pf(),cc=Vs(),eD=Tb(),Ys=Ob(),If=Nb(),T=D(),z=dr(),tD=Ks(),lr=G(),Js=Bs();function rD(t){if(Jb(t)&&(Yb(t),Kb(t))){sD(t);return}Vb(t,()=>(0,Bb.topBoolOrEmptySchema)(t))}qr.validateFunctionCode=rD;function Vb({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,T._)`${z.default.data}, ${z.default.valCxt}`,n.$async,()=>{t.code((0,T._)`"use strict"; ${Gb(r,o)}`),oD(t,o),t.code(s)}):t.func(e,(0,T._)`${z.default.data}, ${nD(o)}`,n.$async,()=>t.code(Gb(r,o)).code(s))}function nD(t){return(0,T._)`{${z.default.instancePath}="", ${z.default.parentData}, ${z.default.parentDataProperty}, ${z.default.rootData}=${z.default.data}${t.dynamicRef?(0,T._)`, ${z.default.dynamicAnchors}={}`:T.nil}}={}`}function oD(t,e){t.if(z.default.valCxt,()=>{t.var(z.default.instancePath,(0,T._)`${z.default.valCxt}.${z.default.instancePath}`),t.var(z.default.parentData,(0,T._)`${z.default.valCxt}.${z.default.parentData}`),t.var(z.default.parentDataProperty,(0,T._)`${z.default.valCxt}.${z.default.parentDataProperty}`),t.var(z.default.rootData,(0,T._)`${z.default.valCxt}.${z.default.rootData}`),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`${z.default.valCxt}.${z.default.dynamicAnchors}`)},()=>{t.var(z.default.instancePath,(0,T._)`""`),t.var(z.default.parentData,(0,T._)`undefined`),t.var(z.default.parentDataProperty,(0,T._)`undefined`),t.var(z.default.rootData,z.default.data),e.dynamicRef&&t.var(z.default.dynamicAnchors,(0,T._)`{}`)})}function sD(t){let{schema:e,opts:r,gen:n}=t;Vb(t,()=>{r.$comment&&e.$comment&&Qb(t),dD(t),n.let(z.default.vErrors,null),n.let(z.default.errors,0),r.unevaluated&&iD(t),Xb(t),pD(t)})}function iD(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,T._)`${r}.evaluated`),e.if((0,T._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,T._)`${t.evaluated}.props`,(0,T._)`undefined`)),e.if((0,T._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,T._)`${t.evaluated}.items`,(0,T._)`undefined`))}function Gb(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,T._)`/*# sourceURL=${r} */`:T.nil}function aD(t,e){if(Jb(t)&&(Yb(t),Kb(t))){cD(t,e);return}(0,Bb.boolOrEmptySchema)(t,e)}function Kb({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 Jb(t){return typeof t.schema!="boolean"}function cD(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Qb(t),lD(t),fD(t);let s=n.const("_errs",z.default.errors);Xb(t,s),n.var(e,(0,T._)`${s} === ${z.default.errors}`)}function Yb(t){(0,lr.checkUnknownRules)(t),uD(t)}function Xb(t,e){if(t.opts.jtd)return Zb(t,[],!1,e);let r=(0,Hb.getSchemaTypes)(t.schema),n=(0,Hb.coerceAndCheckDataType)(t,r);Zb(t,r,!n,e)}function uD(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,lr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function dD(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,lr.checkStrictMode)(t,"default is ignored in the schema root")}function lD(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,tD.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function fD(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qb({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,T._)`${z.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,T.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,T._)`${z.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function pD(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,T._)`${z.default.errors} === 0`,()=>e.return(z.default.data),()=>e.throw((0,T._)`new ${o}(${z.default.vErrors})`)):(e.assign((0,T._)`${n}.errors`,z.default.vErrors),s.unevaluated&&hD(t),e.return((0,T._)`${z.default.errors} === 0`))}function hD({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 Zb(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,lr.schemaHasRulesButRef)(s,d))){o.block(()=>tR(t,"$ref",d.all.$ref.definition));return}c.jtd||mD(t,e),o.block(()=>{for(let f of d.rules)l(f);l(d.post)});function l(f){(0,Of.shouldUseGroup)(s,f)&&(f.type?(o.if((0,cc.checkDataType)(f.type,i,c.strictNumbers)),Wb(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,cc.reportTypeError)(t)),o.endIf()):Wb(t,f),a||o.if((0,T._)`${z.default.errors} === ${n||0}`))}}function Wb(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,eD.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Of.shouldUseRule)(n,s)&&tR(t,s.keyword,s.definition,e.type)})}function mD(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(gD(t,e),t.opts.allowUnionTypes||yD(t,e),vD(t,t.dataTypes))}function gD(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{eR(t.dataTypes,r)||zf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),SD(t,e)}}function yD(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&zf(t,"use allowUnionTypes to allow union type keyword")}function vD(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Of.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>_D(e,i))&&zf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function _D(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function eR(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function SD(t,e){let r=[];for(let n of t.dataTypes)eR(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function zf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,lr.checkStrictMode)(t,e,t.opts.strictTypes)}var uc=class{constructor(e,r,n){if((0,Ys.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,lr.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",rR(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",z.default.errors))}result(e,r,n){this.failResult((0,T.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,T.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,T._)`${r} !== undefined && (${(0,T.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Js.reportExtraError:Js.reportError)(this,this.def.error,r)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=T.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=T.nil,r=T.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,T.or)((0,T._)`${o} === undefined`,r)),e!==T.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==T.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,T.or)(i(),a());function i(){if(n.length){if(!(r instanceof T.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,T._)`${(0,cc.checkDataTypes)(c,r,s.opts.strictNumbers,cc.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,If.getSubschema)(this.it,e);(0,If.extendSubschemaData)(n,this.it,e),(0,If.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return aD(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=lr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=lr.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}};qr.KeywordCxt=uc;function tR(t,e,r,n){let o=new uc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ys.funcKeywordCode)(o,r):"macro"in r?(0,Ys.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ys.funcKeywordCode)(o,r)}var wD=/^\/(?:[^~]|~0|~1)*$/,bD=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function rR(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return z.default.rootData;if(t[0]==="/"){if(!wD.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=z.default.rootData}else{let u=bD.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,lr.unescapeJsonPointer)(u))}`,i=(0,T._)`${i} && ${s}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}qr.getData=rR});var dc=R(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var Nf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Df.default=Nf});var Qs=R(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var Lf=Ks(),jf=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lf.resolveUrl)(e,r,n),this.missingSchema=(0,Lf.normalizeId)((0,Lf.getFullPath)(e,this.missingRef))}};Ff.default=jf});var fc=R(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.resolveSchema=_t.getCompilingSchema=_t.resolveRef=_t.compileSchema=_t.SchemaEnv=void 0;var Mt=D(),RD=dc(),bn=dr(),It=Ks(),nR=G(),PD=Xs(),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,It.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};_t.SchemaEnv=So;function qf(t){let e=oR.call(this,t);if(e)return e;let r=(0,It.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Mt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:RD.default,code:(0,Mt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:bn.default.data,parentData:bn.default.parentData,parentDataProperty:bn.default.parentDataProperty,dataNames:[bn.default.data],dataPathArr:[Mt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Mt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Mt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Mt._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,PD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(bn.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let p=new Function(`${bn.default.self}`,`${bn.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=t.schema,p.schemaEnv=t,t.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=u;p.evaluated={props:h instanceof Mt.Name?void 0:h,items:m instanceof Mt.Name?void 0:m,dynamicProps:h instanceof Mt.Name,dynamicItems:m instanceof Mt.Name},p.source&&(p.source.evaluated=(0,Mt.stringify)(p.evaluated))}return t.validate=p,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}_t.compileSchema=qf;function CD(t,e,r){var n;r=(0,It.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=ED.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]=xD.call(this,s)}_t.resolveRef=CD;function xD(t){return(0,It.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:qf.call(this,t)}function oR(t){for(let e of this._compilations)if(kD(e,t))return e}_t.getCompilingSchema=oR;function kD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function ED(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||lc.call(this,t,e)}function lc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,It._getFullPath)(this.opts.uriResolver,r),o=(0,It.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Uf.call(this,r,t);let s=(0,It.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=lc.call(this,t,i);return typeof a?.schema!="object"?void 0:Uf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||qf.call(this,i),s===(0,It.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,It.resolveUrl)(this.opts.uriResolver,o,u)),new So({schema:a,schemaId:c,root:t,baseId:o})}return Uf.call(this,r,i)}}_t.resolveSchema=lc;var TD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Uf(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,nR.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!TD.has(a)&&u&&(e=(0,It.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,nR.schemaHasRulesButRef)(r,this.RULES)){let a=(0,It.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=lc.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 sR=R((WJ,AD)=>{AD.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 Zf=R((BJ,lR)=>{"use strict";var $D=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),aR=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),Hf=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),cR=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),MD=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Gf(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 ID=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function iR(t){return t.length=0,!0}function OD(t,e,r){if(t.length){let n=Gf(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function zD(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=OD;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=iR}else{o.push(u);continue}}return o.length&&(a===iR?r.zone=o.join(""):i?n.push(o.join("")):n.push(Gf(o))),r.address=n.join(""),r}function uR(t){if(ND(t,":")<2)return{host:t,isIPV6:!1};let e=zD(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 ND(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function DD(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 LD={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},jD=/[@/?#:]/g,FD=/[@/?#]/g;function dR(t,e){let r=e?FD:jD;return r.lastIndex=0,t.replace(r,n=>LD[n])}function UD(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(Hf(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&cR(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function qD(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(Hf(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&cR(s)?e+=s:e+="%"+o,r+=2;continue}}MD(t[r])?e+=t[r]:e+=escape(t[r])}return e}function HD(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(Hf(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function GD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!aR(r)){let n=uR(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=dR(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}lR.exports={nonSimpleDomain:ID,recomposeAuthority:GD,reescapeHostDelimiters:dR,normalizePercentEncoding:UD,normalizePathEncoding:qD,escapePreservingEscapes:HD,removeDotSegments:DD,isIPv4:aR,isUUID:$D,normalizeIPv6:uR,stringArrayToHexStripped:Gf}});var gR=R((VJ,mR)=>{"use strict";var{isUUID:ZD}=Zf(),WD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,BD=["http","https","ws","wss","urn","urn:uuid"];function VD(t){return BD.indexOf(t)!==-1}function Wf(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 fR(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function pR(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function KD(t){return t.secure=Wf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function JD(t){if((t.port===(Wf(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 YD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WD);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=Bf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function XD(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=Bf(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 QD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!ZD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function eL(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var hR={scheme:"http",domainHost:!0,parse:fR,serialize:pR},tL={scheme:"https",domainHost:hR.domainHost,parse:fR,serialize:pR},pc={scheme:"ws",domainHost:!0,parse:KD,serialize:JD},rL={scheme:"wss",domainHost:pc.domainHost,parse:pc.parse,serialize:pc.serialize},nL={scheme:"urn",parse:YD,serialize:XD,skipNormalize:!0},oL={scheme:"urn:uuid",parse:QD,serialize:eL,skipNormalize:!0},hc={http:hR,https:tL,ws:pc,wss:rL,urn:nL,"urn:uuid":oL};Object.setPrototypeOf(hc,null);function Bf(t){return t&&(hc[t]||hc[t.toLowerCase()])||void 0}mR.exports={wsIsSecure:Wf,SCHEMES:hc,isValidSchemeName:VD,getSchemeHandler:Bf}});var wR=R((KJ,yc)=>{"use strict";var{normalizeIPv6:sL,removeDotSegments:ei,recomposeAuthority:iL,normalizePercentEncoding:aL,normalizePathEncoding:cL,escapePreservingEscapes:uL,reescapeHostDelimiters:dL,isIPv4:lL,nonSimpleDomain:fL}=Zf(),{SCHEMES:pL,getSchemeHandler:vR}=gR();function hL(t,e){return typeof t=="string"?t=wL(t,e):typeof t=="object"&&(t=gc(Rn(t,e),e)),t}function mL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=mc(t,n),{parsed:i,malformedAuthorityOrPort:a}=mc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=_R(o,i,n,!0);return n.skipEscape=!0,Rn(c,n)}function _R(t,e,r,n){let o={};return n||(t=gc(Rn(t,r),r),e=gc(Rn(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=ei(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=ei(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ei(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=ei(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 gL(t,e,r){let n=yR(t,r),o=yR(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Rn(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=vR(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=aL(r.path):(r.path=uL(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=iL(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=ei(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 yL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,vL=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,_L=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function SL(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 mc(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(vL);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(_L);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(yL);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=SL(n,c);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(lL(n.host)===!1){let f=sL(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let d=vR(r.scheme||n.scheme);if(!r.unicodeSupport&&(!d||!d.unicodeSupport)&&n.host&&(r.domainHost||d&&d.domainHost)&&s===!1&&fL(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=dL(unescape(n.host),s))),n.path&&(n.path=cL(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 gc(t,e){return mc(t,e).parsed}function wL(t,e){return SR(t,e).normalized}function SR(t,e){let{parsed:r,malformedAuthorityOrPort:n}=mc(t,e);return{normalized:n?t:Rn(r,e),malformedAuthorityOrPort:n}}function yR(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=SR(t,e);return n?void 0:r}if(typeof t=="object")return Rn(t,e)}var Vf={SCHEMES:pL,normalize:hL,resolve:mL,resolveComponent:_R,equal:gL,serialize:Rn,parse:gc};yc.exports=Vf;yc.exports.default=Vf;yc.exports.fastUri=Vf});var RR=R(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var bR=wR();bR.code='require("ajv/dist/runtime/uri").default';Kf.default=bR});var $R=R(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var bL=Xs();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return bL.KeywordCxt}});var wo=D();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return wo._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return wo.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return wo.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return wo.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return wo.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return wo.CodeGen}});var RL=dc(),ER=Qs(),PL=Rf(),ti=fc(),CL=D(),ri=Ks(),vc=Vs(),Yf=G(),PR=sR(),xL=RR(),TR=(t,e)=>new RegExp(t,e);TR.code="new RegExp";var kL=["removeAdditional","useDefaults","coerceTypes"],EL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),TL={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."},AL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},CR=200;function $L(t){var e,r,n,o,s,i,a,c,u,d,l,f,p,h,m,y,v,b,w,x,S,P,I,re,fe;let Re=t.strict,Kr=(e=t.code)===null||e===void 0?void 0:e.optimize,Jr=Kr===!0||Kr===void 0?1:Kr||0,ct=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:TR,yr=(o=t.uriResolver)!==null&&o!==void 0?o:xL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Re)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Re)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:Re)!==null&&d!==void 0?d:"log",strictTuples:(f=(l=t.strictTuples)!==null&&l!==void 0?l:Re)!==null&&f!==void 0?f:"log",strictRequired:(h=(p=t.strictRequired)!==null&&p!==void 0?p:Re)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:Jr,regExp:ct}:{optimize:Jr,regExp:ct},loopRequired:(m=t.loopRequired)!==null&&m!==void 0?m:CR,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:CR,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(x=t.schemaId)!==null&&x!==void 0?x:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(I=t.validateFormats)!==null&&I!==void 0?I:!0,unicodeRegExp:(re=t.unicodeRegExp)!==null&&re!==void 0?re:!0,int32range:(fe=t.int32range)!==null&&fe!==void 0?fe:!0,uriResolver:yr}}var ni=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,...$L(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new CL.ValueScope({scope:{},prefixes:EL,es5:r,lines:n}),this.logger=DL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,PL.getRules)(),xR.call(this,TL,e,"NOT SUPPORTED"),xR.call(this,AL,e,"DEPRECATED","warn"),this._metaOpts=zL.call(this),e.formats&&IL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&OL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),ML.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=PR;n==="id"&&(o={...PR},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(d,l){await s.call(this,d.$schema);let f=this._addSchema(d,l);return f.validate||i.call(this,f)}async function s(d){d&&!this.getSchema(d)&&await o.call(this,{$ref:d},!0)}async function i(d){try{return this._compileSchemaEnv(d)}catch(l){if(!(l instanceof ER.default))throw l;return a.call(this,l),await c.call(this,l.missingSchema),i.call(this,d)}}function a({missingSchema:d,missingRef:l}){if(this.refs[d])throw new Error(`AnySchema ${d} is loaded but ${l} cannot be resolved`)}async function c(d){let l=await u.call(this,d);this.refs[d]||await s.call(this,l.$schema),this.refs[d]||this.addSchema(l,d,r)}async function u(d){let l=this._loading[d];if(l)return l;try{return await(this._loading[d]=n(d))}finally{delete this._loading[d]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ri.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=kR.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ti.SchemaEnv({schema:{},schemaId:n});if(r=ti.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=kR.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,ri.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(jL.call(this,n,r),!r)return(0,Yf.eachItem)(n,s=>Jf.call(this,s)),this;UL.call(this,r);let o={...r,type:(0,vc.getJSONTypes)(r.type),schemaType:(0,vc.getJSONTypes)(r.schemaType)};return(0,Yf.eachItem)(n,o.type.length===0?s=>Jf.call(this,s,o):s=>o.type.forEach(i=>Jf.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]=AR(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,ri.normalizeId)(i||n);let u=ri.getSchemaRefs.call(this,e,n);return c=new ti.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):ti.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{ti.compileSchema.call(this,e)}finally{this.opts=r}}};ni.ValidationError=RL.default;ni.MissingRefError=ER.default;Oe.default=ni;function xR(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 kR(t){return t=(0,ri.normalizeId)(t),this.schemas[t]||this.refs[t]}function ML(){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 IL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function OL(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 zL(){let t={...this.opts};for(let e of kL)delete t[e];return t}var NL={log(){},warn(){},error(){}};function DL(t){if(t===!1)return NL;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 LL=/^[a-z_$][a-z0-9_$:-]*$/i;function jL(t,e){let{RULES:r}=this;if((0,Yf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!LL.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 Jf(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,vc.getJSONTypes)(e.type),schemaType:(0,vc.getJSONTypes)(e.schemaType)}};e.before?FL.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 FL(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 UL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=AR(e)),t.validateSchema=this.compile(e,!0))}var qL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function AR(t){return{anyOf:[t,qL]}}});var MR=R(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var HL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xf.default=HL});var NR=R(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.callRef=Pn.getValidate=void 0;var GL=Qs(),IR=vt(),et=D(),bo=dr(),OR=fc(),_c=G(),ZL={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=OR.resolveRef.call(c,u,o,r);if(d===void 0)throw new GL.default(n.opts.uriResolver,o,r);if(d instanceof OR.SchemaEnv)return f(d);return p(d);function l(){if(s===u)return Sc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:u});return Sc(t,(0,et._)`${h}.validate`,u,u.$async)}function f(h){let m=zR(t,h);Sc(t,m,h,h.$async)}function p(h){let m=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,et.stringify)(h)}:{ref:h}),y=e.name("valid"),v=t.subschema({schema:h,dataTypes:[],schemaPath:et.nil,topSchemaRef:m,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function zR(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Pn.getValidate=zR;function Sc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?bo.default.this:et.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,IR.callValidateCode)(t,e,u)}`),p(e),i||o.assign(h,!0)},m=>{o.if((0,et._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),f(m),i||o.assign(h,!1)}),t.ok(h)}function l(){t.result((0,IR.callValidateCode)(t,e,u),()=>p(e),()=>f(e))}function f(h){let m=(0,et._)`${h}.errors`;o.assign(bo.default.vErrors,(0,et._)`${bo.default.vErrors} === null ? ${m} : ${bo.default.vErrors}.concat(${m})`),o.assign(bo.default.errors,(0,et._)`${bo.default.vErrors}.length`)}function p(h){var m;if(!s.opts.unevaluated)return;let y=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=_c.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,et._)`${h}.evaluated.props`);s.props=_c.mergeEvaluated.props(o,v,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=_c.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,et._)`${h}.evaluated.items`);s.items=_c.mergeEvaluated.items(o,v,s.items,et.Name)}}}Pn.callRef=Sc;Pn.default=ZL});var DR=R(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var WL=MR(),BL=NR(),VL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",WL.default,BL.default];Qf.default=VL});var LR=R(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var wc=D(),Hr=wc.operators,bc={maximum:{okStr:"<=",ok:Hr.LTE,fail:Hr.GT},minimum:{okStr:">=",ok:Hr.GTE,fail:Hr.LT},exclusiveMaximum:{okStr:"<",ok:Hr.LT,fail:Hr.GTE},exclusiveMinimum:{okStr:">",ok:Hr.GT,fail:Hr.LTE}},KL={message:({keyword:t,schemaCode:e})=>(0,wc.str)`must be ${bc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wc._)`{comparison: ${bc[t].okStr}, limit: ${e}}`},JL={keyword:Object.keys(bc),type:"number",schemaType:"number",$data:!0,error:KL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,wc._)`${r} ${bc[e].fail} ${n} || isNaN(${r})`)}};ep.default=JL});var jR=R(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var oi=D(),YL={message:({schemaCode:t})=>(0,oi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,oi._)`{multipleOf: ${t}}`},XL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,oi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,oi._)`${i} !== parseInt(${i})`;t.fail$data((0,oi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};tp.default=XL});var UR=R(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});function FR(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}rp.default=FR;FR.code='require("ajv/dist/runtime/ucs2length").default'});var qR=R(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var Cn=D(),QL=G(),ej=UR(),tj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Cn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Cn._)`{limit: ${t}}`},rj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tj,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Cn.operators.GT:Cn.operators.LT,i=o.opts.unicode===!1?(0,Cn._)`${r}.length`:(0,Cn._)`${(0,QL.useFunc)(t.gen,ej.default)}(${r})`;t.fail$data((0,Cn._)`${i} ${s} ${n}`)}};np.default=rj});var HR=R(op=>{"use strict";Object.defineProperty(op,"__esModule",{value:!0});var nj=vt(),oj=G(),Ro=D(),sj={message:({schemaCode:t})=>(0,Ro.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ro._)`{pattern: ${t}}`},ij={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:sj,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,Ro._)`new RegExp`:(0,oj.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,Ro._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,Ro._)`!${d}`)}else{let c=(0,nj.usePattern)(t,o);t.fail$data((0,Ro._)`!${c}.test(${r})`)}}};op.default=ij});var GR=R(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var si=D(),aj={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,si.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,si._)`{limit: ${t}}`},cj={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:aj,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?si.operators.GT:si.operators.LT;t.fail$data((0,si._)`Object.keys(${r}).length ${o} ${n}`)}};sp.default=cj});var ZR=R(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var ii=vt(),ai=D(),uj=G(),dj={message:({params:{missingProperty:t}})=>(0,ai.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ai._)`{missingProperty: ${t}}`},lj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:dj,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let p=t.parentSchema.properties,{definedProperties:h}=t.it;for(let m of r)if(p?.[m]===void 0&&!h.has(m)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,uj.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ai.nil,l);else for(let p of r)(0,ii.checkReportMissingProp)(t,p)}function d(){let p=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>f(p,h)),t.ok(h)}else e.if((0,ii.checkMissingProp)(t,r,p)),(0,ii.reportMissingProp)(t,p),e.else()}function l(){e.forOf("prop",n,p=>{t.setParams({missingProperty:p}),e.if((0,ii.noPropertyInData)(e,o,p,a.ownProperties),()=>t.error())})}function f(p,h){t.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(h,(0,ii.propertyInData)(e,o,p,a.ownProperties)),e.if((0,ai.not)(h),()=>{t.error(),e.break()})},ai.nil)}}};ip.default=lj});var WR=R(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var ci=D(),fj={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ci.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ci._)`{limit: ${t}}`},pj={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:fj,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ci.operators.GT:ci.operators.LT;t.fail$data((0,ci._)`${r}.length ${o} ${n}`)}};ap.default=pj});var Rc=R(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var BR=$f();BR.code='require("ajv/dist/runtime/equal").default';cp.default=BR});var VR=R(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var up=Vs(),ze=D(),hj=G(),mj=Rc(),gj={message:({params:{i:t,j:e}})=>(0,ze.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ze._)`{i: ${t}, j: ${e}}`},yj={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gj,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,ze._)`${i} === false`),t.ok(c);function d(){let h=e.let("i",(0,ze._)`${r}.length`),m=e.let("j");t.setParams({i:h,j:m}),e.assign(c,!0),e.if((0,ze._)`${h} > 1`,()=>(l()?f:p)(h,m))}function l(){return u.length>0&&!u.some(h=>h==="object"||h==="array")}function f(h,m){let y=e.name("item"),v=(0,up.checkDataTypes)(u,y,a.opts.strictNumbers,up.DataType.Wrong),b=e.const("indices",(0,ze._)`{}`);e.for((0,ze._)`;${h}--;`,()=>{e.let(y,(0,ze._)`${r}[${h}]`),e.if(v,(0,ze._)`continue`),u.length>1&&e.if((0,ze._)`typeof ${y} == "string"`,(0,ze._)`${y} += "_"`),e.if((0,ze._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(m,(0,ze._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,ze._)`${b}[${y}] = ${h}`)})}function p(h,m){let y=(0,hj.useFunc)(e,mj.default),v=e.name("outer");e.label(v).for((0,ze._)`;${h}--;`,()=>e.for((0,ze._)`${m} = ${h}; ${m}--;`,()=>e.if((0,ze._)`${y}(${r}[${h}], ${r}[${m}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};dp.default=yj});var KR=R(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var lp=D(),vj=G(),_j=Rc(),Sj={message:"must be equal to constant",params:({schemaCode:t})=>(0,lp._)`{allowedValue: ${t}}`},wj={keyword:"const",$data:!0,error:Sj,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,lp._)`!${(0,vj.useFunc)(e,_j.default)}(${r}, ${o})`):t.fail((0,lp._)`${s} !== ${r}`)}};fp.default=wj});var JR=R(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var ui=D(),bj=G(),Rj=Rc(),Pj={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ui._)`{allowedValues: ${t}}`},Cj={keyword:"enum",schemaType:"array",$data:!0,error:Pj,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,bj.useFunc)(e,Rj.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=e.const("vSchema",s);d=(0,ui.or)(...o.map((h,m)=>f(p,m)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",s,p=>e.if((0,ui._)`${u()}(${r}, ${p})`,()=>e.assign(d,!0).break()))}function f(p,h){let m=o[h];return typeof m=="object"&&m!==null?(0,ui._)`${u()}(${r}, ${p}[${h}])`:(0,ui._)`${r} === ${m}`}}};pp.default=Cj});var YR=R(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var xj=LR(),kj=jR(),Ej=qR(),Tj=HR(),Aj=GR(),$j=ZR(),Mj=WR(),Ij=VR(),Oj=KR(),zj=JR(),Nj=[xj.default,kj.default,Ej.default,Tj.default,Aj.default,$j.default,Mj.default,Ij.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Oj.default,zj.default];hp.default=Nj});var gp=R(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.validateAdditionalItems=void 0;var xn=D(),mp=G(),Dj={message:({params:{len:t}})=>(0,xn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xn._)`{limit: ${t}}`},Lj={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Dj,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,mp.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}XR(t,n)}};function XR(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,xn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,xn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,mp.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,xn._)`${a} <= ${e.length}`);r.if((0,xn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:s,dataProp:d,dataPropType:mp.Type.Num},u),i.allErrors||r.if((0,xn.not)(u),()=>r.break())})}}di.validateAdditionalItems=XR;di.default=Lj});var yp=R(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.validateTuple=void 0;var QR=D(),Pc=G(),jj=vt(),Fj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return eP(t,"additionalItems",e);r.items=!0,!(0,Pc.alwaysValidSchema)(r,e)&&t.ok((0,jj.validateArray)(t))}};function eP(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=Pc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,QR._)`${s}.length`);r.forEach((l,f)=>{(0,Pc.alwaysValidSchema)(a,l)||(n.if((0,QR._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function d(l){let{opts:f,errSchemaPath:p}=a,h=r.length,m=h===l.minItems&&(h===l.maxItems||l[e]===!1);if(f.strictTuples&&!m){let y=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Pc.checkStrictMode)(a,y,f.strictTuples)}}}li.validateTuple=eP;li.default=Fj});var tP=R(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var Uj=yp(),qj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Uj.validateTuple)(t,"items")};vp.default=qj});var nP=R(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});var rP=D(),Hj=G(),Gj=vt(),Zj=gp(),Wj={message:({params:{len:t}})=>(0,rP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,rP._)`{limit: ${t}}`},Bj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Wj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,Hj.alwaysValidSchema)(n,e)&&(o?(0,Zj.validateAdditionalItems)(t,o):t.ok((0,Gj.validateArray)(t)))}};_p.default=Bj});var oP=R(Sp=>{"use strict";Object.defineProperty(Sp,"__esModule",{value:!0});var St=D(),Cc=G(),Vj={message:({params:{min:t,max:e}})=>e===void 0?(0,St.str)`must contain at least ${t} valid item(s)`:(0,St.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,St._)`{minContains: ${t}}`:(0,St._)`{minContains: ${t}, maxContains: ${e}}`},Kj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Vj,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let d=e.const("len",(0,St._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Cc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Cc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Cc.alwaysValidSchema)(s,r)){let m=(0,St._)`${d} >= ${i}`;a!==void 0&&(m=(0,St._)`${m} && ${d} <= ${a}`),t.pass(m);return}s.items=!0;let l=e.name("valid");a===void 0&&i===1?p(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,St._)`${o}.length > 0`,f)):(e.let(l,!1),f()),t.result(l,()=>t.reset());function f(){let m=e.name("_valid"),y=e.let("count",0);p(m,()=>e.if(m,()=>h(y)))}function p(m,y){e.forRange("i",0,d,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Cc.Type.Num,compositeRule:!0},m),y()})}function h(m){e.code((0,St._)`${m}++`),a===void 0?e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,St._)`${m} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,St._)`${m} >= ${i}`,()=>e.assign(l,!0)))}}};Sp.default=Kj});var aP=R(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.validateSchemaDeps=Jt.validatePropertyDeps=Jt.error=void 0;var wp=D(),Jj=G(),fi=vt();Jt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,wp.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,wp._)`{property: ${t},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${e},
8
- deps: ${r}}`};var Gj={keyword:"dependencies",type:"object",schemaType:"object",error:Jt.error,code(t){let[e,r]=Zj(t);rP(t,e),nP(t,r)}};function Zj({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 rP(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,fi.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,fi.checkReportMissingProp)(t,u)}):(r.if((0,wp._)`${c} && (${(0,fi.checkMissingProp)(t,a,s)})`),(0,fi.reportMissingProp)(t,s),r.else())}}Jt.validatePropertyDeps=rP;function nP(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Hj.alwaysValidSchema)(s,e[a])||(r.if((0,fi.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))}Jt.validateSchemaDeps=nP;Jt.default=Gj});var iP=R(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var sP=D(),Wj=G(),Bj={message:"property name must be valid",params:({params:t})=>(0,sP._)`{propertyName: ${t.propertyName}}`},Vj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Bj,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Wj.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,sP.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};bp.default=Vj});var Pp=R(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var xc=vt(),Ot=D(),Kj=dr(),kc=G(),Jj={message:"must NOT have additional properties",params:({params:t})=>(0,Ot._)`{additionalProperty: ${t.additionalProperty}}`},Yj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Jj,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,kc.alwaysValidSchema)(i,r))return;let u=(0,xc.allSchemaProperties)(n.properties),d=(0,xc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Ot._)`${s} === ${Kj.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(u.length>8){let b=(0,kc.schemaRefOrVal)(i,n.properties,"properties");v=(0,xc.isOwnProperty)(e,b,y)}else u.length?v=(0,Ot.or)(...u.map(b=>(0,Ot._)`${y} === ${b}`)):v=Ot.nil;return d.length&&(v=(0,Ot.or)(v,...d.map(b=>(0,Ot._)`${(0,xc.usePattern)(t,b)}.test(${y})`))),(0,Ot.not)(v)}function p(y){e.code((0,Ot._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,kc.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,Ot.not)(v),()=>{t.reset(),p(y)})):(m(y,v),a||e.if((0,Ot.not)(v),()=>e.break()))}}function m(y,v,b){let w={keyword:"additionalProperties",dataProp:y,dataPropType:kc.Type.Str};b===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,v)}}};Rp.default=Yj});var uP=R(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var Xj=Xs(),aP=vt(),Cp=G(),cP=Pp(),Qj={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&&cP.default.code(new Xj.KeywordCxt(s,cP.default,"additionalProperties"));let i=(0,aP.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Cp.mergeEvaluated.props(e,(0,Cp.toHash)(i),s.props));let a=i.filter(l=>!(0,Cp.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,aP.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)}}};xp.default=Qj});var pP=R(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var dP=vt(),Ec=D(),lP=G(),fP=G(),e1={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,dP.allSchemaProperties)(r),c=a.filter(m=>(0,lP.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 Ec.Name)&&(s.props=(0,fP.evaluatedPropsToName)(e,s.props));let{props:l}=s;f();function f(){for(let m of a)u&&p(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in u)new RegExp(m).test(y)&&(0,lP.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,Ec._)`${(0,dP.usePattern)(t,m)}.test(${y})`,()=>{let v=c.includes(m);v||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:fP.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,Ec._)`${l}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Ec.not)(d),()=>e.break())})})}}};kp.default=e1});var hP=R(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var t1=G(),r1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,t1.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"}};Ep.default=r1});var mP=R(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var n1=vt(),o1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:n1.validateUnion,error:{message:"must match a schema in anyOf"}};Tp.default=o1});var gP=R(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var Tc=D(),s1=G(),i1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Tc._)`{passingSchemas: ${t.passing}}`},a1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:i1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let f;(0,s1.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Tc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Tc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),f&&t.mergeEvaluated(f,Tc.Name)})})}}};Ap.default=a1});var yP=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var c1=G(),u1={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,c1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};$p.default=u1});var SP=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var Ac=D(),_P=G(),d1={message:({params:t})=>(0,Ac.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ac._)`{failingKeyword: ${t.ifClause}}`},l1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:d1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,_P.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=vP(n,"then"),s=vP(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,Ac.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),l?e.assign(l,(0,Ac._)`${d}`):t.setParams({ifClause:d})}}}};function vP(t,e){let r=t.schema[e];return r!==void 0&&!(0,_P.alwaysValidSchema)(t,r)}Mp.default=l1});var wP=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var f1=G(),p1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,f1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ip.default=p1});var bP=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var h1=gp(),m1=XR(),g1=yp(),y1=eP(),v1=tP(),_1=oP(),S1=iP(),w1=Pp(),b1=uP(),R1=pP(),P1=hP(),C1=mP(),x1=gP(),k1=yP(),E1=SP(),T1=wP();function A1(t=!1){let e=[P1.default,C1.default,x1.default,k1.default,E1.default,T1.default,S1.default,w1.default,_1.default,b1.default,R1.default];return t?e.push(m1.default,y1.default):e.push(h1.default,g1.default),e.push(v1.default),e}Op.default=A1});var RP=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var _e=D(),$1={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},M1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:$1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(v,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(v,m)),t.fail$data((0,_e.or)(b(),w()));function b(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${v}`}function w(){let x=d.$async?(0,_e._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,_e._)`${v}(${n})`,S=(0,_e._)`(typeof ${v} == "function" ? ${x} : ${v}.test(${n}))`;return(0,_e._)`${v} && ${v} !== true && ${y} === ${e} && !${S}`}}function p(){let h=l.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,v]=w(h);m===e&&t.pass(x());function b(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(S){let P=S instanceof RegExp?(0,_e.regexpCode)(S):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,I=r.scopeValue("formats",{key:s,ref:S,code:P});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,_e._)`${I}.validate`]:["string",S,I]}function x(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${v}(${n})`}return typeof y=="function"?(0,_e._)`${v}(${n})`:(0,_e._)`${v}.test(${n})`}}}};zp.default=M1});var PP=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var I1=RP(),O1=[I1.default];Np.default=O1});var CP=R(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.contentVocabulary=Po.metadataVocabulary=void 0;Po.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Po.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kP=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var z1=OR(),N1=VR(),D1=bP(),L1=PP(),xP=CP(),j1=[z1.default,N1.default,(0,D1.default)(),L1.default,xP.metadataVocabulary,xP.contentVocabulary];Dp.default=j1});var TP=R($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.DiscrError=void 0;var EP;(function(t){t.Tag="tag",t.Mapping="mapping"})(EP||($c.DiscrError=EP={}))});var $P=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Co=D(),Lp=TP(),AP=fc(),F1=Qs(),U1=G(),q1={message:({params:{discrError:t,tagName:e}})=>t===Lp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Co._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},H1={keyword:"discriminator",type:"object",schemaType:"object",error:q1,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,Co._)`${r}${(0,Co.getProperty)(a)}`);e.if((0,Co._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Lp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Co._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:Lp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,Co.Name),h}function f(){var p;let h={},m=v(o),y=!0;for(let x=0;x<i.length;x++){let S=i[x];if(S?.$ref&&!(0,U1.schemaHasRulesButRef)(S,s.self.RULES)){let I=S.$ref;if(S=AP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,I),S instanceof AP.SchemaEnv&&(S=S.schema),S===void 0)throw new F1.default(s.opts.uriResolver,s.baseId,I)}let P=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||v(S)),b(P,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:x}){return Array.isArray(x)&&x.includes(a)}function b(x,S){if(x.const)w(x.const,S);else if(x.enum)for(let P of x.enum)w(P,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(x,S){if(typeof x!="string"||x in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[x]=S}}}};jp.default=H1});var MP=R((A5,G1)=>{G1.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 Up=R((le,Fp)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var Z1=ER(),W1=kP(),B1=$P(),IP=MP(),V1=["/properties"],Mc="http://json-schema.org/draft-07/schema",xo=class extends Z1.default{_addVocabularies(){super._addVocabularies(),W1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(B1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(IP,V1):IP;this.addMetaSchema(e,Mc,!1),this.refs["http://json-schema.org/schema"]=Mc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mc)?Mc:void 0)}};le.Ajv=xo;Fp.exports=le=xo;Fp.exports.Ajv=xo;Object.defineProperty(le,"__esModule",{value:!0});le.default=xo;var K1=Xs();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return K1.KeywordCxt}});var ko=D();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return ko._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return ko.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return ko.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return ko.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return ko.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return ko.CodeGen}});var J1=dc();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return J1.default}});var Y1=Qs();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return Y1.default}})});var UP=R(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.formatNames=Xt.fastFormats=Xt.fullFormats=void 0;function Yt(t,e){return{validate:t,compare:e}}Xt.fullFormats={date:Yt(DP,Zp),time:Yt(Hp(!0),Wp),"date-time":Yt(OP(!0),jP),"iso-time":Yt(Hp(),LP),"iso-date-time":Yt(OP(),FP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nF,"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:dF,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:oF,int32:{type:"number",validate:aF},int64:{type:"number",validate:cF},float:{type:"number",validate:NP},double:{type:"number",validate:NP},password:!0,binary:!0};Xt.fastFormats={...Xt.fullFormats,date:Yt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zp),time:Yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wp),"date-time":Yt(/^\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,jP),"iso-time":Yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,LP),"iso-date-time":Yt(/^\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,FP),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};Xt.formatNames=Object.keys(Xt.fullFormats);function X1(t){return t%4===0&&(t%100!==0||t%400===0)}var Q1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function DP(t){let e=Q1.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&&X1(r)?29:eF[n])}function Zp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var qp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hp(t){return function(r){let n=qp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&i<61}}function Wp(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 LP(t,e){if(!(t&&e))return;let r=qp.exec(t),n=qp.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 Gp=/t|\s/i;function OP(t){let e=Hp(t);return function(n){let o=n.split(Gp);return o.length===2&&DP(o[0])&&e(o[1])}}function jP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function FP(t,e){if(!(t&&e))return;let[r,n]=t.split(Gp),[o,s]=e.split(Gp),i=Zp(r,o);if(i!==void 0)return i||Wp(n,s)}var tF=/\/|:/,rF=/^(?:[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 nF(t){return tF.test(t)&&rF.test(t)}var zP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function oF(t){return zP.lastIndex=0,zP.test(t)}var sF=-(2**31),iF=2**31-1;function aF(t){return Number.isInteger(t)&&t<=iF&&t>=sF}function cF(t){return Number.isInteger(t)}function NP(){return!0}var uF=/[^\\]\\Z/;function dF(t){if(uF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var qP=R(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.formatLimitDefinition=void 0;var lF=Up(),zt=D(),Gr=zt.operators,Ic={formatMaximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},formatMinimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},formatExclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},formatExclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},fF={message:({keyword:t,schemaCode:e})=>(0,zt.str)`should be ${Ic[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,zt._)`{comparison: ${Ic[t].okStr}, limit: ${e}}`};Eo.formatLimitDefinition={keyword:Object.keys(Ic),type:"string",schemaType:"string",$data:!0,error:fF,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 lF.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,zt._)`${f}[${c.schemaCode}]`);t.fail$data((0,zt.or)((0,zt._)`typeof ${p} != "object"`,(0,zt._)`${p} instanceof RegExp`,(0,zt._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:i.code.formats?(0,zt._)`${i.code.formats}${(0,zt.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,zt._)`${f}.compare(${r}, ${n}) ${Ic[o].fail} 0`}},dependencies:["format"]};var pF=t=>(t.addKeyword(Eo.formatLimitDefinition),t);Eo.default=pF});var WP=R((pi,ZP)=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});var To=UP(),hF=qP(),Bp=D(),HP=new Bp.Name("fullFormats"),mF=new Bp.Name("fastFormats"),Vp=(t,e={keywords:!0})=>{if(Array.isArray(e))return GP(t,e,To.fullFormats,HP),t;let[r,n]=e.mode==="fast"?[To.fastFormats,mF]:[To.fullFormats,HP],o=e.formats||To.formatNames;return GP(t,o,r,n),e.keywords&&(0,hF.default)(t),t};Vp.get=(t,e="full")=>{let n=(e==="fast"?To.fastFormats:To.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function GP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Bp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}ZP.exports=pi=Vp;Object.defineProperty(pi,"__esModule",{value:!0});pi.default=Vp});var wC=R((f3,SC)=>{SC.exports=_C;_C.sync=BF;var yC=vr("fs");function WF(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 vC(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:WF(e,r)}function _C(t,e,r){yC.stat(t,function(n,o){r(n,n?!1:vC(o,t,e))})}function BF(t,e){return vC(yC.statSync(t),t,e)}});var xC=R((p3,CC)=>{CC.exports=RC;RC.sync=VF;var bC=vr("fs");function RC(t,e,r){bC.stat(t,function(n,o){r(n,n?!1:PC(o,e))})}function VF(t,e){return PC(bC.statSync(t),e)}function PC(t,e){return t.isFile()&&KF(t,e)}function KF(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 EC=R((m3,kC)=>{var h3=vr("fs"),Gc;process.platform==="win32"||global.TESTING_WINDOWS?Gc=wC():Gc=xC();kC.exports=ph;ph.sync=JF;function ph(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){ph(t,e||{},function(s,i){s?o(s):n(i)})})}Gc(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function JF(t,e){try{return Gc.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var zC=R((g3,OC)=>{var Do=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",TC=vr("path"),YF=Do?";":":",AC=EC(),$C=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),MC=(t,e)=>{let r=e.colon||YF,n=t.match(/\//)||Do&&t.match(/\\/)?[""]:[...Do?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Do?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Do?o.split(r):[""];return Do&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},IC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=MC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l($C(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=TC.join(p,t),m=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];AC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},XF=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=MC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=TC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if(AC.sync(f,{pathExt:o}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw $C(t)};OC.exports=IC;IC.sync=XF});var DC=R((y3,hh)=>{"use strict";var NC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};hh.exports=NC;hh.exports.default=NC});var UC=R((v3,FC)=>{"use strict";var LC=vr("path"),QF=zC(),eU=DC();function jC(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=QF.sync(t.command,{path:r[eU({env:r})],pathExt:e?LC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=LC.resolve(o?t.options.cwd:"",i)),i}function tU(t){return jC(t)||jC(t,!0)}FC.exports=tU});var qC=R((_3,gh)=>{"use strict";var mh=/([()\][%!^"`<>&|;, *?])/g;function rU(t){return t=t.replace(mh,"^$1"),t}function nU(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(mh,"^$1"),e&&(t=t.replace(mh,"^$1")),t}gh.exports.command=rU;gh.exports.argument=nU});var GC=R((S3,HC)=>{"use strict";HC.exports=/^#!(.*)/});var WC=R((w3,ZC)=>{"use strict";var oU=GC();ZC.exports=(t="")=>{let e=t.match(oU);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var VC=R((b3,BC)=>{"use strict";var yh=vr("fs"),sU=WC();function iU(t){let r=Buffer.alloc(150),n;try{n=yh.openSync(t,"r"),yh.readSync(n,r,0,150,0),yh.closeSync(n)}catch{}return sU(r.toString())}BC.exports=iU});var XC=R((R3,YC)=>{"use strict";var aU=vr("path"),KC=UC(),JC=qC(),cU=VC(),uU=process.platform==="win32",dU=/\.(?:com|exe)$/i,lU=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function fU(t){t.file=KC(t);let e=t.file&&cU(t.file);return e?(t.args.unshift(t.file),t.command=e,KC(t)):t.file}function pU(t){if(!uU)return t;let e=fU(t),r=!dU.test(e);if(t.options.forceShell||r){let n=lU.test(e);t.command=aU.normalize(t.command),t.command=JC.command(t.command),t.args=t.args.map(s=>JC.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 hU(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:pU(n)}YC.exports=hU});var tx=R((P3,ex)=>{"use strict";var vh=process.platform==="win32";function _h(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 mU(t,e){if(!vh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=QC(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function QC(t,e){return vh&&t===1&&!e.file?_h(e.original,"spawn"):null}function gU(t,e){return vh&&t===1&&!e.file?_h(e.original,"spawnSync"):null}ex.exports={hookChildProcess:mU,verifyENOENT:QC,verifyENOENTSync:gU,notFoundError:_h}});var ox=R((C3,Lo)=>{"use strict";var rx=vr("child_process"),Sh=XC(),wh=tx();function nx(t,e,r){let n=Sh(t,e,r),o=rx.spawn(n.command,n.args,n.options);return wh.hookChildProcess(o,n),o}function yU(t,e,r){let n=Sh(t,e,r),o=rx.spawnSync(n.command,n.args,n.options);return o.error=o.error||wh.verifyENOENTSync(o.status,n),o}Lo.exports=nx;Lo.exports.spawn=nx;Lo.exports.sync=yU;Lo.exports._parse=Sh;Lo.exports._enoent=wh});var dx=R(Rh=>{"use strict";var ax=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,bU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,cx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,RU=/\\([\u000b\u0020-\u00ff])/g,PU=/([\\"])/g,ux=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Rh.format=CU;Rh.parse=xU;function CU(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!ux.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],!cx.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+EU(e[o])}return n}function xU(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?kU(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(!ux.test(n))throw new TypeError("invalid media type");var o=new TU(n.toLowerCase());if(r!==-1){var s,i,a;for(ax.lastIndex=r;i=ax.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(RU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function kU(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 EU(t){var e=String(t);if(cx.test(e))return e;if(e.length>0&&!bU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(PU,"\\$1")+'"'}function TU(t){this.parameters=Object.create(null),this.type=t}});import{logger as WZ}from"@hermes/logger";import{logger as Kq}from"@hermes/logger";var DE="mcp-auth";function Te(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(DE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as Pq}from"@augmentcode/auggie-v2";import{logger as Cq}from"@hermes/logger";import{logger as cT}from"@hermes/logger";import{logger as jE}from"@hermes/logger";function LE(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 _r(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":LE(t,e,r)?"plugin":"local"}function FE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var hm=jE.child({prefix:"pi-mcp"}),UE="augment:mcp-status-report";function tr(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 Zo(t,e,r,n){let o=tr(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 nt(t,e,r){if(r){let o=tr(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 qE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=tr(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 Fi=3e4;function HE(t){switch(t.status){case"success":return"connected";case"failed":case"auth_required":return"failed";case"initializing":{let e=t.connectStartedAt;return e!==void 0&&Date.now()-e>=Fi?"failed":void 0}default:return}}var mm="authentication required",GE="Authentication refresh is pending in the backend; retry shortly.",ZE="timed out connecting after 30s",WE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",BE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",VE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",KE="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",JE="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function YE(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),s=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),i=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=i(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?BE:WE,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=i(a);s.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...XE({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}}function XE(t){let{state:e,id:r,name:n,reportedNames:o}=t;return e.authFallbackDisplacedConfigIds.has(r)?{errorMessage:JE,failureCategory:"auth_terminal"}:{errorMessage:o.has(n)?KE:VE,failureCategory:"configuration"}}function QE(t,e){return e!==void 0?e.isAuthError?mm:e.error:t.status==="initializing"?ZE:t.lastError??(t.status==="auth_required"?mm:void 0)}function eT(t,e){let r=HE(t);if(r===void 0)return;let n=qE(e,t.name),o=r==="connected"?FE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:_r(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"?GE:QE(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 tT(t){let e=[];for(let r of t.servers.values()){let n=eT(r,t);n!==void 0&&e.push(n)}return YE(t,e),e}function J(t,e){try{let r=tT(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(UE,o),hm.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){hm.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Ui={local:4,registry:3,plugin:2,vfs:1};function Ft(t){return t.hostLeases??=new Map,t.hostLeases}function rT(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Wo(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Bo(t,e){return t.kind===e.kind&&t.identity===e.identity}function gm(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 Pu(t,e){let r=rT(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function qi(t,e,r){if(r.kind==="registry"){Wo(t).set(e,{kind:"domain",domain:r.identity});return}Wo(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 Fn(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=Ft(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?Fn(i,s):{kind:s??"local",identity:e},c={owner:a,revision:Pu(t,e),host:r};return n.set(e,c),qi(t,e,a),c}function ym(t){let{state:e,name:r,host:n}=t,o=Ft(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:Pu(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),qi(e,r,i.owner),i}function Vo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Ft(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Ui[n.kind]>Ui[a.owner.kind],f=Ui[n.kind]===Ui[a.owner.kind],p=o===a.revision&&(s===void 0||s===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?gm(a):void 0;Cu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:Pu(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),qi(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function xu(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=Ft(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Wo(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function Hi(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e).get(r);return!i||i.revision!==o||!Bo(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 Pt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e).get(r);if(!i||i.revision!==o||!Bo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=gm(i);if(a)return Cu(e,r,s),i.host=void 0,i.retirement=a,a}function vm(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Ft(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Bo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Bo(i.owner,n)||i.revision!==o.incumbent.revision?(qi(e,r,i.owner),!0):(s.delete(r),Wo(e).set(r,{kind:"blocked"}),!0))}function Pe(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e),a=i.get(r);return!a||a.revision!==o||!Bo(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),Wo(e).set(r,{kind:"blocked"}),!0)}function W(t,e){return Ft(t).get(e)}function _m(t,e,r){return Ft(t).get(e)?.host===r}function Sm(t){if(t!==void 0)try{return new URL(t).toString()}catch{return t}}function Sr(t,e){return!t||!e?!1:t.id===e.id&&t.name===e.name&&t.type===e.type&&Sm(t.url)===Sm(e.url)&&t.registrySource===e.registrySource&&t.vfsSource===e.vfsSource}var Un=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;_credentialIdentities=new Map;get(e){return this._tokens.get(e)}commit(e,r,n){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e),n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e)}hasCredentialIdentity(e,r){return Sr(this._credentialIdentities.get(e),r)}reconcileCredentialIdentity(e,r,n){return this._tokens.get(e)!==r||this._retiredCredentials.has(e)?!1:(n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e),!0)}set(e,r,n){this.commit(e,r,n)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,s,i){return this.persist(e,n,i)}restoreAfterSupersededRefresh(e,r,n,o,s,i){return this.restoreAfterSupersededAuthentication(e,r,n,o,s,i)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations),credentialIdentities:new Map([...this._credentialIdentities].map(([e,r])=>[e,{...r}]))}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n);for(let[r,n]of e.credentialIdentities??[])this._credentialIdentities.set(r,{...n})}delete(e,r){this._tokens.delete(e),this._credentialIdentities.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._credentialIdentities.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};function Jo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function ku(t){try{return new URL(t).toString()}catch{return t}}function Ko(t){if(!(t.type!=="http"&&t.type!=="sse"))return{id:t.id,name:t.name,type:t.type,url:ku(t.url),auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Ut(t,e){return Ko(e.config)}function ut(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:ku(t.url)===ku(e.url)}function Eu(t,e){let r=Ko(t),n=Ko(e);return!r||!n?ut(t,e):Sr(r,n)}function Tu(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function nT(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 oT(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!ut(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function wm(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!Tu(e,r):n!==void 0&&e!==n}function bm(t,e,r){return r&&e!==void 0&&t!==void 0&&Tu(t,e)}function sT(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!Tu(s,n))}function Rm(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(oT({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||wm({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&wm({identity:i.domain,...l})?!0:sT({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function iT(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return Ko(r);if(n!==void 0)return{id:n,name:e}}function aT(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!Ko(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function Pm(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=nT({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,f=Rm({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),p=bm(s,u,d),h=bm(i,u,d),m=!f,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,b=f&&!(m||p||h||y);if(o==="durable"){let P=iT({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:b})}let w=Rm({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),x=m&&!w,S=!1;return t.equalRevisionRebindDomains?.delete(e),(x||p)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),S=!0),(x||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),S=!0),x&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),aT({state:t,name:e,mode:o,stillOwnsNameScopedRevision:x,retiredConfig:c}),S&&(Jo(t,e),nt(t,e),t.authRefreshNeededReportKeys?.delete(e)),x}function dt(t,e,r,n){return Pm(t,e,r,n,"durable")}function Yo(t,e,r,n){return Pm(t,e,r,n,"session")}function Cm(t){let e=[];if(Object.hasOwn(t,"credential_owner_domain")&&e.push(t.credential_owner_domain),Object.hasOwn(t,"credentialOwnerDomain")&&e.push(t.credentialOwnerDomain),e.length===0)return{kind:"absent"};if(e.some(n=>typeof n!="string"||!/^user:.+/.test(n)))return{kind:"invalid"};let r=e[0];return e.every(n=>n===r)?{kind:"valid",ownerDomain:r}:{kind:"invalid"}}function wr(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 xm="augment:mcp-oauth-credentials",km=300*1e3,uT=256,Au=cT.child({prefix:"pi-mcp"}),Ct=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function ot(t){return`user:${t}`}function Yr(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||wr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function Rr(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="recipient"&&r!=="user"&&r!=="tenant"?t:ot(t.slice(e+1))}function st(t){return/^secret:(private|shared):.+/.test(t)}function Xr(t){return t.ownerDomain??Rr(t.domain)}function Em(t,e,r){let n=ot(e);return r!==void 0?r===n:st(t)||Rr(t)===n}function dT(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function lT(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 fT(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function pT(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&dT(t.credentialRevisions.get(e),r.credentialRevision)&&fT(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function hT(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 mT(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??"")||!ut(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Qr(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function br(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function Tm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=km&&br(t,n)}function gT(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&br(t,e)}function Am(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Qr(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();Tm(e,a);let c=Xr(n),u=st(c)?`${c}\0${r}`:c,d=i.get(u),l=d?.credential.credential_revision??d?.credential.credentialRevision;if(typeof l=="string"&&wr(n.revision,l)<=0)return;!d&&i.size>=uT&&gT(e),br(e,u);let f={serverName:r,credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(u,f),f.expiryTimer=setTimeout(()=>{i.get(u)===f&&br(e,u)},km),f.expiryTimer.unref?.(),Au.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function yT(t,e){Qr(t);let r=(t.registryCredentialIntentEpochs.get(e)??0)+1;return t.registryCredentialIntentEpochs.set(e,r),r}function We(t){let{state:e,domain:r,epoch:n,preserveFence:o=!1,preserveBootCredential:s=!1}=t;Qr(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||br(e,r)}}function Gi(t){let{state:e,domain:r,forceNew:n=!1}=t;Qr(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let s=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&We({state:e,domain:r,epoch:o.epoch});let i={epoch:yT(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 $m(t,e){Qr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||We({state:t,domain:r,epoch:n.epoch});for(let r of t.pendingRegistryCredentialDomains)e.has(r)||(t.pendingRegistryCredentialDomains.delete(r),t.stagedOAuthCredentials.delete(r));for(let r of t.stagedOAuthCredentials.keys())e.has(r)||t.stagedOAuthCredentials.delete(r);for(let r of t.bootOAuthCredentialBuffer?.keys()??[]){let n=r.split("\0",1)[0];!e.has(r)&&!st(n)&&br(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);Gi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function vT(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||W(e,r.name)?.owner.kind==="local")return;Qr(e);let n=ot(r.id),o=hT(r),s=mT({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?(We({state:e,domain:n,epoch:i.epoch}),i=void 0):i&&(i.allowEqualRevisionRebind=s);if(!i){let a=Gi({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),_T({state:e,config:r,domain:n}),{domain:n,...i}}function Mm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Qr(e);let s=Xr(r),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:wr(r.revision,a),f=l===0;l!==void 0&&l<0||f&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&wr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:f})}function _T(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n});let s=e.credentialRevisions.get(r.name);(o===void 0||s?.ownerDomain!==void 0&&s.ownerDomain!==n||s?.ownerDomain===void 0&&!st(o)&&Rr(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),nt(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function ST(t){let{state:e,config:r,pi:n,intent:o}=t,s=e.stagedOAuthCredentials.get(o.domain);if(!s||s.intentEpoch!==o.epoch||s.configFingerprint!==o.configFingerprint||s.requiresEqualRevisionRebind&&!o.allowEqualRevisionRebind)return;e.stagedOAuthCredentials.delete(o.domain),s.requiresEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),We({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0,preserveBootCredential:!0});let i={[r.name]:s.credential};n.events.emit(xm,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function wT(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();Tm(e,o);let s=e.bootOAuthCredentialBuffer?.get(r);if(s)return br(e,r),s;for(let[i,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&st(i.split("\0",1)[0]))return br(e,i),a}function bT(t){let{config:e,pi:r,buffered:n}=t;Au.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),Au.info("MCP OAuth boot credential replayed",{hasRegistryConfigId:e.id!==void 0,registryOwned:e.registrySource!==void 0,visibility:"public"});let o={[e.name]:n.credential};r.events.emit(xm,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function RT(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(ut(n,r)){if(n.name===r.name)return;await Yo(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await dt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function PT(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=pT(e,r.name,o);We({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 Ct(a)}async function CT(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 RT({state:e,config:r,previousConfig:s})}catch(h){throw PT({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 We({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),ST({state:e,config:r,pi:n,intent:o});let p=wT({state:e,domain:o.domain,serverName:r.name});return We({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&bT({config:r,pi:n,buffered:p}),!0}function Pr(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=vT({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=lT(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 CT({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 FT}from"@augmentcode/auggie-v2";import{homedir as Im}from"node:os";import{sep as xT}from"node:path";var $u=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},kT=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,ET=/\\\$\{/g,TT=new Set(["workspaceFolder","augmentToken"]),Om="${workspaceFolder}";function zm(t,e){return t.includes(Om)?t.split(Om).join(e):t}function Nm(t,e){return t.includes("${")?t.replace(kT,(n,o,s)=>{if(TT.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new $u(o)}).replace(ET,"${"):t}function AT(t){return t.startsWith("~")?t==="~"?Im():t.startsWith("~/")||t.startsWith(`~${xT}`)?Im()+t.slice(1):t:t}function Mu(t,e,r){return AT(Nm(zm(t,e),r))}function Zi(t,e,r){return Nm(zm(t,e),r)}function Dm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Zi(s,e,r);return n}var $T="$augment-";function MT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith($T)?s:Zi(s,e,r);return n}function qt(t,e){let r=process.env;return{...t,url:Zi(t.url,e,r),headers:MT(t.headers,e,r)}}function Ht(t,e){let r=process.env;return{...t,command:Mu(t.command,e,r),args:t.args,env:t.env?Dm(t.env,e,r):void 0,cwd:t.cwd?Mu(t.cwd,e,r):e}}import{readFileSync as NT}from"node:fs";import{logger as IT}from"@hermes/logger";var OT=IT.child({prefix:"pi-mcp"}),xt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function qn(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 zT(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 Hn(t,e){let r=qn(e);if(!r)throw new xt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new xt(`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 xt(`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&&OT.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:zT(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var Fm=t=>NT(t,"utf8");function Wi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Lm(t){return Wi(t)&&("command"in t||"url"in t)}function Ou(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function jm(t,e){return Ou(t.name)??e}function Iu(t,e){let r=qn(t);if(r==="http"||r==="sse")return Ou(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return Ou(t.name,t.title,n)??e}function DT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[Iu(n,String(r)),n]});if(Wi(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[Iu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(Wi(n))return Object.entries(n).map(([o,s])=>{let i=s;return[jm(i,o),i]})}if(Lm(t)){let r=t;return[[Iu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(Lm))return Object.entries(t).map(([r,n])=>{if(!Wi(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[jm(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 zu(t){return t instanceof Error?t.message:String(t)}function LT(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}": ${zu(s)}`});return}}function jT(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=LT(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}: ${zu(c)}`}),[]}try{return DT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${zu(c)}`}),[]}}function Nu(t,e=Fm){let r={},n=[];for(let o of t)for(let[s,i]of jT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function Du(t,e=Fm){return!t||t.length===0?new Set:new Set(Object.keys(Nu(t,e).servers))}var UT=["global","project","local","managed"];function qT(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 HT(t){let e={};for(let r of t)if(r)for(let[n,o]of Object.entries(r)){if(o===null){delete e[n];continue}o&&(e[n]=structuredClone(o))}return e}function GT(t,e,r){let n=Nu(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 ZT(t,e,r){let n=FT.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 HT(UT.map(o=>qT(n,o)))}function Gn(t,e,r,n){let o=[],s=r&&r.length>0?GT(r,n,o):ZT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Hn(a,c);i.push(u.type==="stdio"?Ht(u,t):qt(u,t))}catch(u){let d=u instanceof xt?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 Bm}from"@augmentcode/auggie-v2";import{logger as nA}from"@hermes/logger";import{Type as oA}from"@sinclair/typebox";var Bi=Symbol.for("__pi_mcp_state__");function WT(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 BT(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function VT(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&WT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&BT(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 KT(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&VT(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 Xo(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 Vi(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 JT(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 Um(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Ki(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()?JT({state:e,configId:r,generation:n}):Um({state:e,configId:r,generation:n}),i),i=>{throw Um({state:e,configId:r,generation:n}),i})}function ie(){let t=globalThis;if(t[Bi])return KT(t[Bi]),t[Bi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Un,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations:new Map,serverGenerations:new Map,configRevisions:new Map,configDesiredRevisions:new Map,configDesiredSources:new Map,credentialRevisions:new Map,oauthCredentialRevisions:new Map,oauthCredentialDomains:new Map,equalRevisionRebindDomains:new Map,preservedCredentialIdentities:new Map,stagedOAuthCredentials:new Map,bootOAuthCredentialBuffer:new Map,pendingRegistryCredentialDomains:new Set,registryCredentialIntents:new Map,registryCredentialIntentEpochs:new Map,registryCredentialFinalizationsByName:new Map,statusHostGeneration:1,statusReportSequence:0,statusFailureCategories:new Map,authRefreshNeededReportKeys:new Map,hostedCredentialOwnership:new Map,shouldProactivelyRefreshTokens:!0,backgroundRefreshIntervalId:void 0,credsListenerBound:!1,configIdsListenerBound:!1,registryGeneration:0,liveEditGenerations:new Map,attachmentCommandGenerations:new Map,attachmentCommandInFlightGenerations:new Map,attachmentCommandAppliedGenerations:new Map,mcpConfigsListenerBound:!1,embeddedRegistryConfigs:void 0,vfsListenerBound:!1,addServerListenerBound:!1,restartServerListenerBound:!1,removeServerListenerBound:!1,mcpRestartState:new Map,vfsGeneration:0,lastSuccessfulVfsMcpSignature:void 0,blockedVfsMcpNames:new Set,credentials:void 0,secretsClient:void 0,headerSecrets:{},headerSecretFailures:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,authFallbackDisplacedConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1};return t[Bi]=e,e}var qm=Symbol.for("__hermes_mcp_tool_registry__"),YT=Symbol.for("__hermes_mcp_extension_factory__");function Hm(){let t=globalThis;return t[qm]??=new Map,t[qm]}function Cr(t){Hm().set(t.name,t)}function Gm(t,e){let r=Hm();(e===void 0||r.get(t)===e)&&r.delete(t)}function Zm(t){Reflect.set(t,YT,!0)}function Ji(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 XT(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function QT(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 eA(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
- `).trim()}function Lu(t,e,r){if(t.isError){let o=eA(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=QT(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 Wm(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Ji(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=XT(t.params),o=await e.callTool(r,n,t.signal);return Lu(o,t.serverName,r)}var tA=/[^a-zA-Z0-9_-]/g;function ju(t){return t.replace(tA,"_")}function rA(t,e){let r=ju(e),n=ju(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var xr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=rA(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=`_${ju(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Fu=nA.child({prefix:"pi-mcp"});function Yi(){return ie().toolRegistrationsByPi}function Vm(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=oA.Unsafe(n.inputSchema??{})}catch(c){Fu.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>ie().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,f)=>Wm({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(p=>p.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function Uu(t,e,r,n){if(e.ownerByToolName.get(n)!==r)return;let o=t.getActiveTools().includes(n),s=r.definitionsByName?.get(n);e.ownerByToolName.delete(n),t.unregisterTool(n),Gm(n,s),r.definitionsByName?.delete(n),sA(t,e,n,r,o)}function sA(t,e,r,n,o){let s=ie();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 xr(i);for(let d of c.listTools()){let{namespaced:l,collision:f}=u.put(d.name);if(f||l!==r)continue;let p=Vm({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!p)return;Bm(r,"mcp"),t.registerTool(p),Cr(p),a.definitionsByName??=new Map,a.definitionsByName.set(r,p),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function iA(t,e){let r=Yi(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=ie().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)Uu(t,n,s,a);let i={generation:o,host:e,map:new xr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function qu(t,e){let{registration:r,replaced:n}=iA(t,e),o=new Set(r.registeredNames),s=new xr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:f}=s.put(d.name);if(f){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=ie();y.diagnostics.some(b=>b.server===i&&b.message.includes(`both map to "${l}"`))||(Fu.warn(m),y.diagnostics.push({server:i,message:m}));continue}let p=Vm({pi:t,serverName:i,tool:d,map:s,namespaced:l});p&&(Bm(l,"mcp"),t.registerTool(p),Cr(p),r.definitionsByName??=new Map,r.definitionsByName.set(l,p),Yi().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Yi().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&Uu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Fu.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Hu(t,e,r){let n=Yi().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)Uu(t,n,o,s);return n.byServer.delete(e.name),!0}function Km(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&qu(t,r)}import{getToolSource as yA}from"@augmentcode/auggie-v2";import{Type as aA}from"@sinclair/typebox";var cA="cliMcpToolSearchAutoEnable",uA="cliMcpToolSearchTokenThreshold",dA=!1,Jm=2e4;function lA(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function fA(t){let e=0;for(let r of t.servers.values())e+=pA(r);return e}function pA(t){if(t.status!=="success")return 0;let e=new xr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||hA(n.inputSchema)&&(r+=lA(n))}return r}function hA(t){try{return aA.Unsafe(t??{}),!0}catch{return!1}}function mA(t){let r=t.featureFlags?.flags?.[cA];return typeof r=="boolean"?r:dA}function gA(t){let r=t.featureFlags?.flags?.[uA];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:Jm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:Jm}function Ym(t){return mA(t)?fA(t)>=gA(t):!1}var vA="AUGGIE_ENABLE_TOOL_SEARCH",_A=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Qo(){return process.env[vA]==="1"}function Zn(t){return Qo()||t.toolSearchLatched?!0:Ym(t)?(t.toolSearchLatched=!0,!0):!1}function Xi(t){let e=t.getActiveTools(),r=e.filter(n=>!SA(n)||_A.has(n));r.length!==e.length&&t.setActiveTools(r)}function SA(t){return yA(t)==="mcp"}import{setToolSource as sg}from"@augmentcode/auggie-v2";import{logger as FA}from"@hermes/logger";import{Type as ig}from"@sinclair/typebox";import{logger as wA}from"@hermes/logger";var es={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},en={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var Xm=wA.child({prefix:"pi-mcp"}),bA=5e3,RA=1,PA=2,CA=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),xA=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function kA(t){if(typeof t=="number")return t===2||t===3;if(typeof t=="string"){let e=t.toUpperCase();return e.includes("OAUTH")||e.includes("API_KEY")}return!1}function EA(t){return t===RA||typeof t=="string"&&CA.has(t)?"available":t===PA||typeof t=="string"&&xA.has(t)?"opt_in_required":"unknown"}function TA(t){if(!(typeof t.id!="string"||t.id.length===0))return{id:t.id,name:typeof t.name=="string"&&t.name.length>0?t.name:t.id,description:typeof t.description=="string"?t.description:"",requiresAuth:kA(t.auth_type),state:EA(t.state)}}function Gu(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 tn(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Gu(t,r))}async function Qm(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:en.UNSPECIFIED}),signal:AbortSignal.timeout(r??bA)});if(!s.ok)return Xm.debug(`MCP catalog fetch failed with ${s.status}; treating catalog as empty`),{ok:!1,disable:s.status===404};let i=await s.json(),a=[];for(let c of i.entries??[]){let u=TA(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return Xm.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var AA="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",$A=`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 Yj={keyword:"dependencies",type:"object",schemaType:"object",error:Jt.error,code(t){let[e,r]=Xj(t);sP(t,e),iP(t,r)}};function Xj({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 sP(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,fi.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,fi.checkReportMissingProp)(t,u)}):(r.if((0,wp._)`${c} && (${(0,fi.checkMissingProp)(t,a,s)})`),(0,fi.reportMissingProp)(t,s),r.else())}}Jt.validatePropertyDeps=sP;function iP(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Jj.alwaysValidSchema)(s,e[a])||(r.if((0,fi.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))}Jt.validateSchemaDeps=iP;Jt.default=Yj});var uP=R(bp=>{"use strict";Object.defineProperty(bp,"__esModule",{value:!0});var cP=D(),Qj=G(),e1={message:"property name must be valid",params:({params:t})=>(0,cP._)`{propertyName: ${t.propertyName}}`},t1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:e1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Qj.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,cP.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};bp.default=t1});var Pp=R(Rp=>{"use strict";Object.defineProperty(Rp,"__esModule",{value:!0});var xc=vt(),Ot=D(),r1=dr(),kc=G(),n1={message:"must NOT have additional properties",params:({params:t})=>(0,Ot._)`{additionalProperty: ${t.additionalProperty}}`},o1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:n1,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,kc.alwaysValidSchema)(i,r))return;let u=(0,xc.allSchemaProperties)(n.properties),d=(0,xc.allSchemaProperties)(n.patternProperties);l(),t.ok((0,Ot._)`${s} === ${r1.default.errors}`);function l(){e.forIn("key",o,y=>{!u.length&&!d.length?h(y):e.if(f(y),()=>h(y))})}function f(y){let v;if(u.length>8){let b=(0,kc.schemaRefOrVal)(i,n.properties,"properties");v=(0,xc.isOwnProperty)(e,b,y)}else u.length?v=(0,Ot.or)(...u.map(b=>(0,Ot._)`${y} === ${b}`)):v=Ot.nil;return d.length&&(v=(0,Ot.or)(v,...d.map(b=>(0,Ot._)`${(0,xc.usePattern)(t,b)}.test(${y})`))),(0,Ot.not)(v)}function p(y){e.code((0,Ot._)`delete ${o}[${y}]`)}function h(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,kc.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(m(y,v,!1),e.if((0,Ot.not)(v),()=>{t.reset(),p(y)})):(m(y,v),a||e.if((0,Ot.not)(v),()=>e.break()))}}function m(y,v,b){let w={keyword:"additionalProperties",dataProp:y,dataPropType:kc.Type.Str};b===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,v)}}};Rp.default=o1});var fP=R(xp=>{"use strict";Object.defineProperty(xp,"__esModule",{value:!0});var s1=Xs(),dP=vt(),Cp=G(),lP=Pp(),i1={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&&lP.default.code(new s1.KeywordCxt(s,lP.default,"additionalProperties"));let i=(0,dP.allSchemaProperties)(r);for(let l of i)s.definedProperties.add(l);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Cp.mergeEvaluated.props(e,(0,Cp.toHash)(i),s.props));let a=i.filter(l=>!(0,Cp.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,dP.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)}}};xp.default=i1});var gP=R(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var pP=vt(),Ec=D(),hP=G(),mP=G(),a1={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,pP.allSchemaProperties)(r),c=a.filter(m=>(0,hP.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 Ec.Name)&&(s.props=(0,mP.evaluatedPropsToName)(e,s.props));let{props:l}=s;f();function f(){for(let m of a)u&&p(m),s.allErrors?h(m):(e.var(d,!0),h(m),e.if(d))}function p(m){for(let y in u)new RegExp(m).test(y)&&(0,hP.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function h(m){e.forIn("key",n,y=>{e.if((0,Ec._)`${(0,pP.usePattern)(t,m)}.test(${y})`,()=>{let v=c.includes(m);v||t.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:mP.Type.Str},d),s.opts.unevaluated&&l!==!0?e.assign((0,Ec._)`${l}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Ec.not)(d),()=>e.break())})})}}};kp.default=a1});var yP=R(Ep=>{"use strict";Object.defineProperty(Ep,"__esModule",{value:!0});var c1=G(),u1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,c1.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"}};Ep.default=u1});var vP=R(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var d1=vt(),l1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:d1.validateUnion,error:{message:"must match a schema in anyOf"}};Tp.default=l1});var _P=R(Ap=>{"use strict";Object.defineProperty(Ap,"__esModule",{value:!0});var Tc=D(),f1=G(),p1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Tc._)`{passingSchemas: ${t.passing}}`},h1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:p1,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((d,l)=>{let f;(0,f1.alwaysValidSchema)(o,d)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Tc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Tc._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),f&&t.mergeEvaluated(f,Tc.Name)})})}}};Ap.default=h1});var SP=R($p=>{"use strict";Object.defineProperty($p,"__esModule",{value:!0});var m1=G(),g1={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,m1.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};$p.default=g1});var RP=R(Mp=>{"use strict";Object.defineProperty(Mp,"__esModule",{value:!0});var Ac=D(),bP=G(),y1={message:({params:t})=>(0,Ac.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ac._)`{failingKeyword: ${t.ifClause}}`},v1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:y1,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,bP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=wP(n,"then"),s=wP(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,Ac.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let f=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(f,i),l?e.assign(l,(0,Ac._)`${d}`):t.setParams({ifClause:d})}}}};function wP(t,e){let r=t.schema[e];return r!==void 0&&!(0,bP.alwaysValidSchema)(t,r)}Mp.default=v1});var PP=R(Ip=>{"use strict";Object.defineProperty(Ip,"__esModule",{value:!0});var _1=G(),S1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,_1.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ip.default=S1});var CP=R(Op=>{"use strict";Object.defineProperty(Op,"__esModule",{value:!0});var w1=gp(),b1=tP(),R1=yp(),P1=nP(),C1=oP(),x1=aP(),k1=uP(),E1=Pp(),T1=fP(),A1=gP(),$1=yP(),M1=vP(),I1=_P(),O1=SP(),z1=RP(),N1=PP();function D1(t=!1){let e=[$1.default,M1.default,I1.default,O1.default,z1.default,N1.default,k1.default,E1.default,x1.default,T1.default,A1.default];return t?e.push(b1.default,P1.default):e.push(w1.default,R1.default),e.push(C1.default),e}Op.default=D1});var xP=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var _e=D(),L1={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},j1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:L1,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:d,self:l}=a;if(!c.validateFormats)return;o?f():p();function f(){let h=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),m=r.const("fDef",(0,_e._)`${h}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,_e._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(y,(0,_e._)`${m}.type || "string"`).assign(v,(0,_e._)`${m}.validate`),()=>r.assign(y,(0,_e._)`"string"`).assign(v,m)),t.fail$data((0,_e.or)(b(),w()));function b(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${v}`}function w(){let x=d.$async?(0,_e._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,_e._)`${v}(${n})`,S=(0,_e._)`(typeof ${v} == "function" ? ${x} : ${v}.test(${n}))`;return(0,_e._)`${v} && ${v} !== true && ${y} === ${e} && !${S}`}}function p(){let h=l.formats[s];if(!h){b();return}if(h===!0)return;let[m,y,v]=w(h);m===e&&t.pass(x());function b(){if(c.strictSchema===!1){l.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(S){let P=S instanceof RegExp?(0,_e.regexpCode)(S):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,I=r.scopeValue("formats",{key:s,ref:S,code:P});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,_e._)`${I}.validate`]:["string",S,I]}function x(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!d.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${v}(${n})`}return typeof y=="function"?(0,_e._)`${v}(${n})`:(0,_e._)`${v}.test(${n})`}}}};zp.default=j1});var kP=R(Np=>{"use strict";Object.defineProperty(Np,"__esModule",{value:!0});var F1=xP(),U1=[F1.default];Np.default=U1});var EP=R(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.contentVocabulary=Po.metadataVocabulary=void 0;Po.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Po.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var AP=R(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});var q1=DR(),H1=YR(),G1=CP(),Z1=kP(),TP=EP(),W1=[q1.default,H1.default,(0,G1.default)(),Z1.default,TP.metadataVocabulary,TP.contentVocabulary];Dp.default=W1});var MP=R($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});$c.DiscrError=void 0;var $P;(function(t){t.Tag="tag",t.Mapping="mapping"})($P||($c.DiscrError=$P={}))});var OP=R(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});var Co=D(),Lp=MP(),IP=fc(),B1=Qs(),V1=G(),K1={message:({params:{discrError:t,tagName:e}})=>t===Lp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Co._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},J1={keyword:"discriminator",type:"object",schemaType:"object",error:K1,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Co._)`${r}${(0,Co.getProperty)(a)}`);e.if((0,Co._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Lp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let p=f();e.if(!1);for(let h in p)e.elseIf((0,Co._)`${u} === ${h}`),e.assign(c,l(p[h]));e.else(),t.error(!1,{discrError:Lp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(p){let h=e.name("valid"),m=t.subschema({keyword:"oneOf",schemaProp:p},h);return t.mergeEvaluated(m,Co.Name),h}function f(){var p;let h={},m=v(o),y=!0;for(let x=0;x<i.length;x++){let S=i[x];if(S?.$ref&&!(0,V1.schemaHasRulesButRef)(S,s.self.RULES)){let I=S.$ref;if(S=IP.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,I),S instanceof IP.SchemaEnv&&(S=S.schema),S===void 0)throw new B1.default(s.opts.uriResolver,s.baseId,I)}let P=(p=S?.properties)===null||p===void 0?void 0:p[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||v(S)),b(P,x)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return h;function v({required:x}){return Array.isArray(x)&&x.includes(a)}function b(x,S){if(x.const)w(x.const,S);else if(x.enum)for(let P of x.enum)w(P,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(x,S){if(typeof x!="string"||x in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[x]=S}}}};jp.default=J1});var zP=R((D5,Y1)=>{Y1.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 Up=R((le,Fp)=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.MissingRefError=le.ValidationError=le.CodeGen=le.Name=le.nil=le.stringify=le.str=le._=le.KeywordCxt=le.Ajv=void 0;var X1=$R(),Q1=AP(),eF=OP(),NP=zP(),tF=["/properties"],Mc="http://json-schema.org/draft-07/schema",xo=class extends X1.default{_addVocabularies(){super._addVocabularies(),Q1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(eF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(NP,tF):NP;this.addMetaSchema(e,Mc,!1),this.refs["http://json-schema.org/schema"]=Mc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mc)?Mc:void 0)}};le.Ajv=xo;Fp.exports=le=xo;Fp.exports.Ajv=xo;Object.defineProperty(le,"__esModule",{value:!0});le.default=xo;var rF=Xs();Object.defineProperty(le,"KeywordCxt",{enumerable:!0,get:function(){return rF.KeywordCxt}});var ko=D();Object.defineProperty(le,"_",{enumerable:!0,get:function(){return ko._}});Object.defineProperty(le,"str",{enumerable:!0,get:function(){return ko.str}});Object.defineProperty(le,"stringify",{enumerable:!0,get:function(){return ko.stringify}});Object.defineProperty(le,"nil",{enumerable:!0,get:function(){return ko.nil}});Object.defineProperty(le,"Name",{enumerable:!0,get:function(){return ko.Name}});Object.defineProperty(le,"CodeGen",{enumerable:!0,get:function(){return ko.CodeGen}});var nF=dc();Object.defineProperty(le,"ValidationError",{enumerable:!0,get:function(){return nF.default}});var oF=Qs();Object.defineProperty(le,"MissingRefError",{enumerable:!0,get:function(){return oF.default}})});var GP=R(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.formatNames=Xt.fastFormats=Xt.fullFormats=void 0;function Yt(t,e){return{validate:t,compare:e}}Xt.fullFormats={date:Yt(FP,Zp),time:Yt(Hp(!0),Wp),"date-time":Yt(DP(!0),qP),"iso-time":Yt(Hp(),UP),"iso-date-time":Yt(DP(),HP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:dF,"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:yF,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:lF,int32:{type:"number",validate:hF},int64:{type:"number",validate:mF},float:{type:"number",validate:jP},double:{type:"number",validate:jP},password:!0,binary:!0};Xt.fastFormats={...Xt.fullFormats,date:Yt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Zp),time:Yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wp),"date-time":Yt(/^\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,qP),"iso-time":Yt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,UP),"iso-date-time":Yt(/^\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,HP),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};Xt.formatNames=Object.keys(Xt.fullFormats);function sF(t){return t%4===0&&(t%100!==0||t%400===0)}var iF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function FP(t){let e=iF.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&&sF(r)?29:aF[n])}function Zp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var qp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Hp(t){return function(r){let n=qp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),d=+(n[7]||0);if(u>23||d>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let l=s-d*c,f=o-u*c-(l<0?1:0);return(f===23||f===-1)&&(l===59||l===-1)&&i<61}}function Wp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function UP(t,e){if(!(t&&e))return;let r=qp.exec(t),n=qp.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 Gp=/t|\s/i;function DP(t){let e=Hp(t);return function(n){let o=n.split(Gp);return o.length===2&&FP(o[0])&&e(o[1])}}function qP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function HP(t,e){if(!(t&&e))return;let[r,n]=t.split(Gp),[o,s]=e.split(Gp),i=Zp(r,o);if(i!==void 0)return i||Wp(n,s)}var cF=/\/|:/,uF=/^(?:[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 dF(t){return cF.test(t)&&uF.test(t)}var LP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function lF(t){return LP.lastIndex=0,LP.test(t)}var fF=-(2**31),pF=2**31-1;function hF(t){return Number.isInteger(t)&&t<=pF&&t>=fF}function mF(t){return Number.isInteger(t)}function jP(){return!0}var gF=/[^\\]\\Z/;function yF(t){if(gF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ZP=R(Eo=>{"use strict";Object.defineProperty(Eo,"__esModule",{value:!0});Eo.formatLimitDefinition=void 0;var vF=Up(),zt=D(),Gr=zt.operators,Ic={formatMaximum:{okStr:"<=",ok:Gr.LTE,fail:Gr.GT},formatMinimum:{okStr:">=",ok:Gr.GTE,fail:Gr.LT},formatExclusiveMaximum:{okStr:"<",ok:Gr.LT,fail:Gr.GTE},formatExclusiveMinimum:{okStr:">",ok:Gr.GT,fail:Gr.LTE}},_F={message:({keyword:t,schemaCode:e})=>(0,zt.str)`should be ${Ic[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,zt._)`{comparison: ${Ic[t].okStr}, limit: ${e}}`};Eo.formatLimitDefinition={keyword:Object.keys(Ic),type:"string",schemaType:"string",$data:!0,error:_F,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 vF.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),p=e.const("fmt",(0,zt._)`${f}[${c.schemaCode}]`);t.fail$data((0,zt.or)((0,zt._)`typeof ${p} != "object"`,(0,zt._)`${p} instanceof RegExp`,(0,zt._)`typeof ${p}.compare != "function"`,l(p)))}function d(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let h=e.scopeValue("formats",{key:f,ref:p,code:i.code.formats?(0,zt._)`${i.code.formats}${(0,zt.getProperty)(f)}`:void 0});t.fail$data(l(h))}function l(f){return(0,zt._)`${f}.compare(${r}, ${n}) ${Ic[o].fail} 0`}},dependencies:["format"]};var SF=t=>(t.addKeyword(Eo.formatLimitDefinition),t);Eo.default=SF});var KP=R((pi,VP)=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});var To=GP(),wF=ZP(),Bp=D(),WP=new Bp.Name("fullFormats"),bF=new Bp.Name("fastFormats"),Vp=(t,e={keywords:!0})=>{if(Array.isArray(e))return BP(t,e,To.fullFormats,WP),t;let[r,n]=e.mode==="fast"?[To.fastFormats,bF]:[To.fullFormats,WP],o=e.formats||To.formatNames;return BP(t,o,r,n),e.keywords&&(0,wF.default)(t),t};Vp.get=(t,e="full")=>{let n=(e==="fast"?To.fastFormats:To.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function BP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Bp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}VP.exports=pi=Vp;Object.defineProperty(pi,"__esModule",{value:!0});pi.default=Vp});var PC=R((_3,RC)=>{RC.exports=bC;bC.sync=eU;var SC=vr("fs");function QF(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 wC(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:QF(e,r)}function bC(t,e,r){SC.stat(t,function(n,o){r(n,n?!1:wC(o,t,e))})}function eU(t,e){return wC(SC.statSync(t),t,e)}});var TC=R((S3,EC)=>{EC.exports=xC;xC.sync=tU;var CC=vr("fs");function xC(t,e,r){CC.stat(t,function(n,o){r(n,n?!1:kC(o,e))})}function tU(t,e){return kC(CC.statSync(t),e)}function kC(t,e){return t.isFile()&&rU(t,e)}function rU(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 $C=R((b3,AC)=>{var w3=vr("fs"),Gc;process.platform==="win32"||global.TESTING_WINDOWS?Gc=PC():Gc=TC();AC.exports=ph;ph.sync=nU;function ph(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){ph(t,e||{},function(s,i){s?o(s):n(i)})})}Gc(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function nU(t,e){try{return Gc.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var LC=R((R3,DC)=>{var Do=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",MC=vr("path"),oU=Do?";":":",IC=$C(),OC=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),zC=(t,e)=>{let r=e.colon||oU,n=t.match(/\//)||Do&&t.match(/\\/)?[""]:[...Do?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=Do?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=Do?o.split(r):[""];return Do&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},NC=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=zC(t,e),i=[],a=u=>new Promise((d,l)=>{if(u===n.length)return e.all&&i.length?d(i):l(OC(t));let f=n[u],p=/^".*"$/.test(f)?f.slice(1,-1):f,h=MC.join(p,t),m=!p&&/^\.[\\\/]/.test(t)?t.slice(0,2)+h:h;d(c(m,u,0))}),c=(u,d,l)=>new Promise((f,p)=>{if(l===o.length)return f(a(d+1));let h=o[l];IC(u+h,{pathExt:s},(m,y)=>{if(!m&&y)if(e.all)i.push(u+h);else return f(u+h);return f(c(u,d,l+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},sU=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=zC(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=MC.join(c,t),d=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let l=0;l<n.length;l++){let f=d+n[l];try{if(IC.sync(f,{pathExt:o}))if(e.all)s.push(f);else return f}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw OC(t)};DC.exports=NC;NC.sync=sU});var FC=R((P3,hh)=>{"use strict";var jC=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};hh.exports=jC;hh.exports.default=jC});var GC=R((C3,HC)=>{"use strict";var UC=vr("path"),iU=LC(),aU=FC();function qC(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=iU.sync(t.command,{path:r[aU({env:r})],pathExt:e?UC.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=UC.resolve(o?t.options.cwd:"",i)),i}function cU(t){return qC(t)||qC(t,!0)}HC.exports=cU});var ZC=R((x3,gh)=>{"use strict";var mh=/([()\][%!^"`<>&|;, *?])/g;function uU(t){return t=t.replace(mh,"^$1"),t}function dU(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(mh,"^$1"),e&&(t=t.replace(mh,"^$1")),t}gh.exports.command=uU;gh.exports.argument=dU});var BC=R((k3,WC)=>{"use strict";WC.exports=/^#!(.*)/});var KC=R((E3,VC)=>{"use strict";var lU=BC();VC.exports=(t="")=>{let e=t.match(lU);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((T3,JC)=>{"use strict";var yh=vr("fs"),fU=KC();function pU(t){let r=Buffer.alloc(150),n;try{n=yh.openSync(t,"r"),yh.readSync(n,r,0,150,0),yh.closeSync(n)}catch{}return fU(r.toString())}JC.exports=pU});var tx=R((A3,ex)=>{"use strict";var hU=vr("path"),XC=GC(),QC=ZC(),mU=YC(),gU=process.platform==="win32",yU=/\.(?:com|exe)$/i,vU=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function _U(t){t.file=XC(t);let e=t.file&&mU(t.file);return e?(t.args.unshift(t.file),t.command=e,XC(t)):t.file}function SU(t){if(!gU)return t;let e=_U(t),r=!yU.test(e);if(t.options.forceShell||r){let n=vU.test(e);t.command=hU.normalize(t.command),t.command=QC.command(t.command),t.args=t.args.map(s=>QC.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 wU(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:SU(n)}ex.exports=wU});var ox=R(($3,nx)=>{"use strict";var vh=process.platform==="win32";function _h(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 bU(t,e){if(!vh)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=rx(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function rx(t,e){return vh&&t===1&&!e.file?_h(e.original,"spawn"):null}function RU(t,e){return vh&&t===1&&!e.file?_h(e.original,"spawnSync"):null}nx.exports={hookChildProcess:bU,verifyENOENT:rx,verifyENOENTSync:RU,notFoundError:_h}});var ax=R((M3,Lo)=>{"use strict";var sx=vr("child_process"),Sh=tx(),wh=ox();function ix(t,e,r){let n=Sh(t,e,r),o=sx.spawn(n.command,n.args,n.options);return wh.hookChildProcess(o,n),o}function PU(t,e,r){let n=Sh(t,e,r),o=sx.spawnSync(n.command,n.args,n.options);return o.error=o.error||wh.verifyENOENTSync(o.status,n),o}Lo.exports=ix;Lo.exports.spawn=ix;Lo.exports.sync=PU;Lo.exports._parse=Sh;Lo.exports._enoent=wh});var px=R(Rh=>{"use strict";var dx=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,TU=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,lx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,AU=/\\([\u000b\u0020-\u00ff])/g,$U=/([\\"])/g,fx=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;Rh.format=MU;Rh.parse=IU;function MU(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!fx.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],!lx.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+zU(e[o])}return n}function IU(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?OU(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(!fx.test(n))throw new TypeError("invalid media type");var o=new NU(n.toLowerCase());if(r!==-1){var s,i,a;for(dx.lastIndex=r;i=dx.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(AU,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function OU(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 zU(t){var e=String(t);if(lx.test(e))return e;if(e.length>0&&!TU.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace($U,"\\$1")+'"'}function NU(t){this.parameters=Object.create(null),this.type=t}});import{logger as QZ}from"@hermes/logger";import{logger as rH}from"@hermes/logger";var FE="mcp-auth";function Te(t,e=t.ui){if(!e)return;let r=0;for(let n of t.servers.values())n.status==="auth_required"&&r++;e.setStatus(FE,r>0?e.theme.fg("warning",`[${r} MCP needs auth, use /mcp]`):void 0)}import{MCP_CONNECTION_STATE_TOPIC as $q}from"@augmentcode/auggie-v2";import{logger as Mq}from"@hermes/logger";import{logger as mT}from"@hermes/logger";import{logger as qE}from"@hermes/logger";function UE(t,e,r){let n=r?.get(t.name);return n!==void 0?n.host===t&&n.owner.kind==="plugin":e?.get(t.name)===t}function _r(t,e,r){let n=r?.get(t.name);if(n?.host===t)return n.owner.kind;let o=t.config;return o?.vfsSource!==void 0?"vfs":o?.registrySource!==void 0?"registry":UE(t,e,r)?"plugin":"local"}function HE(t){let e=t.getLastProbeResult();return e!==void 0&&!e.ok&&e.outcome==="authFailure"?e:void 0}var mm=qE.child({prefix:"pi-mcp"}),GE="augment:mcp-status-report";function tr(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 Zo(t,e,r,n){let o=tr(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 nt(t,e,r){if(r){let o=tr(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 ZE(t,e){t.statusFailureCategories??=new Map;let r=t.statusFailureCategories.get(e);if(typeof r=="string")return r;let n=tr(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 Fi=3e4;function WE(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>=Fi?"failed":void 0}default:return}}var gm="authentication required",BE="Authentication refresh is pending in the backend; retry shortly.",VE="timed out connecting after 30s",KE="Couldn't add this MCP server: its configuration could not be loaded from the MCP registry. Remove it and try again.",JE="Couldn't add this MCP server: another connected server already uses this name. Remove or rename one of them, then try again.",YE="Server was selected for this session but could not be loaded (it may be disabled or misconfigured in the MCP registry).",XE="Server was not loaded: another selected MCP server with the same name takes precedence. Rename or deselect one of them.",QE="Server requires re-authentication \u2014 its saved credential is no longer valid. Reconnect it from the session MCP panel.",eT="Server was not started: this session's Space policy does not allow it.",tT="Server was not started: its shared credential is not available to this session's identity.",rT="Server requires authentication \u2014 a same-named MCP server was connected in its place. Reconnect this server from the session MCP panel to use it instead.";function nT(t,e){let r=new Set;for(let a of t.servers.values())a.config.id!==void 0&&r.add(a.config.id);let n=new Set(e.map(a=>a.mcpConfigId).filter(a=>a!==void 0)),o=new Set(e.map(a=>a.name)),s=new Set(e.filter(a=>a.mcpConfigId===void 0).map(a=>a.name)),i=a=>t.registryConfigNamesById.get(a)??a;for(let a of t.failedAddConfigIds){if(r.has(a)||n.has(a))continue;let c=i(a);n.add(a),o.add(c),e.push({name:c,source:"registry",status:"failed",failureCategory:"configuration",errorMessage:t.nameCollisionAddConfigIds.has(a)?JE:KE,mcpConfigId:a,dynamicallyAdded:!0})}for(let a of t.selectedRegistryConfigIds??[]){if(r.has(a)||n.has(a)||t.sessionRemovedConfigIds.has(a))continue;let c=i(a);s.has(c)||(n.add(a),e.push({name:c,source:"registry",status:"failed",...sT({state:t,id:a,name:c,reportedNames:o}),mcpConfigId:a}),o.add(c))}oT({state:t,servers:e,liveConfigIds:r,reportedConfigIds:n,reportedNames:o,idlessReportedNames:s})}function oT(t){let{state:e,servers:r,liveConfigIds:n,reportedConfigIds:o,reportedNames:s,idlessReportedNames:i}=t;for(let[a,c]of e.oauthFailureCategoriesByConfigId??[]){if(n.has(a)||o.has(a)||e.sessionRemovedConfigIds.has(a))continue;let u=vm(e,a);if(u===void 0)continue;let d=e.registryConfigNamesById.get(a)??c.serverName;i.has(d)||(o.add(a),r.push({name:d,source:"registry",status:"failed",...u,mcpConfigId:a}),s.add(d))}}function ym(t,e){let r=new Map;for(let[n,o]of Object.entries(e)){if(!o||typeof o!="object")continue;let s=o;typeof s.category=="string"&&typeof s.config_id=="string"&&s.config_id!==""&&r.set(s.config_id,{category:s.category,serverName:n})}t.oauthFailureCategoriesByConfigId=r}function vm(t,e){switch(t.oauthFailureCategoriesByConfigId?.get(e)?.category){case"reauth_required":case"auth_terminal":return{errorMessage:QE,failureCategory:"auth_terminal"};case"policy_excluded":return{errorMessage:eT,failureCategory:"policy_excluded"};case"share_identity_excluded":return{errorMessage:tT,failureCategory:"share_identity_excluded"};default:return}}function sT(t){let{state:e,id:r,name:n,reportedNames:o}=t;if(e.authFallbackDisplacedConfigIds.has(r))return{errorMessage:rT,failureCategory:"auth_terminal"};let s=vm(e,r);return s!==void 0?s:{errorMessage:o.has(n)?XE:YE,failureCategory:"configuration"}}function iT(t,e){return e!==void 0?e.isAuthError?gm:e.error:t.status==="initializing"?VE:t.lastError??(t.status==="auth_required"?gm:void 0)}function aT(t,e){let r=WE(t);if(r===void 0)return;let n=ZE(e,t.name),o=r==="connected"?HE(t):void 0;(o!==void 0||n==="auth_refresh_needed")&&(r="failed");let s={name:t.name,source:_r(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"?BE:iT(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 cT(t){let e=[];for(let r of t.servers.values()){let n=aT(r,t);n!==void 0&&e.push(n)}return nT(t,e),e}function J(t,e){try{let r=cT(e),n=JSON.stringify(r);if(n===e.lastStatusReport)return;e.lastStatusReport=n,e.statusHostGeneration??=1,e.statusReportSequence=(e.statusReportSequence??0)+1;let o={servers:r,observedAtMs:Date.now(),hostGeneration:e.statusHostGeneration,reportSequence:e.statusReportSequence};t.events.emit(GE,o),mm.info(`Emitted MCP status report: ${r.length} server(s)`)}catch(r){mm.warn(`Failed to emit MCP status report: ${r instanceof Error?r.message:String(r)}`)}}var Ui={local:4,registry:3,plugin:2,vfs:1};function Ft(t){return t.hostLeases??=new Map,t.hostLeases}function uT(t){return t.hostLeaseRevisions??=new Map,t.hostLeaseRevisions}function Wo(t){return t.expectedCredentialDomains??=new Map,t.expectedCredentialDomains}function Bo(t,e){return t.kind===e.kind&&t.identity===e.identity}function _m(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 Pu(t,e){let r=uT(t),n=(r.get(e)??0)+1;return r.set(e,n),n}function qi(t,e,r){if(r.kind==="registry"){Wo(t).set(e,{kind:"domain",domain:r.identity});return}Wo(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 Fn(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=Ft(t),o=n.get(e);if(o)return o;let s=t.pluginServerHosts.get(e)===r?"plugin":void 0,i=r.config,a=i?Fn(i,s):{kind:s??"local",identity:e},c={owner:a,revision:Pu(t,e),host:r};return n.set(e,c),qi(t,e,a),c}function Sm(t){let{state:e,name:r,host:n}=t,o=Ft(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:Pu(e,r),host:n};return o.set(r,i),e.pluginServerNames.add(r),e.pluginServerHosts.set(r,n),qi(e,r,i.owner),i}function Vo(t){let{state:e,name:r,owner:n,expectedRevision:o,expectedHost:s}=t,i=Ft(e),a=i.get(r);if(a){if(a.retirement?.settled)return;let l=Ui[n.kind]>Ui[a.owner.kind],f=Ui[n.kind]===Ui[a.owner.kind],p=o===a.revision&&(s===void 0||s===a.host);if(!(l||f&&p))return}let c=a?.host,u=a?_m(a):void 0;Cu(e,r,c),a?.owner.kind==="plugin"&&(e.pluginServerNames.delete(r),e.pluginServerHosts.delete(r));let d={owner:n,revision:Pu(e,r),host:void 0,...u?{retirement:u}:{}};return i.set(r,d),qi(e,r,n),{lease:d,...c?{displacedHost:c}:{},...u?{retirement:u}:{}}}async function xu(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=Ft(e).get(r);return i?.retirement===n&&(o.status==="failed"?(i.host=void 0,Wo(e).set(r,{kind:"blocked"})):i.retirement=void 0),n.resolve(o),!0}function Hi(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e).get(r);return!i||i.revision!==o||!Bo(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 Pt(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e).get(r);if(!i||i.revision!==o||!Bo(i.owner,n)||i.host!==s||i.retirement!==void 0)return;let a=_m(i);if(a)return Cu(e,r,s),i.host=void 0,i.retirement=a,a}function wm(t){let{state:e,name:r,retiredOwner:n,retirement:o}=t,s=Ft(e),i=s.get(r),a=o.result;return!i||i.retirement!==o||i.host!==void 0||!o.settled||!Bo(o.incumbent.owner,n)||a?.status!=="failed"||a.transportDisposed!==!0?!1:(i.retirement=void 0,!Bo(i.owner,n)||i.revision!==o.incumbent.revision?(qi(e,r,i.owner),!0):(s.delete(r),Wo(e).set(r,{kind:"blocked"}),!0))}function Pe(t){let{state:e,name:r,owner:n,revision:o,host:s}=t,i=Ft(e),a=i.get(r);return!a||a.revision!==o||!Bo(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),Wo(e).set(r,{kind:"blocked"}),!0)}function W(t,e){return Ft(t).get(e)}function bm(t,e,r){return Ft(t).get(e)?.host===r}function Rm(t){if(t!==void 0)try{return new URL(t).toString()}catch{return t}}function Sr(t,e){return!t||!e?!1:t.id===e.id&&t.name===e.name&&t.type===e.type&&Rm(t.url)===Rm(e.url)&&t.registrySource===e.registrySource&&t.vfsSource===e.vfsSource}var Un=class{_tokens=new Map;_authRequired=new Set;_retiredCredentials=new Set;_credentialRetirementGenerations=new Map;_credentialIdentities=new Map;get(e){return this._tokens.get(e)}commit(e,r,n){this._tokens.set(e,r),this._authRequired.delete(e),this._retiredCredentials.delete(e),n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e)}hasCredentialIdentity(e,r){return Sr(this._credentialIdentities.get(e),r)}reconcileCredentialIdentity(e,r,n){return this._tokens.get(e)!==r||this._retiredCredentials.has(e)?!1:(n?this._credentialIdentities.set(e,{...n}):this._credentialIdentities.delete(e),!0)}set(e,r,n){this.commit(e,r,n)}persist(e,r,n){return Promise.resolve(void 0)}captureAuthenticatedIdentityVersion(e){return Promise.resolve(void 0)}captureRefreshIdentityVersion(e){return Promise.resolve(void 0)}persistAuthenticated(e,r,n,o){return this.persist(e,r,n)}persistRefresh(e,r,n,o){return this.persist(e,r,n)}restoreAfterSupersededAuthentication(e,r,n,o,s,i){return this.persist(e,n,i)}restoreAfterSupersededRefresh(e,r,n,o,s,i){return this.restoreAfterSupersededAuthentication(e,r,n,o,s,i)}async setAndPersist(e,r,n){await this.persist(e,r,n),this.set(e,r,n)}snapshot(){return{tokens:new Map(this._tokens),authRequired:new Set(this._authRequired),retiredCredentials:new Set(this._retiredCredentials),credentialRetirementGenerations:new Map(this._credentialRetirementGenerations),credentialIdentities:new Map([...this._credentialIdentities].map(([e,r])=>[e,{...r}]))}}seed(e){for(let[r,n]of e.tokens)this._tokens.set(r,n);for(let r of e.authRequired)this._authRequired.add(r);for(let r of e.retiredCredentials??[])this._retiredCredentials.add(r);for(let[r,n]of e.credentialRetirementGenerations??[])this._credentialRetirementGenerations.set(r,n);for(let[r,n]of e.credentialIdentities??[])this._credentialIdentities.set(r,{...n})}delete(e,r){this._tokens.delete(e),this._credentialIdentities.delete(e)}clearLocalCredential(e){this._tokens.delete(e),this._credentialIdentities.delete(e),this._authRequired.delete(e),this._retiredCredentials.add(e),this._credentialRetirementGenerations.set(e,(this._credentialRetirementGenerations.get(e)??0)+1)}retireCredential(e,r,n){return n?.preserveNameState||this.clearLocalCredential(e),Promise.resolve()}credentialRetirementGeneration(e){return this._credentialRetirementGenerations.get(e)??0}isCredentialRetired(e){return this._retiredCredentials.has(e)}markAuthRequired(e){this._authRequired.add(e)}isAuthRequired(e){return this._authRequired.has(e)}clearAuthRequired(e){this._authRequired.delete(e)}};function Jo(t,e){t.authenticatingServerName===e&&(t.authenticationGeneration=(t.authenticationGeneration??0)+1,t.authenticating=!1,t.authenticatingServerName=void 0)}function ku(t){try{return new URL(t).toString()}catch{return t}}function Ko(t){if(!(t.type!=="http"&&t.type!=="sse"))return{id:t.id,name:t.name,type:t.type,url:ku(t.url),auth:t.auth,registrySource:t.registrySource,vfsSource:t.vfsSource}}function Ut(t,e){return Ko(e.config)}function ut(t,e){return t.type!==e.type||t.id!==e.id?!1:t.type==="stdio"||e.type==="stdio"?!0:ku(t.url)===ku(e.url)}function Eu(t,e){let r=Ko(t),n=Ko(e);return!r||!n?ut(t,e):Sr(r,n)}function Tu(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function dT(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 lT(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}=t;return e?r?!ut(e,r):n===void 0?!1:e.id===void 0?e.registrySource===void 0:e.id!==n:!1}function Pm(t){let{identity:e,retiredConfigId:r,retiredOwnerIdentity:n}=t;return r!==void 0?!Tu(e,r):n!==void 0&&e!==n}function Cm(t,e,r){return r&&e!==void 0&&t!==void 0&&Tu(t,e)}function fT(t){let{acceptedDomain:e,currentDomain:r,retiredConfigId:n,retiresRegistryIdentity:o}=t;return!o||n===void 0?!1:[e,r].some(s=>s!==void 0&&!Tu(s,n))}function xm(t){let{currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n,retiresRegistryIdentity:o,currentLease:s,expectedFence:i,retiredConfigId:a,retiredOwnerIdentity:c,acceptedDomain:u,currentDomain:d}=t;if(lT({currentConfig:e,retiredConfig:r,expectedRegistryConfigId:n}))return!0;let l={retiredConfigId:a,retiredOwnerIdentity:c};return o&&s!==void 0&&(s.owner.kind!=="registry"||Pm({identity:s.owner.identity,...l}))||o&&i?.kind==="domain"&&Pm({identity:i.domain,...l})?!0:fT({acceptedDomain:u,currentDomain:d,retiredConfigId:a,retiresRegistryIdentity:o})}function pT(t){let{name:e,retiredConfig:r,expectedRegistryConfigId:n}=t;if(r)return Ko(r);if(n!==void 0)return{id:n,name:e}}function hT(t){let{state:e,name:r,mode:n,stillOwnsNameScopedRevision:o,retiredConfig:s}=t;if(n==="durable"){e.preservedCredentialIdentities?.delete(r);return}!o||!s||!Ko(s)||!e.tokens?.get(r)||(e.preservedCredentialIdentities??=new Map,e.preservedCredentialIdentities.set(r,{...s}))}async function km(t,e,r,n,o){let s=t.oauthCredentialDomains?.get(e),i=t.credentialRevisions?.get(e)?.domain,a=t.servers?.get(e)?.config,c=dT({state:t,name:e,expectedRegistryConfigId:r,expectedConfig:n,currentConfig:a}),u=c?.id??r,d=c?.registrySource!==void 0||c===void 0&&r!==void 0,l=c?.registrySource===void 0?void 0:`user:${c.id??c.name}`,f=xm({currentConfig:a,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:s,currentDomain:i}),p=Cm(s,u,d),h=Cm(i,u,d),m=!f,y=t.tokens?.get(e)!==void 0&&s===void 0&&i===void 0,b=f&&!(m||p||h||y);if(o==="durable"){let P=pT({name:e,retiredConfig:c,expectedRegistryConfigId:r});await t.tokens?.retireCredential(e,P,{preserveNameState:b})}let w=xm({currentConfig:t.servers?.get(e)?.config,retiredConfig:c,expectedRegistryConfigId:r,retiresRegistryIdentity:d,currentLease:t.hostLeases?.get(e),expectedFence:t.expectedCredentialDomains?.get(e),retiredConfigId:u,retiredOwnerIdentity:l,acceptedDomain:t.oauthCredentialDomains?.get(e),currentDomain:t.credentialRevisions?.get(e)?.domain}),x=m&&!w,S=!1;return t.equalRevisionRebindDomains?.delete(e),(x||p)&&t.oauthCredentialDomains?.get(e)===s&&(t.oauthCredentialDomains.delete(e),S=!0),(x||h)&&t.credentialRevisions?.get(e)?.domain===i&&(t.credentialRevisions.delete(e),t.hostedCredentialOwnership?.delete(e),S=!0),x&&o==="durable"&&t.expectedCredentialDomains?.set(e,{kind:"blocked"}),hT({state:t,name:e,mode:o,stillOwnsNameScopedRevision:x,retiredConfig:c}),S&&(Jo(t,e),nt(t,e),t.authRefreshNeededReportKeys?.delete(e)),x}function dt(t,e,r,n){return km(t,e,r,n,"durable")}function Yo(t,e,r,n){return km(t,e,r,n,"session")}function Em(t){let e=[];if(Object.hasOwn(t,"credential_owner_domain")&&e.push(t.credential_owner_domain),Object.hasOwn(t,"credentialOwnerDomain")&&e.push(t.credentialOwnerDomain),e.length===0)return{kind:"absent"};if(e.some(n=>typeof n!="string"||!/^user:.+/.test(n)))return{kind:"invalid"};let r=e[0];return e.every(n=>n===r)?{kind:"valid",ownerDomain:r}:{kind:"invalid"}}function wr(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 Tm="augment:mcp-oauth-credentials",Am=300*1e3,gT=256,Au=mT.child({prefix:"pi-mcp"}),Ct=class extends Error{constructor(e){super(e),this.name="RegistryCredentialRetirementError"}};function ot(t){return`user:${t}`}function Yr(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||wr(o.revision,i)>0)&&e.oauthCredentialRevisions.set(o.domain,o.revision),e.oauthCredentialDomains.set(r,o.domain)}function Rr(t){let e=t.indexOf(":");if(e<=0||e===t.length-1)return t;let r=t.slice(0,e);return r!=="private"&&r!=="shared"&&r!=="recipient"&&r!=="user"&&r!=="tenant"?t:ot(t.slice(e+1))}function st(t){return/^secret:(private|shared):.+/.test(t)}function Xr(t){return t.ownerDomain??Rr(t.domain)}function $m(t,e,r){let n=ot(e);return r!==void 0?r===n:st(t)||Rr(t)===n}function yT(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain&&t?.ownerDomain===e?.ownerDomain}function vT(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 _T(t,e){return t?.kind===e?.kind&&(t?.kind!=="domain"||e?.kind==="domain"&&t.domain===e.domain)}function ST(t,e,r){return t.oauthCredentialDomains.get(e)===r.acceptedDomain&&yT(t.credentialRevisions.get(e),r.credentialRevision)&&_T(t.expectedCredentialDomains.get(e),r.expectedDomain)&&t.statusFailureCategories.get(e)===r.failure}function wT(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 bT(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??"")||!ut(o,r)?!1:o.name!==r.name||e.equalRevisionRebindDomains.get(r.name)===n}function Qr(t){t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.stagedOAuthCredentials??=new Map,t.equalRevisionRebindDomains??=new Map,t.bootOAuthCredentialBuffer??=new Map}function br(t,e){let r=t.bootOAuthCredentialBuffer?.get(e);r?.expiryTimer!==void 0&&clearTimeout(r.expiryTimer),t.bootOAuthCredentialBuffer?.delete(e)}function Mm(t,e){let r=t.bootOAuthCredentialBuffer;if(r)for(let[n,o]of r)e-o.insertedAtMs>=Am&&br(t,n)}function RT(t){let e=t.bootOAuthCredentialBuffer?.keys().next().value;typeof e=="string"&&br(t,e)}function Im(t){let{state:e,serverName:r,revision:n,credential:o,suppressReconnect:s}=t;Qr(e),e.bootOAuthCredentialBuffer??=new Map;let i=e.bootOAuthCredentialBuffer,a=Date.now();Mm(e,a);let c=Xr(n),u=st(c)?`${c}\0${r}`:c,d=i.get(u),l=d?.credential.credential_revision??d?.credential.credentialRevision;if(typeof l=="string"&&wr(n.revision,l)<=0)return;!d&&i.size>=gT&&RT(e),br(e,u);let f={serverName:r,credential:o,suppressReconnect:s,insertedAtMs:a,expiryTimer:void 0};i.set(u,f),f.expiryTimer=setTimeout(()=>{i.get(u)===f&&br(e,u)},Am),f.expiryTimer.unref?.(),Au.warn(`MCP OAuth credential for "${r}" arrived before its server was known; buffered for replay after discovery`)}function PT(t,e){Qr(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;Qr(e);let i=e.registryCredentialIntents.get(r);if(!(n!==void 0&&i?.epoch!==n)){if(!o&&i?.configName){let a=e.expectedCredentialDomains.get(i.configName);a?.kind==="domain"&&a.domain===r&&e.expectedCredentialDomains.set(i.configName,{kind:"blocked"})}e.pendingRegistryCredentialDomains.delete(r),e.registryCredentialIntents.delete(r),e.stagedOAuthCredentials.delete(r),s||br(e,r)}}function Gi(t){let{state:e,domain:r,forceNew:n=!1}=t;Qr(e);let o=e.registryCredentialIntents.get(r);if(o&&!n)return e.pendingRegistryCredentialDomains.add(r),{domain:r,...o};let s=o?.configFingerprint===void 0?e.stagedOAuthCredentials.get(r):void 0;o&&Be({state:e,domain:r,epoch:o.epoch});let i={epoch:PT(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 Om(t,e){Qr(t);for(let[r,n]of t.registryCredentialIntents)e.has(r)||Be({state:t,domain:r,epoch:n.epoch});for(let r of t.pendingRegistryCredentialDomains)e.has(r)||(t.pendingRegistryCredentialDomains.delete(r),t.stagedOAuthCredentials.delete(r));for(let r of t.stagedOAuthCredentials.keys())e.has(r)||t.stagedOAuthCredentials.delete(r);for(let r of t.bootOAuthCredentialBuffer?.keys()??[]){let n=r.split("\0",1)[0];!e.has(r)&&!st(n)&&br(t,r)}for(let r of e){let n=t.registryCredentialIntents.get(r);Gi({state:t,domain:r,forceNew:n?.configFingerprint===void 0})}}function CT(t){let{state:e,config:r}=t;if(r.id===void 0||r.registrySource===void 0||W(e,r.name)?.owner.kind==="local")return;Qr(e);let n=ot(r.id),o=wT(r),s=bT({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=Gi({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),xT({state:e,config:r,domain:n}),{domain:n,...i}}function zm(t){let{state:e,revision:r,credential:n,suppressReconnect:o}=t;Qr(e);let s=Xr(r),i=e.registryCredentialIntents.get(s);if(!i||!e.pendingRegistryCredentialDomains.has(s))return;let a=e.oauthCredentialRevisions.get(r.domain),c=e.stagedOAuthCredentials.get(s),d=c?.intentEpoch===i.epoch&&c.configFingerprint===i.configFingerprint?c.credential.credential_revision??c.credential.credentialRevision:void 0,l=a===void 0?void 0:wr(r.revision,a),f=l===0;l!==void 0&&l<0||f&&i.configFingerprint!==void 0&&!i.allowEqualRevisionRebind||typeof d=="string"&&wr(r.revision,d)<=0||e.stagedOAuthCredentials.set(s,{credential:n,suppressReconnect:o,intentEpoch:i.epoch,configFingerprint:i.configFingerprint,requiresEqualRevisionRebind:f})}function xT(t){let{state:e,config:r,domain:n}=t,o=e.oauthCredentialDomains.get(r.name);e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:n});let s=e.credentialRevisions.get(r.name);(o===void 0||s?.ownerDomain!==void 0&&s.ownerDomain!==n||s?.ownerDomain===void 0&&!st(o)&&Rr(o)!==n)&&(e.oauthCredentialDomains.delete(r.name),e.credentialRevisions.delete(r.name),e.hostedCredentialOwnership?.delete(r.name),nt(e,r.name),e.authRefreshNeededReportKeys?.delete(r.name))}function kT(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(Tm,s.suppressReconnect?{credentials:i,suppressReconnect:!0}:i)}function ET(t){let{state:e,domain:r,serverName:n}=t,o=Date.now();Mm(e,o);let s=e.bootOAuthCredentialBuffer?.get(r);if(s)return br(e,r),s;for(let[i,a]of e.bootOAuthCredentialBuffer??[])if(a.serverName===n&&st(i.split("\0",1)[0]))return br(e,i),a}function TT(t){let{config:e,pi:r,buffered:n}=t;Au.info(`Replaying boot-buffered MCP OAuth credential for "${e.name}"`),Au.info("MCP OAuth boot credential replayed",{hasRegistryConfigId:e.id!==void 0,registryOwned:e.registrySource!==void 0,visibility:"public"});let o={[e.name]:n.credential};r.events.emit(Tm,n.suppressReconnect?{credentials:o,suppressReconnect:!0}:o)}async function AT(t){let{state:e,config:r,previousConfig:n}=t;if(!n)return;if(ut(n,r)){if(n.name===r.name)return;await Yo(e,n.name,n.id,n),e.tokens.clearLocalCredential(n.name),e.preservedCredentialIdentities?.delete(n.name),e.expectedCredentialDomains.set(n.name,{kind:"blocked"}),e.registryCredentialConfigs.delete(n.name);return}await dt(e,r.name,n.id,n);let o=e.expectedCredentialDomains.get(r.name);return o?.kind==="blocked"?o:void 0}function $T(t){let{state:e,config:r,intent:n,rollbackSnapshot:o,cause:s}=t;if(e.registryCredentialIntents.get(n.domain)?.epoch===n.epoch){let c=ST(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 Ct(a)}async function MT(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 AT({state:e,config:r,previousConfig:s})}catch(h){throw $T({state:e,config:r,intent:o,rollbackSnapshot:i,cause:h})}let u=e.registryCredentialIntents.get(o.domain);c&&u?.epoch===o.epoch&&e.expectedCredentialDomains.get(r.name)===c&&e.expectedCredentialDomains.set(r.name,{kind:"domain",domain:o.domain});let d=e.expectedCredentialDomains.get(r.name);if(u?.epoch!==o.epoch||u.configFingerprint!==o.configFingerprint||d?.kind!=="domain"||d.domain!==o.domain)return Be({state:e,domain:o.domain,epoch:o.epoch}),!1;let l=r.id;if(l===void 0)return!1;let f={...r};e.registryConfigNamesById.set(l,r.name),e.registryCredentialConfigs.set(r.name,f),e.registryCredentialConfigsById.set(l,f),o.allowEqualRevisionRebind&&e.equalRevisionRebindDomains.set(r.name,o.domain),kT({state:e,config:r,pi:n,intent:o});let p=ET({state:e,domain:o.domain,serverName:r.name});return Be({state:e,domain:o.domain,epoch:o.epoch,preserveFence:!0}),p&&TT({config:r,pi:n,buffered:p}),!0}function Pr(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=CT({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=vT(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 MT({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 BT}from"@augmentcode/auggie-v2";import{homedir as Nm}from"node:os";import{sep as IT}from"node:path";var $u=class extends Error{variableName;constructor(e){super(`Missing environment variable "${e}"`),this.name="EnvVariableExpansionError",this.variableName=e}},OT=/(?<!\\)\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([\s\S]*?))?\}/g,zT=/\\\$\{/g,NT=new Set(["workspaceFolder","augmentToken"]),Dm="${workspaceFolder}";function Lm(t,e){return t.includes(Dm)?t.split(Dm).join(e):t}function jm(t,e){return t.includes("${")?t.replace(OT,(n,o,s)=>{if(NT.has(o))return n;let i=e[o];if(i!==void 0)return i;if(s!==void 0)return s;throw new $u(o)}).replace(zT,"${"):t}function DT(t){return t.startsWith("~")?t==="~"?Nm():t.startsWith("~/")||t.startsWith(`~${IT}`)?Nm()+t.slice(1):t:t}function Mu(t,e,r){return DT(jm(Lm(t,e),r))}function Zi(t,e,r){return jm(Lm(t,e),r)}function Fm(t,e,r){let n={};for(let[o,s]of Object.entries(t))n[o]=Zi(s,e,r);return n}var LT="$augment-";function jT(t,e,r){if(!t)return;let n={};for(let[o,s]of Object.entries(t))n[o]=s.startsWith(LT)?s:Zi(s,e,r);return n}function qt(t,e){let r=process.env;return{...t,url:Zi(t.url,e,r),headers:jT(t.headers,e,r)}}function Ht(t,e){let r=process.env;return{...t,command:Mu(t.command,e,r),args:t.args,env:t.env?Fm(t.env,e,r):void 0,cwd:t.cwd?Mu(t.cwd,e,r):e}}import{readFileSync as HT}from"node:fs";import{logger as FT}from"@hermes/logger";var UT=FT.child({prefix:"pi-mcp"}),xt=class extends Error{constructor(e){super(e),this.name="McpConfigError"}};function qn(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 qT(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 Hn(t,e){let r=qn(e);if(!r)throw new xt(`MCP server "${t}" must declare a 'command' (stdio) or 'url' (http/sse) property`);if(r==="http"||r==="sse"){if(!e.url)throw new xt(`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 xt(`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&&UT.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:qT(e.env),cwd:e.cwd,timeoutMs:e.timeoutMs,useShellInterpolation:!0}}var Hm=t=>HT(t,"utf8");function Wi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Um(t){return Wi(t)&&("command"in t||"url"in t)}function Ou(...t){for(let e of t)if(typeof e=="string"&&e.length>0)return e}function qm(t,e){return Ou(t.name)??e}function Iu(t,e){let r=qn(t);if(r==="http"||r==="sse")return Ou(t.name,t.title,t.url)??e;let n=typeof t.command=="string"&&t.command.length>0?t.command.split(" ")[0]:void 0;return Ou(t.name,t.title,n)??e}function GT(t){if(Array.isArray(t))return t.map((e,r)=>{let n=e;return[Iu(n,String(r)),n]});if(Wi(t)){for(let r of["servers","mcpServers"]){let n=t[r];if(Array.isArray(n))return n.map((o,s)=>{let i=o;return[Iu(i,String(s)),i]})}for(let r of["servers","mcpServers"]){let n=t[r];if(Wi(n))return Object.entries(n).map(([o,s])=>{let i=s;return[qm(i,o),i]})}if(Um(t)){let r=t;return[[Iu(r,"server"),r]]}let e=Object.values(t);if(e.length>0&&e.some(Um))return Object.entries(t).map(([r,n])=>{if(!Wi(n))throw new Error(`entry "${r}" is not a server config object (got ${n===null?"null":typeof n})`);let o=n;return[qm(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 zu(t){return t instanceof Error?t.message:String(t)}function ZT(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}": ${zu(s)}`});return}}function WT(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=ZT(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}: ${zu(c)}`}),[]}try{return GT(a)}catch(c){return r.push({message:`Invalid --mcp-config ${s}: ${zu(c)}`}),[]}}function Nu(t,e=Hm){let r={},n=[];for(let o of t)for(let[s,i]of WT(o,e,n))r[s]=i;return{servers:r,diagnostics:n}}function Du(t,e=Hm){return!t||t.length===0?new Set:new Set(Object.keys(Nu(t,e).servers))}var VT=["global","project","local","managed"];function KT(t,e){switch(e){case"global":return t.getGlobalSettings().mcpServers;case"project":return t.getProjectSettings().mcpServers;case"local":return t.getLocalSettings().mcpServers;case"managed":return t.getManagedSettings().mcpServers}}function JT(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 YT(t,e,r){let n=Nu(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 XT(t,e,r){let n=BT.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 JT(VT.map(o=>KT(n,o)))}function Gn(t,e,r,n){let o=[],s=r&&r.length>0?YT(r,n,o):XT(t,e,o),i=[];for(let[a,c]of Object.entries(s))try{let u=Hn(a,c);i.push(u.type==="stdio"?Ht(u,t):qt(u,t))}catch(u){let d=u instanceof xt?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 Jm}from"@augmentcode/auggie-v2";import{logger as dA}from"@hermes/logger";import{Type as lA}from"@sinclair/typebox";var Bi=Symbol.for("__pi_mcp_state__");function QT(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 eA(t,e){return["user","tenant","private","shared"].some(r=>t===`${r}:${e}`)}function tA(t){for(let[e,r]of t.registryCredentialConfigsById){let n=[...t.registryCredentialConfigs.entries()].filter(([i,a])=>i!==r.name&&a.id===e&&QT(a,r)).map(([i])=>i),o=n.some(i=>{let a=t.oauthCredentialDomains.get(i);return a!==void 0&&eA(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 rA(t){t.dynamicallyAddedConfigIds??=new Set,t.failedAddConfigIds??=new Set,t.nameCollisionAddConfigIds??=new Set,t.authFallbackDisplacedConfigIds??=new Set,t.sessionRemovedConfigIds??=new Set,t.registryConfigNamesById??=new Map,t.registryCredentialConfigs??=new Map,t.registryCredentialConfigsById??=new Map,t.toolSearchLatched??=!1,t.sessionMcpConfigDisabledOverrides??=new Map,t.reconnects??=new Map,t.missingHostRemovals??=new Map,t.missingHostRemovalFences??=new Map,t.reconnectDesiredGenerations??=new Map,t.serverGenerations??=t.hostGenerations??new Map,t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map,t.credentialRevisions??=new Map,t.oauthCredentialRevisions??=new Map,t.oauthCredentialDomains??=new Map;let e=t.equalRevisionRebindDomains===void 0;t.equalRevisionRebindDomains??=new Map,t.preservedCredentialIdentities??=new Map,t.stagedOAuthCredentials??=new Map,t.pendingRegistryCredentialDomains??=new Set,t.registryCredentialIntents??=new Map,t.registryCredentialIntentEpochs??=new Map,t.registryCredentialFinalizationsByName??=new Map;for(let r of t.pendingRegistryCredentialDomains)if(!t.registryCredentialIntents.has(r)){let n=(t.registryCredentialIntentEpochs.get(r)??0)+1;t.registryCredentialIntentEpochs.set(r,n),t.registryCredentialIntents.set(r,{epoch:n,configFingerprint:void 0,configName:void 0,allowEqualRevisionRebind:!1,finalization:void 0})}for(let r of t.registryCredentialIntents.values())r.allowEqualRevisionRebind??=!1;for(let[r,n]of t.stagedOAuthCredentials){let o=t.registryCredentialIntents.get(r);if(!o){t.stagedOAuthCredentials.delete(r);continue}let s=n;s.intentEpoch??=o.epoch,s.configFingerprint??=o.configFingerprint,s.requiresEqualRevisionRebind??=!1}t.statusHostGeneration??=1,t.statusReportSequence??=0,t.statusFailureCategories??=new Map,t.authRefreshNeededReportKeys??=new Map,t.hostedCredentialOwnership??=new Map,e&&tA(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 Xo(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 Vi(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 nA(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 Gm(t){let{state:e,configId:r,generation:n}=t;typeof n=="number"&&e.attachmentCommandInFlightGenerations?.get(r)===n&&e.attachmentCommandInFlightGenerations.delete(r)}function Ki(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()?nA({state:e,configId:r,generation:n}):Gm({state:e,configId:r,generation:n}),i),i=>{throw Gm({state:e,configId:r,generation:n}),i})}function ie(){let t=globalThis;if(t[Bi])return rA(t[Bi]),t[Bi];let e={servers:new Map,toolRegistrationsByPi:new WeakMap,hostLeases:new Map,hostLeaseRevisions:new Map,expectedCredentialDomains:new Map,tokens:new Un,refreshes:new Map,reconnects:new Map,missingHostRemovals:new Map,missingHostRemovalFences:new Map,reconnectDesiredGenerations:new Map,serverGenerations:new Map,configRevisions:new Map,configDesiredRevisions:new Map,configDesiredSources:new Map,credentialRevisions:new Map,oauthCredentialRevisions:new Map,oauthCredentialDomains:new Map,equalRevisionRebindDomains:new Map,preservedCredentialIdentities:new Map,stagedOAuthCredentials:new Map,bootOAuthCredentialBuffer:new Map,pendingRegistryCredentialDomains:new Set,registryCredentialIntents:new Map,registryCredentialIntentEpochs:new Map,registryCredentialFinalizationsByName:new Map,statusHostGeneration:1,statusReportSequence:0,statusFailureCategories:new Map,authRefreshNeededReportKeys:new Map,hostedCredentialOwnership:new Map,shouldProactivelyRefreshTokens:!0,backgroundRefreshIntervalId:void 0,credsListenerBound:!1,configIdsListenerBound:!1,registryGeneration:0,liveEditGenerations:new Map,attachmentCommandGenerations:new Map,attachmentCommandInFlightGenerations:new Map,attachmentCommandAppliedGenerations:new Map,mcpConfigsListenerBound:!1,embeddedRegistryConfigs:void 0,vfsListenerBound:!1,addServerListenerBound:!1,restartServerListenerBound:!1,removeServerListenerBound:!1,mcpRestartState:new Map,vfsGeneration:0,lastSuccessfulVfsMcpSignature:void 0,blockedVfsMcpNames:new Set,credentials:void 0,secretsClient:void 0,headerSecrets:{},headerSecretFailures:{},headerSecretsListenerBound:!1,featureFlagsListenerBound:!1,workspaceRoot:void 0,mcpConfigOverride:void 0,connectStarted:!1,reconnecting:!1,authenticating:!1,authenticationGeneration:0,authenticatingServerName:void 0,restartHistory:new Map,dynamicallyAddedConfigIds:new Set,failedAddConfigIds:new Set,nameCollisionAddConfigIds:new Set,authFallbackDisplacedConfigIds:new Set,sessionRemovedConfigIds:new Set,selectedRegistryConfigIds:void 0,registryConfigNamesById:new Map,oauthFailureCategoriesByConfigId:void 0,registryCredentialConfigs:new Map,registryCredentialConfigsById:new Map,lastStatusReport:void 0,diagnostics:[],pluginServerSource:void 0,pluginServerNames:new Set,pluginServerHosts:new Map,pluginReconcileQueue:Promise.resolve(),sessionPluginDisabledOverrides:new Map,sessionRegistryDisabledOverrides:new Map,sessionMcpConfigDisabledOverrides:new Map,currentLoad:void 0,ui:void 0,featureFlags:void 0,toolSearchLatched:!1,mcpCatalog:void 0,mcpAttachDisabled:!1,mcpAttachCloudSignaled:!1,catalogRefreshInFlight:void 0,attachResolvers:new Map,attachResultListenerBound:!1};return t[Bi]=e,e}var Zm=Symbol.for("__hermes_mcp_tool_registry__"),oA=Symbol.for("__hermes_mcp_extension_factory__");function Wm(){let t=globalThis;return t[Zm]??=new Map,t[Zm]}function Cr(t){Wm().set(t.name,t)}function Bm(t,e){let r=Wm();(e===void 0||r.get(t)===e)&&r.delete(t)}function Vm(t){Reflect.set(t,oA,!0)}function Ji(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 sA(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t}function iA(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 aA(t){let e=[];for(let r of t)r.type==="text"&&e.push(r.text);return e.join(`
9
+ `).trim()}function Lu(t,e,r){if(t.isError){let o=aA(t.content);throw new Error(o||`MCP tool "${e}/${r}" reported an error`)}let n=iA(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 Km(t){let e=t.getHost();if(!e||e.status!=="success")throw new Error(Ji(t.serverName,e?.status,t.getAllToolNames(),t.getActiveToolNames()));let r=t.map.resolve(t.namespaced),n=sA(t.params),o=await e.callTool(r,n,t.signal);return Lu(o,t.serverName,r)}var cA=/[^a-zA-Z0-9_-]/g;function ju(t){return t.replace(cA,"_")}function uA(t,e){let r=ju(e),n=ju(t),o=`${r}_${n}`;return o.length<=64?o:o.slice(0,64)}var xr=class{_serverName;_map=new Map;constructor(e){this._serverName=e}put(e){let r=uA(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=`_${ju(this._serverName)}`;return e.endsWith(n)?e.slice(0,e.length-n.length):e}};var Fu=dA.child({prefix:"pi-mcp"});function Yi(){return ie().toolRegistrationsByPi}function Ym(t){let{pi:e,serverName:r,tool:n,map:o,namespaced:s}=t,i;try{i=lA.Unsafe(n.inputSchema??{})}catch(c){Fu.warn(`Skipping MCP tool "${r}/${n.name}": invalid input schema (${c instanceof Error?c.message:String(c)})`);return}let a=()=>ie().servers.get(r);return{name:s,label:n.name,description:n.description??"",parameters:i,execute:(c,u,d,l,f)=>Km({serverName:r,namespaced:s,map:o,getHost:a,getAllToolNames:()=>e.getAllTools().map(p=>p.name),getActiveToolNames:()=>e.getActiveTools(),params:u,signal:d})}}function Uu(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),Bm(n,s),r.definitionsByName?.delete(n),fA(t,e,n,r,o)}function fA(t,e,r,n,o){let s=ie();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 xr(i);for(let d of c.listTools()){let{namespaced:l,collision:f}=u.put(d.name);if(f||l!==r)continue;let p=Ym({pi:t,serverName:i,tool:d,map:u,namespaced:l});if(!p)return;Jm(r,"mcp"),t.registerTool(p),Cr(p),a.definitionsByName??=new Map,a.definitionsByName.set(r,p),e.ownerByToolName.set(r,a),o?t.setActiveTools([...new Set([...t.getActiveTools(),r])]):t.setActiveTools(t.getActiveTools().filter(h=>h!==r));return}}}function pA(t,e){let r=Yi(),n=r.get(t);n||(n={byServer:new Map,ownerByToolName:new Map},r.set(t,n));let o=ie().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)Uu(t,n,s,a);let i={generation:o,host:e,map:new xr(e.name),registeredNames:new Set,definitionsByName:new Map};return n.byServer.set(e.name,i),{registration:i,replaced:s!==void 0}}function qu(t,e){let{registration:r,replaced:n}=pA(t,e),o=new Set(r.registeredNames),s=new xr(e.name);r.map=s,r.registeredNames.clear();let i=e.name,a=0,c=[];for(let d of e.listTools()){let{namespaced:l,collision:f}=s.put(d.name);if(f){let h=s.resolve(l),m=`Tool name collision detected in MCP server "${i}": "${d.name}" and "${h}" both map to "${l}". Only the first tool will be available.`,y=ie();y.diagnostics.some(b=>b.server===i&&b.message.includes(`both map to "${l}"`))||(Fu.warn(m),y.diagnostics.push({server:i,message:m}));continue}let p=Ym({pi:t,serverName:i,tool:d,map:s,namespaced:l});p&&(Jm(l,"mcp"),t.registerTool(p),Cr(p),r.definitionsByName??=new Map,r.definitionsByName.set(l,p),Yi().get(t)?.ownerByToolName.set(l,r),r.registeredNames.add(l),c.push(l),a+=1)}let u=Yi().get(t);for(let d of o)!r.registeredNames.has(d)&&u&&Uu(t,u,r,d);n&&c.length>0&&t.setActiveTools([...new Set([...t.getActiveTools(),...c])]),a>0&&Fu.info(`Registered ${a} MCP tool(s) from server "${i}"`)}function Hu(t,e,r){let n=Yi().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)Uu(t,n,o,s);return n.byServer.delete(e.name),!0}function Xm(t,e){for(let r of e.servers.values())r.status==="success"&&r.config.registrySource===void 0&&qu(t,r)}import{getToolSource as PA}from"@augmentcode/auggie-v2";import{Type as hA}from"@sinclair/typebox";var mA="cliMcpToolSearchAutoEnable",gA="cliMcpToolSearchTokenThreshold",yA=!1,Qm=2e4;function vA(t){let e=JSON.stringify({name:t.name,description:t.description,inputSchema:t.inputSchema});return Math.ceil(e.length/4)}function _A(t){let e=0;for(let r of t.servers.values())e+=SA(r);return e}function SA(t){if(t.status!=="success")return 0;let e=new xr(t.name),r=0;for(let n of t.listTools()){let{collision:o}=e.put(n.name);o||wA(n.inputSchema)&&(r+=vA(n))}return r}function wA(t){try{return hA.Unsafe(t??{}),!0}catch{return!1}}function bA(t){let r=t.featureFlags?.flags?.[mA];return typeof r=="boolean"?r:yA}function RA(t){let r=t.featureFlags?.flags?.[gA];if(typeof r=="bigint"){let n=Number(r);return Number.isFinite(n)&&n>0?n:Qm}return typeof r=="number"&&Number.isFinite(r)&&r>0?r:Qm}function eg(t){return bA(t)?_A(t)>=RA(t):!1}var CA="AUGGIE_ENABLE_TOOL_SEARCH",xA=new Set(["find-tool","execute-tool","attach-mcp-server"]);function Qo(){return process.env[CA]==="1"}function Zn(t){return Qo()||t.toolSearchLatched?!0:eg(t)?(t.toolSearchLatched=!0,!0):!1}function Xi(t){let e=t.getActiveTools(),r=e.filter(n=>!kA(n)||xA.has(n));r.length!==e.length&&t.setActiveTools(r)}function kA(t){return PA(t)==="mcp"}import{setToolSource as cg}from"@augmentcode/auggie-v2";import{logger as BA}from"@hermes/logger";import{Type as ug}from"@sinclair/typebox";import{logger as EA}from"@hermes/logger";var es={UNSPECIFIED:0,NONE:1,OAUTH:2,API_KEY:3},en={UNSPECIFIED:0,CLI:1,CLOUD_AGENT:2};var tg=EA.child({prefix:"pi-mcp"}),TA=5e3,AA=1,$A=2,MA=new Set(["AVAILABLE","MCP_CATALOG_ENTRY_STATE_AVAILABLE"]),IA=new Set(["OPT_IN_REQUIRED","MCP_CATALOG_ENTRY_STATE_OPT_IN_REQUIRED"]);function OA(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 zA(t){return t===AA||typeof t=="string"&&MA.has(t)?"available":t===$A||typeof t=="string"&&IA.has(t)?"opt_in_required":"unknown"}function NA(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:OA(t.auth_type),state:zA(t.state)}}function Gu(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 tn(t){return(t.mcpCatalog??[]).filter(r=>(r.state==="available"||r.state==="opt_in_required")&&!Gu(t,r))}async function rg(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:en.UNSPECIFIED}),signal:AbortSignal.timeout(r??TA)});if(!s.ok)return tg.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=NA(c);u!==void 0&&a.push(u)}return{ok:!0,entries:a}}catch(s){return tg.debug(`MCP catalog fetch failed: ${s instanceof Error?s.message:String(s)}`),{ok:!1,disable:!1}}}var DA="AUGGIE_TOOL_SEARCH_FIND_TOOL_PROMPT",LA=`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).`,MA=/[\n\r]/g,IA=/</g,OA=/>/g;function rn(t){return t.replace(MA," ").replace(IA,"\u2039").replace(OA,"\u203A").trim()}function zA(){let t=process.env[AA];return t?.trim()?t:$A}var NA=/\{\{(query|server_name|tool_list)\}\}/g;function eg(t,e,r){let n={"{{query}}":rn(t),"{{server_name}}":rn(e),"{{tool_list}}":r};return zA().replace(NA,o=>n[o]??o)}function be(t){return{content:[{type:"text",text:t}],details:void 0}}function tg(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Zu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Qi(t,e,r){let n={mcp_server:t,tools:tg(e).map(Zu),note:r};return be(JSON.stringify(n,null,2))}function rg(t){return tg(t).map(e=>{let r=rn(e.name),n=rn(e.description??"");return`- ${r}: ${n}`}).join(`
17
- `)}function ng(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 DA}from"@earendil-works/pi-ai";var LA="augment:tool-search-usage";function jA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function og(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 DA(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(LA,a),jA(i)}var cg=FA.child({prefix:"pi-mcp"}),Wn="find-tool",kr="execute-tool",UA=10,ag=15,qA=20,HA={type:"object",properties:{query:{type:"string",description:"Detailed description of the task you need a tool for: the action (create, read, search, delete, \u2026), the target resource, and relevant context (field names, filters). More specific queries match better."},mcp_server:{type:"string",description:"Name of the MCP server to search."}},required:["query","mcp_server"]},GA={type:"object",properties:{mcp_server:{type:"string",description:"Name of the MCP server hosting the tool."},tool_name:{type:"string",description:"Original MCP tool name returned by find-tool."},arguments:{type:"object",description:"Arguments object to pass to the tool."}},required:["mcp_server","tool_name","arguments"]};function Wu(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ").trim().replace(/\s+/g," ")}function ZA(t){let e=[...ie().servers.values()].filter(c=>c.status==="success"),r=e.find(c=>c.name===t);if(r)return{server:r,name:r.name};let n=Wu(t),o=e.filter(c=>n.length>0&&Wu(c.name)===n);if(o.length===1){let[c]=o;return{server:c,name:c.name}}let s=n.split(" ").filter(Boolean),i=e.filter(c=>{let u=new Set(Wu(c.name).split(" "));return n.length>0&&s.every(d=>u.has(d))});if(i.length===1){let[c]=i;return{server:c,name:c.name}}let a=[...o,...i].map(c=>c.name).filter((c,u,d)=>d.indexOf(c)===u).sort();if(a.length>1){let c=e.map(u=>u.name).sort();throw new Error(`MCP server name "${t}" is ambiguous. Matching servers: ${a.join(", ")}. Use an exact server name. Available servers: ${c.join(", ")}.`)}}function ug(t,e){let r=ie(),n=t.getAllTools().map(u=>u.name);if(!n.includes(e)){let u=e.trim().toLowerCase(),d=tn(r).find(l=>l.id===e.trim()||l.name.toLowerCase()===u);if(d)throw new Error(`MCP server "${d.name}" is available but not attached. Call attach-mcp-server now with config_id "${d.id}"; it attaches directly without requiring user approval.`)}let o=n.includes(e)?void 0:ZA(e);if(o)return o;let s=t.getActiveTools(),i=r.servers.get(e),a=[...r.servers.values()].filter(u=>u.status==="success").map(u=>u.name).sort(),c=Ji(e,i?.status,n,s);throw new Error(`${c} Available servers: ${a.join(", ")||"none"}.`)}function WA(t){if(t==null)throw new Error(`${kr} 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(`${kr} "arguments" must be an object, not ${e}.`)}return t}async function BA(t,e,r,n,o){let s=eg(r,n,rg(o)),i=await og(t,e,s);if(!i)return;let a=ng(i);return o.find(c=>c.name===a)}async function VA(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Wn} requires string "query" and "mcp_server" parameters.`);let s=ug(t,o),i=s.server.listTools();if(i.length===0)throw new Error(`No tools available on MCP server "${s.name}".`);if(i.length<=UA)return Qi(s.name,i,"All tools on this server.");try{let a=await BA(t,e,n,s.name,i);return a?be(JSON.stringify(Zu(a),null,2)):Qi(s.name,i,"No single best match; all tools listed.")}catch(a){return cg.warn(`${Wn} LLM match failed: ${a instanceof Error?a.message:String(a)}`),Qi(s.name,i,"Search failed; all tools listed.")}}async function KA(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${kr} requires string "mcp_server" and "tool_name" parameters.`);let i=WA(s),a=ug(t,n),c=await a.server.callTool(o,i,r);return Lu(c,a.name,o)}function JA(){let t=ie(),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 ${kr}. When this gateway is present, MCP tools may intentionally be absent as top-level tools. Before reporting an expected MCP capability unavailable, search its attached server with ${Wn}, then invoke it with ${kr}.`,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,ag).join(", "),u=a.length>ag?", \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).`,jA=/[\n\r]/g,FA=/</g,UA=/>/g;function rn(t){return t.replace(jA," ").replace(FA,"\u2039").replace(UA,"\u203A").trim()}function qA(){let t=process.env[DA];return t?.trim()?t:LA}var HA=/\{\{(query|server_name|tool_list)\}\}/g;function ng(t,e,r){let n={"{{query}}":rn(t),"{{server_name}}":rn(e),"{{tool_list}}":r};return qA().replace(HA,o=>n[o]??o)}function be(t){return{content:[{type:"text",text:t}],details:void 0}}function og(t){return[...t].sort((e,r)=>e.name.localeCompare(r.name))}function Zu(t){return{tool_name:t.name,description:t.description??"",input_schema:t.inputSchema??{}}}function Qi(t,e,r){let n={mcp_server:t,tools:og(e).map(Zu),note:r};return be(JSON.stringify(n,null,2))}function sg(t){return og(t).map(e=>{let r=rn(e.name),n=rn(e.description??"");return`- ${r}: ${n}`}).join(`
17
+ `)}function ig(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 GA}from"@earendil-works/pi-ai";var ZA="augment:tool-search-usage";function WA(t){let e="";for(let r of t.content)r.type==="text"&&(e+=r.text);return e.trim()}async function ag(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 GA(n,{messages:[s]},{apiKey:o.apiKey,headers:o.headers,signal:e.signal}),a={model:i.model,usage:i.usage};return t.events.emit(ZA,a),WA(i)}var lg=BA.child({prefix:"pi-mcp"}),Wn="find-tool",kr="execute-tool",VA=10,dg=15,KA=20,JA={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"]},YA={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 Wu(t){return t.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ").trim().replace(/\s+/g," ")}function XA(t){let e=[...ie().servers.values()].filter(c=>c.status==="success"),r=e.find(c=>c.name===t);if(r)return{server:r,name:r.name};let n=Wu(t),o=e.filter(c=>n.length>0&&Wu(c.name)===n);if(o.length===1){let[c]=o;return{server:c,name:c.name}}let s=n.split(" ").filter(Boolean),i=e.filter(c=>{let u=new Set(Wu(c.name).split(" "));return n.length>0&&s.every(d=>u.has(d))});if(i.length===1){let[c]=i;return{server:c,name:c.name}}let a=[...o,...i].map(c=>c.name).filter((c,u,d)=>d.indexOf(c)===u).sort();if(a.length>1){let c=e.map(u=>u.name).sort();throw new Error(`MCP server name "${t}" is ambiguous. Matching servers: ${a.join(", ")}. Use an exact server name. Available servers: ${c.join(", ")}.`)}}function fg(t,e){let r=ie(),n=t.getAllTools().map(u=>u.name);if(!n.includes(e)){let u=e.trim().toLowerCase(),d=tn(r).find(l=>l.id===e.trim()||l.name.toLowerCase()===u);if(d)throw new Error(`MCP server "${d.name}" is available but not attached. Call attach-mcp-server now with config_id "${d.id}"; it attaches directly without requiring user approval.`)}let o=n.includes(e)?void 0:XA(e);if(o)return o;let s=t.getActiveTools(),i=r.servers.get(e),a=[...r.servers.values()].filter(u=>u.status==="success").map(u=>u.name).sort(),c=Ji(e,i?.status,n,s);throw new Error(`${c} Available servers: ${a.join(", ")||"none"}.`)}function QA(t){if(t==null)throw new Error(`${kr} 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(`${kr} "arguments" must be an object, not ${e}.`)}return t}async function e0(t,e,r,n,o){let s=ng(r,n,sg(o)),i=await ag(t,e,s);if(!i)return;let a=ig(i);return o.find(c=>c.name===a)}async function t0(t,e,r){let{query:n,mcp_server:o}=r??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${Wn} requires string "query" and "mcp_server" parameters.`);let s=fg(t,o),i=s.server.listTools();if(i.length===0)throw new Error(`No tools available on MCP server "${s.name}".`);if(i.length<=VA)return Qi(s.name,i,"All tools on this server.");try{let a=await e0(t,e,n,s.name,i);return a?be(JSON.stringify(Zu(a),null,2)):Qi(s.name,i,"No single best match; all tools listed.")}catch(a){return lg.warn(`${Wn} LLM match failed: ${a instanceof Error?a.message:String(a)}`),Qi(s.name,i,"Search failed; all tools listed.")}}async function r0(t,e,r){let{mcp_server:n,tool_name:o,arguments:s}=e??{};if(typeof n!="string"||typeof o!="string")throw new Error(`${kr} requires string "mcp_server" and "tool_name" parameters.`);let i=QA(s),a=fg(t,n),c=await a.server.callTool(o,i,r);return Lu(c,a.name,o)}function n0(){let t=ie(),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 ${kr}. When this gateway is present, MCP tools may intentionally be absent as top-level tools. Before reporting an expected MCP capability unavailable, search its attached server with ${Wn}, then invoke it with ${kr}.`,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,dg).join(", "),u=a.length>dg?", \u2026":"";return`- ${i.name} (${a.length} tool(s): ${c}${u})`});n.push(`${r} Available MCP servers:
18
18
  ${s.join(`
19
- `)}`)}let o=tn(t).slice(0,qA);if(o.length>0){let s=o.map(i=>{let a=rn(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=tn(t).slice(0,KA);if(o.length>0){let s=o.map(i=>{let a=rn(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 nn(t){let e={name:Wn,label:Wn,description:JA(),parameters:ig.Unsafe(HA),execute:(n,o,s,i,a)=>VA(t,a,o)},r={name:kr,label:kr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:ig.Unsafe(GA),execute:(n,o,s)=>KA(t,o,s)};sg(Wn,"mcp"),sg(kr,"mcp"),t.registerTool(e),t.registerTool(r),Cr(e),Cr(r),cg.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as zU}from"@hermes/logger";import{logger as o0}from"@hermes/logger";import{logger as YA}from"@hermes/logger";function on(t){return new Promise(e=>setTimeout(e,t))}var dg=YA.child({prefix:"pi-mcp"}),ts={maxTries:3,initialMs:500,mult:2,maxMs:2e3},Bu=3e4,rr=200,lt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function Vu(t){return t instanceof lt?t.statusCode>=500:!0}async function sn(t){let e;for(let r=0;r<ts.maxTries;r++)try{return await t()}catch(n){if(e=n,!Vu(n))throw n;if(r<ts.maxTries-1){let o=Math.min(ts.initialMs*ts.mult**r,ts.maxMs);await on(o)}}throw e}var ea=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??Bu}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>rr?`${s.slice(0,rr)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return sn(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return sn(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function lg(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)}`;dg.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)}`;dg.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function XA(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var fg=32;function QA(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>fg&&(e=e.slice(0,fg)),e=e.replace(/_+$/,""),e}function pg(t,e){let r=e?QA(e):"",n=XA(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function hg(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var e0=1e12,t0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function r0(t){let e=t0.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=Number(e[4]),i=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||s>23||i>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function n0(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<e0?t*1e3:t;if(typeof t=="string")return r0(t)}function mg(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:n0(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Gt=o0.child({prefix:"pi-mcp"}),H=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},Vn=class extends Error{},yg=[100,500],s0=yg.length+1,i0=t=>new Promise(e=>{setTimeout(e,t)});function gg(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Ju="augment.mcp-access-token.",a0=JSON.stringify({retired:!0}),ta=3;function Zt(t){return`${Ju}${t}`}function ra(t){return`legacy:${t}`}function kt(t){return t?.id?pg(t.id,t.name):void 0}function os(t){if(t)return{type:t.type??null,id:t.id??null,name:t.name??null,url:vg(t.url),auth:null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function vg(t){if(typeof t!="string")return null;try{return new URL(t).toString()}catch{return t}}function ss(t){if(typeof t=="string")try{return ss(JSON.parse(t))??t}catch{return t}if(typeof t!="object"||t===null||Array.isArray(t))return t===void 0?void 0:JSON.stringify(t);let e=t;return JSON.stringify({type:e.type??null,id:e.id??null,name:e.name??null,url:vg(e.url),auth:null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function Et(t){return ss(os(t))}function c0(t){return ss(os(t))}function u0(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function Bn(t){try{let e=JSON.parse(t);return{credentialIdentity:ss(e.credentialIdentity),state:u0(e)}}catch{return{}}}function rs(t,e){let r={...t,type:"oauth",credentialIdentity:os(e)};return JSON.stringify(r)}function an(t,e){let r=hg({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:os(e),credentialState:"active"})}function d0(t){return JSON.stringify({credentialIdentity:os(t),credentialState:"retired",retired:!0})}function l0(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=c0(e),s=ss(n.credentialIdentity);if(!(o&&(s===void 0?e?.auth!=="oauth":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{identityMatched:o!==void 0&&s===o,token:n}}function Ku(t){try{let e=mg(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||typeof r.authorization_endpoint!="string"||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var ns=class{_memory=new Un;_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=i0){if(this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"){this._memory.seed(n);for(let[s,i]of n.credentialIdentities??[]){let a=Et(i);a&&this._registryMemoryCommittedAuthorities.set(s,a)}}}get(e){return this._memory.get(e)}commit(e,r,n){this._memory.commit(e,r,n);let o=Et(n);o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e)}hasCredentialIdentity(e,r){return this._memory.hasCredentialIdentity(e,r)}reconcileCredentialIdentity(e,r,n){if(!this._memory.reconcileCredentialIdentity(e,r,n))return!1;let o=Et(n);return o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e),!0}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,n,o)}).catch(()=>{Gt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).then(o=>{o&&this._memory.get(e)===r&&this.commit(e,r,n)}).catch(()=>{Gt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let s=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,n,s)});return}let o=await this._persist(e,r,n,!1);this.commit(e,r,o?n:void 0)}_beginRegistryMemoryWrite(e,r){let n=Et(r);if(!n)throw new H;let o=(this._registryMemoryWriteGenerations.get(e)??0)+1;return this._registryMemoryWriteGenerations.set(e,o),this._registryMemoryAuthorities.set(e,n),{generation:o,identity:n,retirementGeneration:this._memory.credentialRetirementGeneration(e)}}_commitRegistryMemoryWrite(e,r,n,o){this._registryMemoryWriteGenerations.get(e)!==o.generation||this._registryMemoryAuthorities.get(e)!==o.identity||this._memory.credentialRetirementGeneration(e)!==o.retirementGeneration||(this._memory.commit(e,r,n),this._registryMemoryCommittedAuthorities.set(e,o.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=kt(e),n=Et(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 H}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<ta;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new H}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=Bn(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new H;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=Ku(i.value);if(!c)throw new H;try{await r.upsertUserSecret(n,an(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=kt(e),n=Et(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new H;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new H;let i=Bn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Ku(s.value))throw new H;return s.version})}catch{throw new H}}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=kt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,an(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 H;if(c)return{revision:await this._asPersistenceResult(c()),domain:ra(e)}}restoreAfterSupersededRefresh(e,r,n,o,s,i){return this.restoreAfterSupersededAuthentication(e,r,n,o,s,i)}async restoreAfterSupersededAuthentication(e,r,n,o,s,i=o){let a=this._getClient(),c=kt(o),u;if(c&&o){if(!a||!i||s?.domain!==`private:${o.id}`||kt(i)!==c)throw new H;if(u=await this._enqueueWrite(c,()=>this._restoreRegistryCredential({client:a,key:c,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i,persistedRevision:s})),!u)return}if(!c&&kt(i))throw new H;if(!this._shouldPersist())return u;if(!a)throw new H;if(c&&o){try{await this._enqueueWrite(Zt(e),()=>this._restoreLegacyCredential({client:a,key:Zt(e),persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i}))}catch{Gt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return u}if(s?.domain!==ra(e))throw new H;try{return await this._enqueueWrite(Zt(e),()=>this._restoreLegacyCredentialExact({client:a,key:Zt(e),serverName:e,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i,persistedRevision:s}))}catch{throw new H}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:s,currentToken:i,persistedIdentity:a,currentIdentity:c,persistedRevision:u}=e,d=await r.getUserSecretWithVersion(n);if(!(!d||d.version!==u.revision||d.value!==rs(s,a)))try{return{revision:await r.upsertUserSecret(n,rs(i,c),u.revision),domain:ra(o)}}catch(l){if(this._isVersionConflict(l))return;throw l}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,persistedIdentity:i,currentIdentity:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==an(o,i)))try{return{revision:await r.upsertUserSecret(n,an(s,a),c.revision),domain:`private:${a.id}`}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,persistedIdentity:i,currentIdentity:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.value!==rs(o,i)))try{await r.upsertUserSecret(n,rs(s,a),c.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async _drainRegistryWrites(e,r,n,o,s){let i;try{i=await r}catch{throw new H}if(o?.(),s?.id&&!i)throw new H;try{await n?.()}catch{Gt.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=Et(o);if(!s)throw new H;for(let i=0;i<ta;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?Bn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new H;try{return await this._upsertUserSecretOnce(e,r,an(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new H}async _retireRegistryCredential(e,r,n){let o=Et(n);if(!o)throw new H;for(let s=0;s<ta;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?Bn(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new H;try{await this._upsertUserSecretOnce(e,r,d0(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new H}_isVersionConflict(e){return e instanceof lt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=kt(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 H;if(u)return{revision:await this._asPersistenceResult(u()),domain:ra(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new H}}_enqueueWrite(e,r,n){let o=gg(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?s0:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new Vn;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 H}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new Vn}_persistenceRetryDelay(e,r,n){let o=n?yg[r]:void 0,s=!(e instanceof H)&&Vu(e);if(o===void 0||!s){n&&Gt.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(Zt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,Zt(e),rs(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 Vn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=Et(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=kt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new H));let l=this._shouldPersist()&&!i,f;return l&&(c?f=this._enqueueWrite(Zt(e),async()=>{let p=await c.upsertUserSecret(Zt(e),a0)}):f=Promise.reject(new H)),this._awaitRetirements(e,d,f).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Gt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Gt.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=Zt(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 Vn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=kt(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(()=>{Gt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(gg(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=kt(r),o=Et(r);if(!n||!o||!r)return{identityRejected:!1};try{return await this._enqueueWrite(n,()=>this._readRegistryToken({client:e,key:n,expectedIdentity:o,registry:r}))}catch{return{identityRejected:!0}}}async _readRegistryToken(e){for(let r=0;r<ta;r+=1){let n=await this._readRegistryTokenAttempt(e);if(n!==void 0)return n}return{identityRejected:!0}}async _readRegistryTokenAttempt(e){let{client:r,key:n,expectedIdentity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return{identityRejected:!1,authorityVersion:"0"};let a=Bn(i.value);if(a.state==="retired"||(a.credentialIdentity===void 0?s.auth!=="oauth":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,an(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=kt(n),i=Et(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=Bn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,an(a.token,n),o),{identityMatched:!0,token:a.token}}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(Zt(r));return o?l0(o,n):void 0}catch{return}}async ensureLoaded(e,r){if(this._memory.get(e)||!this._shouldPersist()||this.hasInFlightWrite(e))return;let o=this._getClient();if(!o)return;let s=this._memory.credentialRetirementGeneration(e),i=await this._loadRegistryToken(o,r);if(i.identityRejected)return;let a=i.token?{identityMatched:!0,token:i.token}:void 0;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){Gt.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.commit(e,a.token,a.identityMatched?r:void 0),Gt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var _g="Augment Code",Sg="https://augmentcode.com",wg="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var p0=1e3,h0=500;function Xu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function is(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Yu=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function bg(t){return new URLSearchParams({k:t}).toString().slice(2)}function m0(t,e){let r=`${bg(t)}:${bg(e)}`;return`Basic ${btoa(r)}`}function xg(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function g0(t){return t.client.token_endpoint_auth_method==="none"||!xg(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function y0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function v0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var _0=401,kg=500;function Qu(t,...e){return t.status<kg&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function Rg(t){return Qu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===_0}async function Pg(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=xg(t);e==="basic"&&s?n.Authorization=m0(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=v0(c),d=c.slice(0,h0);throw new cn(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Yu;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*p0:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function Cg(t,e){try{return await Pg(t,e,t.resource)}catch(r){if(r instanceof cn&&t.resource&&Qu(r,"invalid_target"))return await Pg(t,e,void 0);throw r}}var cn=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 ed(t){return!(t instanceof cn)||t.status>=kg?!1:Qu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function td(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=g0(t);try{return await Cg(e,r)}catch(n){let o=y0(r);if(!(n instanceof cn)||!o||!Rg(n))throw n;try{return await Cg(e,o)}catch(s){throw s instanceof cn&&Rg(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as p$}from"@hermes/logger";var od;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(od="oauth4webapi/v3.8.6");function Xn(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 Wt="ERR_INVALID_ARG_VALUE",Be="ERR_INVALID_ARG_TYPE";function pe(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var ud=Symbol(),S0=Symbol(),w0=Symbol(),dn=Symbol();var Eg=Symbol();var b0=new TextEncoder,R0=new TextDecoder;function sd(t){return typeof t=="string"?b0.encode(t):R0.decode(t)}var id;Uint8Array.prototype.toBase64?id=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):id=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 ad;Uint8Array.fromBase64?ad=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw pe("The input to be decoded is not correctly encoded.",Wt,e)}}:ad=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw pe("The input to be decoded is not correctly encoded.",Wt,e)}};function oa(t){return typeof t=="string"?ad(t):id(t)}var Jn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=t$,Error.captureStackTrace?.(this,this.constructor)}},as=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new as(t,{code:e,cause:r})}function sa(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function dd(t){Xn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(od&&!e.has("user-agent")&&e.set("user-agent",od),e.has("authorization"))throw pe('"options.headers" must not include the "authorization" header name',Wt);return e}function ld(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw pe('"options.signal" must return or be an instance of AbortSignal',Be);return e}}function P0(t){return t.includes("//")?t.replace("//","/"):t}function C0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=P0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function x0(t,e,r,n){if(!(t instanceof URL))throw pe(`"${e}" must be an instance of URL`,Be);jg(t,n?.[ud]!==!0);let o=r(new URL(t.href)),s=dd(n?.headers);return s.set("accept","application/json"),(n?.[dn]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ld(o,n?.signal)})}function Kn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw pe(`${r} must be a number`,Be,o);if(t>0)return;if(e){if(t!==0)throw pe(`${r} must be a non-negative number`,Wt,o);return}throw pe(`${r} must be a positive number`,Wt,o)}catch(s){throw n?O(s.message,n,o):s}}function Ae(t,e,r,n){try{if(typeof t!="string")throw pe(`${e} must be a string`,Be,n);if(t.length===0)throw pe(`${e} must not be empty`,Wt,n)}catch(o){throw r?O(o.message,r,n):o}}async function $g(t,e){let r=t;if(!(r instanceof URL)&&r!==ca)throw pe('"expectedIssuerIdentifier" must be an instance of URL',Be);if(!Xn(e,Response))throw pe('"response" must be an instance of Response',Be);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',_d,e);ds(e);let n=await fa(e);if(Ae(n.issuer,'"response" body "issuer" property',B,{body:n}),r!==ca&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',da,{expected:r.href,body:n,attribute:"issuer"});return n}function Mg(t){E0(t,"application/json")}function k0(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,n$,t)}function E0(t,e){if(F0(t)!==e)throw k0(t,e)}function fd(){return oa(crypto.getRandomValues(new Uint8Array(32)))}function Ig(){return fd()}function Og(){return fd()}function zg(){return fd()}async function Ng(t){return Ae(t,"codeVerifier"),oa(await crypto.subtle.digest("SHA-256",sd(t)))}function pd(t){let e=t?.[S0];return typeof e=="number"&&Number.isFinite(e)?e:0}function hd(t){let e=t?.[w0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function md(){return Math.floor(Date.now()/1e3)}function ua(t){if(typeof t!="object"||t===null)throw pe('"as" must be an object',Be);Ae(t.issuer,'"as.issuer"')}function gd(t){if(typeof t!="object"||t===null)throw pe('"client" must be an object',Be);Ae(t.client_id,'"client.client_id"')}function Tg(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 yd(t){return Ae(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function Dg(t){return Ae(t,'"clientSecret"'),(e,r,n,o)=>{let s=Tg(r.client_id),i=Tg(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function Lg(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var T0=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function jg(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",o$,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",s$,t)}function Ag(t,e,r,n){let o;if(typeof t!="string"||!(o=T0(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?i$:a$,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return jg(o,n),o}function Fg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Ag(t.mtls_endpoint_aliases[e],e,r,n):Ag(t[e],e,r,n)}var Yn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=e$,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)}},cs=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=r$,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)}},us=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=Q0,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ia="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",A0="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",$0='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',M0="("+ia+")\\s*=\\s*"+$0,I0="("+ia+")\\s*=\\s*("+ia+")",O0=new RegExp("^[,\\s]*("+ia+")"),z0=new RegExp("^[,\\s]*"+M0+"[,\\s]*(.*)"),N0=new RegExp("^[,\\s]*"+I0+"[,\\s]*(.*)"),D0=new RegExp("^("+A0+")(?:$|[,\\s])(.*)");function L0(t){if(!Xn(t,Response))throw pe('"response" must be an instance of Response',Be);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(O0),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let f,p;if(o=n.match(z0)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(N0)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match(D0)){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 j0(t){if(t.status>399&&t.status<500){ds(t),Mg(t);try{let e=await t.clone().json();if(sa(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Ug(t,e,r){if(t.status!==e){G0(t);let n;throw(n=await j0(t))?(await t.body?.cancel(),new Yn("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,_d,t)}}function qg(t){if(!vd.has(t))throw pe('"options.DPoP" is not a valid DPoPHandle',Wt)}function F0(t){return t.headers.get("content-type")?.split(";")[0]}async function U0(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?.[dn]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ld(n,i?.signal)})}async function q0(t,e,r,n,o,s){let i=Fg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[ud]!==!0);o.set("grant_type",n);let a=dd(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(qg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await U0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var Hg=new WeakMap,H0=new WeakMap;function Gg(t){if(!t.id_token)return;let e=Hg.get(t);if(!e)throw pe('"ref" was already garbage collected or did not resolve from the proper sources',Wt);return e}async function Zg(t,e,r,n,o,s){if(ua(t),gd(e),!Xn(r,Response))throw pe('"response" must be an instance of Response',Be);await Ug(r,200,"Token Endpoint"),ds(r);let i=await fa(r);if(Ae(i.access_token,'"response" body "access_token" property',B,{body:i}),Ae(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;Kn(a,!0,'"response" body "expires_in" property',B,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ae(i.refresh_token,'"response" body "refresh_token" property',B,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw O('"response" body "scope" property must be a string',B,{body:i});if(i.id_token!==void 0){Ae(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&&(Kn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await c$(i.id_token,u$.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),pd(e),hd(e),o).then(J0.bind(void 0,a)).then(W0.bind(void 0,t)).then(Z0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',Er,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',Er,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Kn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',B,{claims:c}),H0.set(r,u),Hg.set(i,c)}if(s?.[i.token_type]!==void 0)s[i.token_type](r,i);else if(i.token_type!=="dpop"&&i.token_type!=="bearer")throw new Jn("unsupported `token_type` value",{cause:{body:i}});return i}function G0(t){let e;if(e=L0(t))throw new us("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function Z0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',Er,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',Er,{expected:t,claims:e.claims,claim:"aud"});return e}function W0(t,e){let r=t[f$]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',Er,{expected:r,claims:e.claims,claim:"iss"});return e}var vd=new WeakSet;function B0(t){return vd.add(t),t}var V0=Symbol();async function Wg(t,e,r,n,o,s,i){if(ua(t),gd(e),!vd.has(n))throw pe('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Wt);Ae(o,'"redirectUri"');let a=un(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',B);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==V0&&(Ae(s,'"codeVerifier"'),c.set("code_verifier",s)),q0(t,e,r,"authorization_code",c,i)}var K0={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 J0(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${K0[r]}) claim missing`,B,{claims:e.claims});return e}var rd=Symbol(),nd=Symbol();async function Bg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?Y0(t,e,r,n.expectedNonce,n.maxAge,n[Eg],n.recognizedTokenTypes):X0(t,e,r,n?.[Eg],n?.recognizedTokenTypes)}async function Y0(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=rd;break;case rd:break;default:Ae(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=nd;break;case nd:break;default:Kn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await Zg(t,e,r,a,s,i);Ae(c.id_token,'"response" body "id_token" property',B,{body:c});let u=Gg(c);if(o!==nd){let d=md()+pd(e),l=hd(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",aa,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===rd){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Er,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',Er,{expected:n,claims:u,claim:"nonce"});return c}async function X0(t,e,r,n,o){let s=await Zg(t,e,r,void 0,n,o),i=Gg(s);if(i){if(e.default_max_age!==void 0){Kn(e.default_max_age,!0,'"client.default_max_age"');let a=md()+pd(e),c=hd(e);if(i.auth_time+e.default_max_age<a-c)throw O("too much time has elapsed since the last End-User authentication",aa,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Er,{expected:void 0,claims:i,claim:"nonce"})}return s}var Q0="OAUTH_WWW_AUTHENTICATE_CHALLENGE",e$="OAUTH_RESPONSE_BODY_ERROR",t$="OAUTH_UNSUPPORTED_OPERATION",r$="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var cd="OAUTH_PARSE_ERROR",B="OAUTH_INVALID_RESPONSE";var n$="OAUTH_RESPONSE_IS_NOT_JSON",_d="OAUTH_RESPONSE_IS_NOT_CONFORM",o$="OAUTH_HTTP_REQUEST_FORBIDDEN",s$="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",aa="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Er="OAUTH_JWT_CLAIM_COMPARISON_FAILED",da="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var i$="OAUTH_MISSING_SERVER_METADATA",a$="OAUTH_INVALID_SERVER_METADATA";function ds(t){if(t.bodyUsed)throw pe('"response" body has been used already',Wt)}async function c$(t,e,r,n,o){let{0:s,1:i,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:s,1:i,length:a}=t.split(".");else throw new Jn("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",B,t);let c;try{c=JSON.parse(sd(oa(s)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",cd,l)}if(!sa(c))throw O("JWT Header must be a top level object",B,t);if(e(c),c.crit!==void 0)throw new Jn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(sd(oa(i)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",cd,l)}if(!sa(u))throw O("JWT Payload must be a top level object",B,t);let d=md()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',B,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',aa,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',B,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',B,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',B,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',aa,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',B,{claims:u});return{header:c,claims:u,jwt:t}}function u$(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function un(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,B);return r}var d$=Symbol(),l$=Symbol();function Vg(t,e,r,n){if(ua(t),gd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw pe('"parameters" must be an instance of URLSearchParams, or URL',Be);if(un(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',B,{parameters:r});let o=un(r,"iss"),s=un(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',B,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',B,{expected:t.issuer,parameters:r});switch(n){case void 0:case l$:if(s!==void 0)throw O('unexpected "state" response parameter encountered',B,{expected:void 0,parameters:r});break;case d$:break;default:if(Ae(n,'"expectedState" argument'),s!==n)throw O(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',B,{expected:n,parameters:r})}if(un(r,"error"))throw new cs("authorization response from the server is an error",{cause:r});let a=un(r,"id_token"),c=un(r,"token");if(a!==void 0||c!==void 0)throw new Jn("implicit and hybrid flows are not supported");return B0(new URLSearchParams(r))}async function Kg(t,e,r){ua(t);let n=Fg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[ud]!==!0),o=dd(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(qg(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?.[dn]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:ld(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Jg(t){if(!Xn(t,Response))throw pe('"response" must be an instance of Response',Be);await Ug(t,201,"Dynamic Client Registration Endpoint"),ds(t);let e=await fa(t);return Ae(e.client_id,'"response" body "client_id" property',B,{body:e}),e.client_secret!==void 0&&Ae(e.client_secret,'"response" body "client_secret" property',B,{body:e}),e.client_secret&&Kn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',B,{body:e}),e}async function Yg(t,e){return x0(t,"resourceIdentifier",r=>(C0(r,".well-known/oauth-protected-resource",!0),r),e)}async function la(t,e){let r=t;if(!(r instanceof URL)&&r!==ca)throw pe('"expectedResourceIdentifier" must be an instance of URL',Be);if(!Xn(e,Response))throw pe('"response" must be an instance of Response',Be);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',_d,e);ds(e);let n=await fa(e);if(Ae(n.resource,'"response" body "resource" property',B,{body:n}),r!==ca&&new URL(n.resource).href!==r.href)throw O('"response" body "resource" property does not match the expected value',da,{expected:r.href,body:n,attribute:"resource"});return n}async function fa(t,e=Mg){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',cd,n)}if(!sa(r))throw O('"response" body must be a top level object',B,{body:r});return r}var ca=Symbol(),f$=Symbol();var ey=p$.child({prefix:"pi-mcp"}),ls=1e4,h$=1e3,m$=401,Xg=200,g$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,y$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,ty;function Qn(){return ty??globalThis.fetch}function ry(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function ny(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function wd(t){let e=ny(t);try{let r=await v$(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await R$(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ma(r)}throw new Error("Failed to discover metadata URL")}async function v$(t){try{let e=await Yg(t,{signal:AbortSignal.timeout(ls),[dn]:ty??void 0});return e.ok?await la(t,e):(e.body?.cancel().catch(()=>{}),await oy(t,e.headers.get("www-authenticate"))??await Qg(t))}catch{return await Qg(t)}}async function Qg(t){for(let e of["HEAD","GET"])try{let r=await Qn()(t,{method:e,signal:AbortSignal.timeout(ls)});r.body?.cancel().catch(()=>{});let n=await oy(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function oy(t,e){let r=b$(e);if(r)try{let n=await Qn()(r,{signal:AbortSignal.timeout(ls)});return await _$(t,n)}catch{return}}async function _$(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await la(t,new Response(r,n))}catch(o){if(!(o instanceof as)||o.code!==da)throw o;let s=S$(r);if(!s||!w$(s,t))throw o;return await la(s,new Response(r,n))}}function S$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function w$(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 b$(t){if(!t)return;let e=t.match(g$),r=t.match(y$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function R$(t){for(let e of P$(t))try{let r=new URL(e,t),n=await Qn()(r,{signal:AbortSignal.timeout(ls)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function P$(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 bd(t){try{let e=await Qn()(t,{signal:AbortSignal.timeout(ls)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await C$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await $g(o,new Response(r,n))}catch(e){throw ma(e)}}async function C$(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 Sd=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 x$(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 x$({...t,clientId:n});if(!e.registration_endpoint)throw new Sd(e.issuer);return await k$(e,r)}async function k$(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Kg(t,{client_name:_g,client_uri:Sg,logo_uri:wg,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[dn]:E$});return n.ok||ey.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Jg(n)}catch(r){throw ma(r)}}async function E$(t,e){let r=await Qn()(t,ry(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||ey.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${A$(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 T$(t,e){let r=new Headers(e?.headers),n=r.get("content-type"),o=e;return n?.toLowerCase().startsWith("application/x-www-form-urlencoded;")&&(r.set("content-type","application/x-www-form-urlencoded"),o={...e,headers:r}),Qn()(t,ry(o))}function A$(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>Xg?`${t.slice(0,Xg)}\u2026`:t}}async function pa(t,e,r,n,o,s,i){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=Ig(),c=await Ng(a),u=Og(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!i?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=ny(s??t).toString(),m=new URL(r.authorization_endpoint);return m.searchParams.set("response_type","code"),m.searchParams.set("client_id",e.client_id),m.searchParams.set("code_challenge",c),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("redirect_uri",n),m.searchParams.set("resource",h),m.searchParams.set("state",u),p&&m.searchParams.set("scope",p),l?.includes("offline_access")&&m.searchParams.set("prompt","consent"),r.code_challenge_methods_supported?.includes("S256")||(d=zg(),m.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:m}}function ha(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function Pd(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await pa(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function $$(t,e,r){let n=await Wg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[dn]:T$,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Bg(t.serverMetadata,t.client,await M$(n))}async function Cd(t,e){try{let r=Vg(e.serverMetadata,e.client,t,e.state),n=await O$(e.client,o=>$$(e,r,o));return D$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ma(r)}}async function M$(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 sy(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function I$(t){let e=sy(t);return e===void 0?Lg():t.token_endpoint_auth_method==="client_secret_basic"?Dg(e):yd(e)}async function O$(t,e){try{return await e(I$(t))}catch(r){let n=z$(t);if(n&&N$(r))return await e(n);throw r}}function z$(t){let e=sy(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return yd(e)}function N$(t){return t instanceof Yn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof us?t.status===m$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function D$(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*h$:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ma(t){if(t instanceof Yn||t instanceof cs){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 L$=/(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,iy=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,ay=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,cy=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,fs="[redacted]";function j$(t){return iy.test(t)||ay.test(t)||cy.test(t)}var F$=new RegExp(iy.source,"g"),U$=new RegExp(ay.source,"gi"),q$=new RegExp(cy.source,"g");function uy(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function kd(t){return t&&uy(t,8192).replace(F$,fs).replace(U$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${fs}`).replace(q$,fs)}function xd(t,e,r){if(e)return fs;if(typeof t=="string")return j$(t)?fs:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>xd(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=xd(s,L$.test(o),r+1);return n}function dy(t,e=500){if(t==null)return;let r=xd(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return uy(n,e)}var fy={reportError:()=>{}},ly=Symbol.for("__pi_mcp_error_reporter_slot__");function py(){let t=globalThis,e=t[ly];return e||(e={reporter:null},t[ly]=e),e}function hy(t){let e=py(),r=e.reporter??fy;return e.reporter=t,r}function H$(){return py().reporter??fy}function Ed(t,e){try{H$().reportError(t,e)}catch{}}import{logger as G$}from"@hermes/logger";var Td=G$.child({prefix:"pi-mcp"});function my(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++):Td.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];Td.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function gy(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Ju)){let o=t.headerSecrets[e];if(o!==void 0)return o;let s=t.headerSecretFailures[e];if(s==="missing"||s==="permission_denied")return{reason:s}}let r=t.secretsClient;if(r)try{let o=await r.getSecret(e);return o!==void 0?(delete t.headerSecretFailures[e],o):{reason:t.headerSecretFailures[e]??"missing"}}catch{return{reason:"transient"}}let n=t.headerSecretFailures[e];return n===void 0?void 0:{reason:n}}}function yy(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[s,i]of Object.entries(e))(i==="missing"||i==="permission_denied"||i==="transient")&&(n[s]=i,delete o[s]);t.headerSecrets=o,t.headerSecretFailures=n,Td.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function vy(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as Z$}from"@hermes/logger";var ps=Z$.child({prefix:"pi-mcp"}),W$="$augment-",hs=/\$augment-[a-zA-Z0-9_.-]+/g,B$=new RegExp(hs.source);function ga(t){return B$.test(t)}function ya(t){return t.slice(W$.length)}function Ad(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(hs))e.add(ya(n[0]));return[...e].sort()}var V$=["permission_denied","missing","transient"];function _y(t){let e=new Set(t);return V$.find(r=>e.has(r))??"missing"}var ft=class extends Error{serverName;missingKeys;reason;constructor(e,r,n,o=n===void 0?"missing":"transient"){super(`MCP server "${e}" not started: missing secret(s) ${r.join(", ")}`,n===void 0?void 0:{cause:n}),this.name="McpSecretResolutionError",this.serverName=e,this.missingKeys=r,this.reason=o}};async function Sy(t,e,r,n,o,s,i){let a=[...t.matchAll(hs)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=ya(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),s.set(f,p===void 0?"missing":p.reason),ps.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),ps.warn(`Secret "${f}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),ps.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),s.set(f,"transient"),ps.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function wy({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set,i=new Map;for(let[a,c]of Object.entries(t)){if(!ga(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){ps.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await Sy(c,a,r,o,s,i)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var K$=/["$`\\]/g;function J$(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 Y$(t,e){let r=J$(e);if(r==="double")return t.replace(K$,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function by(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await Sy(t,"command",e,r,n,o,Y$),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as $U}from"node:async_hooks";var Ry,$d=Object.freeze({status:"aborted"});function _(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Bt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},eo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Ry=globalThis).__zod_globalConfig??(Ry.__zod_globalConfig={});var to=globalThis.__zod_globalConfig;function Ve(t){return t&&Object.assign(to,t),to}var U={};Ru(U,{BIGINT_FORMAT_RANGES:()=>ky,Class:()=>Id,NUMBER_FORMAT_RANGES:()=>jd,aborted:()=>$r,allowsEval:()=>Nd,assert:()=>rM,assertEqual:()=>X$,assertIs:()=>eM,assertNever:()=>tM,assertNotEqual:()=>Q$,assignProp:()=>Tr,base64ToUint8Array:()=>Ty,base64urlToUint8Array:()=>_M,cached:()=>no,captureStackTrace:()=>Sa,cleanEnum:()=>vM,cleanRegex:()=>vs,clone:()=>pt,cloneDef:()=>oM,createTransparentProxy:()=>dM,defineLazy:()=>Y,esc:()=>_a,escapeRegex:()=>or,explicitlyAborted:()=>Fd,extend:()=>pM,finalizeIssue:()=>ht,floatSafeRemainder:()=>Od,getElementAtPath:()=>sM,getEnumValues:()=>gs,getLengthableOrigin:()=>_s,getParsedType:()=>uM,getSizableOrigin:()=>Ey,hexToUint8Array:()=>wM,isObject:()=>ln,isPlainObject:()=>Ar,issue:()=>oo,joinValues:()=>va,jsonStringifyReplacer:()=>ro,merge:()=>mM,mergeDefs:()=>nr,normalizeParams:()=>A,nullish:()=>ys,numKeys:()=>cM,objectClone:()=>nM,omit:()=>fM,optionalKeys:()=>Ld,parsedType:()=>Ud,partial:()=>gM,pick:()=>lM,prefixIssues:()=>sr,primitiveTypes:()=>xy,promiseAllObject:()=>iM,propertyKeyTypes:()=>Dd,randomString:()=>aM,required:()=>yM,safeExtend:()=>hM,shallowClone:()=>Cy,slugify:()=>zd,stringifyPrimitive:()=>wa,uint8ArrayToBase64:()=>Ay,uint8ArrayToBase64url:()=>SM,uint8ArrayToHex:()=>bM,unwrapMessage:()=>ms});function X$(t){return t}function Q$(t){return t}function eM(t){}function tM(t){throw new Error("Unexpected value in exhaustive check")}function rM(t){}function gs(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 va(t,e="|"){return t.map(r=>wa(r)).join(e)}function ro(t,e){return typeof e=="bigint"?e.toString():e}function no(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ys(t){return t==null}function vs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Od(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 Py=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==Py)return n===void 0&&(n=Py,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function nM(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Tr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function nr(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function oM(t){return nr(t._zod.def)}function sM(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function iM(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 aM(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function _a(t){return JSON.stringify(t)}function zd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Sa="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Nd=no(()=>{if(to.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Ar(t){if(ln(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Cy(t){return Ar(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function cM(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var uM=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}`)}},Dd=new Set(["string","number","symbol"]),xy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function A(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function dM(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 wa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ld(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var jd={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]},ky={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function lM(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=nr(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 Tr(this,"shape",i),i},checks:[]});return pt(t,s)}function fM(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=nr(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 Tr(this,"shape",i),i},checks:[]});return pt(t,s)}function pM(t,e){if(!Ar(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=nr(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Tr(this,"shape",s),s}});return pt(t,o)}function hM(t,e){if(!Ar(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=nr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Tr(this,"shape",n),n}});return pt(t,r)}function mM(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=nr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Tr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function gM(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=nr(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 Tr(this,"shape",c),c},checks:[]});return pt(e,i)}function yM(t,e,r){let n=nr(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 Tr(this,"shape",s),s}});return pt(e,n)}function $r(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 Fd(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 sr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ms(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n=t.message?t.message:ms(t.inst?._zod.def?.error?.(t))??ms(e?.error?.(t))??ms(r.customError?.(t))??ms(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 Ey(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function _s(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ud(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 oo(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function vM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function Ty(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 Ay(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function _M(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return Ty(e+r)}function SM(t){return Ay(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wM(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 bM(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Id=class{constructor(...e){}};var $y=(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,ro,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ba=_("$ZodError",$y),qd=_("$ZodError",$y,{Parent:Error});function Hd(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 Gd(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 Ra=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 Bt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ve())));throw Sa(a,o?.callee),a}return i.value};var Pa=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ve())));throw Sa(a,o?.callee),a}return i.value};var Ss=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Bt;return s.issues.length?{success:!1,error:new(t??ba)(s.issues.map(i=>ht(i,o,Ve())))}:{success:!0,data:s.value}},ws=Ss(qd),bs=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ht(i,o,Ve())))}:{success:!0,data:s.value}},Ca=bs(qd),My=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ra(t)(e,r,o)};var Iy=t=>(e,r,n)=>Ra(t)(e,r,n);var Oy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pa(t)(e,r,o)};var zy=t=>async(e,r,n)=>Pa(t)(e,r,n);var Ny=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ss(t)(e,r,o)};var Dy=t=>(e,r,n)=>Ss(t)(e,r,n);var Ly=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return bs(t)(e,r,o)};var jy=t=>async(e,r,n)=>bs(t)(e,r,n);var Fy=/^[cC][0-9a-z]{6,}$/,Uy=/^[0-9a-z]+$/,qy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Hy=/^[0-9a-vA-V]{20}$/,Gy=/^[A-Za-z0-9]{27}$/,Zy=/^[a-zA-Z0-9_-]{21}$/,Wy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var By=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Zd=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 Vy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var PM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Ky(){return new RegExp(PM,"u")}var Jy=/^(?:(?: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])$/,Yy=/^(([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 Xy=/^((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])$/,Qy=/^(([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])$/,ev=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wd=/^[A-Za-z0-9_-]*$/;var tv=/^https?$/,rv=/^\+[1-9]\d{6,14}$/,nv="(?:(?:\\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])))",ov=new RegExp(`^${nv}$`);function sv(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 iv(t){return new RegExp(`^${sv(t)}$`)}function av(t){let e=sv({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(`^${nv}T(?:${n})$`)}var cv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},uv=/^-?\d+n?$/,dv=/^-?\d+$/,Bd=/^-?\d+(?:\.\d+)?$/,lv=/^(?:true|false)$/i,fv=/^null$/i;var pv=/^[^A-Z]*$/,hv=/^[^a-z]*$/;var $e=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),mv={number:"number",bigint:"bigint",object:"date"},Vd=_("$ZodCheckLessThan",(t,e)=>{$e.init(t,e);let r=mv[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=_("$ZodCheckGreaterThan",(t,e)=>{$e.init(t,e);let r=mv[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})}}),gv=_("$ZodCheckMultipleOf",(t,e)=>{$e.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):Od(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})}}),yv=_("$ZodCheckNumberFormat",(t,e)=>{$e.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=jd[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=dv)}),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 vv=_("$ZodCheckMaxLength",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),_v=_("$ZodCheckMinLength",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Sv=_("$ZodCheckLengthEquals",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ps=_("$ZodCheckStringFormat",(t,e)=>{var r,n;$e.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=()=>{})}),wv=_("$ZodCheckRegex",(t,e)=>{Ps.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),bv=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=pv),Ps.init(t,e)}),Rv=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=hv),Ps.init(t,e)}),Pv=_("$ZodCheckIncludes",(t,e)=>{$e.init(t,e);let r=or(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Cv=_("$ZodCheckStartsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`^${or(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})}}),xv=_("$ZodCheckEndsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`.*${or(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 kv=_("$ZodCheckOverwrite",(t,e)=>{$e.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var xa=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 nn(t){let e={name:Wn,label:Wn,description:n0(),parameters:ug.Unsafe(JA),execute:(n,o,s,i,a)=>t0(t,a,o)},r={name:kr,label:kr,description:"Execute a discovered MCP tool by its original name, using the tool_name and mcp_server returned by find-tool.",parameters:ug.Unsafe(YA),execute:(n,o,s)=>r0(t,o,s)};cg(Wn,"mcp"),cg(kr,"mcp"),t.registerTool(e),t.registerTool(r),Cr(e),Cr(r),lg.debug("Registered tool-search gateway (find-tool, execute-tool)")}import{logger as qU}from"@hermes/logger";import{logger as l0}from"@hermes/logger";import{logger as o0}from"@hermes/logger";function on(t){return new Promise(e=>setTimeout(e,t))}var pg=o0.child({prefix:"pi-mcp"}),ts={maxTries:3,initialMs:500,mult:2,maxMs:2e3},Bu=3e4,rr=200,lt=class extends Error{statusCode;statusText;responseBody;constructor(e,r,n){super(`${e} ${r}: ${n}`),this.name="McpRegistryHttpError",this.statusCode=e,this.statusText=r,this.responseBody=n}};function Vu(t){return t instanceof lt?t.statusCode>=500:!0}async function sn(t){let e;for(let r=0;r<ts.maxTries;r++)try{return await t()}catch(n){if(e=n,!Vu(n))throw n;if(r<ts.maxTries-1){let o=Math.min(ts.initialMs*ts.mult**r,ts.maxMs);await on(o)}}throw e}var ea=class{apiKey;apiUrl;fetchImpl;timeoutMs;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.fetchImpl=r,this.timeoutMs=n??Bu}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>rr?`${s.slice(0,rr)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}getMcpTenantConfigs(e){return sn(()=>this.callApi("/settings/get-mcp-tenant-configs",e))}getMcpUserConfigs(e){return sn(()=>this.callApi("/settings/get-mcp-user-configs",e))}};async function hg(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)}`;pg.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)}`;pg.warn(a),r.push({message:a})}return{tenant:s,user:i,diagnostics:r}}function s0(t){return t.replace(/[^A-Za-z0-9]/g,"_").toUpperCase()}var mg=32;function i0(t){let e=t.toUpperCase();return e=e.replace(/[^A-Za-z0-9]/g,"_"),e=e.replace(/_+/g,"_"),e=e.replace(/^_+|_+$/g,""),e.length>mg&&(e=e.slice(0,mg)),e=e.replace(/_+$/,""),e}function gg(t,e){let r=e?i0(e):"",n=s0(t);return r?`AUGMENT_MCP_${r}_${n}_OAUTH_CREDENTIALS`:`AUGMENT_MCP_${n}_OAUTH_CREDENTIALS`}function yg(t){let e={accessToken:t.accessToken,refreshToken:t.refreshToken,clientSecret:t.clientSecret};return t.expiresAt!==void 0&&(e.expiresAt=t.expiresAt),t.resource&&(e.resource=t.resource),t.serverMetadata&&(e.serverMetadata=t.serverMetadata),t.client&&(e.client=t.client),JSON.stringify(e)}var a0=1e12,c0=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;function u0(t){let e=c0.exec(t);if(!e)return;let r=Number(e[1]),n=Number(e[2]),o=Number(e[3]),s=Number(e[4]),i=Number(e[5]),a=Number(e[6]),c=Number(e[7]??0),u=Number(e[8]??0),f=[31,r%4===0&&(r%100!==0||r%400===0)?29:28,31,30,31,30,31,31,30,31,30,31][n-1];if(f===void 0||o<1||o>f||s>23||i>59||a>59||c>23||u>59)return;let p=Date.parse(t);return Number.isNaN(p)?void 0:p}function d0(t){if(typeof t=="number"&&Number.isFinite(t))return t>0&&t<a0?t*1e3:t;if(typeof t=="string")return u0(t)}function vg(t){let e=JSON.parse(t),r=typeof e.accessToken=="string"?e.accessToken:"",n=typeof e.refreshToken=="string"?e.refreshToken:void 0;if(!r&&!n)throw new Error("Invalid OAuth secret: missing or invalid accessToken");return{accessToken:r,refreshToken:n,clientSecret:typeof e.clientSecret=="string"?e.clientSecret:void 0,expiresAt:d0(e.expiresAt),resource:typeof e.resource=="string"?e.resource:void 0,serverMetadata:e.serverMetadata&&typeof e.serverMetadata=="object"?e.serverMetadata:void 0,client:e.client&&typeof e.client=="object"?e.client:void 0}}var Gt=l0.child({prefix:"pi-mcp"}),H=class extends Error{constructor(){super("MCP OAuth credential persistence failed"),this.name="TokenPersistenceError"}},Vn=class extends Error{},Sg=[100,500],f0=Sg.length+1,p0=t=>new Promise(e=>{setTimeout(e,t)});function _g(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}var Ju="augment.mcp-access-token.",h0=JSON.stringify({retired:!0}),ta=3;function Zt(t){return`${Ju}${t}`}function ra(t){return`legacy:${t}`}function kt(t){return t?.id?gg(t.id,t.name):void 0}function os(t){if(t)return{type:t.type??null,id:t.id??null,name:t.name??null,url:wg(t.url),auth:null,registrySource:t.registrySource??null,vfsSource:t.vfsSource??null}}function wg(t){if(typeof t!="string")return null;try{return new URL(t).toString()}catch{return t}}function ss(t){if(typeof t=="string")try{return ss(JSON.parse(t))??t}catch{return t}if(typeof t!="object"||t===null||Array.isArray(t))return t===void 0?void 0:JSON.stringify(t);let e=t;return JSON.stringify({type:e.type??null,id:e.id??null,name:e.name??null,url:wg(e.url),auth:null,registrySource:e.registrySource??null,vfsSource:e.vfsSource??null})}function Et(t){return ss(os(t))}function m0(t){return ss(os(t))}function g0(t){if(t.credentialState==="active"||t.credentialState==="retired")return t.credentialState;if(t.retired===!0)return"retired"}function Bn(t){try{let e=JSON.parse(t);return{credentialIdentity:ss(e.credentialIdentity),state:g0(e)}}catch{return{}}}function rs(t,e){let r={...t,type:"oauth",credentialIdentity:os(e)};return JSON.stringify(r)}function an(t,e){let r=yg({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:os(e),credentialState:"active"})}function y0(t){return JSON.stringify({credentialIdentity:os(t),credentialState:"retired",retired:!0})}function v0(t,e){let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null)return;let n=r,o=m0(e),s=ss(n.credentialIdentity);if(!(o&&(s===void 0?e?.auth!=="oauth":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{identityMatched:o!==void 0&&s===o,token:n}}function Ku(t){try{let e=vg(t),r=e.serverMetadata,n=e.client;if(!r||!n||!e.accessToken&&!e.refreshToken||typeof r.authorization_endpoint!="string"||typeof r.token_endpoint!="string"||typeof n.client_id!="string")return;let o;return e.clientSecret?o=e.clientSecret:typeof n.client_secret=="string"&&(o=n.client_secret),{accessToken:e.accessToken,refreshToken:e.refreshToken,expiresAt:e.expiresAt,resource:e.resource,serverMetadata:{issuer:typeof r.issuer=="string"?r.issuer:r.authorization_endpoint,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint},client:{client_id:n.client_id,...o?{client_secret:o}:{}}}}catch{return}}var ns=class{_memory=new Un;_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=p0){if(this._getClient=e,this._shouldPersist=r,this._delay=typeof n=="function"?n:o,n&&typeof n!="function"){this._memory.seed(n);for(let[s,i]of n.credentialIdentities??[]){let a=Et(i);a&&this._registryMemoryCommittedAuthorities.set(s,a)}}}get(e){return this._memory.get(e)}commit(e,r,n){this._memory.commit(e,r,n);let o=Et(n);o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e)}hasCredentialIdentity(e,r){return this._memory.hasCredentialIdentity(e,r)}reconcileCredentialIdentity(e,r,n){if(!this._memory.reconcileCredentialIdentity(e,r,n))return!1;let o=Et(n);return o?this._registryMemoryCommittedAuthorities.set(e,o):this._registryMemoryCommittedAuthorities.delete(e),!0}clearLocalCredential(e){this._memory.clearLocalCredential(e),this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e),this._registryMemoryWriteGenerations.set(e,(this._registryMemoryWriteGenerations.get(e)??0)+1),this._registryMemoryAuthorities.delete(e)}set(e,r,n){if(n?.id){let o=this._beginRegistryMemoryWrite(e,n);this._persist(e,r,n,!0,()=>{this._commitRegistryMemoryWrite(e,r,n,o)}).catch(()=>{Gt.error(`Failed to persist MCP OAuth token for "${e}"; authoritative memory was not changed`)});return}this._memory.set(e,r),this._registryMemoryCommittedAuthorities.delete(e),this._persist(e,r,n,!0).then(o=>{o&&this._memory.get(e)===r&&this.commit(e,r,n)}).catch(()=>{Gt.error(`Failed to persist MCP OAuth token for "${e}"; stored in-memory only`)})}async setAndPersist(e,r,n){if(n?.id){let s=this._beginRegistryMemoryWrite(e,n);await this._persist(e,r,n,!1,()=>{this._commitRegistryMemoryWrite(e,r,n,s)});return}let o=await this._persist(e,r,n,!1);this.commit(e,r,o?n:void 0)}_beginRegistryMemoryWrite(e,r){let n=Et(r);if(!n)throw new H;let o=(this._registryMemoryWriteGenerations.get(e)??0)+1;return this._registryMemoryWriteGenerations.set(e,o),this._registryMemoryAuthorities.set(e,n),{generation:o,identity:n,retirementGeneration:this._memory.credentialRetirementGeneration(e)}}_commitRegistryMemoryWrite(e,r,n,o){this._registryMemoryWriteGenerations.get(e)!==o.generation||this._registryMemoryAuthorities.get(e)!==o.identity||this._memory.credentialRetirementGeneration(e)!==o.retirementGeneration||(this._memory.commit(e,r,n),this._registryMemoryCommittedAuthorities.set(e,o.identity))}persist(e,r,n){return this._persist(e,r,n,!1)}async captureAuthenticatedIdentityVersion(e){let r=kt(e),n=Et(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 H}}async _captureAuthenticatedIdentityVersion(e){for(let r=0;r<ta;r+=1){let n=await this._captureIdentityVersionAttempt(e);if(n!==void 0)return n}throw new H}async _captureIdentityVersionAttempt(e){let{client:r,key:n,identity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return"0";let a=Bn(i.value);if(a.state==="retired")return i.version;if(a.credentialIdentity!==void 0&&a.credentialIdentity!==o)throw new H;if(a.credentialIdentity===o&&a.state==="active")return i.version;let c=Ku(i.value);if(!c)throw new H;try{await r.upsertUserSecret(n,an(c,s),i.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async captureRefreshIdentityVersion(e){let r=kt(e),n=Et(e),o=this._getClient();if(!r||!n||!o){if(e?.id)throw new H;return}try{return await this._enqueueWrite(r,async()=>{let s=await o.getUserSecretWithVersion(r);if(!s)throw new H;let i=Bn(s.value);if(i.state!=="active"||i.credentialIdentity!==n||!Ku(s.value))throw new H;return s.version})}catch{throw new H}}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=kt(n),a=n&&i&&s&&o!==void 0?this._enqueueWrite(i,()=>s.upsertUserSecret(i,an(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 H;if(c)return{revision:await this._asPersistenceResult(c()),domain:ra(e)}}restoreAfterSupersededRefresh(e,r,n,o,s,i){return this.restoreAfterSupersededAuthentication(e,r,n,o,s,i)}async restoreAfterSupersededAuthentication(e,r,n,o,s,i=o){let a=this._getClient(),c=kt(o),u;if(c&&o){if(!a||!i||s?.domain!==`private:${o.id}`||kt(i)!==c)throw new H;if(u=await this._enqueueWrite(c,()=>this._restoreRegistryCredential({client:a,key:c,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i,persistedRevision:s})),!u)return}if(!c&&kt(i))throw new H;if(!this._shouldPersist())return u;if(!a)throw new H;if(c&&o){try{await this._enqueueWrite(Zt(e),()=>this._restoreLegacyCredential({client:a,key:Zt(e),persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i}))}catch{Gt.error(`Failed to mirror restored MCP OAuth token for "${e}" to the legacy key`)}return u}if(s?.domain!==ra(e))throw new H;try{return await this._enqueueWrite(Zt(e),()=>this._restoreLegacyCredentialExact({client:a,key:Zt(e),serverName:e,persistedToken:r,currentToken:n,persistedIdentity:o,currentIdentity:i,persistedRevision:s}))}catch{throw new H}}async _restoreLegacyCredentialExact(e){let{client:r,key:n,serverName:o,persistedToken:s,currentToken:i,persistedIdentity:a,currentIdentity:c,persistedRevision:u}=e,d=await r.getUserSecretWithVersion(n);if(!(!d||d.version!==u.revision||d.value!==rs(s,a)))try{return{revision:await r.upsertUserSecret(n,rs(i,c),u.revision),domain:ra(o)}}catch(l){if(this._isVersionConflict(l))return;throw l}}async _restoreRegistryCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,persistedIdentity:i,currentIdentity:a,persistedRevision:c}=e,u=await r.getUserSecretWithVersion(n);if(!(!u||u.version!==c.revision||u.value!==an(o,i)))try{return{revision:await r.upsertUserSecret(n,an(s,a),c.revision),domain:`private:${a.id}`}}catch(d){if(this._isVersionConflict(d))return;throw d}}async _restoreLegacyCredential(e){let{client:r,key:n,persistedToken:o,currentToken:s,persistedIdentity:i,currentIdentity:a}=e,c=await r.getUserSecretWithVersion(n);if(!(!c||c.value!==rs(o,i)))try{await r.upsertUserSecret(n,rs(s,a),c.version)}catch(u){if(!this._isVersionConflict(u))throw u}}async _drainRegistryWrites(e,r,n,o,s){let i;try{i=await r}catch{throw new H}if(o?.(),s?.id&&!i)throw new H;try{await n?.()}catch{Gt.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=Et(o);if(!s)throw new H;for(let i=0;i<ta;i+=1){let a=await e.getUserSecretWithVersion(r),c=a?Bn(a.value):{};if(c.state==="retired"||c.credentialIdentity!==void 0&&c.credentialIdentity!==s)throw new H;try{return await this._upsertUserSecretOnce(e,r,an(n,o),a?.version??"0")}catch(u){if(!this._isVersionConflict(u))throw u}}throw new H}async _retireRegistryCredential(e,r,n){let o=Et(n);if(!o)throw new H;for(let s=0;s<ta;s+=1){let i=await e.getUserSecretWithVersion(r),a=i?Bn(i.value):{};if(a.state==="retired"||a.credentialIdentity!==void 0&&a.credentialIdentity!==o)return;if(i&&a.credentialIdentity===void 0)throw new H;try{await this._upsertUserSecretOnce(e,r,y0(n),i?.version??"0");return}catch(c){if(!this._isVersionConflict(c))throw c}}throw new H}_isVersionConflict(e){return e instanceof lt&&(e.statusCode===412||e.statusCode===400&&e.responseBody.includes("version mismatch"))}async _persist(e,r,n,o,s){let i=this._getClient(),a=kt(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 H;if(u)return{revision:await this._asPersistenceResult(u()),domain:ra(e)}}snapshot(){return this._memory.snapshot()}async _asPersistenceResult(e){try{return await e}catch{throw new H}}_enqueueWrite(e,r,n){let o=_g(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?f0:1;for(let i=0;i<s;i+=1){if(this._isLegacyPersistenceGateClosed(o))throw new Vn;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 H}_isLegacyPersistenceGateClosed(e){return e?.credentialShape==="legacy"&&!this._shouldPersist()}_throwIfPersistenceCanceled(e,r,n){if(n!==void 0&&e.latestMutationGeneration!==r||this._isLegacyPersistenceGateClosed(n))throw new Vn}_persistenceRetryDelay(e,r,n){let o=n?Sg[r]:void 0,s=!(e instanceof H)&&Vu(e);if(o===void 0||!s){n&&Gt.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(Zt(e),async()=>{let a=this._getClient();if(!a)throw new Error("MCP secrets client unavailable");let c=await this._upsertUserSecretOnce(a,Zt(e),rs(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 Vn||!n)&&this._dirtyGenerations.get(e)===s&&this._dirtyGenerations.delete(e)}),i}retireCredential(e,r,n){let o=Et(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=kt(r),d;u&&r&&(c?d=this._enqueueWrite(u,()=>{let p=this._getClient();if(!p)throw new Error("MCP secrets client unavailable");return this._retireRegistryCredential(p,u,r)},{credentialShape:"registry",operation:"delete"}):d=Promise.reject(new H));let l=this._shouldPersist()&&!i,f;return l&&(c?f=this._enqueueWrite(Zt(e),async()=>{let p=await c.upsertUserSecret(Zt(e),h0)}):f=Promise.reject(new H)),this._awaitRetirements(e,d,f).then(()=>{this._registryMemoryWriteGenerations.get(e)===a&&(this._memory.retireCredential(e,r,{preserveNameState:i}),i||(this._dirtyGenerations.delete(e),this._registryMemoryCommittedAuthorities.delete(e)))})}async _awaitRetirements(e,r,n){let[o,s]=await Promise.allSettled([r,n]);if(o.status==="rejected"&&Gt.error(`Failed to retire MCP OAuth credential identity for "${e}" durably`),s.status==="rejected"&&Gt.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=Zt(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 Vn&&this._dirtyGenerations.get(e)===o&&this._dirtyGenerations.delete(e)})}_retireRegistryKey(e){let r=kt(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(()=>{Gt.error(`Failed to retire MCP OAuth registry credential "${r}" durably; cleared in-memory only`)})}_canScheduleDurableOperation(e){return!!(this._getClient()??this._durableQueues.get(_g(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=kt(r),o=Et(r);if(!n||!o||!r)return{identityRejected:!1};try{return await this._enqueueWrite(n,()=>this._readRegistryToken({client:e,key:n,expectedIdentity:o,registry:r}))}catch{return{identityRejected:!0}}}async _readRegistryToken(e){for(let r=0;r<ta;r+=1){let n=await this._readRegistryTokenAttempt(e);if(n!==void 0)return n}return{identityRejected:!0}}async _readRegistryTokenAttempt(e){let{client:r,key:n,expectedIdentity:o,registry:s}=e,i=await r.getUserSecretWithVersion(n);if(!i)return{identityRejected:!1,authorityVersion:"0"};let a=Bn(i.value);if(a.state==="retired"||(a.credentialIdentity===void 0?s.auth!=="oauth":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,an(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=kt(n),i=Et(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=Bn(c.value);if(u.state==="retired"||u.credentialIdentity!==void 0&&u.credentialIdentity!==i)return}return await e.upsertUserSecret(s,an(a.token,n),o),{identityMatched:!0,token:a.token}}})}catch{return}}async _loadLegacyToken(e,r,n){try{let o=await e.getSecret(Zt(r));return o?v0(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?{identityMatched:!0,token:i.token}:void 0;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){Gt.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.commit(e,a.token,a.identityMatched?r:void 0),Gt.debug(`Seeded MCP OAuth token for "${e}" from backend`))}}};var bg="Augment Code",Rg="https://augmentcode.com",Pg="https://storage.googleapis.com/augment-bazel-data/public/auth0/2024-10-15-auth0-augment-logo-512x512.png";var S0=1e3,w0=500;function Xu(t,e=Date.now()){return t.expiresAt!==void 0&&e+2e4>=t.expiresAt}function is(t,e=Date.now()){return t.expiresAt!==void 0&&t.expiresAt<=e}var Yu=class extends Error{constructor(){super("OAuth token response contained no access token"),Object.defineProperty(this,"name",{value:"MalformedRefreshResponseError",configurable:!0})}};function Cg(t){return new URLSearchParams({k:t}).toString().slice(2)}function b0(t,e){let r=`${Cg(t)}:${Cg(e)}`;return`Basic ${btoa(r)}`}function Tg(t){let e=t.client.client_secret;return e?.trim()?e:void 0}function R0(t){return t.client.token_endpoint_auth_method==="none"||!Tg(t)?"none":t.client.token_endpoint_auth_method==="client_secret_basic"?"basic":"body"}function P0(t){return t==="basic"?"body":t==="body"?"basic":void 0}function C0(t){try{let e=JSON.parse(t);return typeof e.error=="string"?e.error:void 0}catch{return}}var x0=401,Ag=500;function Qu(t,...e){return t.status<Ag&&t.oauthErrorCode!==void 0&&e.includes(t.oauthErrorCode)}function xg(t){return Qu(t,"invalid_client","unauthorized")?!0:t.oauthErrorCode===void 0&&t.status===x0}async function kg(t,e,r){let n={"Content-Type":"application/x-www-form-urlencoded"},o=new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refreshToken});r&&o.set("resource",r);let s=Tg(t);e==="basic"&&s?n.Authorization=b0(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=C0(c),d=c.slice(0,w0);throw new cn(i.status,i.statusText,d,u)}let a=await i.json();if(!a.access_token)throw new Yu;return{accessToken:a.access_token,refreshToken:a.refresh_token||t.refreshToken,expiresAt:a.expires_in?Date.now()+a.expires_in*S0:void 0,tokenType:a.token_type??t.tokenType,scope:a.scope??t.scope,serverMetadata:t.serverMetadata,client:t.client,resource:t.resource}}async function Eg(t,e){try{return await kg(t,e,t.resource)}catch(r){if(r instanceof cn&&t.resource&&Qu(r,"invalid_target"))return await kg(t,e,void 0);throw r}}var cn=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 ed(t){return!(t instanceof cn)||t.status>=Ag?!1:Qu(t,"invalid_grant","invalid_client")||t.clientAuthPlacementsExhausted}async function td(t){if(!t.refreshToken)throw new Error("No refresh token available");let e=t,r=R0(t);try{return await Eg(e,r)}catch(n){let o=P0(r);if(!(n instanceof cn)||!o||!xg(n))throw n;try{return await Eg(e,o)}catch(s){throw s instanceof cn&&xg(s)?s.withClientAuthPlacementsExhausted():s}}}import{logger as S$}from"@hermes/logger";var od;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(od="oauth4webapi/v3.8.6");function Xn(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 Wt="ERR_INVALID_ARG_VALUE",Ve="ERR_INVALID_ARG_TYPE";function pe(t,e,r){let n=new TypeError(t,{cause:r});return Object.assign(n,{code:e}),n}var ud=Symbol(),k0=Symbol(),E0=Symbol(),dn=Symbol();var $g=Symbol();var T0=new TextEncoder,A0=new TextDecoder;function sd(t){return typeof t=="string"?T0.encode(t):A0.decode(t)}var id;Uint8Array.prototype.toBase64?id=t=>(t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t.toBase64({alphabet:"base64url",omitPadding:!0})):id=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 ad;Uint8Array.fromBase64?ad=t=>{try{return Uint8Array.fromBase64(t,{alphabet:"base64url"})}catch(e){throw pe("The input to be decoded is not correctly encoded.",Wt,e)}}:ad=t=>{try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}catch(e){throw pe("The input to be decoded is not correctly encoded.",Wt,e)}};function oa(t){return typeof t=="string"?ad(t):id(t)}var Jn=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=c$,Error.captureStackTrace?.(this,this.constructor)}},as=class extends Error{code;constructor(e,r){super(e,r),this.name=this.constructor.name,r?.code&&(this.code=r?.code),Error.captureStackTrace?.(this,this.constructor)}};function O(t,e,r){return new as(t,{code:e,cause:r})}function sa(t){return!(t===null||typeof t!="object"||Array.isArray(t))}function dd(t){Xn(t,Headers)&&(t=Object.fromEntries(t.entries()));let e=new Headers(t??{});if(od&&!e.has("user-agent")&&e.set("user-agent",od),e.has("authorization"))throw pe('"options.headers" must not include the "authorization" header name',Wt);return e}function ld(t,e){if(e!==void 0){if(typeof e=="function"&&(e=e(t.href)),!(e instanceof AbortSignal))throw pe('"options.signal" must return or be an instance of AbortSignal',Ve);return e}}function $0(t){return t.includes("//")?t.replace("//","/"):t}function M0(t,e,r=!1){return t.pathname==="/"?t.pathname=e:t.pathname=$0(`${e}/${r?t.pathname:t.pathname.replace(/(\/)$/,"")}`),t}async function I0(t,e,r,n){if(!(t instanceof URL))throw pe(`"${e}" must be an instance of URL`,Ve);qg(t,n?.[ud]!==!0);let o=r(new URL(t.href)),s=dd(n?.headers);return s.set("accept","application/json"),(n?.[dn]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(s.entries()),method:"GET",redirect:"manual",signal:ld(o,n?.signal)})}function Kn(t,e,r,n,o){try{if(typeof t!="number"||!Number.isFinite(t))throw pe(`${r} must be a number`,Ve,o);if(t>0)return;if(e){if(t!==0)throw pe(`${r} must be a non-negative number`,Wt,o);return}throw pe(`${r} must be a positive number`,Wt,o)}catch(s){throw n?O(s.message,n,o):s}}function Ae(t,e,r,n){try{if(typeof t!="string")throw pe(`${e} must be a string`,Ve,n);if(t.length===0)throw pe(`${e} must not be empty`,Wt,n)}catch(o){throw r?O(o.message,r,n):o}}async function Og(t,e){let r=t;if(!(r instanceof URL)&&r!==ca)throw pe('"expectedIssuerIdentifier" must be an instance of URL',Ve);if(!Xn(e,Response))throw pe('"response" must be an instance of Response',Ve);if(e.status!==200)throw O('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',_d,e);ds(e);let n=await fa(e);if(Ae(n.issuer,'"response" body "issuer" property',B,{body:n}),r!==ca&&new URL(n.issuer).href!==r.href)throw O('"response" body "issuer" property does not match the expected value',da,{expected:r.href,body:n,attribute:"issuer"});return n}function zg(t){z0(t,"application/json")}function O0(t,...e){let r='"response" content-type must be ';if(e.length>2){let n=e.pop();r+=`${e.join(", ")}, or ${n}`}else e.length===2?r+=`${e[0]} or ${e[1]}`:r+=e[0];return O(r,d$,t)}function z0(t,e){if(B0(t)!==e)throw O0(t,e)}function fd(){return oa(crypto.getRandomValues(new Uint8Array(32)))}function Ng(){return fd()}function Dg(){return fd()}function Lg(){return fd()}async function jg(t){return Ae(t,"codeVerifier"),oa(await crypto.subtle.digest("SHA-256",sd(t)))}function pd(t){let e=t?.[k0];return typeof e=="number"&&Number.isFinite(e)?e:0}function hd(t){let e=t?.[E0];return typeof e=="number"&&Number.isFinite(e)&&Math.sign(e)!==-1?e:30}function md(){return Math.floor(Date.now()/1e3)}function ua(t){if(typeof t!="object"||t===null)throw pe('"as" must be an object',Ve);Ae(t.issuer,'"as.issuer"')}function gd(t){if(typeof t!="object"||t===null)throw pe('"client" must be an object',Ve);Ae(t.client_id,'"client.client_id"')}function Mg(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 yd(t){return Ae(t,'"clientSecret"'),(e,r,n,o)=>{n.set("client_id",r.client_id),n.set("client_secret",t)}}function Fg(t){return Ae(t,'"clientSecret"'),(e,r,n,o)=>{let s=Mg(r.client_id),i=Mg(t),a=btoa(`${s}:${i}`);o.set("authorization",`Basic ${a}`)}}function Ug(){return(t,e,r,n)=>{r.set("client_id",e.client_id)}}var N0=URL.parse?(t,e)=>URL.parse(t,e):(t,e)=>{try{return new URL(t,e)}catch{return null}};function qg(t,e){if(e&&t.protocol!=="https:")throw O("only requests to HTTPS are allowed",l$,t);if(t.protocol!=="https:"&&t.protocol!=="http:")throw O("only HTTP and HTTPS requests are allowed",f$,t)}function Ig(t,e,r,n){let o;if(typeof t!="string"||!(o=N0(t)))throw O(`authorization server metadata does not contain a valid ${r?`"as.mtls_endpoint_aliases.${e}"`:`"as.${e}"`}`,t===void 0?p$:h$,{attribute:r?`mtls_endpoint_aliases.${e}`:e});return qg(o,n),o}function Hg(t,e,r,n){return r&&t.mtls_endpoint_aliases&&e in t.mtls_endpoint_aliases?Ig(t.mtls_endpoint_aliases[e],e,r,n):Ig(t[e],e,r,n)}var Yn=class extends Error{cause;code;error;status;error_description;response;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=a$,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)}},cs=class extends Error{cause;code;error;error_description;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=u$,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)}},us=class extends Error{cause;code;response;status;constructor(e,r){super(e,r),this.name=this.constructor.name,this.code=i$,this.cause=r.cause,this.status=r.response.status,this.response=r.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ia="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",D0="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",L0='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',j0="("+ia+")\\s*=\\s*"+L0,F0="("+ia+")\\s*=\\s*("+ia+")",U0=new RegExp("^[,\\s]*("+ia+")"),q0=new RegExp("^[,\\s]*"+j0+"[,\\s]*(.*)"),H0=new RegExp("^[,\\s]*"+F0+"[,\\s]*(.*)"),G0=new RegExp("^("+D0+")(?:$|[,\\s])(.*)");function Z0(t){if(!Xn(t,Response))throw pe('"response" must be an instance of Response',Ve);let e=t.headers.get("www-authenticate");if(e===null)return;let r=[],n=e;for(;n;){let o=n.match(U0),s=o?.[1].toLowerCase();if(!s)return;let i=n.substring(o[0].length);if(i&&!i.match(/^[\s,]/))return;let a=i.match(/^\s+(.*)$/),c=!!a;n=a?a[1]:void 0;let u={},d;if(c)for(;n;){let f,p;if(o=n.match(q0)){if([,f,p,n]=o,p.includes("\\"))try{p=JSON.parse(`"${p}"`)}catch{}u[f.toLowerCase()]=p;continue}if(o=n.match(H0)){[,f,p,n]=o,u[f.toLowerCase()]=p;continue}if(o=n.match(G0)){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 W0(t){if(t.status>399&&t.status<500){ds(t),zg(t);try{let e=await t.clone().json();if(sa(e)&&typeof e.error=="string"&&e.error.length)return e}catch{}}}async function Gg(t,e,r){if(t.status!==e){Y0(t);let n;throw(n=await W0(t))?(await t.body?.cancel(),new Yn("server responded with an error in the response body",{cause:n,response:t})):O(`"response" is not a conform ${r} response (unexpected HTTP status code)`,_d,t)}}function Zg(t){if(!vd.has(t))throw pe('"options.DPoP" is not a valid DPoPHandle',Wt)}function B0(t){return t.headers.get("content-type")?.split(";")[0]}async function V0(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?.[dn]||fetch)(n.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:ld(n,i?.signal)})}async function K0(t,e,r,n,o,s){let i=Hg(t,"token_endpoint",e.use_mtls_endpoint_aliases,s?.[ud]!==!0);o.set("grant_type",n);let a=dd(s?.headers);a.set("accept","application/json"),s?.DPoP!==void 0&&(Zg(s.DPoP),await s.DPoP.addProof(i,a,"POST"));let c=await V0(t,e,r,i,o,a,s);return s?.DPoP?.cacheNonce(c,i),c}var Wg=new WeakMap,J0=new WeakMap;function Bg(t){if(!t.id_token)return;let e=Wg.get(t);if(!e)throw pe('"ref" was already garbage collected or did not resolve from the proper sources',Wt);return e}async function Vg(t,e,r,n,o,s){if(ua(t),gd(e),!Xn(r,Response))throw pe('"response" must be an instance of Response',Ve);await Gg(r,200,"Token Endpoint"),ds(r);let i=await fa(r);if(Ae(i.access_token,'"response" body "access_token" property',B,{body:i}),Ae(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;Kn(a,!0,'"response" body "expires_in" property',B,{body:i}),i.expires_in=a}if(i.refresh_token!==void 0&&Ae(i.refresh_token,'"response" body "refresh_token" property',B,{body:i}),i.scope!==void 0&&typeof i.scope!="string")throw O('"response" body "scope" property must be a string',B,{body:i});if(i.id_token!==void 0){Ae(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&&(Kn(e.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),n?.length&&a.push(...n);let{claims:c,jwt:u}=await m$(i.id_token,g$.bind(void 0,e.id_token_signed_response_alg,t.id_token_signing_alg_values_supported,"RS256"),pd(e),hd(e),o).then(n$.bind(void 0,a)).then(Q0.bind(void 0,t)).then(X0.bind(void 0,e.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw O('ID Token "aud" (audience) claim includes additional untrusted audiences',Er,{claims:c,claim:"aud"});if(c.azp!==e.client_id)throw O('unexpected ID Token "azp" (authorized party) claim value',Er,{expected:e.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&Kn(c.auth_time,!0,'ID Token "auth_time" (authentication time)',B,{claims:c}),J0.set(r,u),Wg.set(i,c)}if(s?.[i.token_type]!==void 0)s[i.token_type](r,i);else if(i.token_type!=="dpop"&&i.token_type!=="bearer")throw new Jn("unsupported `token_type` value",{cause:{body:i}});return i}function Y0(t){let e;if(e=Z0(t))throw new us("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:e,response:t})}function X0(t,e){if(Array.isArray(e.claims.aud)){if(!e.claims.aud.includes(t))throw O('unexpected JWT "aud" (audience) claim value',Er,{expected:t,claims:e.claims,claim:"aud"})}else if(e.claims.aud!==t)throw O('unexpected JWT "aud" (audience) claim value',Er,{expected:t,claims:e.claims,claim:"aud"});return e}function Q0(t,e){let r=t[_$]?.(e)??t.issuer;if(e.claims.iss!==r)throw O('unexpected JWT "iss" (issuer) claim value',Er,{expected:r,claims:e.claims,claim:"iss"});return e}var vd=new WeakSet;function e$(t){return vd.add(t),t}var t$=Symbol();async function Kg(t,e,r,n,o,s,i){if(ua(t),gd(e),!vd.has(n))throw pe('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',Wt);Ae(o,'"redirectUri"');let a=un(n,"code");if(!a)throw O('no authorization code in "callbackParameters"',B);let c=new URLSearchParams(i?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),s!==t$&&(Ae(s,'"codeVerifier"'),c.set("code_verifier",s)),K0(t,e,r,"authorization_code",c,i)}var r$={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 n$(t,e){for(let r of t)if(e.claims[r]===void 0)throw O(`JWT "${r}" (${r$[r]}) claim missing`,B,{claims:e.claims});return e}var rd=Symbol(),nd=Symbol();async function Jg(t,e,r,n){return typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number"||n?.requireIdToken?o$(t,e,r,n.expectedNonce,n.maxAge,n[$g],n.recognizedTokenTypes):s$(t,e,r,n?.[$g],n?.recognizedTokenTypes)}async function o$(t,e,r,n,o,s,i){let a=[];switch(n){case void 0:n=rd;break;case rd:break;default:Ae(n,'"expectedNonce" argument'),a.push("nonce")}switch(o??=e.default_max_age,o){case void 0:o=nd;break;case nd:break;default:Kn(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await Vg(t,e,r,a,s,i);Ae(c.id_token,'"response" body "id_token" property',B,{body:c});let u=Bg(c);if(o!==nd){let d=md()+pd(e),l=hd(e);if(u.auth_time+o<d-l)throw O("too much time has elapsed since the last End-User authentication",aa,{claims:u,now:d,tolerance:l,claim:"auth_time"})}if(n===rd){if(u.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Er,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==n)throw O('unexpected ID Token "nonce" claim value',Er,{expected:n,claims:u,claim:"nonce"});return c}async function s$(t,e,r,n,o){let s=await Vg(t,e,r,void 0,n,o),i=Bg(s);if(i){if(e.default_max_age!==void 0){Kn(e.default_max_age,!0,'"client.default_max_age"');let a=md()+pd(e),c=hd(e);if(i.auth_time+e.default_max_age<a-c)throw O("too much time has elapsed since the last End-User authentication",aa,{claims:i,now:a,tolerance:c,claim:"auth_time"})}if(i.nonce!==void 0)throw O('unexpected ID Token "nonce" claim value',Er,{expected:void 0,claims:i,claim:"nonce"})}return s}var i$="OAUTH_WWW_AUTHENTICATE_CHALLENGE",a$="OAUTH_RESPONSE_BODY_ERROR",c$="OAUTH_UNSUPPORTED_OPERATION",u$="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var cd="OAUTH_PARSE_ERROR",B="OAUTH_INVALID_RESPONSE";var d$="OAUTH_RESPONSE_IS_NOT_JSON",_d="OAUTH_RESPONSE_IS_NOT_CONFORM",l$="OAUTH_HTTP_REQUEST_FORBIDDEN",f$="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",aa="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Er="OAUTH_JWT_CLAIM_COMPARISON_FAILED",da="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var p$="OAUTH_MISSING_SERVER_METADATA",h$="OAUTH_INVALID_SERVER_METADATA";function ds(t){if(t.bodyUsed)throw pe('"response" body has been used already',Wt)}async function m$(t,e,r,n,o){let{0:s,1:i,length:a}=t.split(".");if(a===5)if(o!==void 0)t=await o(t),{0:s,1:i,length:a}=t.split(".");else throw new Jn("JWE decryption is not configured",{cause:t});if(a!==3)throw O("Invalid JWT",B,t);let c;try{c=JSON.parse(sd(oa(s)))}catch(l){throw O("failed to parse JWT Header body as base64url encoded JSON",cd,l)}if(!sa(c))throw O("JWT Header must be a top level object",B,t);if(e(c),c.crit!==void 0)throw new Jn('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(sd(oa(i)))}catch(l){throw O("failed to parse JWT Payload body as base64url encoded JSON",cd,l)}if(!sa(u))throw O("JWT Payload must be a top level object",B,t);let d=md()+r;if(u.exp!==void 0){if(typeof u.exp!="number")throw O('unexpected JWT "exp" (expiration time) claim type',B,{claims:u});if(u.exp<=d-n)throw O('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',aa,{claims:u,now:d,tolerance:n,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw O('unexpected JWT "iat" (issued at) claim type',B,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw O('unexpected JWT "iss" (issuer) claim type',B,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw O('unexpected JWT "nbf" (not before) claim type',B,{claims:u});if(u.nbf>d+n)throw O('unexpected JWT "nbf" (not before) claim value',aa,{claims:u,now:d,tolerance:n,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw O('unexpected JWT "aud" (audience) claim type',B,{claims:u});return{header:c,claims:u,jwt:t}}function g$(t,e,r,n){if(t!==void 0){if(typeof t=="string"?n.alg!==t:!t.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:t,reason:"client configuration"});return}if(Array.isArray(e)){if(!e.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:e,reason:"authorization server metadata"});return}if(r!==void 0){if(typeof r=="string"?n.alg!==r:typeof r=="function"?!r(n.alg):!r.includes(n.alg))throw O('unexpected JWT "alg" header parameter',B,{header:n,expected:r,reason:"default value"});return}throw O('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:t,issuer:e,fallback:r})}function un(t,e){let{0:r,length:n}=t.getAll(e);if(n>1)throw O(`"${e}" parameter must be provided only once`,B);return r}var y$=Symbol(),v$=Symbol();function Yg(t,e,r,n){if(ua(t),gd(e),r instanceof URL&&(r=r.searchParams),!(r instanceof URLSearchParams))throw pe('"parameters" must be an instance of URLSearchParams, or URL',Ve);if(un(r,"response"))throw O('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',B,{parameters:r});let o=un(r,"iss"),s=un(r,"state");if(!o&&t.authorization_response_iss_parameter_supported)throw O('response parameter "iss" (issuer) missing',B,{parameters:r});if(o&&o!==t.issuer)throw O('unexpected "iss" (issuer) response parameter value',B,{expected:t.issuer,parameters:r});switch(n){case void 0:case v$:if(s!==void 0)throw O('unexpected "state" response parameter encountered',B,{expected:void 0,parameters:r});break;case y$:break;default:if(Ae(n,'"expectedState" argument'),s!==n)throw O(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',B,{expected:n,parameters:r})}if(un(r,"error"))throw new cs("authorization response from the server is an error",{cause:r});let a=un(r,"id_token"),c=un(r,"token");if(a!==void 0||c!==void 0)throw new Jn("implicit and hybrid flows are not supported");return e$(new URLSearchParams(r))}async function Xg(t,e,r){ua(t);let n=Hg(t,"registration_endpoint",e.use_mtls_endpoint_aliases,r?.[ud]!==!0),o=dd(r?.headers);o.set("accept","application/json"),o.set("content-type","application/json");let s="POST";r?.DPoP&&(Zg(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?.[dn]||fetch)(n.href,{body:JSON.stringify(e),headers:Object.fromEntries(o.entries()),method:s,redirect:"manual",signal:ld(n,r?.signal)});return r?.DPoP?.cacheNonce(i,n),i}async function Qg(t){if(!Xn(t,Response))throw pe('"response" must be an instance of Response',Ve);await Gg(t,201,"Dynamic Client Registration Endpoint"),ds(t);let e=await fa(t);return Ae(e.client_id,'"response" body "client_id" property',B,{body:e}),e.client_secret!==void 0&&Ae(e.client_secret,'"response" body "client_secret" property',B,{body:e}),e.client_secret&&Kn(e.client_secret_expires_at,!0,'"response" body "client_secret_expires_at" property',B,{body:e}),e}async function ey(t,e){return I0(t,"resourceIdentifier",r=>(M0(r,".well-known/oauth-protected-resource",!0),r),e)}async function la(t,e){let r=t;if(!(r instanceof URL)&&r!==ca)throw pe('"expectedResourceIdentifier" must be an instance of URL',Ve);if(!Xn(e,Response))throw pe('"response" must be an instance of Response',Ve);if(e.status!==200)throw O('"response" is not a conform Resource Server Metadata response (unexpected HTTP status code)',_d,e);ds(e);let n=await fa(e);if(Ae(n.resource,'"response" body "resource" property',B,{body:n}),r!==ca&&new URL(n.resource).href!==r.href)throw O('"response" body "resource" property does not match the expected value',da,{expected:r.href,body:n,attribute:"resource"});return n}async function fa(t,e=zg){let r;try{r=await t.json()}catch(n){throw e(t),O('failed to parse "response" body as JSON',cd,n)}if(!sa(r))throw O('"response" body must be a top level object',B,{body:r});return r}var ca=Symbol(),_$=Symbol();var ny=S$.child({prefix:"pi-mcp"}),ls=1e4,w$=1e3,b$=401,ty=200,R$=/(?:^|[\s,])resource_metadata\s*=\s*"([^"]+)"/,P$=/(?:^|[\s,])resource_metadata\s*=\s*([^,\s]+)/,oy;function Qn(){return oy??globalThis.fetch}function sy(t){let e=AbortSignal.timeout(1e4),r=t?.signal?AbortSignal.any([t.signal,e]):e;return{...t,signal:r}}function iy(t){let e=new URL(t.href);return e.search="",e.hash="",e}async function wd(t){let e=iy(t);try{let r=await C$(e),n=r?.authorization_servers?.map(o=>new URL(o))??[e];for(let o of n){let s=await A$(o);if(s)return Object.assign(s,{resourceScopes:r?.scopes_supported,resourceIdentifier:r?.resource})}}catch(r){throw ma(r)}throw new Error("Failed to discover metadata URL")}async function C$(t){try{let e=await ey(t,{signal:AbortSignal.timeout(ls),[dn]:oy??void 0});return e.ok?await la(t,e):(e.body?.cancel().catch(()=>{}),await ay(t,e.headers.get("www-authenticate"))??await ry(t))}catch{return await ry(t)}}async function ry(t){for(let e of["HEAD","GET"])try{let r=await Qn()(t,{method:e,signal:AbortSignal.timeout(ls)});r.body?.cancel().catch(()=>{});let n=await ay(t,r.headers.get("www-authenticate"));if(n)return n}catch{}}async function ay(t,e){let r=T$(e);if(r)try{let n=await Qn()(r,{signal:AbortSignal.timeout(ls)});return await x$(t,n)}catch{return}}async function x$(t,e){let r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers};try{return await la(t,new Response(r,n))}catch(o){if(!(o instanceof as)||o.code!==da)throw o;let s=k$(r);if(!s||!E$(s,t))throw o;return await la(s,new Response(r,n))}}function k$(t){try{let e=JSON.parse(t);return typeof e.resource!="string"?void 0:new URL(e.resource)}catch{return}}function E$(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 T$(t){if(!t)return;let e=t.match(R$),r=t.match(P$),n=e?.[1]??r?.[1];if(n)try{return new URL(n)}catch{return}}async function A$(t){for(let e of $$(t))try{let r=new URL(e,t),n=await Qn()(r,{signal:AbortSignal.timeout(ls)});if(n.body?.cancel().catch(()=>{}),!n.ok)continue;return r}catch{}}function $$(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 bd(t){try{let e=await Qn()(t,{signal:AbortSignal.timeout(ls)}),r=await e.text(),n={status:e.status,statusText:e.statusText,headers:e.headers},o=await M$(new Response(r,n));if(!o)throw new Error("Missing issuer from discovery response");return await Og(o,new Response(r,n))}catch(e){throw ma(e)}}async function M$(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 Sd=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 I$(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 I$({...t,clientId:n});if(!e.registration_endpoint)throw new Sd(e.issuer);return await O$(e,r)}async function O$(t,e){try{let r=t.token_endpoint_auth_methods_supported?.includes("none")??!1,n=await Xg(t,{client_name:bg,client_uri:Rg,logo_uri:Pg,redirect_uris:e,grant_types:["authorization_code","refresh_token"],response_types:["code"],...r?{token_endpoint_auth_method:"none"}:{}},{[dn]:z$});return n.ok||ny.error(`Dynamic client registration failed with HTTP status ${n.status} (${n.statusText})`),await Qg(n)}catch(r){throw ma(r)}}async function z$(t,e){let r=await Qn()(t,sy(e)),n=await r.text(),o={status:r.status,statusText:r.statusText,headers:r.headers};if(r.ok||ny.error(`Dynamic client registration error response body (HTTP ${r.status} ${r.statusText}): ${D$(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 N$(t,e){let r=new Headers(e?.headers),n=r.get("content-type"),o=e;return n?.toLowerCase().startsWith("application/x-www-form-urlencoded;")&&(r.set("content-type","application/x-www-form-urlencoded"),o={...e,headers:r}),Qn()(t,sy(o))}function D$(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>ty?`${t.slice(0,ty)}\u2026`:t}}async function pa(t,e,r,n,o,s,i){if(!r.authorization_endpoint)throw new Error("No authorization endpoint");let a=Ng(),c=await jg(a),u=Dg(),d,l=(o??r.scopes_supported?.join(" "))?.split(/\s+/).filter(Boolean),f=!1;!i?.disableOfflineAccessAugmentation&&l?.length&&!l.includes("offline_access")&&r.scopes_supported?.includes("offline_access")&&(l.push("offline_access"),f=!0);let p=l?.join(" ")||void 0,h=iy(s??t).toString(),m=new URL(r.authorization_endpoint);return m.searchParams.set("response_type","code"),m.searchParams.set("client_id",e.client_id),m.searchParams.set("code_challenge",c),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("redirect_uri",n),m.searchParams.set("resource",h),m.searchParams.set("state",u),p&&m.searchParams.set("scope",p),l?.includes("offline_access")&&m.searchParams.set("prompt","consent"),r.code_challenge_methods_supported?.includes("S256")||(d=Lg(),m.searchParams.set("nonce",d)),{client:e,serverMetadata:r,redirectUri:n,codeVerifier:a,nonce:d,scope:p,state:u,resource:h,offlineAccessAugmented:f,authUri:m}}function ha(t,e){return e.offlineAccessAugmented===!0&&t.get("error")==="invalid_scope"&&t.get("state")===e.state}async function Pd(t){if(!t.resource)throw new Error("Cannot rebuild authorization state without a resource");let e=t.scope?.split(/\s+/).filter(r=>r&&r!=="offline_access").join(" ");return await pa(new URL(t.resource),t.client,t.serverMetadata,t.redirectUri,e||void 0,void 0,{disableOfflineAccessAugmentation:!0})}async function L$(t,e,r){let n=await Kg(t.serverMetadata,t.client,r,e,t.redirectUri,t.codeVerifier,{[dn]:N$,...t.resource?{additionalParameters:{resource:t.resource}}:{}});return Jg(t.serverMetadata,t.client,await j$(n))}async function Cd(t,e){try{let r=Yg(e.serverMetadata,e.client,t,e.state),n=await U$(e.client,o=>L$(e,r,o));return G$(n,e.serverMetadata,e.client,void 0,e.resource)}catch(r){throw ma(r)}}async function j$(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 cy(t){let e=t.client_secret;return typeof e=="string"&&e.length>0?e:void 0}function F$(t){let e=cy(t);return e===void 0?Ug():t.token_endpoint_auth_method==="client_secret_basic"?Fg(e):yd(e)}async function U$(t,e){try{return await e(F$(t))}catch(r){let n=q$(t);if(n&&H$(r))return await e(n);throw r}}function q$(t){let e=cy(t);if(t.token_endpoint_auth_method==="client_secret_basic"&&e!==void 0)return yd(e)}function H$(t){return t instanceof Yn?t.error==="invalid_client"||t.error==="unauthorized":t instanceof us?t.status===b$||t.cause.some(({parameters:e})=>{let{error:r}=e;return r==="invalid_client"||r==="unauthorized"}):!1}function G$(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*w$:void 0,tokenType:t.token_type,scope:t.scope,resource:o,serverMetadata:e,client:r}}function ma(t){if(t instanceof Yn||t instanceof cs){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 Z$=/(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,uy=/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/,dy=/\b(bearer|token)\s+[A-Za-z0-9._~+/-]{12,}=*/i,ly=/\b(?=[A-Za-z0-9._-]*[A-Za-z])(?=[A-Za-z0-9._-]*\d)[A-Za-z0-9._-]{24,}\b/,fs="[redacted]";function W$(t){return uy.test(t)||dy.test(t)||ly.test(t)}var B$=new RegExp(uy.source,"g"),V$=new RegExp(dy.source,"gi"),K$=new RegExp(ly.source,"g");function fy(t,e){let r=[...t];return r.length<=e?t:`${r.slice(0,Math.max(e-3,0)).join("")}...`}function kd(t){return t&&fy(t,8192).replace(B$,fs).replace(V$,r=>`${r.match(/^(bearer|token)\s+/i)?.[0]??""}${fs}`).replace(K$,fs)}function xd(t,e,r){if(e)return fs;if(typeof t=="string")return W$(t)?fs:t;if(t===null||typeof t!="object")return t;if(r>=6)return"[truncated]";if(Array.isArray(t))return t.map(o=>xd(o,!1,r+1));let n={};for(let[o,s]of Object.entries(t))n[o]=xd(s,Z$.test(o),r+1);return n}function py(t,e=500){if(t==null)return;let r=xd(t,!1,0),n;try{n=JSON.stringify(r)}catch{return"[unserializable structured content]"}if(!(!n||n==="{}"||n==="[]"||n==='""'))return fy(n,e)}var my={reportError:()=>{}},hy=Symbol.for("__pi_mcp_error_reporter_slot__");function gy(){let t=globalThis,e=t[hy];return e||(e={reporter:null},t[hy]=e),e}function yy(t){let e=gy(),r=e.reporter??my;return e.reporter=t,r}function J$(){return gy().reporter??my}function Ed(t,e){try{J$().reportError(t,e)}catch{}}import{logger as Y$}from"@hermes/logger";var Td=Y$.child({prefix:"pi-mcp"});function vy(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++):Td.warn(`Skipping malformed header-secret entry "${i}"`);t.headerSecrets=s,t.headerSecretFailures??={};for(let i of Object.keys(s))delete t.headerSecretFailures[i];Td.info(`Applied pushed MCP header secret update for ${n} key(s), deleted ${o}`)}function _y(t){return async e=>{if(t.headerSecretFailures??={},!e.startsWith(Ju)){let o=t.headerSecrets[e];if(o!==void 0)return o;let s=t.headerSecretFailures[e];if(s==="missing"||s==="permission_denied")return{reason:s}}let r=t.secretsClient;if(r)try{let o=await r.getSecret(e);return o!==void 0?(delete t.headerSecretFailures[e],o):{reason:t.headerSecretFailures[e]??"missing"}}catch{return{reason:"transient"}}let n=t.headerSecretFailures[e];return n===void 0?void 0:{reason:n}}}function Sy(t,e,r){t.headerSecretFailures??={};let n=r?.authoritative?{}:{...t.headerSecretFailures},o={...t.headerSecrets};for(let[s,i]of Object.entries(e))(i==="missing"||i==="permission_denied"||i==="transient")&&(n[s]=i,delete o[s]);t.headerSecrets=o,t.headerSecretFailures=n,Td.info(`Applied MCP header secret failure update for ${Object.keys(n).length} key(s)`)}function wy(t){return t.secretsClient!==void 0||Object.keys(t.headerSecrets).length>0||Object.keys(t.headerSecretFailures??{}).length>0}import{logger as X$}from"@hermes/logger";var ps=X$.child({prefix:"pi-mcp"}),Q$="$augment-",hs=/\$augment-[a-zA-Z0-9_.-]+/g,eM=new RegExp(hs.source);function ga(t){return eM.test(t)}function ya(t){return t.slice(Q$.length)}function Ad(t){let e=new Set;for(let r of Object.values(t))for(let n of r.matchAll(hs))e.add(ya(n[0]));return[...e].sort()}var tM=["permission_denied","missing","transient"];function by(t){let e=new Set(t);return tM.find(r=>e.has(r))??"missing"}var ft=class extends Error{serverName;missingKeys;reason;constructor(e,r,n,o=n===void 0?"missing":"transient"){super(`MCP server "${e}" not started: missing secret(s) ${r.join(", ")}`,n===void 0?void 0:{cause:n}),this.name="McpSecretResolutionError",this.serverName=e,this.missingKeys=r,this.reason=o}};async function Ry(t,e,r,n,o,s,i){let a=[...t.matchAll(hs)];if(a.length===0)return t;let c=t;for(let u of a.reverse()){let d=u[0],l=u.index,f=ya(d);try{let p=await r(f);if(p===void 0||typeof p=="object"){n.add(f),s.set(f,p===void 0?"missing":p.reason),ps.warn(`Secret "${f}" unavailable for "${e}"; leaving reference as-is`);continue}let h=p;h.trim()===""&&(o.add(f),ps.warn(`Secret "${f}" resolved empty for "${e}"`));let m=c.slice(0,l),y=i?i(h,m):h;c=m+y+c.slice(l+d.length),ps.debug(`Resolved secret reference for "${e}"`)}catch(p){n.add(f),s.set(f,"transient"),ps.error(`Failed to resolve secret "${f}" for "${e}" (${p instanceof Error?p.name:"non-Error"}); leaving reference as-is`)}}return c}async function Py({configEnv:t,localEnv:e,getSecret:r}){let n={},o=new Set,s=new Set,i=new Map;for(let[a,c]of Object.entries(t)){if(!ga(c)){n[a]=c;continue}let u=e[a];if(u!==void 0){ps.debug(`"${a}" references a secret but is already set in the local environment; using local value`),n[a]=u;continue}n[a]=await Ry(c,a,r,o,s,i)}return{resolved:n,unresolvedKeys:[...o].sort(),emptyKeys:[...s].sort(),...i.size===0?{}:{failureReasons:Object.fromEntries([...i.entries()].sort(([a],[c])=>a.localeCompare(c)))}}}var rM=/["$`\\]/g;function nM(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 oM(t,e){let r=nM(e);if(r==="double")return t.replace(rM,"\\$&");let n=t.replaceAll("'","'\\''");return r==="single"?n:`'${n}'`}async function Cy(t,e){let r=new Set,n=new Set,o=new Map;return{resolved:await Ry(t,"command",e,r,n,o,oM),unresolvedKeys:[...r].sort(),emptyKeys:[...n].sort(),...o.size===0?{}:{failureReasons:Object.fromEntries([...o.entries()].sort(([i],[a])=>i.localeCompare(a)))}}}import{AsyncLocalStorage as LU}from"node:async_hooks";var xy,$d=Object.freeze({status:"aborted"});function _(t,e,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:i,traits:new Set},enumerable:!1}),a._zod.traits.has(t))return;a._zod.traits.add(t),e(a,c);let u=i.prototype,d=Object.keys(u);for(let l=0;l<d.length;l++){let f=d[l];f in a||(a[f]=u[f].bind(a))}}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let d of u._zod.deferred)d();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Bt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},eo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(xy=globalThis).__zod_globalConfig??(xy.__zod_globalConfig={});var to=globalThis.__zod_globalConfig;function Ke(t){return t&&Object.assign(to,t),to}var U={};Ru(U,{BIGINT_FORMAT_RANGES:()=>Ay,Class:()=>Id,NUMBER_FORMAT_RANGES:()=>jd,aborted:()=>$r,allowsEval:()=>Nd,assert:()=>uM,assertEqual:()=>sM,assertIs:()=>aM,assertNever:()=>cM,assertNotEqual:()=>iM,assignProp:()=>Tr,base64ToUint8Array:()=>My,base64urlToUint8Array:()=>xM,cached:()=>no,captureStackTrace:()=>Sa,cleanEnum:()=>CM,cleanRegex:()=>vs,clone:()=>pt,cloneDef:()=>lM,createTransparentProxy:()=>yM,defineLazy:()=>Y,esc:()=>_a,escapeRegex:()=>or,explicitlyAborted:()=>Fd,extend:()=>SM,finalizeIssue:()=>ht,floatSafeRemainder:()=>Od,getElementAtPath:()=>fM,getEnumValues:()=>gs,getLengthableOrigin:()=>_s,getParsedType:()=>gM,getSizableOrigin:()=>$y,hexToUint8Array:()=>EM,isObject:()=>ln,isPlainObject:()=>Ar,issue:()=>oo,joinValues:()=>va,jsonStringifyReplacer:()=>ro,merge:()=>bM,mergeDefs:()=>nr,normalizeParams:()=>A,nullish:()=>ys,numKeys:()=>mM,objectClone:()=>dM,omit:()=>_M,optionalKeys:()=>Ld,parsedType:()=>Ud,partial:()=>RM,pick:()=>vM,prefixIssues:()=>sr,primitiveTypes:()=>Ty,promiseAllObject:()=>pM,propertyKeyTypes:()=>Dd,randomString:()=>hM,required:()=>PM,safeExtend:()=>wM,shallowClone:()=>Ey,slugify:()=>zd,stringifyPrimitive:()=>wa,uint8ArrayToBase64:()=>Iy,uint8ArrayToBase64url:()=>kM,uint8ArrayToHex:()=>TM,unwrapMessage:()=>ms});function sM(t){return t}function iM(t){return t}function aM(t){}function cM(t){throw new Error("Unexpected value in exhaustive check")}function uM(t){}function gs(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 va(t,e="|"){return t.map(r=>wa(r)).join(e)}function ro(t,e){return typeof e=="bigint"?e.toString():e}function no(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ys(t){return t==null}function vs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Od(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 ky=Symbol("evaluating");function Y(t,e,r){let n;Object.defineProperty(t,e,{get(){if(n!==ky)return n===void 0&&(n=ky,n=r()),n},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function dM(t){return Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t))}function Tr(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function nr(...t){let e={};for(let r of t){let n=Object.getOwnPropertyDescriptors(r);Object.assign(e,n)}return Object.defineProperties({},e)}function lM(t){return nr(t._zod.def)}function fM(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function pM(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 hM(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function _a(t){return JSON.stringify(t)}function zd(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Sa="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Nd=no(()=>{if(to.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Ar(t){if(ln(t)===!1)return!1;let e=t.constructor;if(e===void 0||typeof e!="function")return!0;let r=e.prototype;return!(ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Ey(t){return Ar(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}function mM(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var gM=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}`)}},Dd=new Set(["string","number","symbol"]),Ty=new Set(["string","number","bigint","boolean","symbol","undefined"]);function or(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function A(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function yM(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 wa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ld(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var jd={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]},Ay={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function vM(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=nr(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 Tr(this,"shape",i),i},checks:[]});return pt(t,s)}function _M(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=nr(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 Tr(this,"shape",i),i},checks:[]});return pt(t,s)}function SM(t,e){if(!Ar(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=nr(t._zod.def,{get shape(){let s={...t._zod.def.shape,...e};return Tr(this,"shape",s),s}});return pt(t,o)}function wM(t,e){if(!Ar(e))throw new Error("Invalid input to safeExtend: expected a plain object");let r=nr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e};return Tr(this,"shape",n),n}});return pt(t,r)}function bM(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=nr(t._zod.def,{get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return Tr(this,"shape",n),n},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return pt(t,r)}function RM(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=nr(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 Tr(this,"shape",c),c},checks:[]});return pt(e,i)}function PM(t,e,r){let n=nr(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 Tr(this,"shape",s),s}});return pt(e,n)}function $r(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 Fd(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 sr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ms(t){return typeof t=="string"?t:t?.message}function ht(t,e,r){let n=t.message?t.message:ms(t.inst?._zod.def?.error?.(t))??ms(e?.error?.(t))??ms(r.customError?.(t))??ms(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 $y(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function _s(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ud(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 oo(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function CM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function My(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 Iy(t){let e="";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return btoa(e)}function xM(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-e.length%4)%4);return My(e+r)}function kM(t){return Iy(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function EM(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 TM(t){return Array.from(t).map(e=>e.toString(16).padStart(2,"0")).join("")}var Id=class{constructor(...e){}};var Oy=(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,ro,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ba=_("$ZodError",Oy),qd=_("$ZodError",Oy,{Parent:Error});function Hd(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 Gd(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 Ra=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 Bt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ke())));throw Sa(a,o?.callee),a}return i.value};var Pa=t=>async(e,r,n,o)=>{let s=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>ht(c,s,Ke())));throw Sa(a,o?.callee),a}return i.value};var Ss=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Bt;return s.issues.length?{success:!1,error:new(t??ba)(s.issues.map(i=>ht(i,o,Ke())))}:{success:!0,data:s.value}},ws=Ss(qd),bs=t=>async(e,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>ht(i,o,Ke())))}:{success:!0,data:s.value}},Ca=bs(qd),zy=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ra(t)(e,r,o)};var Ny=t=>(e,r,n)=>Ra(t)(e,r,n);var Dy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Pa(t)(e,r,o)};var Ly=t=>async(e,r,n)=>Pa(t)(e,r,n);var jy=t=>(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Ss(t)(e,r,o)};var Fy=t=>(e,r,n)=>Ss(t)(e,r,n);var Uy=t=>async(e,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return bs(t)(e,r,o)};var qy=t=>async(e,r,n)=>bs(t)(e,r,n);var Hy=/^[cC][0-9a-z]{6,}$/,Gy=/^[0-9a-z]+$/,Zy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Wy=/^[0-9a-vA-V]{20}$/,By=/^[A-Za-z0-9]{27}$/,Vy=/^[a-zA-Z0-9_-]{21}$/,Ky=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Jy=/^([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})$/,Zd=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 $M="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Xy(){return new RegExp($M,"u")}var Qy=/^(?:(?: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])$/,ev=/^(([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 tv=/^((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])$/,rv=/^(([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])$/,nv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Wd=/^[A-Za-z0-9_-]*$/;var ov=/^https?$/,sv=/^\+[1-9]\d{6,14}$/,iv="(?:(?:\\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])))",av=new RegExp(`^${iv}$`);function cv(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 uv(t){return new RegExp(`^${cv(t)}$`)}function dv(t){let e=cv({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(`^${iv}T(?:${n})$`)}var lv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},fv=/^-?\d+n?$/,pv=/^-?\d+$/,Bd=/^-?\d+(?:\.\d+)?$/,hv=/^(?:true|false)$/i,mv=/^null$/i;var gv=/^[^A-Z]*$/,yv=/^[^a-z]*$/;var $e=_("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),vv={number:"number",bigint:"bigint",object:"date"},Vd=_("$ZodCheckLessThan",(t,e)=>{$e.init(t,e);let r=vv[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=_("$ZodCheckGreaterThan",(t,e)=>{$e.init(t,e);let r=vv[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})}}),_v=_("$ZodCheckMultipleOf",(t,e)=>{$e.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):Od(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})}}),Sv=_("$ZodCheckNumberFormat",(t,e)=>{$e.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=jd[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=pv)}),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 wv=_("$ZodCheckMaxLength",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),bv=_("$ZodCheckMinLength",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Rv=_("$ZodCheckLengthEquals",(t,e)=>{var r;$e.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(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=_s(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ps=_("$ZodCheckStringFormat",(t,e)=>{var r,n;$e.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=()=>{})}),Pv=_("$ZodCheckRegex",(t,e)=>{Ps.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Cv=_("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=gv),Ps.init(t,e)}),xv=_("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=yv),Ps.init(t,e)}),kv=_("$ZodCheckIncludes",(t,e)=>{$e.init(t,e);let r=or(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Ev=_("$ZodCheckStartsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`^${or(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Tv=_("$ZodCheckEndsWith",(t,e)=>{$e.init(t,e);let r=new RegExp(`.*${or(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 Av=_("$ZodCheckOverwrite",(t,e)=>{$e.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var xa=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 Tv={major:4,minor:4,patch:3};var ee=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Tv;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=$r(i),d;for(let l of a){if(l._zod.def.when){if(Fd(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Bt;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=$r(i,f)))});else{if(i.issues.length===f)continue;u||(u=$r(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if($r(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Bt;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 Bt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=ws(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ca(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ta=_("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??cv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=_("$ZodStringFormat",(t,e)=>{Ps.init(t,e),Ta.init(t,e)}),Lv=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=By),ce.init(t,e)}),jv=_("$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=Zd(n))}else e.pattern??(e.pattern=Zd());ce.init(t,e)}),Fv=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Vy),ce.init(t,e)}),Uv=_("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===tv.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})}}}),qv=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ky()),ce.init(t,e)}),Hv=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Zy),ce.init(t,e)}),Gv=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Fy),ce.init(t,e)}),Zv=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Uy),ce.init(t,e)}),Wv=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=qy),ce.init(t,e)}),Bv=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Hy),ce.init(t,e)}),Vv=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Gy),ce.init(t,e)}),Kv=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=av(e)),ce.init(t,e)}),Jv=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=ov),ce.init(t,e)}),Yv=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=iv(e)),ce.init(t,e)}),Xv=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Wy),ce.init(t,e)}),Qv=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Jy),ce.init(t,e),t._zod.bag.format="ipv4"}),e_=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Yy),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var t_=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Xy),ce.init(t,e)}),r_=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Qy),ce.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function n_(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var o_=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ev),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{n_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function kM(t){if(!Wd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return n_(r)}var s_=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Wd),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{kM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),i_=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=rv),ce.init(t,e)});function EM(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 a_=_("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{EM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Yd=_("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??Bd,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}}),c_=_("$ZodNumberFormat",(t,e)=>{yv.init(t,e),Yd.init(t,e)}),u_=_("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=lv,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}}),d_=_("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=uv,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 l_=_("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=fv,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}}),f_=_("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),p_=_("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),h_=_("$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 m_=_("$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 Av(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}var g_=_("$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=>Av(u,r,i))):Av(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Ea(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...sr(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 y_(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=Ld(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function v_(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>Ea(h,r,f,e,d,l))):Ea(p,r,f,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var TM=_("$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=no(()=>y_(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=ln,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],h=p._zod.optin==="optional",m=p._zod.optout==="optional",y=p._zod.run({value:u[f],issues:[]},c);y instanceof Promise?d.push(y.then(v=>Ea(v,a,f,u,h,m))):Ea(y,a,f,u,h,m)}return s?v_(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),__=_("$ZodObjectJIT",(t,e)=>{TM.init(t,e);let r=t._zod.parse,n=no(()=>y_(e)),o=f=>{let p=new xa(["shape","payload","ctx"]),h=n.value,m=w=>{let x=_a(w);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),v=0;for(let w of h.keys)y[w]=`key_${v++}`;p.write("const newResult = {};");for(let w of h.keys){let x=y[w],S=_a(w),P=f[w],I=P?._zod?.optin==="optional",re=P?._zod?.optout==="optional";p.write(`const ${x} = ${m(w)};`),I&&re?p.write(`
26
+ `))}};var Mv={major:4,minor:4,patch:3};var ee=_("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Mv;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=$r(i),d;for(let l of a){if(l._zod.def.when){if(Fd(i)||!l._zod.def.when(i))continue}else if(u)continue;let f=i.issues.length,p=l._zod.check(i);if(p instanceof Promise&&c?.async===!1)throw new Bt;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,i.issues.length!==f&&(u||(u=$r(i,f)))});else{if(i.issues.length===f)continue;u||(u=$r(i,f))}}return d?d.then(()=>i):i},s=(i,a,c)=>{if($r(i))return i.aborted=!0,i;let u=o(a,n,c);if(u instanceof Promise){if(c.async===!1)throw new Bt;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 Bt;return c.then(u=>o(u,n,a))}return o(c,n,a)}}Y(t,"~standard",()=>({validate:o=>{try{let s=ws(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Ca(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}))}),Ta=_("$ZodString",(t,e)=>{ee.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??lv(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),ce=_("$ZodStringFormat",(t,e)=>{Ps.init(t,e),Ta.init(t,e)}),Uv=_("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Jy),ce.init(t,e)}),qv=_("$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=Zd(n))}else e.pattern??(e.pattern=Zd());ce.init(t,e)}),Hv=_("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Yy),ce.init(t,e)}),Gv=_("$ZodURL",(t,e)=>{ce.init(t,e),t._zod.check=r=>{try{let n=r.value.trim();if(!e.normalize&&e.protocol?.source===ov.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})}}}),Zv=_("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Xy()),ce.init(t,e)}),Wv=_("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Vy),ce.init(t,e)}),Bv=_("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hy),ce.init(t,e)}),Vv=_("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Gy),ce.init(t,e)}),Kv=_("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Zy),ce.init(t,e)}),Jv=_("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Wy),ce.init(t,e)}),Yv=_("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=By),ce.init(t,e)}),Xv=_("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=dv(e)),ce.init(t,e)}),Qv=_("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=av),ce.init(t,e)}),e_=_("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=uv(e)),ce.init(t,e)}),t_=_("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ky),ce.init(t,e)}),r_=_("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Qy),ce.init(t,e),t._zod.bag.format="ipv4"}),n_=_("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ev),ce.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}});var o_=_("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=tv),ce.init(t,e)}),s_=_("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=rv),ce.init(t,e),t._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,s]=n;if(!s)throw new Error;let i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function i_(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var a_=_("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=nv),ce.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{i_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function OM(t){if(!Wd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return i_(r)}var c_=_("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Wd),ce.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{OM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),u_=_("$ZodE164",(t,e)=>{e.pattern??(e.pattern=sv),ce.init(t,e)});function zM(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 d_=_("$ZodJWT",(t,e)=>{ce.init(t,e),t._zod.check=r=>{zM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Yd=_("$ZodNumber",(t,e)=>{ee.init(t,e),t._zod.pattern=t._zod.bag.pattern??Bd,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}}),l_=_("$ZodNumberFormat",(t,e)=>{Sv.init(t,e),Yd.init(t,e)}),f_=_("$ZodBoolean",(t,e)=>{ee.init(t,e),t._zod.pattern=hv,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}}),p_=_("$ZodBigInt",(t,e)=>{ee.init(t,e),t._zod.pattern=fv,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 h_=_("$ZodNull",(t,e)=>{ee.init(t,e),t._zod.pattern=mv,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}}),m_=_("$ZodAny",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),g_=_("$ZodUnknown",(t,e)=>{ee.init(t,e),t._zod.parse=r=>r}),y_=_("$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 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 Iv(t,e,r){t.issues.length&&e.issues.push(...sr(r,t.issues)),e.value[r]=t.value}var __=_("$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=>Iv(u,r,i))):Iv(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function Ea(t,e,r,n,o,s){let i=r in n;if(t.issues.length){if(o&&s&&!i)return;e.issues.push(...sr(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 S_(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=Ld(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function w_(t,e,r,n,o,s){let i=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d=c.optin==="optional",l=c.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(u==="never"){i.push(f);continue}let p=c.run({value:e[f],issues:[]},n);p instanceof Promise?t.push(p.then(h=>Ea(h,r,f,e,d,l))):Ea(p,r,f,e,d,l)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:s}),t.length?Promise.all(t).then(()=>r):r}var NM=_("$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=no(()=>S_(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=ln,s=e.catchall,i;t._zod.parse=(a,c)=>{i??(i=n.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:t}),a;a.value={};let d=[],l=i.shape;for(let f of i.keys){let p=l[f],h=p._zod.optin==="optional",m=p._zod.optout==="optional",y=p._zod.run({value:u[f],issues:[]},c);y instanceof Promise?d.push(y.then(v=>Ea(v,a,f,u,h,m))):Ea(y,a,f,u,h,m)}return s?w_(d,u,a,c,n.value,t):d.length?Promise.all(d).then(()=>a):a}}),b_=_("$ZodObjectJIT",(t,e)=>{NM.init(t,e);let r=t._zod.parse,n=no(()=>S_(e)),o=f=>{let p=new xa(["shape","payload","ctx"]),h=n.value,m=w=>{let x=_a(w);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),v=0;for(let w of h.keys)y[w]=`key_${v++}`;p.write("const newResult = {};");for(let w of h.keys){let x=y[w],S=_a(w),P=f[w],I=P?._zod?.optin==="optional",re=P?._zod?.optout==="optional";p.write(`const ${x} = ${m(w)};`),I&&re?p.write(`
27
27
  if (${x}.issues.length) {
28
28
  if (${S} in input) {
29
29
  payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
@@ -82,23 +82,23 @@ When the user's request requires one of these servers, call attach-mcp-server im
82
82
  }
83
83
  }
84
84
 
85
- `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(w,x)=>b(f,w,x)},s,i=ln,a=!to.jitless,u=a&&Nd.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return i(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?v_([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function $v(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=>!$r(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>ht(i,n,Ve())))}),e)}var Xd=_("$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=>vs(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=>$v(a,n,t,o)):$v(i,n,t,o)}});var S_=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Xd.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=no(()=>{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(!ln(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)}}),w_=_("$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])=>Mv(r,c,u)):Mv(r,s,i)}});function Jd(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(Ar(t)&&Ar(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=Jd(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=Jd(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Mv(t,e,r){let n=new Map,o;for(let a of e.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else t.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else t.issues.push(a);let s=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(s.length&&o&&t.issues.push({...o,keys:s}),$r(t))return t;let i=Jd(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 b_=_("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Ar(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>ht(p,n,Ve())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...sr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...sr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Bd.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>ht(l,n,Ve())),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(...sr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...sr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var R_=_("$ZodEnum",(t,e)=>{ee.init(t,e);let r=gs(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>Dd.has(typeof o)).map(o=>typeof o=="string"?or(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}}),P_=_("$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"?or(n):n?or(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var C_=_("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new eo(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 Bt;return r.value=o,r.fallback=!0,r}});function Iv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Qd=_("$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(`^(${vs(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=>Iv(i,o)):Iv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),x_=_("$ZodExactOptional",(t,e)=>{Qd.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)}),k_=_("$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(`^(${vs(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)}),E_=_("$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=>Ov(s,e)):Ov(o,e)}});function Ov(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var T_=_("$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))}),A_=_("$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=>zv(s,t)):zv(o,t)}});function zv(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 $_=_("$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=>ht(i,n,Ve()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ht(s,n,Ve()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var el=_("$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=>ka(i,e.in,n)):ka(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ka(s,e.out,n)):ka(o,e.out,n)}});function ka(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},r)}var M_=_("$ZodPreprocess",(t,e)=>{el.init(t,e)}),I_=_("$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(Nv):Nv(o)}});function Nv(t){return t.value=Object.freeze(t.value),t}var O_=_("$ZodCustom",(t,e)=>{$e.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=>Dv(s,r,n,t));Dv(o,r,n,t)}});function Dv(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(oo(o))}}var AM=()=>{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=Ud(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${wa(o.values[0])}`:`Invalid option: expected one of ${va(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":""}: ${va(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 z_(){return{localeError:AM()}}var N_;var tl=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 D_(){return new tl}(N_=globalThis).__zod_globalRegistry??(N_.__zod_globalRegistry=D_());var Mr=globalThis.__zod_globalRegistry;function L_(t,e){return new t({type:"string",...A(e)})}function j_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function F_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function rl(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function U_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function q_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function H_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function G_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function nl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function Z_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function W_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function B_(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...A(e)})}function V_(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(e)})}function K_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function J_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function Y_(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function X_(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function Q_(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function eS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function tS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function rS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function nS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function oS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function sS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function iS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function aS(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function cS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function uS(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function dS(t,e){return new t({type:"number",checks:[],...A(e)})}function lS(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function fS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function pS(t,e){return new t({type:"boolean",...A(e)})}function hS(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function mS(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function gS(t,e){return new t({type:"null",...A(e)})}function yS(t){return new t({type:"any"})}function vS(t){return new t({type:"unknown"})}function _S(t,e){return new t({type:"never",...A(e)})}function SS(t,e){return new t({type:"date",coerce:!0,...A(e)})}function so(t,e){return new Vd({check:"less_than",...A(e),value:t,inclusive:!1})}function ir(t,e){return new Vd({check:"less_than",...A(e),value:t,inclusive:!0})}function io(t,e){return new Kd({check:"greater_than",...A(e),value:t,inclusive:!1})}function Tt(t,e){return new Kd({check:"greater_than",...A(e),value:t,inclusive:!0})}function Cs(t,e){return new gv({check:"multiple_of",...A(e),value:t})}function Aa(t,e){return new vv({check:"max_length",...A(e),maximum:t})}function ao(t,e){return new _v({check:"min_length",...A(e),minimum:t})}function $a(t,e){return new Sv({check:"length_equals",...A(e),length:t})}function ol(t,e){return new wv({check:"string_format",format:"regex",...A(e),pattern:t})}function sl(t){return new bv({check:"string_format",format:"lowercase",...A(t)})}function il(t){return new Rv({check:"string_format",format:"uppercase",...A(t)})}function al(t,e){return new Pv({check:"string_format",format:"includes",...A(e),includes:t})}function cl(t,e){return new Cv({check:"string_format",format:"starts_with",...A(e),prefix:t})}function ul(t,e){return new xv({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Ir(t){return new kv({check:"overwrite",tx:t})}function dl(t){return Ir(e=>e.normalize(t))}function ll(){return Ir(t=>t.trim())}function fl(){return Ir(t=>t.toLowerCase())}function pl(){return Ir(t=>t.toUpperCase())}function hl(){return Ir(t=>zd(t))}function wS(t,e,r){return new t({type:"array",element:e,...A(r)})}function bS(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function RS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function PS(t,e){let r=$M(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(oo(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(oo(s))}},t(n.value,n)),e);return r}function $M(t,e){let r=new $e({check:"custom",...A(e)});return r._zod.check=t,r}function ml(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??Mr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&Fe(t)&&(delete i.schema.examples,delete i.schema.default),e.io==="input"&&"_prefault"in i.schema&&((n=i.schema).default??(n.default=i.schema._prefault)),delete i.schema._prefault,e.seen.get(t).schema}function gl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
85
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(w,x)=>b(f,w,x)},s,i=ln,a=!to.jitless,u=a&&Nd.value,d=e.catchall,l;t._zod.parse=(f,p)=>{l??(l=n.value);let h=f.value;return i(h)?a&&u&&p?.async===!1&&p.jitless!==!0?(s||(s=o(e.shape)),f=s(f,p),d?w_([],h,f,p,l,t):f):r(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),f)}});function Ov(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=>!$r(s));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(i=>ht(i,n,Ke())))}),e)}var Xd=_("$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=>vs(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=>Ov(a,n,t,o)):Ov(i,n,t,o)}});var R_=_("$ZodDiscriminatedUnion",(t,e)=>{e.inclusive=!1,Xd.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=no(()=>{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(!ln(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)}}),P_=_("$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])=>zv(r,c,u)):zv(r,s,i)}});function Jd(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(Ar(t)&&Ar(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=Jd(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=Jd(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 zv(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}),$r(t))return t;let i=Jd(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 C_=_("$ZodRecord",(t,e)=>{ee.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Ar(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[],i=e.keyType._zod.values;if(i){r.value={};let a=new Set;for(let u of i)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let d=e.keyType._zod.run({value:u,issues:[]},n);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(p=>ht(p,n,Ke())),input:u,path:[u],inst:t});continue}let l=d.value,f=e.valueType._zod.run({value:o[u],issues:[]},n);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&r.issues.push(...sr(u,p.issues)),r.value[l]=p.value})):(f.issues.length&&r.issues.push(...sr(u,f.issues)),r.value[l]=f.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:c})}else{r.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=e.keyType._zod.run({value:a,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Bd.test(a)&&c.issues.length){let l=e.keyType._zod.run({value:Number(a),issues:[]},n);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");l.issues.length===0&&(c=l)}if(c.issues.length){e.mode==="loose"?r.value[a]=o[a]:r.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(l=>ht(l,n,Ke())),input:a,path:[a],inst:t});continue}let d=e.valueType._zod.run({value:o[a],issues:[]},n);d instanceof Promise?s.push(d.then(l=>{l.issues.length&&r.issues.push(...sr(a,l.issues)),r.value[c.value]=l.value})):(d.issues.length&&r.issues.push(...sr(a,d.issues)),r.value[c.value]=d.value)}}return s.length?Promise.all(s).then(()=>r):r}});var x_=_("$ZodEnum",(t,e)=>{ee.init(t,e);let r=gs(e.entries),n=new Set(r);t._zod.values=n,t._zod.pattern=new RegExp(`^(${r.filter(o=>Dd.has(typeof o)).map(o=>typeof o=="string"?or(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}}),k_=_("$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"?or(n):n?or(n.toString()):String(n)).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var E_=_("$ZodTransform",(t,e)=>{ee.init(t,e),t._zod.optin="optional",t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new eo(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 Bt;return r.value=o,r.fallback=!0,r}});function Nv(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}var Qd=_("$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(`^(${vs(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=>Nv(i,o)):Nv(s,o)}return r.value===void 0?r:e.innerType._zod.run(r,n)}}),T_=_("$ZodExactOptional",(t,e)=>{Qd.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)}),A_=_("$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(`^(${vs(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)}),$_=_("$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=>Dv(s,e)):Dv(o,e)}});function Dv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var M_=_("$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))}),I_=_("$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=>Lv(s,t)):Lv(o,t)}});function Lv(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 O_=_("$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=>ht(i,n,Ke()))},input:r.value}),r.issues=[],r.fallback=!0),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>ht(s,n,Ke()))},input:r.value}),r.issues=[],r.fallback=!0),r)}});var el=_("$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=>ka(i,e.in,n)):ka(s,e.in,n)}let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ka(s,e.out,n)):ka(o,e.out,n)}});function ka(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 z_=_("$ZodPreprocess",(t,e)=>{el.init(t,e)}),N_=_("$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(jv):jv(o)}});function jv(t){return t.value=Object.freeze(t.value),t}var D_=_("$ZodCustom",(t,e)=>{$e.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=>Fv(s,r,n,t));Fv(o,r,n,t)}});function Fv(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(oo(o))}}var DM=()=>{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=Ud(o.input),a=n[i]??i;return`Invalid input: expected ${s}, received ${a}`}case"invalid_value":return o.values.length===1?`Invalid input: expected ${wa(o.values[0])}`:`Invalid option: expected one of ${va(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":""}: ${va(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 L_(){return{localeError:DM()}}var j_;var tl=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 F_(){return new tl}(j_=globalThis).__zod_globalRegistry??(j_.__zod_globalRegistry=F_());var Mr=globalThis.__zod_globalRegistry;function U_(t,e){return new t({type:"string",...A(e)})}function q_(t,e){return new t({type:"string",coerce:!0,...A(e)})}function H_(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...A(e)})}function rl(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...A(e)})}function G_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...A(e)})}function Z_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(e)})}function W_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(e)})}function B_(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(e)})}function nl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...A(e)})}function V_(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...A(e)})}function K_(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(e)})}function J_(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 X_(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...A(e)})}function Q_(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...A(e)})}function eS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(e)})}function tS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(e)})}function rS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(e)})}function nS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(e)})}function oS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(e)})}function sS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...A(e)})}function iS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...A(e)})}function aS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...A(e)})}function cS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...A(e)})}function uS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(e)})}function dS(t,e){return new t({type:"string",format:"date",check:"string_format",...A(e)})}function lS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...A(e)})}function fS(t,e){return new t({type:"string",format:"duration",check:"string_format",...A(e)})}function pS(t,e){return new t({type:"number",checks:[],...A(e)})}function hS(t,e){return new t({type:"number",coerce:!0,checks:[],...A(e)})}function mS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...A(e)})}function gS(t,e){return new t({type:"boolean",...A(e)})}function yS(t,e){return new t({type:"boolean",coerce:!0,...A(e)})}function vS(t,e){return new t({type:"bigint",coerce:!0,...A(e)})}function _S(t,e){return new t({type:"null",...A(e)})}function SS(t){return new t({type:"any"})}function wS(t){return new t({type:"unknown"})}function bS(t,e){return new t({type:"never",...A(e)})}function RS(t,e){return new t({type:"date",coerce:!0,...A(e)})}function so(t,e){return new Vd({check:"less_than",...A(e),value:t,inclusive:!1})}function ir(t,e){return new Vd({check:"less_than",...A(e),value:t,inclusive:!0})}function io(t,e){return new Kd({check:"greater_than",...A(e),value:t,inclusive:!1})}function Tt(t,e){return new Kd({check:"greater_than",...A(e),value:t,inclusive:!0})}function Cs(t,e){return new _v({check:"multiple_of",...A(e),value:t})}function Aa(t,e){return new wv({check:"max_length",...A(e),maximum:t})}function ao(t,e){return new bv({check:"min_length",...A(e),minimum:t})}function $a(t,e){return new Rv({check:"length_equals",...A(e),length:t})}function ol(t,e){return new Pv({check:"string_format",format:"regex",...A(e),pattern:t})}function sl(t){return new Cv({check:"string_format",format:"lowercase",...A(t)})}function il(t){return new xv({check:"string_format",format:"uppercase",...A(t)})}function al(t,e){return new kv({check:"string_format",format:"includes",...A(e),includes:t})}function cl(t,e){return new Ev({check:"string_format",format:"starts_with",...A(e),prefix:t})}function ul(t,e){return new Tv({check:"string_format",format:"ends_with",...A(e),suffix:t})}function Ir(t){return new Av({check:"overwrite",tx:t})}function dl(t){return Ir(e=>e.normalize(t))}function ll(){return Ir(t=>t.trim())}function fl(){return Ir(t=>t.toLowerCase())}function pl(){return Ir(t=>t.toUpperCase())}function hl(){return Ir(t=>zd(t))}function PS(t,e,r){return new t({type:"array",element:e,...A(r)})}function CS(t,e,r){let n=A(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...A(r)})}function kS(t,e){let r=LM(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(oo(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(oo(s))}},t(n.value,n)),e);return r}function LM(t,e){let r=new $e({check:"custom",...A(e)});return r._zod.check=t,r}function ml(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??Mr,target:e,unrepresentable:t?.unrepresentable??"throw",override:t?.override??(()=>{}),io:t?.io??"output",counter:0,seen:new Map,cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0}}function ve(t,e,r={path:[],schemaPath:[]}){var n;let o=t._zod.def,s=e.seen.get(t);if(s)return s.count++,r.schemaPath.includes(t)&&(s.cycle=r.path),s.schema;let i={schema:{},count:1,cycle:void 0,path:r.path};e.seen.set(t,i);let a=t._zod.toJSONSchema?.();if(a)i.schema=a;else{let d={...r,schemaPath:[...r.schemaPath,t],path:r.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,i.schema,d);else{let f=i.schema,p=e.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(t,e,f,d)}let l=t._zod.parent;l&&(i.ref||(i.ref=l),ve(l,e,d),e.seen.get(l).isParent=!0)}let c=e.metadataRegistry.get(t);return c&&Object.assign(i.schema,c),e.io==="input"&&Ue(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 gl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=new Map;for(let i of t.seen.entries()){let a=t.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=i=>{let a=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){let l=t.external.registry.get(i[0])?.id,f=t.external.uri??(h=>h);if(l)return{ref:f(l)};let p=i[1].defId??i[1].schema.id??`schema${t.counter++}`;return i[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(i[1]===r)return{ref:"#"};let u=`#/${a}/`,d=i[1].schema.id??`__schema${t.counter++}`;return{defId:d,ref:u+d}},s=i=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:u}=o(i);a.def={...a.schema},u&&(a.defId=u);let d=a.schema;for(let l in d)delete d[l];d.$ref=c};if(t.cycles==="throw")for(let i of t.seen.entries()){let a=i[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
86
86
 
87
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function yl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:xs(e,"input",t.processors),output:xs(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Fe(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Fe(n.element,r);if(n.type==="set")return Fe(n.valueType,r);if(n.type==="lazy")return Fe(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Fe(n.innerType,r);if(n.type==="intersection")return Fe(n.left,r)||Fe(n.right,r);if(n.type==="record"||n.type==="map")return Fe(n.keyType,r)||Fe(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Fe(n.in,r)||Fe(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Fe(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Fe(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Fe(o,r))return!0;return!!(n.rest&&Fe(n.rest,r))}return!1}var CS=(t,e={})=>r=>{let n=ml({...r,processors:e});return ve(t,n),gl(n,t),yl(n,t)},xs=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ml({...o??{},target:s,io:e,processors:r});return ve(t,i),gl(i,t),yl(i,t)};var MM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},xS=(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=MM[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}))])}},kS=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},ES=(t,e,r,n)=>{r.type="boolean"},TS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var AS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var $S=(t,e,r,n)=>{r.not={}},MS=(t,e,r,n)=>{},IS=(t,e,r,n)=>{},OS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},zS=(t,e,r,n)=>{let o=t._zod.def,s=gs(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},NS=(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 DS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var LS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var jS=(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"]})},FS=(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)},US=(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},qS=(t,e,r,n)=>{let o=t._zod.def,s=ve(o.left,e,{...n,path:[...n.path,"allOf",0]}),i=ve(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c};var HS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object";let i=s.keyType,c=i._zod.bag?.patterns;if(s.mode==="loose"&&c&&c.size>0){let d=ve(s.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let l of c)o.patternProperties[l.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=ve(s.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=ve(s.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=i._zod.values;if(u){let d=[...u].filter(l=>typeof l=="string"||typeof l=="number");d.length>0&&(o.required=d)}},GS=(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"}]},ZS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},WS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},BS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},VS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=i},KS=(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},JS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var vl=(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 Ma(t){return!!t._zod}function At(t,e){return Ma(t)?ws(t,e):t.safeParse(e)}function Ia(t){if(!t)return;let e;if(Ma(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Oa(t){if(Ma(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 ks={};Ru(ks,{ZodISODate:()=>XS,ZodISODateTime:()=>YS,ZodISODuration:()=>ew,ZodISOTime:()=>QS,date:()=>Sl,datetime:()=>_l,duration:()=>bl,time:()=>wl});var YS=_("ZodISODateTime",(t,e)=>{Kv.init(t,e),he.init(t,e)});function _l(t){return iS(YS,t)}var XS=_("ZodISODate",(t,e)=>{Jv.init(t,e),he.init(t,e)});function Sl(t){return aS(XS,t)}var QS=_("ZodISOTime",(t,e)=>{Yv.init(t,e),he.init(t,e)});function wl(t){return cS(QS,t)}var ew=_("ZodISODuration",(t,e)=>{Xv.init(t,e),he.init(t,e)});function bl(t){return uS(ew,t)}var FM=(t,e)=>{ba.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Gd(t,r)},flatten:{value:r=>Hd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ro,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ro,2)}},isEmpty:{get(){return t.issues.length===0}}})};var it=_("ZodError",FM,{Parent:Error});var rw=Ra(it),nw=Pa(it),ow=Ss(it),sw=bs(it),iw=My(it),aw=Iy(it),cw=Oy(it),uw=zy(it),dw=Ny(it),lw=Dy(it),fw=Ly(it),pw=jy(it);var hw=new WeakMap;function Es(t,e,r){let n=Object.getPrototypeOf(t),o=hw.get(n);if(o||(o=new Set,hw.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ne=_("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:xs(t,"input"),output:xs(t,"output")}}),t.toJSONSchema=CS(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>rw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ow(t,r,n),t.parseAsync=async(r,n)=>nw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>sw(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>iw(t,r,n),t.decode=(r,n)=>aw(t,r,n),t.encodeAsync=async(r,n)=>cw(t,r,n),t.decodeAsync=async(r,n)=>uw(t,r,n),t.safeEncode=(r,n)=>dw(t,r,n),t.safeDecode=(r,n)=>lw(t,r,n),t.safeEncodeAsync=async(r,n)=>fw(t,r,n),t.safeDecodeAsync=async(r,n)=>pw(t,r,n),Es(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return pt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(EI(r,n))},superRefine(r,n){return this.check(TI(r,n))},overwrite(r){return this.check(Ir(r))},optional(){return ge(this)},exactOptional(){return gI(this)},nullable(){return vw(this)},nullish(){return ge(vw(this))},nonoptional(r){return bI(this,r)},array(){return C(this)},or(r){return ue([this,r])},and(r){return Da(this,r)},transform(r){return _w(this,Tw(r))},default(r){return _I(this,r)},prefault(r){return wI(this,r)},catch(r){return PI(this,r)},pipe(r){return _w(this,r)},readonly(){return kI(this)},describe(r){let n=this.clone();return Mr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Mr.get(this);let n=this.clone();return Mr.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 Mr.get(t)?.description},configurable:!0}),t)),Sw=_("_ZodString",(t,e)=>{Ta.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>xS(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Es(t,"_ZodString",{regex(...n){return this.check(ol(...n))},includes(...n){return this.check(al(...n))},startsWith(...n){return this.check(cl(...n))},endsWith(...n){return this.check(ul(...n))},min(...n){return this.check(ao(...n))},max(...n){return this.check(Aa(...n))},length(...n){return this.check($a(...n))},nonempty(...n){return this.check(ao(1,...n))},lowercase(n){return this.check(sl(n))},uppercase(n){return this.check(il(n))},trim(){return this.check(ll())},normalize(...n){return this.check(dl(...n))},toLowerCase(){return this.check(fl())},toUpperCase(){return this.check(pl())},slugify(){return this.check(hl())}})}),Pl=_("ZodString",(t,e)=>{Ta.init(t,e),Sw.init(t,e),t.email=r=>t.check(F_(qM,r)),t.url=r=>t.check(nl(ww,r)),t.jwt=r=>t.check(sS(nI,r)),t.emoji=r=>t.check(Z_(HM,r)),t.guid=r=>t.check(rl(mw,r)),t.uuid=r=>t.check(U_(za,r)),t.uuidv4=r=>t.check(q_(za,r)),t.uuidv6=r=>t.check(H_(za,r)),t.uuidv7=r=>t.check(G_(za,r)),t.nanoid=r=>t.check(W_(GM,r)),t.guid=r=>t.check(rl(mw,r)),t.cuid=r=>t.check(B_(ZM,r)),t.cuid2=r=>t.check(V_(WM,r)),t.ulid=r=>t.check(K_(BM,r)),t.base64=r=>t.check(rS(eI,r)),t.base64url=r=>t.check(nS(tI,r)),t.xid=r=>t.check(J_(VM,r)),t.ksuid=r=>t.check(Y_(KM,r)),t.ipv4=r=>t.check(X_(JM,r)),t.ipv6=r=>t.check(Q_(YM,r)),t.cidrv4=r=>t.check(eS(XM,r)),t.cidrv6=r=>t.check(tS(QM,r)),t.e164=r=>t.check(oS(rI,r)),t.datetime=r=>t.check(_l(r)),t.date=r=>t.check(Sl(r)),t.time=r=>t.check(wl(r)),t.duration=r=>t.check(bl(r))});function g(t){return L_(Pl,t)}var he=_("ZodStringFormat",(t,e)=>{ce.init(t,e),Sw.init(t,e)}),qM=_("ZodEmail",(t,e)=>{Fv.init(t,e),he.init(t,e)});var mw=_("ZodGUID",(t,e)=>{Lv.init(t,e),he.init(t,e)});var za=_("ZodUUID",(t,e)=>{jv.init(t,e),he.init(t,e)});var ww=_("ZodURL",(t,e)=>{Uv.init(t,e),he.init(t,e)});function bw(t){return nl(ww,t)}var HM=_("ZodEmoji",(t,e)=>{qv.init(t,e),he.init(t,e)});var GM=_("ZodNanoID",(t,e)=>{Hv.init(t,e),he.init(t,e)});var ZM=_("ZodCUID",(t,e)=>{Gv.init(t,e),he.init(t,e)});var WM=_("ZodCUID2",(t,e)=>{Zv.init(t,e),he.init(t,e)});var BM=_("ZodULID",(t,e)=>{Wv.init(t,e),he.init(t,e)});var VM=_("ZodXID",(t,e)=>{Bv.init(t,e),he.init(t,e)});var KM=_("ZodKSUID",(t,e)=>{Vv.init(t,e),he.init(t,e)});var JM=_("ZodIPv4",(t,e)=>{Qv.init(t,e),he.init(t,e)});var YM=_("ZodIPv6",(t,e)=>{e_.init(t,e),he.init(t,e)});var XM=_("ZodCIDRv4",(t,e)=>{t_.init(t,e),he.init(t,e)});var QM=_("ZodCIDRv6",(t,e)=>{r_.init(t,e),he.init(t,e)});var eI=_("ZodBase64",(t,e)=>{o_.init(t,e),he.init(t,e)});var tI=_("ZodBase64URL",(t,e)=>{s_.init(t,e),he.init(t,e)});var rI=_("ZodE164",(t,e)=>{i_.init(t,e),he.init(t,e)});var nI=_("ZodJWT",(t,e)=>{a_.init(t,e),he.init(t,e)});var Na=_("ZodNumber",(t,e)=>{Yd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>kS(t,n,o,s),Es(t,"ZodNumber",{gt(n,o){return this.check(io(n,o))},gte(n,o){return this.check(Tt(n,o))},min(n,o){return this.check(Tt(n,o))},lt(n,o){return this.check(so(n,o))},lte(n,o){return this.check(ir(n,o))},max(n,o){return this.check(ir(n,o))},int(n){return this.check(gw(n))},safe(n){return this.check(gw(n))},positive(n){return this.check(io(0,n))},nonnegative(n){return this.check(Tt(0,n))},negative(n){return this.check(so(0,n))},nonpositive(n){return this.check(ir(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 V(t){return dS(Na,t)}var oI=_("ZodNumberFormat",(t,e)=>{c_.init(t,e),Na.init(t,e)});function gw(t){return fS(oI,t)}var Cl=_("ZodBoolean",(t,e)=>{u_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ES(t,r,n,o)});function oe(t){return pS(Cl,t)}var Rw=_("ZodBigInt",(t,e)=>{d_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>TS(t,n,o,s),t.gte=(n,o)=>t.check(Tt(n,o)),t.min=(n,o)=>t.check(Tt(n,o)),t.gt=(n,o)=>t.check(io(n,o)),t.gte=(n,o)=>t.check(Tt(n,o)),t.min=(n,o)=>t.check(Tt(n,o)),t.lt=(n,o)=>t.check(so(n,o)),t.lte=(n,o)=>t.check(ir(n,o)),t.max=(n,o)=>t.check(ir(n,o)),t.positive=n=>t.check(io(BigInt(0),n)),t.negative=n=>t.check(so(BigInt(0),n)),t.nonpositive=n=>t.check(ir(BigInt(0),n)),t.nonnegative=n=>t.check(Tt(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 sI=_("ZodNull",(t,e)=>{l_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>AS(t,r,n,o)});function Pw(t){return gS(sI,t)}var iI=_("ZodAny",(t,e)=>{f_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>MS(t,r,n,o)});function Cw(){return yS(iI)}var aI=_("ZodUnknown",(t,e)=>{p_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o)});function me(){return vS(aI)}var cI=_("ZodNever",(t,e)=>{h_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$S(t,r,n,o)});function uI(t){return _S(cI,t)}var xw=_("ZodDate",(t,e)=>{m_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>OS(t,n,o,s),t.min=(n,o)=>t.check(Tt(n,o)),t.max=(n,o)=>t.check(ir(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 dI=_("ZodArray",(t,e)=>{g_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jS(t,r,n,o),t.element=e.element,Es(t,"ZodArray",{min(r,n){return this.check(ao(r,n))},nonempty(r){return this.check(ao(1,r))},max(r,n){return this.check(Aa(r,n))},length(r,n){return this.check($a(r,n))},unwrap(){return this.element}})});function C(t,e){return wS(dI,t,e)}var kw=_("ZodObject",(t,e)=>{__.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>FS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),Es(t,"ZodObject",{keyof(){return Ke(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:me()})},loose(){return this.clone({...this._zod.def,catchall:me()})},strict(){return this.clone({...this._zod.def,catchall:uI()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(Aw,this,r[0])},required(...r){return U.required($w,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new kw(r)}function Ce(t,e){return new kw({type:"object",shape:t,catchall:me(),...U.normalizeParams(e)})}var Ew=_("ZodUnion",(t,e)=>{Xd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>US(t,r,n,o),t.options=e.options});function ue(t,e){return new Ew({type:"union",options:t,...U.normalizeParams(e)})}var lI=_("ZodDiscriminatedUnion",(t,e)=>{Ew.init(t,e),S_.init(t,e)});function xl(t,e,r){return new lI({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var fI=_("ZodIntersection",(t,e)=>{w_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qS(t,r,n,o)});function Da(t,e){return new fI({type:"intersection",left:t,right:e})}var yw=_("ZodRecord",(t,e)=>{b_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>HS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new yw({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new yw({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var Rl=_("ZodEnum",(t,e)=>{R_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>zS(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:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Rl({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Ke(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Rl({type:"enum",entries:r,...U.normalizeParams(e)})}var pI=_("ZodLiteral",(t,e)=>{P_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>NS(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 pI({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var hI=_("ZodTransform",(t,e)=>{C_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>LS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new eo(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Tw(t){return new hI({type:"transform",transform:t})}var Aw=_("ZodOptional",(t,e)=>{Qd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ge(t){return new Aw({type:"optional",innerType:t})}var mI=_("ZodExactOptional",(t,e)=>{x_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function gI(t){return new mI({type:"optional",innerType:t})}var yI=_("ZodNullable",(t,e)=>{k_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>GS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function vw(t){return new yI({type:"nullable",innerType:t})}var vI=_("ZodDefault",(t,e)=>{E_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>WS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function _I(t,e){return new vI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var SI=_("ZodPrefault",(t,e)=>{T_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>BS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function wI(t,e){return new SI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var $w=_("ZodNonOptional",(t,e)=>{A_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ZS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function bI(t,e){return new $w({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var RI=_("ZodCatch",(t,e)=>{$_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>VS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function PI(t,e){return new RI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Mw=_("ZodPipe",(t,e)=>{el.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>KS(t,r,n,o),t.in=e.in,t.out=e.out});function _w(t,e){return new Mw({type:"pipe",in:t,out:e})}var CI=_("ZodPreprocess",(t,e)=>{Mw.init(t,e),M_.init(t,e)}),xI=_("ZodReadonly",(t,e)=>{I_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>JS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function kI(t){return new xI({type:"readonly",innerType:t})}var Iw=_("ZodCustom",(t,e)=>{O_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>DS(t,r,n,o)});function Ow(t,e){return bS(Iw,t??(()=>!0),e)}function EI(t,e={}){return RS(Iw,t,e)}function TI(t,e){return PS(t,e)}function kl(t,e){return new CI({type:"pipe",in:Tw(t),out:e})}var Nw={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 zw;zw||(zw={});var La={};Ru(La,{bigint:()=>II,boolean:()=>MI,date:()=>OI,number:()=>$I,string:()=>AI});function AI(t){return j_(Pl,t)}function $I(t){return lS(Na,t)}function MI(t){return hS(Cl,t)}function II(t){return mS(Rw,t)}function OI(t){return SS(xw,t)}Ve(z_());var lo="2025-11-25";var Dw=[lo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Or="io.modelcontextprotocol/related-task",Fa="2.0",xe=Ow(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Lw=ue([g(),V().int()]),jw=g(),$B=Ce({ttl:V().optional(),pollInterval:V().optional()}),NI=k({ttl:V().optional()}),DI=k({taskId:g()}),Tl=Ce({progressToken:Lw.optional(),[Or]:DI.optional()}),at=k({_meta:Tl.optional()}),Ts=at.extend({task:NI.optional()}),Fw=t=>Ts.safeParse(t).success,Me=k({method:g(),params:at.loose().optional()}),mt=k({_meta:Tl.optional()}),gt=k({method:g(),params:mt.loose().optional()}),ke=Ce({_meta:Tl.optional()}),Ua=ue([g(),V().int()]),Uw=k({jsonrpc:E(Fa),id:Ua,...Me.shape}).strict(),As=t=>Uw.safeParse(t).success,qw=k({jsonrpc:E(Fa),...gt.shape}).strict(),Hw=t=>qw.safeParse(t).success,Al=k({jsonrpc:E(Fa),id:Ua,result:ke}).strict(),fn=t=>Al.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 $l=k({jsonrpc:E(Fa),id:Ua.optional(),error:k({code:V().int(),message:g(),data:me().optional()})}).strict();var Gw=t=>$l.safeParse(t).success;var zr=ue([Uw,qw,Al,$l]),MB=ue([Al,$l]),pn=ke.strict(),LI=mt.extend({requestId:Ua.optional(),reason:g().optional()}),qa=gt.extend({method:E("notifications/cancelled"),params:LI}),jI=k({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Ke(["light","dark"]).optional()}),$s=k({icons:C(jI).optional()}),uo=k({name:g(),title:g().optional()}),Zw=uo.extend({...uo.shape,...$s.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),FI=Da(k({applyDefaults:oe().optional()}),ae(g(),me())),UI=kl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Da(k({form:FI.optional(),url:xe.optional()}),ae(g(),me()).optional())),qI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({sampling:Ce({createMessage:xe.optional()}).optional(),elicitation:Ce({create:xe.optional()}).optional()}).optional()}),HI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({tools:Ce({call:xe.optional()}).optional()}).optional()}),GI=k({experimental:ae(g(),xe).optional(),sampling:k({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:UI.optional(),roots:k({listChanged:oe().optional()}).optional(),tasks:qI.optional(),extensions:ae(g(),xe).optional()}),ZI=at.extend({protocolVersion:g(),capabilities:GI,clientInfo:Zw}),WI=Me.extend({method:E("initialize"),params:ZI});var BI=k({experimental:ae(g(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:k({listChanged:oe().optional()}).optional(),resources:k({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:k({listChanged:oe().optional()}).optional(),tasks:HI.optional(),extensions:ae(g(),xe).optional()}),Ml=ke.extend({protocolVersion:g(),capabilities:BI,serverInfo:Zw,instructions:g().optional()}),Ww=gt.extend({method:E("notifications/initialized"),params:mt.optional()}),Bw=t=>Ww.safeParse(t).success,Ha=Me.extend({method:E("ping"),params:at.optional()}),VI=k({progress:V(),total:ge(V()),message:ge(g())}),KI=k({...mt.shape,...VI.shape,progressToken:Lw}),Ga=gt.extend({method:E("notifications/progress"),params:KI}),JI=at.extend({cursor:jw.optional()}),Ms=Me.extend({params:JI.optional()}),Is=ke.extend({nextCursor:jw.optional()}),YI=Ke(["working","input_required","completed","failed","cancelled"]),Os=k({taskId:g(),status:YI,ttl:ue([V(),Pw()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ge(V()),statusMessage:ge(g())}),hn=ke.extend({task:Os}),XI=mt.merge(Os),zs=gt.extend({method:E("notifications/tasks/status"),params:XI}),Za=Me.extend({method:E("tasks/get"),params:at.extend({taskId:g()})}),Wa=ke.merge(Os),Ba=Me.extend({method:E("tasks/result"),params:at.extend({taskId:g()})}),IB=ke.loose(),Va=Ms.extend({method:E("tasks/list")}),Ka=Is.extend({tasks:C(Os)}),Ja=Me.extend({method:E("tasks/cancel"),params:at.extend({taskId:g()})}),Vw=ke.merge(Os),Kw=k({uri:g(),mimeType:ge(g()),_meta:ae(g(),me()).optional()}),Jw=Kw.extend({text:g()}),Il=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Yw=Kw.extend({blob:Il}),Ns=Ke(["user","assistant"]),fo=k({audience:C(Ns).optional(),priority:V().min(0).max(1).optional(),lastModified:ks.datetime({offset:!0}).optional()}),Xw=k({...uo.shape,...$s.shape,uri:g(),description:ge(g()),mimeType:ge(g()),size:ge(V()),annotations:fo.optional(),_meta:ge(Ce({}))}),QI=k({...uo.shape,...$s.shape,uriTemplate:g(),description:ge(g()),mimeType:ge(g()),annotations:fo.optional(),_meta:ge(Ce({}))}),eO=Ms.extend({method:E("resources/list")}),Ol=Is.extend({resources:C(Xw)}),tO=Ms.extend({method:E("resources/templates/list")}),zl=Is.extend({resourceTemplates:C(QI)}),Nl=at.extend({uri:g()}),rO=Nl,nO=Me.extend({method:E("resources/read"),params:rO}),Dl=ke.extend({contents:C(ue([Jw,Yw]))}),Ll=gt.extend({method:E("notifications/resources/list_changed"),params:mt.optional()}),oO=Nl,sO=Me.extend({method:E("resources/subscribe"),params:oO}),iO=Nl,aO=Me.extend({method:E("resources/unsubscribe"),params:iO}),cO=mt.extend({uri:g()}),uO=gt.extend({method:E("notifications/resources/updated"),params:cO}),dO=k({name:g(),description:ge(g()),required:ge(oe())}),lO=k({...uo.shape,...$s.shape,description:ge(g()),arguments:ge(C(dO)),_meta:ge(Ce({}))}),fO=Ms.extend({method:E("prompts/list")}),jl=Is.extend({prompts:C(lO)}),pO=at.extend({name:g(),arguments:ae(g(),g()).optional()}),hO=Me.extend({method:E("prompts/get"),params:pO}),Fl=k({type:E("text"),text:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),Ul=k({type:E("image"),data:Il,mimeType:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),ql=k({type:E("audio"),data:Il,mimeType:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),mO=k({type:E("tool_use"),name:g(),id:g(),input:ae(g(),me()),_meta:ae(g(),me()).optional()}),gO=k({type:E("resource"),resource:ue([Jw,Yw]),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),yO=Xw.extend({type:E("resource_link")}),Hl=ue([Fl,Ul,ql,yO,gO]),vO=k({role:Ns,content:Hl}),Gl=ke.extend({description:g().optional(),messages:C(vO)}),Zl=gt.extend({method:E("notifications/prompts/list_changed"),params:mt.optional()}),_O=k({title:g().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),SO=k({taskSupport:Ke(["required","optional","forbidden"]).optional()}),Qw=k({...uo.shape,...$s.shape,description:g().optional(),inputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()),outputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()).optional(),annotations:_O.optional(),execution:SO.optional(),_meta:ae(g(),me()).optional()}),wO=Ms.extend({method:E("tools/list")}),Wl=Is.extend({tools:C(Qw)}),mn=ke.extend({content:C(Hl).default([]),structuredContent:ae(g(),me()).optional(),isError:oe().optional()}),OB=mn.or(ke.extend({toolResult:me()})),bO=Ts.extend({name:g(),arguments:ae(g(),me()).optional()}),RO=Me.extend({method:E("tools/call"),params:bO}),Ds=gt.extend({method:E("notifications/tools/list_changed"),params:mt.optional()}),eb=k({autoRefresh:oe().default(!0),debounceMs:V().int().nonnegative().default(300)}),tb=Ke(["debug","info","notice","warning","error","critical","alert","emergency"]),PO=at.extend({level:tb}),CO=Me.extend({method:E("logging/setLevel"),params:PO}),xO=mt.extend({level:tb,logger:g().optional(),data:me()}),kO=gt.extend({method:E("notifications/message"),params:xO}),EO=k({name:g().optional()}),TO=k({hints:C(EO).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),AO=k({mode:Ke(["auto","required","none"]).optional()}),$O=k({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(Hl).default([]),structuredContent:k({}).loose().optional(),isError:oe().optional(),_meta:ae(g(),me()).optional()}),MO=xl("type",[Fl,Ul,ql]),ja=xl("type",[Fl,Ul,ql,mO,$O]),IO=k({role:Ns,content:ue([ja,C(ja)]),_meta:ae(g(),me()).optional()}),OO=Ts.extend({messages:C(IO),modelPreferences:TO.optional(),systemPrompt:g().optional(),includeContext:Ke(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:C(g()).optional(),metadata:xe.optional(),tools:C(Qw).optional(),toolChoice:AO.optional()}),Bl=Me.extend({method:E("sampling/createMessage"),params:OO}),Vl=ke.extend({model:g(),stopReason:ge(Ke(["endTurn","stopSequence","maxTokens"]).or(g())),role:Ns,content:MO}),Kl=ke.extend({model:g(),stopReason:ge(Ke(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Ns,content:ue([ja,C(ja)])}),zO=k({type:E("boolean"),title:g().optional(),description:g().optional(),default:oe().optional()}),NO=k({type:E("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Ke(["email","uri","date","date-time"]).optional(),default:g().optional()}),DO=k({type:Ke(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),LO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),jO=k({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(k({const:g(),title:g()})),default:g().optional()}),FO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),UO=ue([LO,jO]),qO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({type:E("string"),enum:C(g())}),default:C(g()).optional()}),HO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({anyOf:C(k({const:g(),title:g()}))}),default:C(g()).optional()}),GO=ue([qO,HO]),ZO=ue([FO,UO,GO]),WO=ue([ZO,zO,NO,DO]),BO=Ts.extend({mode:E("form").optional(),message:g(),requestedSchema:k({type:E("object"),properties:ae(g(),WO),required:C(g()).optional()})}),VO=Ts.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),KO=ue([BO,VO]),Jl=Me.extend({method:E("elicitation/create"),params:KO}),JO=mt.extend({elicitationId:g()}),YO=gt.extend({method:E("notifications/elicitation/complete"),params:JO}),Yl=ke.extend({action:Ke(["accept","decline","cancel"]),content:kl(t=>t===null?void 0:t,ae(g(),ue([g(),V(),oe(),C(g())])).optional())}),XO=k({type:E("ref/resource"),uri:g()});var QO=k({type:E("ref/prompt"),name:g()}),ez=at.extend({ref:ue([QO,XO]),argument:k({name:g(),value:g()}),context:k({arguments:ae(g(),g()).optional()}).optional()}),tz=Me.extend({method:E("completion/complete"),params:ez});var Xl=ke.extend({completion:Ce({values:C(g()).max(100),total:ge(V().int()),hasMore:ge(oe())})}),rz=k({uri:g().startsWith("file://"),name:g().optional(),_meta:ae(g(),me()).optional()}),nz=Me.extend({method:E("roots/list"),params:at.optional()}),oz=ke.extend({roots:C(rz)}),sz=gt.extend({method:E("notifications/roots/list_changed"),params:mt.optional()}),zB=ue([Ha,WI,tz,CO,hO,fO,eO,tO,nO,sO,aO,RO,wO,Za,Ba,Va,Ja]),NB=ue([qa,Ga,Ww,sz,zs]),DB=ue([pn,Vl,Kl,Yl,oz,Wa,Ka,hn]),LB=ue([Ha,Bl,Jl,nz,Za,Ba,Va,Ja]),jB=ue([qa,Ga,kO,uO,Ll,Ds,Zl,zs,YO]),FB=ue([pn,Ml,Xl,Gl,jl,Ol,zl,Dl,mn,Wl,Wa,Ka,hn]),$=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 El(o.elicitations,r)}return new t(e,r,n)}},El=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 Nr(t){return t==="completed"||t==="failed"||t==="cancelled"}var _V=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ql(t){let r=Ia(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ef(t,e){let r=At(t,e);if(!r.success)throw r.error;return r.data}var lz=6e4,Ya=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(qa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ga,r=>{this._onprogress(r)}),this.setRequestHandler(Ha,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Za,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(Ba,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,f=new $(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!Nr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Or]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Va,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new $(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ja,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nr(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),fn(s)||Gw(s)?this._onresponse(s):As(s)?this._onrequest(s,i):Hw(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=$.fromError(M.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Or]?.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=Fw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,f)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});let h=p.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),fn(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(fn(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),fn(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,hn,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},Nr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=b=>{d(b)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){l(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Or]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let w=b instanceof $?b:new $(M.RequestTimeout,String(b));d(w)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let w=At(r,b.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??lz,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=w=>{let x=this._responseHandlers.get(f);x?x(w):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(f),d(w)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,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},Ka,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Vw,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||{},[Or]: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||{},[Or]: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||{},[Or]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ql(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ef(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=Ql(e);this._notificationHandlers.set(n,o=>{let s=ef(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"&&As(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=zs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Nr(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(Nr(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=zs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Nr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function rb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function nb(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];rb(i)&&rb(s)?r[o]={...i,...s}:r[o]=s}return r}var BP=ji(Up(),1),VP=ji(WP(),1);function gF(){let t=new BP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,VP.default)(t),t}var Oc=class{constructor(e){this._ajv=e??gF()}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 zc=class{constructor(e){this._client=e}async*callToolStream(e,r=mn,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 KP(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 JP(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 Nc(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&&Nc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Nc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Nc(r,e)}}function yF(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 Dc=class extends Ya{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 Oc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ds,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Zl,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ll,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new zc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=nb(this._capabilities,e)}setRequestHandler(e,r){let o=Ia(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Oa(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=At(Jl,c);if(!d.success){let b=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=yF(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let b=At(hn,h);if(!b.success){let w=b.error instanceof Error?b.error.message:String(b.error);throw new $(M.InvalidParams,`Invalid task creation result: ${w}`)}return b.data}let m=At(Yl,h);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${b}`)}let y=m.data,v=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Nc(v,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=At(Bl,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,f=await Promise.resolve(r(c,u));if(l.task){let y=At(hn,f);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let h=l.tools||l.toolChoice?Kl:Vl,m=At(h,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:lo,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ml,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Dw.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){KP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&JP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},pn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Xl,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},pn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Gl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},jl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ol,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},zl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Dl,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},pn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},pn,r)}async callTool(e,r=mn,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},Wl,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=eb.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var hi=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}},YP=10,vF=13,kn=32;function Kp(t){}function Lc(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=Kp,onError:r=Kp,onRetry:n=Kp,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let re=y(S);re!==""&&(i.push(re),a=re.length),m();return}if(S.indexOf(`
87
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of t.seen.entries()){let a=i[1];if(e===i[0]){s(i);continue}if(t.external){let u=t.external.registry.get(i[0])?.id;if(e!==i[0]&&u){s(i);continue}}if(t.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1&&t.reused==="ref"){s(i);continue}}}function yl(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,d={...u},l=c.ref;if(c.ref=null,l){n(l);let p=t.seen.get(l),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,d),a._zod.parent===l)for(let y in u)y==="$ref"||y==="allOf"||y in d||delete u[y];if(h.$ref&&p.def)for(let y in u)y==="$ref"||y==="allOf"||y in p.def&&JSON.stringify(u[y])===JSON.stringify(p.def[y])&&delete u[y]}let f=a._zod.parent;if(f&&f!==l){n(f);let p=t.seen.get(f);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let s=t.metadataRegistry.get(e)?.id;s!==void 0&&o.id===s&&delete o.id;let i=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,i[c.defId]=c.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:xs(e,"input",t.processors),output:xs(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ue(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 Ue(n.element,r);if(n.type==="set")return Ue(n.valueType,r);if(n.type==="lazy")return Ue(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 Ue(n.innerType,r);if(n.type==="intersection")return Ue(n.left,r)||Ue(n.right,r);if(n.type==="record"||n.type==="map")return Ue(n.keyType,r)||Ue(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Ue(n.in,r)||Ue(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ue(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ue(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ue(o,r))return!0;return!!(n.rest&&Ue(n.rest,r))}return!1}var ES=(t,e={})=>r=>{let n=ml({...r,processors:e});return ve(t,n),gl(n,t),yl(n,t)},xs=(t,e,r={})=>n=>{let{libraryOptions:o,target:s}=n??{},i=ml({...o??{},target:s,io:e,processors:r});return ve(t,i),gl(i,t),yl(i,t)};var jM={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},TS=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof s=="number"&&(o.minLength=s),typeof i=="number"&&(o.maxLength=i),a&&(o.format=jM[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}))])}},AS=(t,e,r,n)=>{let o=r,{minimum:s,maximum:i,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let l=typeof d=="number"&&d>=(s??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(i??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";l?p?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof s=="number"&&(o.minimum=s),f?p?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u:typeof i=="number"&&(o.maximum=i),typeof c=="number"&&(o.multipleOf=c)},$S=(t,e,r,n)=>{r.type="boolean"},MS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};var IS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var OS=(t,e,r,n)=>{r.not={}},zS=(t,e,r,n)=>{},NS=(t,e,r,n)=>{},DS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},LS=(t,e,r,n)=>{let o=t._zod.def,s=gs(o.entries);s.every(i=>typeof i=="number")&&(r.type="number"),s.every(i=>typeof i=="string")&&(r.type="string"),r.enum=s},jS=(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 FS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};var US=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};var qS=(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"]})},HS=(t,e,r,n)=>{let o=r,s=t._zod.def;o.type="object",o.properties={};let i=s.shape;for(let u in i)o.properties[u]=ve(i[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(i)),c=new Set([...a].filter(u=>{let d=s.shape[u]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),s.catchall?._zod.def.type==="never"?o.additionalProperties=!1:s.catchall?s.catchall&&(o.additionalProperties=ve(s.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},GS=(t,e,r,n)=>{let o=t._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ve(a,e,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=i:r.anyOf=i},ZS=(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 WS=(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)}},BS=(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"}]},VS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType},KS=(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))},JS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,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},XS=(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},QS=(t,e,r,n)=>{let o=t._zod.def;ve(o.innerType,e,n);let s=e.seen.get(t);s.ref=o.innerType,r.readOnly=!0};var vl=(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 Ma(t){return!!t._zod}function At(t,e){return Ma(t)?ws(t,e):t.safeParse(e)}function Ia(t){if(!t)return;let e;if(Ma(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Oa(t){if(Ma(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 ks={};Ru(ks,{ZodISODate:()=>tw,ZodISODateTime:()=>ew,ZodISODuration:()=>nw,ZodISOTime:()=>rw,date:()=>Sl,datetime:()=>_l,duration:()=>bl,time:()=>wl});var ew=_("ZodISODateTime",(t,e)=>{Xv.init(t,e),he.init(t,e)});function _l(t){return uS(ew,t)}var tw=_("ZodISODate",(t,e)=>{Qv.init(t,e),he.init(t,e)});function Sl(t){return dS(tw,t)}var rw=_("ZodISOTime",(t,e)=>{e_.init(t,e),he.init(t,e)});function wl(t){return lS(rw,t)}var nw=_("ZodISODuration",(t,e)=>{t_.init(t,e),he.init(t,e)});function bl(t){return fS(nw,t)}var BM=(t,e)=>{ba.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Gd(t,r)},flatten:{value:r=>Hd(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ro,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ro,2)}},isEmpty:{get(){return t.issues.length===0}}})};var it=_("ZodError",BM,{Parent:Error});var sw=Ra(it),iw=Pa(it),aw=Ss(it),cw=bs(it),uw=zy(it),dw=Ny(it),lw=Dy(it),fw=Ly(it),pw=jy(it),hw=Fy(it),mw=Uy(it),gw=qy(it);var yw=new WeakMap;function Es(t,e,r){let n=Object.getPrototypeOf(t),o=yw.get(n);if(o||(o=new Set,yw.set(n,o)),!o.has(e)){o.add(e);for(let s in r){let i=r[s];Object.defineProperty(n,s,{configurable:!0,enumerable:!1,get(){let a=i.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ne=_("ZodType",(t,e)=>(ee.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:xs(t,"input"),output:xs(t,"output")}}),t.toJSONSchema=ES(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>sw(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>aw(t,r,n),t.parseAsync=async(r,n)=>iw(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>cw(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>uw(t,r,n),t.decode=(r,n)=>dw(t,r,n),t.encodeAsync=async(r,n)=>lw(t,r,n),t.decodeAsync=async(r,n)=>fw(t,r,n),t.safeEncode=(r,n)=>pw(t,r,n),t.safeDecode=(r,n)=>hw(t,r,n),t.safeEncodeAsync=async(r,n)=>mw(t,r,n),t.safeDecodeAsync=async(r,n)=>gw(t,r,n),Es(t,"ZodType",{check(...r){let n=this.def;return this.clone(U.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return pt(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(zI(r,n))},superRefine(r,n){return this.check(NI(r,n))},overwrite(r){return this.check(Ir(r))},optional(){return ge(this)},exactOptional(){return RI(this)},nullable(){return ww(this)},nullish(){return ge(ww(this))},nonoptional(r){return TI(this,r)},array(){return C(this)},or(r){return ue([this,r])},and(r){return Da(this,r)},transform(r){return bw(this,Mw(r))},default(r){return xI(this,r)},prefault(r){return EI(this,r)},catch(r){return $I(this,r)},pipe(r){return bw(this,r)},readonly(){return OI(this)},describe(r){let n=this.clone();return Mr.add(n,{description:r}),n},meta(...r){if(r.length===0)return Mr.get(this);let n=this.clone();return Mr.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 Mr.get(t)?.description},configurable:!0}),t)),Rw=_("_ZodString",(t,e)=>{Ta.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>TS(t,n,o,s);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Es(t,"_ZodString",{regex(...n){return this.check(ol(...n))},includes(...n){return this.check(al(...n))},startsWith(...n){return this.check(cl(...n))},endsWith(...n){return this.check(ul(...n))},min(...n){return this.check(ao(...n))},max(...n){return this.check(Aa(...n))},length(...n){return this.check($a(...n))},nonempty(...n){return this.check(ao(1,...n))},lowercase(n){return this.check(sl(n))},uppercase(n){return this.check(il(n))},trim(){return this.check(ll())},normalize(...n){return this.check(dl(...n))},toLowerCase(){return this.check(fl())},toUpperCase(){return this.check(pl())},slugify(){return this.check(hl())}})}),Pl=_("ZodString",(t,e)=>{Ta.init(t,e),Rw.init(t,e),t.email=r=>t.check(H_(KM,r)),t.url=r=>t.check(nl(Pw,r)),t.jwt=r=>t.check(cS(dI,r)),t.emoji=r=>t.check(V_(JM,r)),t.guid=r=>t.check(rl(vw,r)),t.uuid=r=>t.check(G_(za,r)),t.uuidv4=r=>t.check(Z_(za,r)),t.uuidv6=r=>t.check(W_(za,r)),t.uuidv7=r=>t.check(B_(za,r)),t.nanoid=r=>t.check(K_(YM,r)),t.guid=r=>t.check(rl(vw,r)),t.cuid=r=>t.check(J_(XM,r)),t.cuid2=r=>t.check(Y_(QM,r)),t.ulid=r=>t.check(X_(eI,r)),t.base64=r=>t.check(sS(aI,r)),t.base64url=r=>t.check(iS(cI,r)),t.xid=r=>t.check(Q_(tI,r)),t.ksuid=r=>t.check(eS(rI,r)),t.ipv4=r=>t.check(tS(nI,r)),t.ipv6=r=>t.check(rS(oI,r)),t.cidrv4=r=>t.check(nS(sI,r)),t.cidrv6=r=>t.check(oS(iI,r)),t.e164=r=>t.check(aS(uI,r)),t.datetime=r=>t.check(_l(r)),t.date=r=>t.check(Sl(r)),t.time=r=>t.check(wl(r)),t.duration=r=>t.check(bl(r))});function g(t){return U_(Pl,t)}var he=_("ZodStringFormat",(t,e)=>{ce.init(t,e),Rw.init(t,e)}),KM=_("ZodEmail",(t,e)=>{Hv.init(t,e),he.init(t,e)});var vw=_("ZodGUID",(t,e)=>{Uv.init(t,e),he.init(t,e)});var za=_("ZodUUID",(t,e)=>{qv.init(t,e),he.init(t,e)});var Pw=_("ZodURL",(t,e)=>{Gv.init(t,e),he.init(t,e)});function Cw(t){return nl(Pw,t)}var JM=_("ZodEmoji",(t,e)=>{Zv.init(t,e),he.init(t,e)});var YM=_("ZodNanoID",(t,e)=>{Wv.init(t,e),he.init(t,e)});var XM=_("ZodCUID",(t,e)=>{Bv.init(t,e),he.init(t,e)});var QM=_("ZodCUID2",(t,e)=>{Vv.init(t,e),he.init(t,e)});var eI=_("ZodULID",(t,e)=>{Kv.init(t,e),he.init(t,e)});var tI=_("ZodXID",(t,e)=>{Jv.init(t,e),he.init(t,e)});var rI=_("ZodKSUID",(t,e)=>{Yv.init(t,e),he.init(t,e)});var nI=_("ZodIPv4",(t,e)=>{r_.init(t,e),he.init(t,e)});var oI=_("ZodIPv6",(t,e)=>{n_.init(t,e),he.init(t,e)});var sI=_("ZodCIDRv4",(t,e)=>{o_.init(t,e),he.init(t,e)});var iI=_("ZodCIDRv6",(t,e)=>{s_.init(t,e),he.init(t,e)});var aI=_("ZodBase64",(t,e)=>{a_.init(t,e),he.init(t,e)});var cI=_("ZodBase64URL",(t,e)=>{c_.init(t,e),he.init(t,e)});var uI=_("ZodE164",(t,e)=>{u_.init(t,e),he.init(t,e)});var dI=_("ZodJWT",(t,e)=>{d_.init(t,e),he.init(t,e)});var Na=_("ZodNumber",(t,e)=>{Yd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>AS(t,n,o,s),Es(t,"ZodNumber",{gt(n,o){return this.check(io(n,o))},gte(n,o){return this.check(Tt(n,o))},min(n,o){return this.check(Tt(n,o))},lt(n,o){return this.check(so(n,o))},lte(n,o){return this.check(ir(n,o))},max(n,o){return this.check(ir(n,o))},int(n){return this.check(_w(n))},safe(n){return this.check(_w(n))},positive(n){return this.check(io(0,n))},nonnegative(n){return this.check(Tt(0,n))},negative(n){return this.check(so(0,n))},nonpositive(n){return this.check(ir(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 V(t){return pS(Na,t)}var lI=_("ZodNumberFormat",(t,e)=>{l_.init(t,e),Na.init(t,e)});function _w(t){return mS(lI,t)}var Cl=_("ZodBoolean",(t,e)=>{f_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$S(t,r,n,o)});function oe(t){return gS(Cl,t)}var xw=_("ZodBigInt",(t,e)=>{p_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>MS(t,n,o,s),t.gte=(n,o)=>t.check(Tt(n,o)),t.min=(n,o)=>t.check(Tt(n,o)),t.gt=(n,o)=>t.check(io(n,o)),t.gte=(n,o)=>t.check(Tt(n,o)),t.min=(n,o)=>t.check(Tt(n,o)),t.lt=(n,o)=>t.check(so(n,o)),t.lte=(n,o)=>t.check(ir(n,o)),t.max=(n,o)=>t.check(ir(n,o)),t.positive=n=>t.check(io(BigInt(0),n)),t.negative=n=>t.check(so(BigInt(0),n)),t.nonpositive=n=>t.check(ir(BigInt(0),n)),t.nonnegative=n=>t.check(Tt(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 fI=_("ZodNull",(t,e)=>{h_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o)});function kw(t){return _S(fI,t)}var pI=_("ZodAny",(t,e)=>{m_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>zS(t,r,n,o)});function Ew(){return SS(pI)}var hI=_("ZodUnknown",(t,e)=>{g_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>NS(t,r,n,o)});function me(){return wS(hI)}var mI=_("ZodNever",(t,e)=>{y_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>OS(t,r,n,o)});function gI(t){return bS(mI,t)}var Tw=_("ZodDate",(t,e)=>{v_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>DS(t,n,o,s),t.min=(n,o)=>t.check(Tt(n,o)),t.max=(n,o)=>t.check(ir(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 yI=_("ZodArray",(t,e)=>{__.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qS(t,r,n,o),t.element=e.element,Es(t,"ZodArray",{min(r,n){return this.check(ao(r,n))},nonempty(r){return this.check(ao(1,r))},max(r,n){return this.check(Aa(r,n))},length(r,n){return this.check($a(r,n))},unwrap(){return this.element}})});function C(t,e){return PS(yI,t,e)}var Aw=_("ZodObject",(t,e)=>{b_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>HS(t,r,n,o),U.defineLazy(t,"shape",()=>e.shape),Es(t,"ZodObject",{keyof(){return Je(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:me()})},loose(){return this.clone({...this._zod.def,catchall:me()})},strict(){return this.clone({...this._zod.def,catchall:gI()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return U.extend(this,r)},safeExtend(r){return U.safeExtend(this,r)},merge(r){return U.merge(this,r)},pick(r){return U.pick(this,r)},omit(r){return U.omit(this,r)},partial(...r){return U.partial(Iw,this,r[0])},required(...r){return U.required(Ow,this,r[0])}})});function k(t,e){let r={type:"object",shape:t??{},...U.normalizeParams(e)};return new Aw(r)}function Ce(t,e){return new Aw({type:"object",shape:t,catchall:me(),...U.normalizeParams(e)})}var $w=_("ZodUnion",(t,e)=>{Xd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>GS(t,r,n,o),t.options=e.options});function ue(t,e){return new $w({type:"union",options:t,...U.normalizeParams(e)})}var vI=_("ZodDiscriminatedUnion",(t,e)=>{$w.init(t,e),R_.init(t,e)});function xl(t,e,r){return new vI({type:"union",options:e,discriminator:t,...U.normalizeParams(r)})}var _I=_("ZodIntersection",(t,e)=>{P_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ZS(t,r,n,o)});function Da(t,e){return new _I({type:"intersection",left:t,right:e})}var Sw=_("ZodRecord",(t,e)=>{C_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>WS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function ae(t,e,r){return!e||!e._zod?new Sw({type:"record",keyType:g(),valueType:t,...U.normalizeParams(e)}):new Sw({type:"record",keyType:t,valueType:e,...U.normalizeParams(r)})}var Rl=_("ZodEnum",(t,e)=>{x_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(n,o,s)=>LS(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:[],...U.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Rl({...e,checks:[],...U.normalizeParams(o),entries:s})}});function Je(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Rl({type:"enum",entries:r,...U.normalizeParams(e)})}var SI=_("ZodLiteral",(t,e)=>{k_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jS(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 SI({type:"literal",values:Array.isArray(t)?t:[t],...U.normalizeParams(e)})}var wI=_("ZodTransform",(t,e)=>{E_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>US(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new eo(t.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(U.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),r.issues.push(U.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Mw(t){return new wI({type:"transform",transform:t})}var Iw=_("ZodOptional",(t,e)=>{Qd.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ge(t){return new Iw({type:"optional",innerType:t})}var bI=_("ZodExactOptional",(t,e)=>{T_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function RI(t){return new bI({type:"optional",innerType:t})}var PI=_("ZodNullable",(t,e)=>{A_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>BS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ww(t){return new PI({type:"nullable",innerType:t})}var CI=_("ZodDefault",(t,e)=>{$_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>KS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function xI(t,e){return new CI({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var kI=_("ZodPrefault",(t,e)=>{M_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>JS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function EI(t,e){return new kI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():U.shallowClone(e)}})}var Ow=_("ZodNonOptional",(t,e)=>{I_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>VS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function TI(t,e){return new Ow({type:"nonoptional",innerType:t,...U.normalizeParams(e)})}var AI=_("ZodCatch",(t,e)=>{O_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>YS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function $I(t,e){return new AI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var zw=_("ZodPipe",(t,e)=>{el.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>XS(t,r,n,o),t.in=e.in,t.out=e.out});function bw(t,e){return new zw({type:"pipe",in:t,out:e})}var MI=_("ZodPreprocess",(t,e)=>{zw.init(t,e),z_.init(t,e)}),II=_("ZodReadonly",(t,e)=>{N_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>QS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function OI(t){return new II({type:"readonly",innerType:t})}var Nw=_("ZodCustom",(t,e)=>{D_.init(t,e),ne.init(t,e),t._zod.processJSONSchema=(r,n,o)=>FS(t,r,n,o)});function Dw(t,e){return CS(Nw,t??(()=>!0),e)}function zI(t,e={}){return xS(Nw,t,e)}function NI(t,e){return kS(t,e)}function kl(t,e){return new MI({type:"pipe",in:Mw(t),out:e})}var jw={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 Lw;Lw||(Lw={});var La={};Ru(La,{bigint:()=>FI,boolean:()=>jI,date:()=>UI,number:()=>LI,string:()=>DI});function DI(t){return q_(Pl,t)}function LI(t){return hS(Na,t)}function jI(t){return yS(Cl,t)}function FI(t){return vS(xw,t)}function UI(t){return RS(Tw,t)}Ke(L_());var lo="2025-11-25";var Fw=[lo,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Or="io.modelcontextprotocol/related-task",Fa="2.0",xe=Dw(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Uw=ue([g(),V().int()]),qw=g(),LB=Ce({ttl:V().optional(),pollInterval:V().optional()}),HI=k({ttl:V().optional()}),GI=k({taskId:g()}),Tl=Ce({progressToken:Uw.optional(),[Or]:GI.optional()}),at=k({_meta:Tl.optional()}),Ts=at.extend({task:HI.optional()}),Hw=t=>Ts.safeParse(t).success,Me=k({method:g(),params:at.loose().optional()}),mt=k({_meta:Tl.optional()}),gt=k({method:g(),params:mt.loose().optional()}),ke=Ce({_meta:Tl.optional()}),Ua=ue([g(),V().int()]),Gw=k({jsonrpc:E(Fa),id:Ua,...Me.shape}).strict(),As=t=>Gw.safeParse(t).success,Zw=k({jsonrpc:E(Fa),...gt.shape}).strict(),Ww=t=>Zw.safeParse(t).success,Al=k({jsonrpc:E(Fa),id:Ua,result:ke}).strict(),fn=t=>Al.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 $l=k({jsonrpc:E(Fa),id:Ua.optional(),error:k({code:V().int(),message:g(),data:me().optional()})}).strict();var Bw=t=>$l.safeParse(t).success;var zr=ue([Gw,Zw,Al,$l]),jB=ue([Al,$l]),pn=ke.strict(),ZI=mt.extend({requestId:Ua.optional(),reason:g().optional()}),qa=gt.extend({method:E("notifications/cancelled"),params:ZI}),WI=k({src:g(),mimeType:g().optional(),sizes:C(g()).optional(),theme:Je(["light","dark"]).optional()}),$s=k({icons:C(WI).optional()}),uo=k({name:g(),title:g().optional()}),Vw=uo.extend({...uo.shape,...$s.shape,version:g(),websiteUrl:g().optional(),description:g().optional()}),BI=Da(k({applyDefaults:oe().optional()}),ae(g(),me())),VI=kl(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Da(k({form:BI.optional(),url:xe.optional()}),ae(g(),me()).optional())),KI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({sampling:Ce({createMessage:xe.optional()}).optional(),elicitation:Ce({create:xe.optional()}).optional()}).optional()}),JI=Ce({list:xe.optional(),cancel:xe.optional(),requests:Ce({tools:Ce({call:xe.optional()}).optional()}).optional()}),YI=k({experimental:ae(g(),xe).optional(),sampling:k({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:VI.optional(),roots:k({listChanged:oe().optional()}).optional(),tasks:KI.optional(),extensions:ae(g(),xe).optional()}),XI=at.extend({protocolVersion:g(),capabilities:YI,clientInfo:Vw}),QI=Me.extend({method:E("initialize"),params:XI});var eO=k({experimental:ae(g(),xe).optional(),logging:xe.optional(),completions:xe.optional(),prompts:k({listChanged:oe().optional()}).optional(),resources:k({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:k({listChanged:oe().optional()}).optional(),tasks:JI.optional(),extensions:ae(g(),xe).optional()}),Ml=ke.extend({protocolVersion:g(),capabilities:eO,serverInfo:Vw,instructions:g().optional()}),Kw=gt.extend({method:E("notifications/initialized"),params:mt.optional()}),Jw=t=>Kw.safeParse(t).success,Ha=Me.extend({method:E("ping"),params:at.optional()}),tO=k({progress:V(),total:ge(V()),message:ge(g())}),rO=k({...mt.shape,...tO.shape,progressToken:Uw}),Ga=gt.extend({method:E("notifications/progress"),params:rO}),nO=at.extend({cursor:qw.optional()}),Ms=Me.extend({params:nO.optional()}),Is=ke.extend({nextCursor:qw.optional()}),oO=Je(["working","input_required","completed","failed","cancelled"]),Os=k({taskId:g(),status:oO,ttl:ue([V(),kw()]),createdAt:g(),lastUpdatedAt:g(),pollInterval:ge(V()),statusMessage:ge(g())}),hn=ke.extend({task:Os}),sO=mt.merge(Os),zs=gt.extend({method:E("notifications/tasks/status"),params:sO}),Za=Me.extend({method:E("tasks/get"),params:at.extend({taskId:g()})}),Wa=ke.merge(Os),Ba=Me.extend({method:E("tasks/result"),params:at.extend({taskId:g()})}),FB=ke.loose(),Va=Ms.extend({method:E("tasks/list")}),Ka=Is.extend({tasks:C(Os)}),Ja=Me.extend({method:E("tasks/cancel"),params:at.extend({taskId:g()})}),Yw=ke.merge(Os),Xw=k({uri:g(),mimeType:ge(g()),_meta:ae(g(),me()).optional()}),Qw=Xw.extend({text:g()}),Il=g().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),eb=Xw.extend({blob:Il}),Ns=Je(["user","assistant"]),fo=k({audience:C(Ns).optional(),priority:V().min(0).max(1).optional(),lastModified:ks.datetime({offset:!0}).optional()}),tb=k({...uo.shape,...$s.shape,uri:g(),description:ge(g()),mimeType:ge(g()),size:ge(V()),annotations:fo.optional(),_meta:ge(Ce({}))}),iO=k({...uo.shape,...$s.shape,uriTemplate:g(),description:ge(g()),mimeType:ge(g()),annotations:fo.optional(),_meta:ge(Ce({}))}),aO=Ms.extend({method:E("resources/list")}),Ol=Is.extend({resources:C(tb)}),cO=Ms.extend({method:E("resources/templates/list")}),zl=Is.extend({resourceTemplates:C(iO)}),Nl=at.extend({uri:g()}),uO=Nl,dO=Me.extend({method:E("resources/read"),params:uO}),Dl=ke.extend({contents:C(ue([Qw,eb]))}),Ll=gt.extend({method:E("notifications/resources/list_changed"),params:mt.optional()}),lO=Nl,fO=Me.extend({method:E("resources/subscribe"),params:lO}),pO=Nl,hO=Me.extend({method:E("resources/unsubscribe"),params:pO}),mO=mt.extend({uri:g()}),gO=gt.extend({method:E("notifications/resources/updated"),params:mO}),yO=k({name:g(),description:ge(g()),required:ge(oe())}),vO=k({...uo.shape,...$s.shape,description:ge(g()),arguments:ge(C(yO)),_meta:ge(Ce({}))}),_O=Ms.extend({method:E("prompts/list")}),jl=Is.extend({prompts:C(vO)}),SO=at.extend({name:g(),arguments:ae(g(),g()).optional()}),wO=Me.extend({method:E("prompts/get"),params:SO}),Fl=k({type:E("text"),text:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),Ul=k({type:E("image"),data:Il,mimeType:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),ql=k({type:E("audio"),data:Il,mimeType:g(),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),bO=k({type:E("tool_use"),name:g(),id:g(),input:ae(g(),me()),_meta:ae(g(),me()).optional()}),RO=k({type:E("resource"),resource:ue([Qw,eb]),annotations:fo.optional(),_meta:ae(g(),me()).optional()}),PO=tb.extend({type:E("resource_link")}),Hl=ue([Fl,Ul,ql,PO,RO]),CO=k({role:Ns,content:Hl}),Gl=ke.extend({description:g().optional(),messages:C(CO)}),Zl=gt.extend({method:E("notifications/prompts/list_changed"),params:mt.optional()}),xO=k({title:g().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),kO=k({taskSupport:Je(["required","optional","forbidden"]).optional()}),rb=k({...uo.shape,...$s.shape,description:g().optional(),inputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()),outputSchema:k({type:E("object"),properties:ae(g(),xe).optional(),required:C(g()).optional()}).catchall(me()).optional(),annotations:xO.optional(),execution:kO.optional(),_meta:ae(g(),me()).optional()}),EO=Ms.extend({method:E("tools/list")}),Wl=Is.extend({tools:C(rb)}),mn=ke.extend({content:C(Hl).default([]),structuredContent:ae(g(),me()).optional(),isError:oe().optional()}),UB=mn.or(ke.extend({toolResult:me()})),TO=Ts.extend({name:g(),arguments:ae(g(),me()).optional()}),AO=Me.extend({method:E("tools/call"),params:TO}),Ds=gt.extend({method:E("notifications/tools/list_changed"),params:mt.optional()}),nb=k({autoRefresh:oe().default(!0),debounceMs:V().int().nonnegative().default(300)}),ob=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),$O=at.extend({level:ob}),MO=Me.extend({method:E("logging/setLevel"),params:$O}),IO=mt.extend({level:ob,logger:g().optional(),data:me()}),OO=gt.extend({method:E("notifications/message"),params:IO}),zO=k({name:g().optional()}),NO=k({hints:C(zO).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),DO=k({mode:Je(["auto","required","none"]).optional()}),LO=k({type:E("tool_result"),toolUseId:g().describe("The unique identifier for the corresponding tool call."),content:C(Hl).default([]),structuredContent:k({}).loose().optional(),isError:oe().optional(),_meta:ae(g(),me()).optional()}),jO=xl("type",[Fl,Ul,ql]),ja=xl("type",[Fl,Ul,ql,bO,LO]),FO=k({role:Ns,content:ue([ja,C(ja)]),_meta:ae(g(),me()).optional()}),UO=Ts.extend({messages:C(FO),modelPreferences:NO.optional(),systemPrompt:g().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:C(g()).optional(),metadata:xe.optional(),tools:C(rb).optional(),toolChoice:DO.optional()}),Bl=Me.extend({method:E("sampling/createMessage"),params:UO}),Vl=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens"]).or(g())),role:Ns,content:jO}),Kl=ke.extend({model:g(),stopReason:ge(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(g())),role:Ns,content:ue([ja,C(ja)])}),qO=k({type:E("boolean"),title:g().optional(),description:g().optional(),default:oe().optional()}),HO=k({type:E("string"),title:g().optional(),description:g().optional(),minLength:V().optional(),maxLength:V().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:g().optional()}),GO=k({type:Je(["number","integer"]),title:g().optional(),description:g().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),ZO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),default:g().optional()}),WO=k({type:E("string"),title:g().optional(),description:g().optional(),oneOf:C(k({const:g(),title:g()})),default:g().optional()}),BO=k({type:E("string"),title:g().optional(),description:g().optional(),enum:C(g()),enumNames:C(g()).optional(),default:g().optional()}),VO=ue([ZO,WO]),KO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({type:E("string"),enum:C(g())}),default:C(g()).optional()}),JO=k({type:E("array"),title:g().optional(),description:g().optional(),minItems:V().optional(),maxItems:V().optional(),items:k({anyOf:C(k({const:g(),title:g()}))}),default:C(g()).optional()}),YO=ue([KO,JO]),XO=ue([BO,VO,YO]),QO=ue([XO,qO,HO,GO]),ez=Ts.extend({mode:E("form").optional(),message:g(),requestedSchema:k({type:E("object"),properties:ae(g(),QO),required:C(g()).optional()})}),tz=Ts.extend({mode:E("url"),message:g(),elicitationId:g(),url:g().url()}),rz=ue([ez,tz]),Jl=Me.extend({method:E("elicitation/create"),params:rz}),nz=mt.extend({elicitationId:g()}),oz=gt.extend({method:E("notifications/elicitation/complete"),params:nz}),Yl=ke.extend({action:Je(["accept","decline","cancel"]),content:kl(t=>t===null?void 0:t,ae(g(),ue([g(),V(),oe(),C(g())])).optional())}),sz=k({type:E("ref/resource"),uri:g()});var iz=k({type:E("ref/prompt"),name:g()}),az=at.extend({ref:ue([iz,sz]),argument:k({name:g(),value:g()}),context:k({arguments:ae(g(),g()).optional()}).optional()}),cz=Me.extend({method:E("completion/complete"),params:az});var Xl=ke.extend({completion:Ce({values:C(g()).max(100),total:ge(V().int()),hasMore:ge(oe())})}),uz=k({uri:g().startsWith("file://"),name:g().optional(),_meta:ae(g(),me()).optional()}),dz=Me.extend({method:E("roots/list"),params:at.optional()}),lz=ke.extend({roots:C(uz)}),fz=gt.extend({method:E("notifications/roots/list_changed"),params:mt.optional()}),qB=ue([Ha,QI,cz,MO,wO,_O,aO,cO,dO,fO,hO,AO,EO,Za,Ba,Va,Ja]),HB=ue([qa,Ga,Kw,fz,zs]),GB=ue([pn,Vl,Kl,Yl,lz,Wa,Ka,hn]),ZB=ue([Ha,Bl,Jl,dz,Za,Ba,Va,Ja]),WB=ue([qa,Ga,OO,gO,Ll,Ds,Zl,zs,oz]),BB=ue([pn,Ml,Xl,Gl,jl,Ol,zl,Dl,mn,Wl,Wa,Ka,hn]),$=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 El(o.elicitations,r)}return new t(e,r,n)}},El=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 Nr(t){return t==="completed"||t==="failed"||t==="cancelled"}var xV=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Ql(t){let r=Ia(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ef(t,e){let r=At(t,e);if(!r.success)throw r.error;return r.data}var vz=6e4,Ya=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(qa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ga,r=>{this._onprogress(r)}),this.setRequestHandler(Ha,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Za,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(Ba,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,f=new $(l.error.code,l.error.message,l.error.data);d(f)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new $(M.InvalidParams,`Task not found: ${s}`);if(!Nr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Or]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Va,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new $(M.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ja,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new $(M.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nr(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),fn(s)||Bw(s)?this._onresponse(s):As(s)?this._onrequest(s,i):Ww(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?.[Or]?.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=Hw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async d=>{if(i.signal.aborted)return;let l={relatedRequestId:e.id};s&&(l.relatedTask={taskId:s}),await this.notification(d,l)},sendRequest:async(d,l,f)=>{if(i.signal.aborted)throw new $(M.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};s&&!p.relatedTask&&(p.relatedTask={taskId:s});let h=p.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(d,l,p)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async d=>{if(i.signal.aborted)return;let l={result:d,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)},async d=>{if(i.signal.aborted)return;let l={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(d.code)?d.code:M.InternalError,message:d.message??"Internal error",...d.data!==void 0&&{data:d.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId):await o?.send(l)}).catch(d=>this._onerror(new Error(`Failed to send response: ${d}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),fn(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(fn(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),fn(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,hn,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},Nr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new $(M.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new $(M.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof $?i:new $(M.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,d)=>{let l=b=>{d(b)};if(!this._transport){l(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){l(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Or]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`)));let w=b instanceof $?b:new $(M.RequestTimeout,String(b));d(w)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let w=At(r,b.result);w.success?u(w.data):d(w.error)}catch(w){d(w)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let m=n?.timeout??vz,y=()=>h($.fromError(M.RequestTimeout,"Request timed out",{timeout:m}));this._setupTimeout(f,m,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=w=>{let x=this._responseHandlers.get(f);x?x(w):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(v,{type:"request",message:p,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(f),d(w)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Wa,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},Ka,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||{},[Or]: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||{},[Or]: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||{},[Or]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ql(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ef(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=Ql(e);this._notificationHandlers.set(n,o=>{let s=ef(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"&&As(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=zs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Nr(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(Nr(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=zs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Nr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function sb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ib(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];sb(i)&&sb(s)?r[o]={...i,...s}:r[o]=s}return r}var JP=ji(Up(),1),YP=ji(KP(),1);function RF(){let t=new JP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,YP.default)(t),t}var Oc=class{constructor(e){this._ajv=e??RF()}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 zc=class{constructor(e){this._client=e}async*callToolStream(e,r=mn,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 XP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function QP(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function Nc(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&&Nc(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Nc(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Nc(r,e)}}function PF(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 Dc=class extends Ya{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 Oc,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Ds,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Zl,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ll,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new zc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ib(this._capabilities,e)}setRequestHandler(e,r){let o=Ia(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Oa(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=At(Jl,c);if(!d.success){let b=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:l}=d.data;l.mode=l.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=PF(this._capabilities.elicitation);if(l.mode==="form"&&!f)throw new $(M.InvalidParams,"Client does not support form-mode elicitation requests");if(l.mode==="url"&&!p)throw new $(M.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(r(c,u));if(l.task){let b=At(hn,h);if(!b.success){let w=b.error instanceof Error?b.error.message:String(b.error);throw new $(M.InvalidParams,`Invalid task creation result: ${w}`)}return b.data}let m=At(Yl,h);if(!m.success){let b=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid elicitation result: ${b}`)}let y=m.data,v=l.mode==="form"?l.requestedSchema:void 0;if(l.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Nc(v,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let d=At(Bl,c);if(!d.success){let y=d.error instanceof Error?d.error.message:String(d.error);throw new $(M.InvalidParams,`Invalid sampling request: ${y}`)}let{params:l}=d.data,f=await Promise.resolve(r(c,u));if(l.task){let y=At(hn,f);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new $(M.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let h=l.tools||l.toolChoice?Kl:Vl,m=At(h,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new $(M.InvalidParams,`Invalid sampling result: ${y}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapability(e,r){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:lo,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ml,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Fw.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){XP(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&QP(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},pn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Xl,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},pn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Gl,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},jl,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ol,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},zl,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},Dl,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},pn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},pn,r)}async callTool(e,r=mn,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},Wl,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=nb.safeParse(n);if(!s.success)throw new Error(`Invalid ${e} listChanged options: ${s.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:i,debounceMs:a}=s.data,{onChanged:c}=n,u=async()=>{if(!i){c(null,null);return}try{let l=await o();c(null,l)}catch(l){let f=l instanceof Error?l:new Error(String(l));c(f,null)}},d=()=>{if(a){let l=this._listChangedDebounceTimers.get(e);l&&clearTimeout(l);let f=setTimeout(u,a);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(r,d)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var hi=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}},eC=10,CF=13,kn=32;function Kp(t){}function Lc(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=Kp,onError:r=Kp,onRetry:n=Kp,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,d="",l=0,f,p=!1;function h(S){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,S.charCodeAt(0)===239&&S.charCodeAt(1)===187&&S.charCodeAt(2)===191&&(S=S.slice(3))),i.length===0){let re=y(S);re!==""&&(i.push(re),a=re.length),m();return}if(S.indexOf(`
88
88
  `)===-1&&S.indexOf("\r")===-1){i.push(S),a+=S.length,m();return}i.push(S);let P=i.join("");i.length=0,a=0;let I=y(P);I!==""&&(i.push(I),a=I.length),m()}function m(){s!==void 0&&(a+d.length<=s||(p=!0,i.length=0,a=0,u=void 0,d="",l=0,f=void 0,r(new hi(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(S){let P=0;if(S.indexOf("\r")===-1){let I=S.indexOf(`
89
89
  `,P);for(;I!==-1;){if(P===I){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0,P=I+1,I=S.indexOf(`
90
- `,P);continue}let re=S.charCodeAt(P);if(XP(S,P,re)){let fe=S.charCodeAt(P+5)===kn?P+6:P+5,Re=S.slice(fe,I);if(l===0&&S.charCodeAt(I+1)===YP){e({id:u,event:f,data:Re}),u=void 0,d="",f=void 0,P=I+2,I=S.indexOf(`
90
+ `,P);continue}let re=S.charCodeAt(P);if(tC(S,P,re)){let fe=S.charCodeAt(P+5)===kn?P+6:P+5,Re=S.slice(fe,I);if(l===0&&S.charCodeAt(I+1)===eC){e({id:u,event:f,data:Re}),u=void 0,d="",f=void 0,P=I+2,I=S.indexOf(`
91
91
  `,P);continue}d=l===0?Re:`${d}
92
- ${Re}`,l++}else QP(S,P,re)?f=S.slice(S.charCodeAt(P+6)===kn?P+7:P+6,I)||void 0:v(S,P,I);P=I+1,I=S.indexOf(`
92
+ ${Re}`,l++}else rC(S,P,re)?f=S.slice(S.charCodeAt(P+6)===kn?P+7:P+6,I)||void 0:v(S,P,I);P=I+1,I=S.indexOf(`
93
93
  `,P)}return S.slice(P)}for(;P<S.length;){let I=S.indexOf("\r",P),re=S.indexOf(`
94
- `,P),fe=-1;if(I!==-1&&re!==-1?fe=I<re?I:re:I!==-1?I===S.length-1?fe=-1:fe=I:re!==-1&&(fe=re),fe===-1)break;v(S,P,fe),P=fe+1,S.charCodeAt(P-1)===vF&&S.charCodeAt(P)===YP&&P++}return S.slice(P)}function v(S,P,I){if(P===I){w();return}let re=S.charCodeAt(P);if(XP(S,P,re)){let yr=S.charCodeAt(P+5)===kn?P+6:P+5,pm=S.slice(yr,I);d=l===0?pm:`${d}
95
- ${pm}`,l++;return}if(QP(S,P,re)){f=S.slice(S.charCodeAt(P+6)===kn?P+7:P+6,I)||void 0;return}if(re===105&&S.charCodeAt(P+1)===100&&S.charCodeAt(P+2)===58){let yr=S.slice(S.charCodeAt(P+3)===kn?P+4:P+3,I);u=yr.includes("\0")?void 0:yr;return}if(re===58){if(o){let yr=S.slice(P,I);o(yr.slice(S.charCodeAt(P+1)===kn?2:1))}return}let fe=S.slice(P,I),Re=fe.indexOf(":");if(Re===-1){b(fe,"",fe);return}let Kr=fe.slice(0,Re),Jr=fe.charCodeAt(Re+1)===kn?2:1,ct=fe.slice(Re+Jr);b(Kr,ct,fe)}function b(S,P,I){switch(S){case"event":f=P||void 0;break;case"data":d=l===0?P:`${d}
96
- ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new hi(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:I}));break;default:r(new hi(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:P,line:I}));break}}function w(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function x(S={}){if(S.consume&&i.length>0){let P=i.join("");v(P,0,P.length)}c=!0,u=void 0,d="",l=0,f=void 0,i.length=0,a=0,p=!1}return{feed:h,reset:x}}function XP(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 QP(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 Fc=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(eC(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(eC(this),r)}};function _F(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Jp(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Jp).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Jp(t.cause)}`:t.message:`${t}`}function eC(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var rC=t=>{throw TypeError(t)},oh=(t,e,r)=>e.has(t)||rC("Cannot "+r),F=(t,e,r)=>(oh(t,e,"read from private field"),r?r.call(t):e.get(t)),Ee=(t,e,r)=>e.has(t)?rC("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ye=(t,e,r,n)=>(oh(t,e,"write to private field"),e.set(t,r),r),fr=(t,e,r)=>(oh(t,e,"access private method"),r),et,En,Ao,jc,Uc,yi,Io,vi,Zr,$o,Oo,Mo,mi,Nt,Yp,Xp,Qp,tC,eh,th,gi,rh,nh,Tn=class extends EventTarget{constructor(e,r){var n,o;super(),Ee(this,Nt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ee(this,et),Ee(this,En),Ee(this,Ao),Ee(this,jc),Ee(this,Uc),Ee(this,yi),Ee(this,Io),Ee(this,vi,null),Ee(this,Zr),Ee(this,$o),Ee(this,Oo,null),Ee(this,Mo,null),Ee(this,mi,null),Ee(this,Xp,async s=>{var i;F(this,$o).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){fr(this,Nt,gi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ye(this,Ao,new URL(s.url)):ye(this,Ao,void 0),u!==200){fr(this,Nt,gi).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){fr(this,Nt,gi).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,et)===this.CLOSED)return;ye(this,et,this.OPEN);let l=new Event("open");if((i=F(this,mi))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){fr(this,Nt,gi).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:m,value:y}=await p.read();y&&F(this,$o).feed(f.decode(y,{stream:!m})),m&&(h=!1,F(this,$o).reset(),fr(this,Nt,rh).call(this))}while(h)}),Ee(this,Qp,s=>{ye(this,Zr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&fr(this,Nt,rh).call(this,Jp(s))}),Ee(this,eh,s=>{typeof s.id=="string"&&ye(this,vi,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,Ao)?F(this,Ao).origin:F(this,En).origin,lastEventId:s.id||""});F(this,Mo)&&(!s.event||s.event==="message")&&F(this,Mo).call(this,i),this.dispatchEvent(i)}),Ee(this,th,s=>{ye(this,yi,s)}),Ee(this,nh,()=>{ye(this,Io,void 0),F(this,et)===this.CONNECTING&&fr(this,Nt,Yp).call(this)});try{if(e instanceof URL)ye(this,En,e);else if(typeof e=="string")ye(this,En,new URL(e,SF()));else throw new Error("Invalid URL")}catch{throw _F("An invalid or illegal string was specified")}ye(this,$o,Lc({onEvent:F(this,eh),onRetry:F(this,th)})),ye(this,et,this.CONNECTING),ye(this,yi,3e3),ye(this,Uc,(n=r?.fetch)!=null?n:globalThis.fetch),ye(this,jc,(o=r?.withCredentials)!=null?o:!1),fr(this,Nt,Yp).call(this)}get readyState(){return F(this,et)}get url(){return F(this,En).href}get withCredentials(){return F(this,jc)}get onerror(){return F(this,Oo)}set onerror(e){ye(this,Oo,e)}get onmessage(){return F(this,Mo)}set onmessage(e){ye(this,Mo,e)}get onopen(){return F(this,mi)}set onopen(e){ye(this,mi,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){F(this,Io)&&clearTimeout(F(this,Io)),F(this,et)!==this.CLOSED&&(F(this,Zr)&&F(this,Zr).abort(),ye(this,et,this.CLOSED),ye(this,Zr,void 0))}};et=new WeakMap,En=new WeakMap,Ao=new WeakMap,jc=new WeakMap,Uc=new WeakMap,yi=new WeakMap,Io=new WeakMap,vi=new WeakMap,Zr=new WeakMap,$o=new WeakMap,Oo=new WeakMap,Mo=new WeakMap,mi=new WeakMap,Nt=new WeakSet,Yp=function(){ye(this,et,this.CONNECTING),ye(this,Zr,new AbortController),F(this,Uc)(F(this,En),fr(this,Nt,tC).call(this)).then(F(this,Xp)).catch(F(this,Qp))},Xp=new WeakMap,Qp=new WeakMap,tC=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,vi)?{"Last-Event-ID":F(this,vi)}:void 0},cache:"no-store",signal:(t=F(this,Zr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},eh=new WeakMap,th=new WeakMap,gi=function(t,e){var r;F(this,et)!==this.CLOSED&&ye(this,et,this.CLOSED);let n=new Fc("error",{code:e,message:t});(r=F(this,Oo))==null||r.call(this,n),this.dispatchEvent(n)},rh=function(t,e){var r;if(F(this,et)===this.CLOSED)return;ye(this,et,this.CONNECTING);let n=new Fc("error",{code:e,message:t});(r=F(this,Oo))==null||r.call(this,n),this.dispatchEvent(n),ye(this,Io,setTimeout(F(this,nh),F(this,yi)))},nh=new WeakMap,Tn.CONNECTING=0,Tn.OPEN=1,Tn.CLOSED=2;function SF(){let t="document"in globalThis?globalThis.document:void 0;return t&&typeof t=="object"&&"baseURI"in t&&typeof t.baseURI=="string"?t.baseURI:void 0}function zo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function qc(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...zo(e.headers),...zo(n.headers)}:e.headers};return t(r,o)}:t}var sh;sh=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function wF(t){return(await sh).getRandomValues(new Uint8Array(t))}async function bF(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await wF(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function RF(t){return await bF(t)}async function PF(t){let e=await(await sh).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function ih(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await RF(t),r=await PF(e);return{code_verifier:e,code_challenge:r}}var Ne=bw().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Nw.custom,message:"URL must be parseable",fatal:!0}),$d}).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"}),oC=Ce({resource:g().url(),authorization_servers:C(Ne).optional(),jwks_uri:g().url().optional(),scopes_supported:C(g()).optional(),bearer_methods_supported:C(g()).optional(),resource_signing_alg_values_supported:C(g()).optional(),resource_name:g().optional(),resource_documentation:g().optional(),resource_policy_uri:g().url().optional(),resource_tos_uri:g().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:oe().optional()}),ah=Ce({issuer:g(),authorization_endpoint:Ne,token_endpoint:Ne,registration_endpoint:Ne.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:Ne.optional(),revocation_endpoint:Ne.optional(),revocation_endpoint_auth_methods_supported:C(g()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(g()).optional(),introspection_endpoint:g().optional(),introspection_endpoint_auth_methods_supported:C(g()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(g()).optional(),code_challenge_methods_supported:C(g()).optional(),client_id_metadata_document_supported:oe().optional()}),CF=Ce({issuer:g(),authorization_endpoint:Ne,token_endpoint:Ne,userinfo_endpoint:Ne.optional(),jwks_uri:Ne,registration_endpoint:Ne.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),acr_values_supported:C(g()).optional(),subject_types_supported:C(g()),id_token_signing_alg_values_supported:C(g()),id_token_encryption_alg_values_supported:C(g()).optional(),id_token_encryption_enc_values_supported:C(g()).optional(),userinfo_signing_alg_values_supported:C(g()).optional(),userinfo_encryption_alg_values_supported:C(g()).optional(),userinfo_encryption_enc_values_supported:C(g()).optional(),request_object_signing_alg_values_supported:C(g()).optional(),request_object_encryption_alg_values_supported:C(g()).optional(),request_object_encryption_enc_values_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),display_values_supported:C(g()).optional(),claim_types_supported:C(g()).optional(),claims_supported:C(g()).optional(),service_documentation:g().optional(),claims_locales_supported:C(g()).optional(),ui_locales_supported:C(g()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Ne.optional(),op_tos_uri:Ne.optional(),client_id_metadata_document_supported:oe().optional()}),sC=k({...CF.shape,...ah.pick({code_challenge_methods_supported:!0}).shape}),iC=k({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:La.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),aC=k({error:g(),error_description:g().optional(),error_uri:g().optional()}),nC=Ne.optional().or(E("").transform(()=>{})),xF=k({redirect_uris:C(Ne),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:Ne.optional(),logo_uri:nC,scope:g().optional(),contacts:C(g()).optional(),tos_uri:nC,policy_uri:g().optional(),jwks_uri:Ne.optional(),jwks:Cw().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),kF=k({client_id:g(),client_secret:g().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),cC=xF.merge(kF),K5=k({error:g(),error_description:g().optional()}).strip(),J5=k({token:g(),token_type_hint:g().optional()}).strip();function uC(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function dC({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}},_i=class extends Se{};_i.errorCode="invalid_request";var An=class extends Se{};An.errorCode="invalid_client";var $n=class extends Se{};$n.errorCode="invalid_grant";var Mn=class extends Se{};Mn.errorCode="unauthorized_client";var Si=class extends Se{};Si.errorCode="unsupported_grant_type";var wi=class extends Se{};wi.errorCode="invalid_scope";var bi=class extends Se{};bi.errorCode="access_denied";var pr=class extends Se{};pr.errorCode="server_error";var Ri=class extends Se{};Ri.errorCode="temporarily_unavailable";var Pi=class extends Se{};Pi.errorCode="unsupported_response_type";var Ci=class extends Se{};Ci.errorCode="unsupported_token_type";var xi=class extends Se{};xi.errorCode="invalid_token";var ki=class extends Se{};ki.errorCode="method_not_allowed";var Ei=class extends Se{};Ei.errorCode="too_many_requests";var In=class extends Se{};In.errorCode="invalid_client_metadata";var Ti=class extends Se{};Ti.errorCode="insufficient_scope";var Ai=class extends Se{};Ai.errorCode="invalid_target";var lC={[_i.errorCode]:_i,[An.errorCode]:An,[$n.errorCode]:$n,[Mn.errorCode]:Mn,[Si.errorCode]:Si,[wi.errorCode]:wi,[bi.errorCode]:bi,[pr.errorCode]:pr,[Ri.errorCode]:Ri,[Pi.errorCode]:Pi,[Ci.errorCode]:Ci,[xi.errorCode]:xi,[ki.errorCode]:ki,[Ei.errorCode]:Ei,[In.errorCode]:In,[Ti.errorCode]:Ti,[Ai.errorCode]:Ai};var He=class extends Error{constructor(e){super(e??"Unauthorized")}};function EF(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var ch="code",uh="S256";function TF(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&EF(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 AF(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":$F(o,s,r);return;case"client_secret_post":MF(o,s,n);return;case"none":IF(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function $F(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 MF(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function IF(t,e){e.set("client_id",t)}async function pC(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=aC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=lC[o]||pr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new pr(o)}}async function hr(t,e){try{return await dh(t,e)}catch(r){if(r instanceof An||r instanceof Mn)return await t.invalidateCredentials?.("all"),await dh(t,e);if(r instanceof $n)return await t.invalidateCredentials?.("tokens"),await dh(t,e);throw r}}async function dh(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 mC(c,{fetchFn:s}),!a)try{a=await hC(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let w=await FF(e,{resourceMetadataUrl:d,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await zF(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,x=t.clientMetadataUrl;if(x&&!OF(x))throw new In(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${x}`);if(w&&x)p={client_id:x},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await ZF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:s});await t.saveClientInformation(P),p=P}}let h=!t.redirectUrl;if(r!==void 0||h){let w=await GF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let w=await HF(c,{metadata:u,clientInformation:p,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Se)||w instanceof pr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:b}=await UF(c,{metadata:u,clientInformation:p,state:y,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(b),await t.redirectToAuthorization(v),"REDIRECT"}function OF(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function zF(t,e,r){let n=uC(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!dC({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 No(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=lh(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=lh(t,"scope")||void 0,a=lh(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function lh(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 hC(t,e,r=fetch){let n=await LF(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 oC.parse(await n.json())}async function fh(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?fh(t,void 0,r):void 0;throw n}}function NF(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function fC(t,e,r=fetch){return await fh(t,{"MCP-Protocol-Version":e},r)}function DF(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function LF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??lo,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=NF(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await fC(i,s,r);if(!n?.metadataUrl&&DF(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await fC(c,s,r)}return a}function jF(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 mC(t,{fetchFn:e=fetch,protocolVersion:r=lo}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=jF(t);for(let{url:s,type:i}of o){let a=await fh(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"?ah.parse(await a.json()):sC.parse(await a.json())}}}async function FF(t,e){let r,n;try{r=await hC(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 mC(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function UF(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(ch))throw new Error(`Incompatible auth server: does not support response type ${ch}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(uh))throw new Error(`Incompatible auth server: does not support code challenge method ${uh}`)}else a=new URL("/authorize",t);let c=await ih(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",ch),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",uh),a.searchParams.set("redirect_uri",String(n)),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 qF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function gC(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=TF(n,d);AF(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await pC(u);return iC.parse(await u.json())}async function HF(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 gC(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function GF(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=qF(o,u,t.redirectUrl)}let c=await t.clientInformation();return gC(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function ZF(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 pC(i);return cC.parse(await i.json())}var $i=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Hc=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=qc(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new He;return await this._startOrAuth()}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=zo(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 Tn(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}=No(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 $i(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=zr.parse(JSON.parse(s.data))}catch(a){this.onerror?.(a);return}this.onmessage?.(i)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new He("No auth provider");if(await hr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{let r=await this._commonHeaders();r.set("content-type","application/json");let n={...this._requestInit,method:"POST",headers:r,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._endpoint,n);if(!o.ok){let s=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){let{resourceMetadataUrl:i,scope:a}=No(o);if(this._resourceMetadataUrl=i,this._scope=a,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${o.status}): ${s}`)}await o.body?.cancel()}catch(r){throw this.onerror?.(r),r}}setProtocolVersion(e){this._protocolVersion=e}};var ix=ji(ox(),1);import bh from"node:process";import{PassThrough as SU}from"node:stream";var vU=10*1024*1024,Zc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??vU}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 zr.parse(JSON.parse(t))}function sx(t){return JSON.stringify(t)+`
98
- `}var wU=bh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Bc(){let t={};for(let e of wU){let r=bh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Wc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Zc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new SU)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{this._process=(0,ix.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Bc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:bh.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=sx(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var lx=ji(dx(),1);function fx(t){if(t)try{return lx.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Vc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Lc({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 AU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Dt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Kc=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=qc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??AU}async _authThenStart(){if(!this._authProvider)throw new He("No auth provider");let e;try{e=await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(e!=="AUTHORIZED")throw new He;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(e.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);let r=zo(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 Dt(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 Vc({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(i=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=zr.parse(JSON.parse(p.data));fn(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new He("No auth provider");if(await hr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,r){try{let{resumptionToken:n,onresumptiontoken:o}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:As(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Dt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=No(a);if(this._resourceMetadataUrl=h,this._scope=m,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new He;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=No(a);if(y==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Dt(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=v??void 0,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new He;return this.send(e)}}throw new Dt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Bw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=fx(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(m=>zr.parse(m)):[zr.parse(p)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new Dt(-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 Dt(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 px(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 MU={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 hx(t){return{...Bc(),...MU,...t??{}}}function mx(){return Bc()}var Ph=class t extends Wc{static MAX_CAPTURED_LINES=100;static MAX_LINE_BUFFER_CHARS=16384;static MAX_LOG_HISTORY=1e3;_captured=[];_lineBuffer="";_logHistory=[];async start(){await super.start();let e=this.stderr;e&&e.on("data",r=>this.ingestStderr(r))}ingestStderr(e){this._lineBuffer+=e.toString();let r=this._lineBuffer.split(`
94
+ `,P),fe=-1;if(I!==-1&&re!==-1?fe=I<re?I:re:I!==-1?I===S.length-1?fe=-1:fe=I:re!==-1&&(fe=re),fe===-1)break;v(S,P,fe),P=fe+1,S.charCodeAt(P-1)===CF&&S.charCodeAt(P)===eC&&P++}return S.slice(P)}function v(S,P,I){if(P===I){w();return}let re=S.charCodeAt(P);if(tC(S,P,re)){let yr=S.charCodeAt(P+5)===kn?P+6:P+5,hm=S.slice(yr,I);d=l===0?hm:`${d}
95
+ ${hm}`,l++;return}if(rC(S,P,re)){f=S.slice(S.charCodeAt(P+6)===kn?P+7:P+6,I)||void 0;return}if(re===105&&S.charCodeAt(P+1)===100&&S.charCodeAt(P+2)===58){let yr=S.slice(S.charCodeAt(P+3)===kn?P+4:P+3,I);u=yr.includes("\0")?void 0:yr;return}if(re===58){if(o){let yr=S.slice(P,I);o(yr.slice(S.charCodeAt(P+1)===kn?2:1))}return}let fe=S.slice(P,I),Re=fe.indexOf(":");if(Re===-1){b(fe,"",fe);return}let Kr=fe.slice(0,Re),Jr=fe.charCodeAt(Re+1)===kn?2:1,ct=fe.slice(Re+Jr);b(Kr,ct,fe)}function b(S,P,I){switch(S){case"event":f=P||void 0;break;case"data":d=l===0?P:`${d}
96
+ ${P}`,l++;break;case"id":u=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?n(parseInt(P,10)):r(new hi(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:I}));break;default:r(new hi(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:P,line:I}));break}}function w(){l>0&&e({id:u,event:f,data:d}),u=void 0,d="",l=0,f=void 0}function x(S={}){if(S.consume&&i.length>0){let P=i.join("");v(P,0,P.length)}c=!0,u=void 0,d="",l=0,f=void 0,i.length=0,a=0,p=!1}return{feed:h,reset:x}}function tC(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 rC(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 Fc=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(nC(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(nC(this),r)}};function xF(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Jp(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Jp).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Jp(t.cause)}`:t.message:`${t}`}function nC(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var sC=t=>{throw TypeError(t)},oh=(t,e,r)=>e.has(t)||sC("Cannot "+r),F=(t,e,r)=>(oh(t,e,"read from private field"),r?r.call(t):e.get(t)),Ee=(t,e,r)=>e.has(t)?sC("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),ye=(t,e,r,n)=>(oh(t,e,"write to private field"),e.set(t,r),r),fr=(t,e,r)=>(oh(t,e,"access private method"),r),tt,En,Ao,jc,Uc,yi,Io,vi,Zr,$o,Oo,Mo,mi,Nt,Yp,Xp,Qp,oC,eh,th,gi,rh,nh,Tn=class extends EventTarget{constructor(e,r){var n,o;super(),Ee(this,Nt),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,Ee(this,tt),Ee(this,En),Ee(this,Ao),Ee(this,jc),Ee(this,Uc),Ee(this,yi),Ee(this,Io),Ee(this,vi,null),Ee(this,Zr),Ee(this,$o),Ee(this,Oo,null),Ee(this,Mo,null),Ee(this,mi,null),Ee(this,Xp,async s=>{var i;F(this,$o).reset();let{body:a,redirected:c,status:u,headers:d}=s;if(u===204){fr(this,Nt,gi).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?ye(this,Ao,new URL(s.url)):ye(this,Ao,void 0),u!==200){fr(this,Nt,gi).call(this,`Non-200 status code (${u})`,u);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){fr(this,Nt,gi).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.OPEN);let l=new Event("open");if((i=F(this,mi))==null||i.call(this,l),this.dispatchEvent(l),typeof a!="object"||!a||!("getReader"in a)){fr(this,Nt,gi).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let f=new TextDecoder,p=a.getReader(),h=!0;do{let{done:m,value:y}=await p.read();y&&F(this,$o).feed(f.decode(y,{stream:!m})),m&&(h=!1,F(this,$o).reset(),fr(this,Nt,rh).call(this))}while(h)}),Ee(this,Qp,s=>{ye(this,Zr,void 0),!(s.name==="AbortError"||s.type==="aborted")&&fr(this,Nt,rh).call(this,Jp(s))}),Ee(this,eh,s=>{typeof s.id=="string"&&ye(this,vi,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,Ao)?F(this,Ao).origin:F(this,En).origin,lastEventId:s.id||""});F(this,Mo)&&(!s.event||s.event==="message")&&F(this,Mo).call(this,i),this.dispatchEvent(i)}),Ee(this,th,s=>{ye(this,yi,s)}),Ee(this,nh,()=>{ye(this,Io,void 0),F(this,tt)===this.CONNECTING&&fr(this,Nt,Yp).call(this)});try{if(e instanceof URL)ye(this,En,e);else if(typeof e=="string")ye(this,En,new URL(e,kF()));else throw new Error("Invalid URL")}catch{throw xF("An invalid or illegal string was specified")}ye(this,$o,Lc({onEvent:F(this,eh),onRetry:F(this,th)})),ye(this,tt,this.CONNECTING),ye(this,yi,3e3),ye(this,Uc,(n=r?.fetch)!=null?n:globalThis.fetch),ye(this,jc,(o=r?.withCredentials)!=null?o:!1),fr(this,Nt,Yp).call(this)}get readyState(){return F(this,tt)}get url(){return F(this,En).href}get withCredentials(){return F(this,jc)}get onerror(){return F(this,Oo)}set onerror(e){ye(this,Oo,e)}get onmessage(){return F(this,Mo)}set onmessage(e){ye(this,Mo,e)}get onopen(){return F(this,mi)}set onopen(e){ye(this,mi,e)}addEventListener(e,r,n){let o=r;super.addEventListener(e,o,n)}removeEventListener(e,r,n){let o=r;super.removeEventListener(e,o,n)}close(){F(this,Io)&&clearTimeout(F(this,Io)),F(this,tt)!==this.CLOSED&&(F(this,Zr)&&F(this,Zr).abort(),ye(this,tt,this.CLOSED),ye(this,Zr,void 0))}};tt=new WeakMap,En=new WeakMap,Ao=new WeakMap,jc=new WeakMap,Uc=new WeakMap,yi=new WeakMap,Io=new WeakMap,vi=new WeakMap,Zr=new WeakMap,$o=new WeakMap,Oo=new WeakMap,Mo=new WeakMap,mi=new WeakMap,Nt=new WeakSet,Yp=function(){ye(this,tt,this.CONNECTING),ye(this,Zr,new AbortController),F(this,Uc)(F(this,En),fr(this,Nt,oC).call(this)).then(F(this,Xp)).catch(F(this,Qp))},Xp=new WeakMap,Qp=new WeakMap,oC=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,vi)?{"Last-Event-ID":F(this,vi)}:void 0},cache:"no-store",signal:(t=F(this,Zr))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},eh=new WeakMap,th=new WeakMap,gi=function(t,e){var r;F(this,tt)!==this.CLOSED&&ye(this,tt,this.CLOSED);let n=new Fc("error",{code:e,message:t});(r=F(this,Oo))==null||r.call(this,n),this.dispatchEvent(n)},rh=function(t,e){var r;if(F(this,tt)===this.CLOSED)return;ye(this,tt,this.CONNECTING);let n=new Fc("error",{code:e,message:t});(r=F(this,Oo))==null||r.call(this,n),this.dispatchEvent(n),ye(this,Io,setTimeout(F(this,nh),F(this,yi)))},nh=new WeakMap,Tn.CONNECTING=0,Tn.OPEN=1,Tn.CLOSED=2;function kF(){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 zo(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function qc(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...zo(e.headers),...zo(n.headers)}:e.headers};return t(r,o)}:t}var sh;sh=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(t=>t.webcrypto);async function EF(t){return(await sh).getRandomValues(new Uint8Array(t))}async function TF(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await EF(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function AF(t){return await TF(t)}async function $F(t){let e=await(await sh).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function ih(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await AF(t),r=await $F(e);return{code_verifier:e,code_challenge:r}}var Ne=Cw().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:jw.custom,message:"URL must be parseable",fatal:!0}),$d}).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"}),aC=Ce({resource:g().url(),authorization_servers:C(Ne).optional(),jwks_uri:g().url().optional(),scopes_supported:C(g()).optional(),bearer_methods_supported:C(g()).optional(),resource_signing_alg_values_supported:C(g()).optional(),resource_name:g().optional(),resource_documentation:g().optional(),resource_policy_uri:g().url().optional(),resource_tos_uri:g().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(g()).optional(),dpop_signing_alg_values_supported:C(g()).optional(),dpop_bound_access_tokens_required:oe().optional()}),ah=Ce({issuer:g(),authorization_endpoint:Ne,token_endpoint:Ne,registration_endpoint:Ne.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:Ne.optional(),revocation_endpoint:Ne.optional(),revocation_endpoint_auth_methods_supported:C(g()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(g()).optional(),introspection_endpoint:g().optional(),introspection_endpoint_auth_methods_supported:C(g()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(g()).optional(),code_challenge_methods_supported:C(g()).optional(),client_id_metadata_document_supported:oe().optional()}),MF=Ce({issuer:g(),authorization_endpoint:Ne,token_endpoint:Ne,userinfo_endpoint:Ne.optional(),jwks_uri:Ne,registration_endpoint:Ne.optional(),scopes_supported:C(g()).optional(),response_types_supported:C(g()),response_modes_supported:C(g()).optional(),grant_types_supported:C(g()).optional(),acr_values_supported:C(g()).optional(),subject_types_supported:C(g()),id_token_signing_alg_values_supported:C(g()),id_token_encryption_alg_values_supported:C(g()).optional(),id_token_encryption_enc_values_supported:C(g()).optional(),userinfo_signing_alg_values_supported:C(g()).optional(),userinfo_encryption_alg_values_supported:C(g()).optional(),userinfo_encryption_enc_values_supported:C(g()).optional(),request_object_signing_alg_values_supported:C(g()).optional(),request_object_encryption_alg_values_supported:C(g()).optional(),request_object_encryption_enc_values_supported:C(g()).optional(),token_endpoint_auth_methods_supported:C(g()).optional(),token_endpoint_auth_signing_alg_values_supported:C(g()).optional(),display_values_supported:C(g()).optional(),claim_types_supported:C(g()).optional(),claims_supported:C(g()).optional(),service_documentation:g().optional(),claims_locales_supported:C(g()).optional(),ui_locales_supported:C(g()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Ne.optional(),op_tos_uri:Ne.optional(),client_id_metadata_document_supported:oe().optional()}),cC=k({...MF.shape,...ah.pick({code_challenge_methods_supported:!0}).shape}),uC=k({access_token:g(),id_token:g().optional(),token_type:g(),expires_in:La.number().optional(),scope:g().optional(),refresh_token:g().optional()}).strip(),dC=k({error:g(),error_description:g().optional(),error_uri:g().optional()}),iC=Ne.optional().or(E("").transform(()=>{})),IF=k({redirect_uris:C(Ne),token_endpoint_auth_method:g().optional(),grant_types:C(g()).optional(),response_types:C(g()).optional(),client_name:g().optional(),client_uri:Ne.optional(),logo_uri:iC,scope:g().optional(),contacts:C(g()).optional(),tos_uri:iC,policy_uri:g().optional(),jwks_uri:Ne.optional(),jwks:Ew().optional(),software_id:g().optional(),software_version:g().optional(),software_statement:g().optional()}).strip(),OF=k({client_id:g(),client_secret:g().optional(),client_id_issued_at:V().optional(),client_secret_expires_at:V().optional()}).strip(),lC=IF.merge(OF),r3=k({error:g(),error_description:g().optional()}).strip(),n3=k({token:g(),token_type_hint:g().optional()}).strip();function fC(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function pC({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}},_i=class extends Se{};_i.errorCode="invalid_request";var An=class extends Se{};An.errorCode="invalid_client";var $n=class extends Se{};$n.errorCode="invalid_grant";var Mn=class extends Se{};Mn.errorCode="unauthorized_client";var Si=class extends Se{};Si.errorCode="unsupported_grant_type";var wi=class extends Se{};wi.errorCode="invalid_scope";var bi=class extends Se{};bi.errorCode="access_denied";var pr=class extends Se{};pr.errorCode="server_error";var Ri=class extends Se{};Ri.errorCode="temporarily_unavailable";var Pi=class extends Se{};Pi.errorCode="unsupported_response_type";var Ci=class extends Se{};Ci.errorCode="unsupported_token_type";var xi=class extends Se{};xi.errorCode="invalid_token";var ki=class extends Se{};ki.errorCode="method_not_allowed";var Ei=class extends Se{};Ei.errorCode="too_many_requests";var In=class extends Se{};In.errorCode="invalid_client_metadata";var Ti=class extends Se{};Ti.errorCode="insufficient_scope";var Ai=class extends Se{};Ai.errorCode="invalid_target";var hC={[_i.errorCode]:_i,[An.errorCode]:An,[$n.errorCode]:$n,[Mn.errorCode]:Mn,[Si.errorCode]:Si,[wi.errorCode]:wi,[bi.errorCode]:bi,[pr.errorCode]:pr,[Ri.errorCode]:Ri,[Pi.errorCode]:Pi,[Ci.errorCode]:Ci,[xi.errorCode]:xi,[ki.errorCode]:ki,[Ei.errorCode]:Ei,[In.errorCode]:In,[Ti.errorCode]:Ti,[Ai.errorCode]:Ai};var Ge=class extends Error{constructor(e){super(e??"Unauthorized")}};function zF(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var ch="code",uh="S256";function NF(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&zF(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 DF(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":LF(o,s,r);return;case"client_secret_post":jF(o,s,n);return;case"none":FF(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function LF(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 jF(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function FF(t,e){e.set("client_id",t)}async function gC(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=dC.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=hC[o]||pr;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new pr(o)}}async function hr(t,e){try{return await dh(t,e)}catch(r){if(r instanceof An||r instanceof Mn)return await t.invalidateCredentials?.("all"),await dh(t,e);if(r instanceof $n)return await t.invalidateCredentials?.("tokens"),await dh(t,e);throw r}}async function dh(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 vC(c,{fetchFn:s}),!a)try{a=await yC(e,{resourceMetadataUrl:d},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let w=await BF(e,{resourceMetadataUrl:d,fetchFn:s});c=w.authorizationServerUrl,u=w.authorizationServerMetadata,a=w.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:d?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let l=await qF(e,t,a),f=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,p=await Promise.resolve(t.clientInformation());if(!p){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let w=u?.client_id_metadata_document_supported===!0,x=t.clientMetadataUrl;if(x&&!UF(x))throw new In(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${x}`);if(w&&x)p={client_id:x},await t.saveClientInformation?.(p);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let P=await XF(c,{metadata:u,clientMetadata:t.clientMetadata,scope:f,fetchFn:s});await t.saveClientInformation(P),p=P}}let h=!t.redirectUrl;if(r!==void 0||h){let w=await YF(t,c,{metadata:u,resource:l,authorizationCode:r,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}let m=await t.tokens();if(m?.refresh_token)try{let w=await JF(c,{metadata:u,clientInformation:p,refreshToken:m.refresh_token,resource:l,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(w),"AUTHORIZED"}catch(w){if(!(!(w instanceof Se)||w instanceof pr))throw w}let y=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:b}=await VF(c,{metadata:u,clientInformation:p,state:y,redirectUrl:t.redirectUrl,scope:f,resource:l});return await t.saveCodeVerifier(b),await t.redirectToAuthorization(v),"REDIRECT"}function UF(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function qF(t,e,r){let n=fC(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!pC({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 No(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=lh(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=lh(t,"scope")||void 0,a=lh(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function lh(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 yC(t,e,r=fetch){let n=await ZF(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 aC.parse(await n.json())}async function fh(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?fh(t,void 0,r):void 0;throw n}}function HF(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function mC(t,e,r=fetch){return await fh(t,{"MCP-Protocol-Version":e},r)}function GF(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function ZF(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??lo,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=HF(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await mC(i,s,r);if(!n?.metadataUrl&&GF(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await mC(c,s,r)}return a}function WF(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 vC(t,{fetchFn:e=fetch,protocolVersion:r=lo}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=WF(t);for(let{url:s,type:i}of o){let a=await fh(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"?ah.parse(await a.json()):cC.parse(await a.json())}}}async function BF(t,e){let r,n;try{r=await yC(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 vC(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function VF(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(ch))throw new Error(`Incompatible auth server: does not support response type ${ch}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(uh))throw new Error(`Incompatible auth server: does not support code challenge method ${uh}`)}else a=new URL("/authorize",t);let c=await ih(),u=c.code_verifier,d=c.code_challenge;return a.searchParams.set("response_type",ch),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",d),a.searchParams.set("code_challenge_method",uh),a.searchParams.set("redirect_uri",String(n)),s&&a.searchParams.set("state",s),o&&a.searchParams.set("scope",o),o?.includes("offline_access")&&a.searchParams.append("prompt","consent"),i&&a.searchParams.set("resource",i.href),{authorizationUrl:a,codeVerifier:u}}function KF(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function _C(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=NF(n,d);DF(l,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await gC(u);return uC.parse(await u.json())}async function JF(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 _C(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function YF(t,e,{metadata:r,resource:n,authorizationCode:o,fetchFn:s}={}){let i=t.clientMetadata.scope,a;if(t.prepareTokenRequest&&(a=await t.prepareTokenRequest(i)),!a){if(!o)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!t.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let u=await t.codeVerifier();a=KF(o,u,t.redirectUrl)}let c=await t.clientInformation();return _C(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function XF(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 gC(i);return lC.parse(await i.json())}var $i=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Hc=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=qc(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new Ge("No auth provider");let e;try{e=await hr(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 Ge;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=zo(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 Tn(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}=No(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 $i(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=zr.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 Ge("No auth provider");if(await hr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ge("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}=No(o);if(this._resourceMetadataUrl=i,this._scope=a,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ge;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 ux=ji(ax(),1);import bh from"node:process";import{PassThrough as kU}from"node:stream";var CU=10*1024*1024,Zc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??CU}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),xU(r)}clear(){this._buffer=void 0}};function xU(t){return zr.parse(JSON.parse(t))}function cx(t){return JSON.stringify(t)+`
98
+ `}var EU=bh.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Bc(){let t={};for(let e of EU){let r=bh.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Wc=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Zc({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new kU)}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,ux.default)(this._serverParams.command,this._serverParams.args??[],{env:{...Bc(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:bh.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=cx(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var hx=ji(px(),1);function mx(t){if(t)try{return hx.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Vc=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Lc({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 DU={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Dt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Kc=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=qc(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??DU}async _authThenStart(){if(!this._authProvider)throw new Ge("No auth provider");let e;try{e=await hr(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 Ge;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=zo(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 Dt(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 Vc({onRetry:p=>{this._serverRetryMs=p}})).getReader();for(;;){let{value:p,done:h}=await d.read();if(h)break;if(p.id&&(i=p.id,a=!0,o?.(p.id)),!!p.data&&(!p.event||p.event==="message"))try{let m=zr.parse(JSON.parse(p.data));fn(m)&&(c=!0,s!==void 0&&(m.id=s)),this.onmessage?.(m)}catch(m){this.onerror?.(m)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(d){if(this.onerror?.(new Error(`SSE stream disconnected: ${d}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(p){this.onerror?.(new Error(`Failed to reconnect: ${p instanceof Error?p.message:String(p)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Ge("No auth provider");if(await hr(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ge("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:As(e)?e.id:void 0}).catch(p=>this.onerror?.(p));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let p=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Dt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:h,scope:m}=No(a);if(this._resourceMetadataUrl=h,this._scope=m,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ge;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:h,scope:m,error:y}=No(a);if(y==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Dt(403,"Server returned 403 after trying upscoping");if(m&&(this._scope=m),h&&(this._resourceMetadataUrl=h),this._lastUpscopingHeader=v??void 0,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ge;return this.send(e)}}throw new Dt(a.status,`Error POSTing to endpoint: ${p}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Jw(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(p=>this.onerror?.(p));return}let d=(Array.isArray(e)?e:[e]).filter(p=>"method"in p&&"id"in p&&p.id!==void 0).length>0,l=a.headers.get("content-type"),f=mx(l);if(d)if(f==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(f==="application/json"){let p=await a.json(),h=Array.isArray(p)?p.map(m=>zr.parse(m)):[zr.parse(p)];for(let m of h)this.onmessage?.(m)}else throw await a.body?.cancel(),new Dt(-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 Dt(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 gx(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 jU={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 yx(t){return{...Bc(),...jU,...t??{}}}function vx(){return Bc()}var Ph=class t extends Wc{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 gx(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new Ph(e)}var On=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},Ch=new $U;function xh(t,e){return Ch.run(t,e)}function IU(t){Ch.getStore()?.onFailure?.(t)}function yx({getHeaders:t,transport:e}){if(t)return async(r,n)=>{let o=r instanceof Request?r.headers:void 0,s=new Headers(o);for(let[u,d]of new Headers(n?.headers).entries())s.set(u,d);for(let[u,d]of Object.entries(t()))s.set(u,d);let i=await fetch(r,{...n,headers:s});if(i.ok||n?.method?.toUpperCase()!=="POST")return i;await i.body?.cancel().catch(()=>{});let a=Ch.getStore(),c=new On({status:i.status,transport:e,operation:a?.operation??"transport"});throw IU(c),c}}function vx(t,e){let r=yx({getHeaders:e.getHeaders,transport:"http"});return new Kc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function _x(t,e){let r=yx({getHeaders:e.getHeaders,transport:"sse"});return new Hc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function Sx(){return new Dc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var wx=Ds,bx=ke;function wt(t){return t instanceof On&&t.status===401||(t instanceof Dt||t instanceof $i)&&t.code===401}function Rx(t){return t instanceof $&&t.code===M.MethodNotFound}function kh(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var OU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function Px(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return OU.some(r=>e.includes(r))}function Cx(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function Eh(t){return t instanceof On&&t.transport==="http"&&t.status===404||t instanceof Dt&&t.code===404}var X=zU.child({prefix:"pi-mcp"});function NU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function DU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&NU(r,o)})}var LU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),jU=/^Node\.js v\d/,FU=/^[\w$.]*error[\w$]*:/i,xx=400,UU=63e3,kx=3,qU=/[\\/]lib[\\/]cli\.js/,HU="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.",Ix=Symbol("mcpReinitReported");function GU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,Ix,{value:!0,enumerable:!1,configurable:!0})}function ZU(t){return typeof t=="object"&&t!==null&&t[Ix]===!0}function WU(t){let e=t.filter(a=>!jU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>qU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return HU;let o=r.findIndex(a=>FU.test(a)),i=(o===-1?r.slice(-kx):r.slice(o,o+kx)).join(" / ");return i.length>xx?`${i.slice(0,xx)}\u2026`:i}function BU(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(LU,"").split(`
101
- `).map(s=>s.trim()).filter(s=>s.length>0),o=WU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var VU=6e5,KU=18e5,Ex=2147483647,JU=3e4,Tx=1e4,Ox=[250,1e3,2e3],zn=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"}},YU=250,Ax=3,XU=[200,500];function QU(t){for(let e of Object.values(t))if(ga(e))return!0;return!1}function zx(t){let e=new Set;for(let r of t.matchAll(hs))e.add(ya(r[0]));return[...e].sort()}function $h(t){return[...new Set(t)].sort()}function $x(t,e){return _y(e.map(r=>t?.[r]??"missing"))}function eq({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return $h([...e&&t?Ad(t):[],...n&&r?zx(r):[]])}var Jc="${augmentToken}";function tq(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 rq(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var Nx="(unknown uri)",Mh="unknown",Mx=/=+$/,nq=/\s+/g,oq=/[-_]/g,sq=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Nn(t,e){return typeof t=="string"?t:e}function Dx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function iq(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function aq(t){let e=t.replace(nq,"").replace(oq,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(Mx,"");if(r.toString("base64").replace(Mx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function Lx(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function cq(t){let e=Lx(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Nn(e.uri,Nx),n=Nn(e.mimeType,Mh);if(typeof e.blob=="string"&&iq(n)){let s=aq(e.blob);if(s!==void 0)return s}let o=Dx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function uq(t){let e=Nn(t.type,"unknown");if(e==="resource")return cq(t);if(e==="audio"){let r=Nn(t.mimeType,Mh),n=Dx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Nn(t.uri,Nx),n=Nn(t.name,""),o=Nn(t.mimeType,Mh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function dq(t){if(t.type!=="resource")return;let e=Lx(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&sq.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function lq(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=dq(t);return e||{type:"text",text:uq(t)}}function fq(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(lq(n))}return e}function pq(t){return dy(t,UU)}function hq(t,e){let r=fq(t);if(r.length===0){let o=pq(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 jx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),mq=new Set([502,503,504]),Ii=Ox.length+1,gq=2;function yq(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 vq(t){if(wt(t)||Eh(t)||t instanceof ft)return;let e=t?.cause?.code;if(typeof e=="string")return jx.has(e)?{totalAttempts:Ii}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:gq}:mq.has(r)?{totalAttempts:Ii}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Ii}:void 0}var _q=80,Sq=10,wq=/[^a-zA-Z0-9_.()-]/g,bq=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Yc(t){return t.replace(wq,"_").slice(0,_q)||"unknown"}function Rq(t){let e=yq(t);if(e!==void 0&&(/^\d{3}$/.test(e)||jx.has(e)))return e}function Ge(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=bq.has(e)?e:"Error",n=Rq(t);return n===void 0?r:`${r}(${n})`}function Th(t,e,r){return t instanceof ft?new ft(Yc(t.serverName),t.missingKeys.slice(0,Sq).map(Yc),void 0,t.reason).message:t instanceof On?t.message:`MCP ${r} ${e} failed (${Ge(t)})`}function Ah(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Yc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Xc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Qc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>kd(e))??[]}connect(){return this._disposing||this._disposed||this._status==="disabled"?Promise.resolve():this._connectPromise?this._connectPromise:(this._connectStartedAt=Date.now(),this._emitState("connecting"),this._connectPromise=this._doConnect().catch(e=>{X.warn(`MCP server "${this.name}" connect failed (${Ge(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=Th(r,"connect",this._config.type),o=this._config.type==="stdio"&&!wt(r)?kd(BU(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ge(r))}}async _connectWithRetries(){let e=Ii,r={available:!0};for(let n=1;n<=Ii;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=vq(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=(Ox[r-1]??0)+Math.floor(Math.random()*(YU+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ge(e)}; retrying in ${s}ms`),await on(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){return wt(e)&&this.hasRefreshEligibleOAuthCredential()&&!!this._usableToken()?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new zn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=Sx();this._client=s;let i;try{if(await xh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(wx,()=>{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=ie();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&nt(c,this.name),X.info(`MCP server "${this.name}" connected (${this._tools.length} tool(s))`),o}catch(a){throw await this._closeFailedInitialization(s,n),i??a}}async _closeFailedInitialization(e,r){if(this._client===e){this._client=void 0,this._activeTransport===r&&(this._activeTransport=void 0);try{await e.close()}catch(n){X.debug(`MCP server "${this.name}" close after failed connect attempt (${Ge(n)})`)}}}_recordConnectFailure(e,r,n=Th(e,r,this._config.type)){if(e instanceof ft){this._status="failed";let o=ie();Zo(o,this.name,e.reason,tr(o,this.name,this._config.id))}else if(e instanceof Mi||e instanceof zn)this._status="failed";else if(wt(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(wt(e)){this._status="auth_required";let o=ie(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=Th(e,r,this._config.type);Ed(Ah(o,Ge(e)),{server:this.name,op:r,transport:this._config.type})}this._lastError=n,this._client=void 0}_createTransport(){let e=this._config;switch(e.type){case"stdio":{let r=px(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=hx(this._resolvedEnv??e.env);return gx({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 _x(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=vx(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?QU(r):!1,o=e.type==="stdio"&&ga(e.command);if(!(n||o))return;let s=ie();if(!vy(s)){let a=eq({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new ft(this.name,a)}let i=gy(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 wy({configEnv:e,localEnv:n?mx():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${Ge(i)})`),new ft(this.name,Ad(e),i,"transient")}let s=$h([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new ft(this.name,s,void 0,$x(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await by(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${Ge(s)})`),new ft(this.name,zx(e),s,"transient")}let o=$h([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new ft(this.name,o,void 0,$x(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Jc)))return;let o;if(tq(e.url)){let i=ie().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Jc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Jc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${rq(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Jc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=ie();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=ie(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!ut(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}hasRefreshEligibleOAuthCredential(){let{config:e}=this;if(e.type!=="http"&&e.type!=="sse"||e.disabled||this._hostedCredentialProvenance!==void 0||!this._usableToken())return!1;if(e.auth==="oauth")return!0;let r=ie();return r.tokens.hasCredentialIdentity?.(this.name,Ut(r,this))===!0}async _maybeProactiveRefresh(){let e=ie(),r=e.tokens,{config:n}=this;(n.type==="http"||n.type==="sse")&&await r.ensureLoaded?.(this.name,Ut(e,this));let s=this._usableToken();s&&this.hasRefreshEligibleOAuthCredential()&&(s.accessToken&&!Xu(s)||e.shouldProactivelyRefreshTokens&&(s.refreshToken?await this._refreshTokenDeduped():is(s)&&e.tokens.markAuthRequired(this.name)))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=ie(),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:tr(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=W(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||!ut(this._config,s.config))return;let u=Ut(e.state,s),d=n===void 0&&u===void 0||Sr(n,u);try{if(a===e.token&&d){i.commit(this.name,r,n),Yr({state:e.state,name:this.name,revision:o});return}let l=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o,u);if(!l||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||!Sr(Ut(e.state,s),u)||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain||i.reconcileCredentialIdentity?.(this.name,a,u)!==!0)return;Yr({state:e.state,name:this.name,revision:l});let f=e.state.currentLoad?.latestPi;f&&J(f,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 H?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof H)&&ed(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&Zo(r.state,this.name,this._refreshFailureCategory(e,n),r.failureScope),X.warn(`MCP server "${this.name}" token refresh failed (${n?"permanent \u2014 auth required":"transient \u2014 will retry"}, ${Ge(e)})`),n&&o?{kind:"terminal_failure"}:{kind:"transient_failure"}}async _performTokenRefresh(e){if(!e.localRefreshEnabled)return{kind:"transient_failure"};if(!e.token?.refreshToken)return this._ownsRefresh(e)?(e.state.tokens.markAuthRequired(this.name),Zo(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=Ut(e.state,this),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await td(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,r),Yr({state:e.state,name:this.name,revision:s}),nt(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:Eh(e)}_reinitializeSession(){return this._reinitializingPromise===void 0&&(this._reinitializingPromise=this._doReinitializeSession().finally(()=>{this._reinitializingPromise=void 0})),this._reinitializingPromise}async _doReinitializeSession(){if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);if(this._config.type!=="http")throw new Error("Session re-initialization is only supported for Streamable HTTP servers");await this._client.close();let e=this._createHttpTransport(this._config.url,this._resolvedHeaders??this._config.headers??{});try{await this._client.connect(e)}catch(r){throw this._recordConnectFailure(r,"reinit"),r}X.info(`MCP server "${this.name}" re-initialized session`)}async _withSessionRetry(e){if(this._config.type!=="http")return e();try{return await e()}catch(r){let n=this._isSessionExpiredError(r),o=this._reinitializingPromise!==void 0;if(!(n||o))throw r;X.info(n?`MCP server "${this.name}" returned 404 (session expired); re-initializing and retrying`:`MCP server "${this.name}" call interrupted by a concurrent re-initialization; retrying once`);try{await this._reinitializeSession()}catch(s){throw X.error(`MCP server "${this.name}" session re-initialization failed (${Ge(s)})`),GU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new zn}async _withAuthRetry(e,r,n){let o=this._config,s=ie(),i=tr(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),xh({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!wt(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new Mi;if(this._hostedCredentialProvenance!==void 0)throw new zn;if(!this.hasRefreshEligibleOAuthCredential())throw this._markAuthRequired(d,i),d;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let f=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw wt(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=ie();Zo(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ge(e)),X.warn(`MCP server "${this.name}" still 401 after refresh \u2014 auth_required`))}_wireLivenessHandlers(){let e=this._client;e&&(e.onclose=()=>{this._handleTransportClosed(new Xc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Xc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},JU),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=ie(),r=tr(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=Ax&&n.outcome==="transient";i++)await on(XU[i-2]??0),n=await this._runProbe();let o=tr(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"&&nt(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 ${Ax} 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:Tx})},"ping",{preserveAuthErrorOnRefreshUnavailable:!0}),{ok:!0,outcome:"alive"}}catch(r){let n=this._classifyProbeError(r,e);if(n==="alive")return{ok:!0,outcome:"alive"};let o=`MCP startup verification failed (${Ge(r)})`,s=`MCP server "${this.name}" failed startup verification ping (${n}): ${o}`;return n==="transient"?X.debug(s):X.warn(s),{ok:!1,outcome:n,error:o,isAuthError:n==="authFailure"}}}_classifyProbeError(e,r){return r||!this._client||this._disposed||this._reinitializingPromise!==void 0?"transient":Rx(e)||kh(e)?"alive":wt(e)?"authFailure":Px(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:Tx})}catch(r){if(this._reinitializingPromise||this._disposed||kh(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return wt(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!wt(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!DU(this._tools,r);if(this._tools=r,n){X.info(`MCP server "${this.name}" tool list updated (${r.length} tool(s))`);try{this.onToolsChanged?.()}catch(o){X.warn(`MCP server "${this.name}" onToolsChanged handler threw (${Ge(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ge(e)}), keeping cached tools`)}}listTools(){return this._tools}async callTool(e,r,n){if(this._disposing||this._disposed)throw new Error(`MCP server "${this.name}" is being disposed`);if(this._status!=="success"||!this._client)throw new Error(`MCP server "${this.name}" is not connected (status: ${this._status})`);if(this._config.timeoutMs!==void 0&&this._config.timeoutMs>Ex)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${Ex}.`);let s={timeout:this._config.timeoutMs??VU,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??KU,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??{}},bx,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=hq(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 zn||e instanceof Mi)throw e;if(wt(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Yc(r),s=Ge(e),i=Cx(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw ZU(e)||Ed(Ah(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),Ah(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 Fx=Cq.child({prefix:"pi-mcp"}),xq=3,kq=6e4;function Eq(t,e){let r=Date.now(),n=r-kq,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=xq?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function Ux(t){nn(t),Xi(t)}async function Tq(t,e,r){if(!Eq(e,t)){Fx.warn(`MCP server "${t}" automatic restart rate-limited`);return}Fx.warn(`MCP server "${t}" wedged; recycling transport`),await Wr(t,e,r)}function eu(t,e,r){if(Aq(e)){Ux(t);return}qu(t,r),Zn(e)&&Ux(t)}function Aq(t){return Qo()||t.toolSearchLatched}function Qt(t,e,r){return _m(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function Ih(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,nt(t,e),t.authRefreshNeededReportKeys.delete(e),r}function $q(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name),a=o!==void 0&&i?.revision===o.revision,c=o!==void 0&&i?.domain===o.domain,u=o!==void 0&&i?.ownerDomain===o.ownerDomain,d=o!==void 0&&e.oauthCredentialDomains.get(r.name)===o.domain,l=o!==void 0&&Em(o.domain,r.id,o.ownerDomain);return o!==void 0&&s!==void 0&&i!==void 0&&a&&c&&u&&d&&l?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function Oh(t){let{state:e,config:r,generation:n}=t;return new Qc(r,$q({state:e,config:r,hostGeneration:n}))}function Ze(t,e,r="base"){t.configRevisions??=new Map,t.configDesiredRevisions??=new Map,t.configDesiredSources??=new Map;let o=Math.max(t.configRevisions.get(e)??0,t.configDesiredRevisions.get(e)??0)+1;return t.configDesiredRevisions.set(e,o),t.configDesiredSources.set(e,r),o}function zh(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 Nh(t,e,r){return t.configDesiredRevisions.get(e)===r}function qx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function Dh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Qt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit(Pq,c)},t.onWedged=()=>{if(!Qt(t,e,r))return;let i=r.currentLoad?.latestPi??n;Tq(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(!Qt(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(!Qt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&nt(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Qt(t,e,r)&&t.status==="success"&&eu(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Hu(i,t,e),i!==n&&Hu(n,t,e)}}async function Hx(t,e,r,n){let o=setTimeout(()=>{Qt(t,e,r)&&J(n(),r)},Fi);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Qt(t,e,r)&&J(n(),r)}}async function Gx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function tu(t,e){if(e.status!=="installed")return!1;let r=W(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function Mq(t){let{state:e,config:r,displaced:n,retirement:o}=t;zh(e,n.config),Jo(e,r.name),n.beginDisposal?.();try{let s=Eu(n.config,r)?Promise.resolve():dt(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function Iq(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=Pt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),Pe({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function Oq(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Qt(r,o,e)?a?.(n)===!1?(await Iq({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&eu(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 zq(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=W(e,r.name);if(!Nh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=Ih(e,r.name),l=Oh({state:e,config:r,generation:d});return Dh(l,d,e,o),Hi({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:Oq({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function Nq(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!Nh(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):W(r,a.name),l=Fn(a,s),f=Vo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>zq({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:i}),m=async()=>(f.displacedHost&&f.retirement?await Mq({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await xu(f.retirement),h());return f.retirement?m():h()}async function bt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??Ze(e,d.name)})).map(async d=>{try{let l=await Nq({intent:d,state:e,pi:r,sourceOwnership:n,sourceKind:s,activePi:i});return"connection"in l?l.connection:l}catch(l){return{status:"failed",config:d.config,error:l}}});if(c.length===0)return[];let u=setTimeout(()=>{J(i(),e)},Fi);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function Dq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!qx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);zh(e,s),Jo(e,t);let a=Pt({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(W(e,t)?.revision!==i.revision||!qx(e,t,n))return Pe({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=Ih(e,t),u=Oh({state:e,config:s,generation:c});if(Dh(u,c,e,r),!Hi({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await Hx(u,c,e,d),Qt(u,c,e)&&u.status==="success"&&eu(d(),e,u),!0}function Wr(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 Dq({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 Lq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;zh(e,n.config),Jo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Eu(n.config,o)?Promise.resolve():dt(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function Zx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=Gn(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=Ze(e,t),u=e.servers.get(t),d=u?Q(e,t,u):W(e,t),l={kind:"local",identity:a?.id??t},f=Vo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await Lq({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await xu(f.retirement),W(e,t)?.revision!==f.lease.revision||!Nh(e,t,c)){Pe({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){Pe({state:e,name:t,owner:l,revision:f.lease.revision}),J(s(),e);return}let p=Ih(e,t),h=Oh({state:e,config:a,generation:p});Dh(h,p,e,r),Hi({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await Hx(h,p,e,s),Qt(h,p,e)&&h.status==="success"&&eu(s(),e,h))}async function Oi(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Wr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as jq}from"@hermes/logger";var Lh=jq.child({prefix:"pi-mcp"}),Fq=1e6,Uq=1e3,qq=/^\d+$/;function Wx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function Dn(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"||!qq.test(e)||typeof r!="string"||r.length===0)return;let n=Cm(t);if(n.kind!=="invalid")return{revision:e.replace(/^0+(?=\d)/,""),domain:Wx(r),...n.kind==="valid"?{ownerDomain:n.ownerDomain}:{}}}function Hq(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:wr(o,n)>0?o:n}function Gq(t,e,r){if(t===void 0)return!0;let n=Wx(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain||r?.kind==="domain"&&(n.startsWith("private:")||n.startsWith("shared:"))&&e.domain.startsWith("recipient:")&&Rr(n)===r.domain&&Rr(e.domain)===r.domain?!0:r?.kind==="domain"&&!st(n)&&st(e.domain)&&Rr(n)===r.domain}function Zq(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 Lh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";let a=Rr(r.domain);if(i?.kind==="blocked"||i?.kind==="domain"&&r.ownerDomain!==void 0&&r.ownerDomain!==i.domain||i?.kind==="domain"&&r.ownerDomain===void 0&&!st(r.domain)&&a!==i.domain)return"reject";let c=n?.acceptedDomains?.get(t);if(!Gq(c,r,i))return"reject";let u=Hq(n?.acceptedRevisions,r.domain,s);if(u===void 0)return"apply";let d=wr(r.revision,u);return d>0||d===0&&c===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":d===0?"equal":"reject"}function Wq(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 Bq(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function Vq(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*Uq+Math.floor(t.access_token_expires_at.nanos/Fq):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret,...t.token_endpoint_auth_method===void 0?{}:{token_endpoint_auth_method:t.token_endpoint_auth_method}}}}function ru(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!Bq(s)){Lh.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=Dn(s),a=Zq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=Vq(s);if(Wq(t,o,c,i)){Lh.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 Bx=Kq.child({prefix:"pi-mcp"});function Jq(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 Yq(t,e,r){let n=Object.entries(t).filter(([o,s])=>{let i=Dn(s);if(i===void 0)return!1;let a=Xr(i);return i.ownerDomain!==void 0?a===`user:${e}`:o===r&&st(i.domain)||a===`user:${e}`});return n.length===1?n[0]?.[1]:void 0}async function Vx(t){let{pi:e,state:r,update:n}=t;if(Object.keys(n.credentials).length!==1){Bx.warn(`Targeted MCP credential update for config ${n.configId} must contain exactly one entry`);return}let o=Jq(r,n.configId),s=o?Yq(n.credentials,n.configId,o.server.config.name):void 0;if(!o||!s)return;let i=W(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||W(r,o.name)!==i)return;let c=ru(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let f=Dn(s);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Wr,l=t.report??J;await d(o.name,r,u).catch(f=>{Bx.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${f instanceof Error?f.name:"non-Error"}`)}),l(u,r),Te(r)}import{logger as dH}from"@hermes/logger";import{execFile as jh}from"node:child_process";import{win32 as Fh}from"node:path";import{logger as Xq}from"@hermes/logger";var Qq=5e3,eH=/^[a-z]:[\\/]/i,tH=/[<>:"|?*]/;function rH(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!eH.test(t)||!Fh.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||tH.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:Fh.join(Fh.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function nH(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function oH(t,e){switch(process.platform){case"darwin":return jh("open",[t],e);case"win32":{let r=rH();return r?jh(r,["-NoProfile","-NonInteractive","-EncodedCommand",nH(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return jh("xdg-open",[t],e)}}function Kx(t,e=Qq){let r=Xq.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let s=!1,i=null,a=setTimeout(()=>{if(!s){s=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{i?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);i=oH(o,c=>{s||(s=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as sH}from"node:http";function nu(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Jx(t){let e=nu(t.title),r=nu(t.heading),n=nu(t.message),o=t.details?nu(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 _x(t){let e={command:t.command,args:t.args,env:t.env,stderr:"pipe",...t.cwd?{cwd:t.cwd}:{}};return new Ph(e)}var On=class extends Error{status;transport;operation;constructor(e){super(`MCP ${e.transport} ${e.operation} request failed with HTTP ${e.status}`),this.status=e.status,this.transport=e.transport,this.operation=e.operation}},Ch=new LU;function xh(t,e){return Ch.run(t,e)}function FU(t){Ch.getStore()?.onFailure?.(t)}function Sx({getHeaders:t,transport:e}){if(t)return async(r,n)=>{let o=r instanceof Request?r.headers:void 0,s=new Headers(o);for(let[u,d]of new Headers(n?.headers).entries())s.set(u,d);for(let[u,d]of Object.entries(t()))s.set(u,d);let i=await fetch(r,{...n,headers:s});if(i.ok||n?.method?.toUpperCase()!=="POST")return i;await i.body?.cancel().catch(()=>{});let a=Ch.getStore(),c=new On({status:i.status,transport:e,operation:a?.operation??"transport"});throw FU(c),c}}function wx(t,e){let r=Sx({getHeaders:e.getHeaders,transport:"http"});return new Kc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function bx(t,e){let r=Sx({getHeaders:e.getHeaders,transport:"sse"});return new Hc(new URL(t),{requestInit:{headers:{...e.headers}},...r?{fetch:r}:{}})}function Rx(){return new Dc({name:"hermes-mcp-client",version:"0.1.0"},{capabilities:{}})}var Px=Ds,Cx=ke;function wt(t){return t instanceof On&&t.status===401||(t instanceof Dt||t instanceof $i)&&t.code===401}function xx(t){return t instanceof $&&t.code===M.MethodNotFound}function kh(t){return t instanceof Error&&t.name==="ZodError"&&Array.isArray(t.issues)}var UU=["ECONNRESET","ECONNREFUSED","socket hang up","EPIPE","ETIMEDOUT"];function kx(t){if(t instanceof $&&(t.code===M.RequestTimeout||t.code===M.ConnectionClosed))return!0;let e=t instanceof Error?t.message:String(t);return UU.some(r=>e.includes(r))}function Ex(t){return t instanceof $&&(t.code===M.MethodNotFound||t.code===M.InvalidRequest)}function Eh(t){return t instanceof On&&t.transport==="http"&&t.status===404||t instanceof Dt&&t.code===404}var X=qU.child({prefix:"pi-mcp"});function HU(t,e){return t.name===e.name&&(t.description??"")===(e.description??"")&&JSON.stringify(t.inputSchema??{})===JSON.stringify(e.inputSchema??{})}function GU(t,e){return t.length===e.length&&t.every((r,n)=>{let o=e[n];return o!==void 0&&HU(r,o)})}var ZU=new RegExp("\x1B\\[[0-9;]*[a-zA-Z]","g"),WU=/^Node\.js v\d/,BU=/^[\w$.]*error[\w$]*:/i,Tx=400,VU=63e3,Ax=3,KU=/[\\/]lib[\\/]cli\.js/,JU="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.",Nx=Symbol("mcpReinitReported");function YU(t){typeof t=="object"&&t!==null&&Object.defineProperty(t,Nx,{value:!0,enumerable:!1,configurable:!0})}function XU(t){return typeof t=="object"&&t!==null&&t[Nx]===!0}function QU(t){let e=t.filter(a=>!WU.test(a)),r=e.length>0?e:t;if(r.length===0)return;if(r.some(a=>KU.test(a))&&r.some(a=>a.includes("MODULE_NOT_FOUND")||a.includes("Cannot find module")))return JU;let o=r.findIndex(a=>BU.test(a)),i=(o===-1?r.slice(-Ax):r.slice(o,o+Ax)).join(" / ");return i.length>Tx?`${i.slice(0,Tx)}\u2026`:i}function eq(t,e){if(!e)return t;try{let r=e.consumeStderr();if(!r.trim())return t;let n=r.replace(ZU,"").split(`
101
+ `).map(s=>s.trim()).filter(s=>s.length>0),o=QU(n);return o?t?`${t}: ${o}`:o:t}catch{return t}}var tq=6e5,rq=18e5,$x=2147483647,nq=3e4,Mx=1e4,Dx=[250,1e3,2e3],zn=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"}},oq=250,Ix=3,sq=[200,500];function iq(t){for(let e of Object.values(t))if(ga(e))return!0;return!1}function Lx(t){let e=new Set;for(let r of t.matchAll(hs))e.add(ya(r[0]));return[...e].sort()}function $h(t){return[...new Set(t)].sort()}function Ox(t,e){return by(e.map(r=>t?.[r]??"missing"))}function aq({source:t,sourceHasSecretRef:e,command:r,commandHasSecretRef:n}){return $h([...e&&t?Ad(t):[],...n&&r?Lx(r):[]])}var Jc="${augmentToken}";function cq(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 uq(t){try{let e=new URL(t);return`${e.protocol}//${e.hostname}`}catch{return"<invalid URL>"}}var jx="(unknown uri)",Mh="unknown",zx=/=+$/,dq=/\s+/g,lq=/[-_]/g,fq=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function Nn(t,e){return typeof t=="string"?t:e}function Fx(t){return typeof t=="string"?Buffer.from(t,"base64").length:0}function pq(t){let e=t.toLowerCase();return e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+json")||e.endsWith("+xml")}function hq(t){let e=t.replace(dq,"").replace(lq,s=>s==="-"?"+":"/"),r=Buffer.from(e,"base64"),n=e.replace(zx,"");if(r.toString("base64").replace(zx,"")!==n)return;let o=r.toString("utf-8");return o.length>0?o:void 0}function Ux(t){return t.resource&&typeof t.resource=="object"?t.resource:void 0}function mq(t){let e=Ux(t);if(!e)return"[MCP resource with no contents]";if(typeof e.text=="string")return e.text;let r=Nn(e.uri,jx),n=Nn(e.mimeType,Mh);if(typeof e.blob=="string"&&pq(n)){let s=hq(e.blob);if(s!==void 0)return s}let o=Fx(e.blob);return`[MCP resource ${r} (${n}), ${o} bytes of binary content not shown]`}function gq(t){let e=Nn(t.type,"unknown");if(e==="resource")return mq(t);if(e==="audio"){let r=Nn(t.mimeType,Mh),n=Fx(t.data);return`[MCP audio content (${r}), ${n} bytes not shown]`}if(e==="resource_link"){let r=Nn(t.uri,jx),n=Nn(t.name,""),o=Nn(t.mimeType,Mh);return`[MCP resource link ${n?`${n} `:""}${r} (${o})]`}return`[MCP content of unsupported type "${e}" was omitted]`}function yq(t){if(t.type!=="resource")return;let e=Ux(t);if(!e)return;let{blob:r,mimeType:n}=e;if(typeof r=="string"&&typeof n=="string"&&fq.has(n.toLowerCase()))return{type:"image",mimeType:n,data:r}}function vq(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=yq(t);return e||{type:"text",text:gq(t)}}function _q(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(vq(n))}return e}function Sq(t){return py(t,VU)}function wq(t,e){let r=_q(t);if(r.length===0){let o=Sq(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 qx=new Set(["UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","ECONNREFUSED","ECONNRESET","EPIPE","ENOTFOUND","EAI_AGAIN","ETIMEDOUT"]),bq=new Set([502,503,504]),Ii=Dx.length+1,Rq=2;function Pq(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 Cq(t){if(wt(t)||Eh(t)||t instanceof ft)return;let e=t?.cause?.code;if(typeof e=="string")return qx.has(e)?{totalAttempts:Ii}:void 0;let r=t?.status??t?.code;return typeof r=="number"?r===524?{totalAttempts:Rq}:bq.has(r)?{totalAttempts:Ii}:void 0:t instanceof TypeError&&t.message==="fetch failed"?{totalAttempts:Ii}:void 0}var xq=80,kq=10,Eq=/[^a-zA-Z0-9_.()-]/g,Tq=new Set(["Error","McpError","McpSecretResolutionError","McpTransportClosedError","McpTransportFailure","MalformedRefreshResponseError","RefreshHttpError","SseError","StreamableHTTPError","TypeError","ZodError"]);function Yc(t){return t.replace(Eq,"_").slice(0,xq)||"unknown"}function Aq(t){let e=Pq(t);if(e!==void 0&&(/^\d{3}$/.test(e)||qx.has(e)))return e}function Ze(t){if(!(t instanceof Error))return"unknown";let e=t.constructor.name,r=Tq.has(e)?e:"Error",n=Aq(t);return n===void 0?r:`${r}(${n})`}function Th(t,e,r){return t instanceof ft?new ft(Yc(t.serverName),t.missingKeys.slice(0,kq).map(Yc),void 0,t.reason).message:t instanceof On?t.message:`MCP ${r} ${e} failed (${Ze(t)})`}function Ah(t,e){let r=new Error(t);return Object.defineProperty(r,"name",{value:Yc(e),configurable:!0}),r.stack=`${r.name}: ${t}`,r}var Xc=class extends Error{operation="transport";transport;kind;constructor(e,r){super(`MCP ${e} transport ${r}`),this.transport=e,this.kind=r}},Qc=class{name;_config;_hostedCredentialProvenance;_client;_stdioTransport;_status;_lastError;_tools=[];_connectPromise;_connectStartedAt;_refreshPromise;_refreshPersisting=!1;_disposing=!1;_disposed=!1;_resolvedEnv;_resolvedHeaders;_resolvedCommand;onStateChange;_lastEmittedState;_activeTransport;_reinitializingPromise;_inFlightCalls=new Set;_wedgeRecoveryOwners=new Set;_wedgePending=!1;_wedgeRequired=!1;_heartbeatTimer;_lastProbeResult;onWedged;onAuthRefreshNeeded;onAuthRefreshCleared;onToolsChanged;onToolsWithdraw;constructor(e,r){this._config=e,this._hostedCredentialProvenance=r?Object.freeze({...r}):void 0,this.name=e.name,this._status=e.disabled?"disabled":"initializing"}_emitState(e,r){if(e!==this._lastEmittedState){this._lastEmittedState=e;try{this.onStateChange?.(e,r)}catch{}}}get status(){return this._status}get config(){return this._config}get hostedCredentialProvenance(){return this._hostedCredentialProvenance}get lastError(){return this._lastError}get connectStartedAt(){return this._connectStartedAt}get tools(){return this._tools}getLogHistory(){return this._stdioTransport?.getLogHistory().map(e=>kd(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 (${Ze(e)})`)}),this._connectPromise)}async _doConnect(){let e;try{e=await this._connectWithRetries()}catch(r){if(this._disposed)return;let n=Th(r,"connect",this._config.type),o=this._config.type==="stdio"&&!wt(r)?kd(eq(n,e??this._stdioTransport)):n;this._recordConnectFailure(r,"connect",o),this._emitState(this._status==="auth_required"?"auth_required":"failed",Ze(r))}}async _connectWithRetries(){let e=Ii,r={available:!0};for(let n=1;n<=Ii;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=Cq(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=(Dx[r-1]??0)+Math.floor(Math.random()*(oq+1));X.warn(`MCP server "${this.name}" connect attempt ${r}/${n} failed with transient ${Ze(e)}; retrying in ${s}ms`),await on(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){return wt(e)&&this.hasRefreshEligibleOAuthCredential()&&!!this._usableToken()?.refreshToken}async _recoverStartupAuthentication(e,r){if(r.available=!1,this._disposed)return"disposed";let n=await this._refreshTokenDeduped();if(this._disposed)return"disposed";if(n.kind==="refreshed")return"retry";throw n.kind==="transient_failure"?new zn:e}async _initializeFreshClient(e){let r=this._config,n=this._createTransport(),o=r.type==="stdio"?n:void 0;o&&(this._stdioTransport=o);let s=Rx();this._client=s;let i;try{if(await xh({operation:"connect",onFailure:u=>{i=u}},()=>s.connect(n)),this._disposed)return await this._closeFailedInitialization(s,n),o;s.setNotificationHandler(Px,()=>{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=ie();return c.tokens.clearAuthRequired(this.name),(c.servers.get(this.name)===void 0||c.servers.get(this.name)===this)&&nt(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 (${Ze(n)})`)}}}_recordConnectFailure(e,r,n=Th(e,r,this._config.type)){if(e instanceof ft){this._status="failed";let o=ie();Zo(o,this.name,e.reason,tr(o,this.name,this._config.id))}else if(e instanceof Mi||e instanceof zn)this._status="failed";else if(wt(e)&&this._isHostedAccessTokenOnly())this._status="failed",this.onAuthRefreshNeeded?.();else if(wt(e)){this._status="auth_required";let o=ie(),s=o.servers.get(this.name);(s===void 0||s===this)&&o.tokens.markAuthRequired(this.name)}else{this._status="failed";let o=Th(e,r,this._config.type);Ed(Ah(o,Ze(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=gx(this._resolvedCommand?{...e,command:this._resolvedCommand}:e),n=yx(this._resolvedEnv??e.env);return _x({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 bx(e.url,{headers:this._resolvedHeaders??e.headers??{},getHeaders:()=>this._buildAuthHeaders()});default:return e}}_createHttpTransport(e,r){let n=wx(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?iq(r):!1,o=e.type==="stdio"&&ga(e.command);if(!(n||o))return;let s=ie();if(!wy(s)){let a=aq({source:r,sourceHasSecretRef:n,command:e.type==="stdio"?e.command:void 0,commandHasSecretRef:o});throw new ft(this.name,a)}let i=_y(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 Py({configEnv:e,localEnv:n?vx():{},getSecret:r})}catch(i){throw X.error(`MCP server "${this.name}" secret resolution failed (${Ze(i)})`),new ft(this.name,Ad(e),i,"transient")}let s=$h([...o.unresolvedKeys,...o.emptyKeys]);if(s.length>0)throw new ft(this.name,s,void 0,Ox(o.failureReasons,s));n?this._resolvedEnv=o.resolved:this._resolvedHeaders=o.resolved}async _resolveCommandSecretRefs(e,r){let n;try{n=await Cy(e,r)}catch(s){throw X.error(`MCP server "${this.name}" command secret resolution failed (${Ze(s)})`),new ft(this.name,Lx(e),s,"transient")}let o=$h([...n.unresolvedKeys,...n.emptyKeys]);if(o.length>0)throw new ft(this.name,o,void 0,Ox(n.failureReasons,o));this._resolvedCommand=n.resolved}_expandAugmentToken(){let e=this._config;if(e.type!=="http"&&e.type!=="sse")return;let r=e.headers;if(!r||!Object.values(r).some(i=>i.includes(Jc)))return;let o;if(cq(e.url)){let i=ie().credentials?.apiKey;i?o=i:this._recordTokenDiagnostic(`${Jc} in a header but no Augment credentials are available; sending the literal placeholder`,"warn")}else this._recordTokenDiagnostic(`${Jc} in a header is only expanded for https augmentcode.com / *.augmentcode.com URLs; "${uq(e.url)}" does not qualify, sending the literal placeholder`,"error");if(o===void 0)return;let s={};for(let[i,a]of Object.entries(r))s[i]=a.replaceAll(Jc,o);this._resolvedHeaders=s}_recordTokenDiagnostic(e,r){let n=ie();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=ie(),r=e.tokens.get(this.name),n=e.preservedCredentialIdentities?.get(this.name);if(!(n&&!ut(n,this._config)))return r}_buildAuthHeaders(){let e=this._usableToken();return e?.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{}}hasRefreshEligibleOAuthCredential(){let{config:e}=this;if(e.type!=="http"&&e.type!=="sse"||e.disabled||this._hostedCredentialProvenance!==void 0||!this._usableToken())return!1;if(e.auth==="oauth")return!0;let r=ie();return r.tokens.hasCredentialIdentity?.(this.name,Ut(r,this))===!0}async _maybeProactiveRefresh(){let e=ie(),r=e.tokens,{config:n}=this;(n.type==="http"||n.type==="sse")&&await r.ensureLoaded?.(this.name,Ut(e,this));let s=this._usableToken();s&&this.hasRefreshEligibleOAuthCredential()&&(s.accessToken&&!Xu(s)||e.shouldProactivelyRefreshTokens&&(s.refreshToken?await this._refreshTokenDeduped():is(s)&&e.tokens.markAuthRequired(this.name)))}refreshTokenIfPossible(){return this._refreshTokenDeduped()}getRefreshInFlight(){return this._refreshPromise}_refreshTokenDeduped(){if(this._disposing||this._disposed)return Promise.resolve({kind:"transient_failure"});let e=ie(),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:tr(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=W(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||!ut(this._config,s.config))return;let u=Ut(e.state,s),d=n===void 0&&u===void 0||Sr(n,u);try{if(a===e.token&&d){i.commit(this.name,r,n),Yr({state:e.state,name:this.name,revision:o});return}let l=await i.restoreAfterSupersededRefresh(this.name,r,a,n,o,u);if(!l||e.state.tokens!==i||e.state.servers.get(this.name)!==s||i.get(this.name)!==a||!Sr(Ut(e.state,s),u)||e.state.credentialRevisions.get(this.name)?.revision!==c?.revision||e.state.credentialRevisions.get(this.name)?.domain!==c?.domain||i.reconcileCredentialIdentity?.(this.name,a,u)!==!0)return;Yr({state:e.state,name:this.name,revision:l});let f=e.state.currentLoad?.latestPi;f&&J(f,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 H?"cannot_persist":"refresh_transient"}_handleRefreshFailure(e,r){let n=!(e instanceof H)&&ed(e),o=this._ownsRefresh(r);return n&&o&&r.state.tokens.markAuthRequired(this.name),o&&Zo(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"}, ${Ze(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),Zo(e.state,this.name,"auth_terminal",e.failureScope),{kind:"terminal_failure"}):{kind:"transient_failure"};try{let r=Ut(e.state,this),n=await e.tokenStore.captureRefreshIdentityVersion(r);if(!this._ownsRefresh(e))return{kind:"transient_failure"};let o=await td(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,r),Yr({state:e.state,name:this.name,revision:s}),nt(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:Eh(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 (${Ze(s)})`),YU(r),r}return await e()}}_throwRefreshUnavailable(e,r,n){throw n&&!r?e:new zn}async _withAuthRetry(e,r,n){let o=this._config,s=ie(),i=tr(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),xh({operation:r,onFailure:a?u=>{a.failure=u}:void 0},e));try{let u=await c();return this._clearHostedAuthFailure(),u}catch(u){let d=a?.failure??u;if(this._disposed||!wt(d))throw d;let l=n?.startupAuthRefreshBudget;if(this._isHostedAccessTokenOnly())throw this.onAuthRefreshNeeded?.(),new Mi;if(this._hostedCredentialProvenance!==void 0)throw new zn;if(!this.hasRefreshEligibleOAuthCredential())throw this._markAuthRequired(d,i),d;if(l&&!l.available)throw this._markAuthRequired(d,i),d;X.debug(`MCP server "${this.name}" got 401, attempting token refresh + retry`);let f=s.shouldProactivelyRefreshTokens;if(l){if(await this._recoverStartupAuthentication(d,l)==="disposed")throw d}else{let p=await this._refreshTokenDeduped();if(this._disposed)throw d;if(p.kind==="transient_failure"&&this._throwRefreshUnavailable(d,f,n?.preserveAuthErrorOnRefreshUnavailable===!0),p.kind==="terminal_failure")throw this._status="auth_required",d}try{let p=await c();return this._clearHostedAuthFailure(),p}catch(p){let h=a?.failure??p;throw wt(h)&&this._markAuthRequired(h,i),h}}}_clearHostedAuthFailure(){this._isHostedAccessTokenOnly()&&this.onAuthRefreshCleared?.()}_isHostedAccessTokenOnly(){return this._hostedCredentialProvenance?.kind==="accepted"&&this._hostedCredentialProvenance.hostedAccessTokenOnly}_markAuthRequired(e,r){let n=ie();Zo(n,this.name,"auth_terminal",r)&&(this._status="auth_required",n.tokens.markAuthRequired(this.name),this._emitState("auth_required",Ze(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 Xc(this._config.type,"closed"))},e.onerror=()=>{this._handleTransportClosed(new Xc(this._config.type,"error"))})}_startHeartbeat(){this._heartbeatTimer===void 0&&(this._heartbeatTimer=setInterval(()=>{this._sendHeartbeat()},nq),this._heartbeatTimer.unref?.())}_stopHeartbeat(){this._heartbeatTimer!==void 0&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=void 0)}async probe(){let e=ie(),r=tr(e,this.name,this._config.id),n=await this._runProbe();for(let i=2;i<=Ix&&n.outcome==="transient";i++)await on(sq[i-2]??0),n=await this._runProbe();let o=tr(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"&&nt(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 ${Ix} 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:Mx})},"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 (${Ze(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":xx(e)||kh(e)?"alive":wt(e)?"authFailure":kx(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:Mx})}catch(r){if(this._reinitializingPromise||this._disposed||kh(r))return;X.warn(`MCP server "${this.name}" failed liveness ping; in-flight tool calls are treated as wedged`),this._failInFlightCalls(new Error(`MCP server "${this.name}" is unresponsive (liveness ping failed)`))}}_handleTransportClosed(e){this._reinitializingPromise||this._disposed||(this._stopHeartbeat(),this._failInFlightCalls(e))}_wedgeRecoveryOwnership(e){let r=e.failure;return wt(r)?(this._wedgeRecoveryOwners.add(e),"recoverable"):this._isSessionExpiredError(r)?(e.sessionRecoveryOwned=!0,this._wedgeRecoveryOwners.add(e),"recoverable"):this._wedgeRecoveryOwners.has(e)?"owned":"none"}_settleInFlightCall(e,r,n){let o=this._releaseWedgeRecoveryOwner(e,r,n);e.failure=void 0,this._inFlightCalls.delete(e),o&&this.onWedged?.()}_releaseWedgeRecoveryOwner(e,r,n){if(!this._wedgeRecoveryOwners.delete(e)||(!r&&e.sessionRecoveryOwned&&!wt(n)&&(this._wedgeRequired=!0),this._wedgeRecoveryOwners.size!==0))return!1;let o=this._wedgePending&&this._wedgeRequired;return this._wedgePending=!1,this._wedgeRequired=!1,o}_failInFlightCalls(e,r=!0){let n=[...this._inFlightCalls].filter(c=>!c.livenessRejected);if(n.length===0)return;if(!r){for(let c of n)c.livenessRejected=!0,c.reject(e);X.warn(`MCP server "${this.name}" failing ${n.length} in-flight tool call(s)`);return}let o=n.map(c=>({call:c,state:this._wedgeRecoveryOwnership(c)})),s=o.some(({state:c})=>c==="recoverable"),i=!1;for(let{call:c,state:u}of o)u==="recoverable"||u==="owned"&&s||(c.livenessRejected=!0,i=!0,c.reject(c.failure??e));let a=n.filter(c=>c.livenessRejected).length;X.warn(`MCP server "${this.name}" failing ${a} in-flight tool call(s)`),this._wedgeRecoveryOwners.size>0?(this._wedgePending=!0,this._wedgeRequired||=i):i&&this.onWedged?.()}_listToolsWithAuthRetry(e){return this._withAuthRetry(()=>{if(!this._client)throw new Error(`MCP server "${this.name}" client is gone`);return this._client.listTools()},"list_tools",{startupAuthRefreshBudget:e})}async _refreshTools(){if(!(this._disposed||this._status!=="success"||!this._client))try{let e=await this._listToolsWithAuthRetry();if(this._disposed)return;let r=e.tools??[],n=!GU(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 (${Ze(o)})`)}}}catch(e){X.warn(`MCP server "${this.name}" tools/list_changed refresh failed (${Ze(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>$x)throw new Error(`MCP server "${this.name}" timeoutMs is too large: ${this._config.timeoutMs}, max is ${$x}.`);let s={timeout:this._config.timeoutMs??tq,signal:n,resetTimeoutOnProgress:!0,maxTotalTimeout:this._config.timeoutMs??rq,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??{}},Cx,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=wq(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 zn||e instanceof Mi)throw e;if(wt(e))throw new Error(`Authentication failed for MCP server "${this.name}". Reconnect "${this.name}" in MCP settings before retrying this tool.`);let o=Yc(r),s=Ze(e),i=Ex(e)&&/[^a-zA-Z0-9_-]/.test(r)?` The tool name "${o}" contains characters that some servers do not support; letters, digits, underscores, and hyphens are portable.`:"",a=`MCP tool "${o}" failed (${s}).${i}`;throw XU(e)||Ed(Ah(a,s),{server:this.name,op:"tool_call",transport:this._config.type,tool:o}),Ah(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 Hx=Mq.child({prefix:"pi-mcp"}),Iq=3,Oq=6e4;function zq(t,e){let r=Date.now(),n=r-Oq,o=(t.restartHistory.get(e)??[]).filter(s=>s>=n);return o.length>=Iq?(t.restartHistory.set(e,o),!1):(o.push(r),t.restartHistory.set(e,o),!0)}function Gx(t){nn(t),Xi(t)}async function Nq(t,e,r){if(!zq(e,t)){Hx.warn(`MCP server "${t}" automatic restart rate-limited`);return}Hx.warn(`MCP server "${t}" wedged; recycling transport`),await Wr(t,e,r)}function eu(t,e,r){if(Dq(e)){Gx(t);return}qu(t,r),Zn(e)&&Gx(t)}function Dq(t){return Qo()||t.toolSearchLatched}function Qt(t,e,r){return bm(r,t.name,t)&&r.serverGenerations?.get(t.name)===e}function Ih(t,e){t.serverGenerations??=new Map;let r=(t.serverGenerations.get(e)??0)+1;return t.serverGenerations.set(e,r),t.statusFailureCategories??=new Map,nt(t,e),t.authRefreshNeededReportKeys.delete(e),r}function Lq(t){let{state:e,config:r,hostGeneration:n}=t;if(r.type!=="http"&&r.type!=="sse"||r.auth!=="oauth"||r.registrySource===void 0||r.id===void 0)return;let o=e.credentialRevisions.get(r.name),s=e.tokens.get(r.name),i=e.hostedCredentialOwnership?.get(r.name),a=o!==void 0&&i?.revision===o.revision,c=o!==void 0&&i?.domain===o.domain,u=o!==void 0&&i?.ownerDomain===o.ownerDomain,d=o!==void 0&&e.oauthCredentialDomains.get(r.name)===o.domain,l=o!==void 0&&$m(o.domain,r.id,o.ownerDomain);return o!==void 0&&s!==void 0&&i!==void 0&&a&&c&&u&&d&&l?Object.freeze({kind:"accepted",configId:r.id,credentialRevision:o.revision,credentialRevisionDomain:o.domain,hostGeneration:n,hostedAccessTokenOnly:i.accessTokenOnly}):i===void 0&&e.shouldProactivelyRefreshTokens?void 0:Object.freeze({kind:"incomplete",configId:r.id,hostGeneration:n})}function Oh(t){let{state:e,config:r,generation:n}=t;return new Qc(r,Lq({state:e,config:r,hostGeneration:n}))}function We(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 zh(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 Nh(t,e,r){return t.configDesiredRevisions.get(e)===r}function Zx(t,e,r){return(t.configRevisions.get(e)??0)===r&&(t.configDesiredRevisions?.get(e)??r)===r}function Dh(t,e,r,n){t.onStateChange=(i,a)=>{if(!Qt(t,e,r))return;let c={server:t.name,state:i,...a===void 0?{}:{errorType:a}};n.events.emit($q,c)},t.onWedged=()=>{if(!Qt(t,e,r))return;let i=r.currentLoad?.latestPi??n;Nq(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(!Qt(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(!Qt(t,e,r)||!s)return;let i=r.statusFailureCategories.get(t.name);typeof i=="object"&&i.category==="auth_refresh_needed"&&nt(r,t.name,s)&&J(r.currentLoad?.latestPi??n,r)},t.onToolsChanged=()=>{Qt(t,e,r)&&t.status==="success"&&eu(r.currentLoad?.latestPi??n,r,t)},t.onToolsWithdraw=()=>{let i=r.currentLoad?.latestPi??n;Hu(i,t,e),i!==n&&Hu(n,t,e)}}async function Wx(t,e,r,n){let o=setTimeout(()=>{Qt(t,e,r)&&J(n(),r)},Fi);typeof o.unref=="function"&&o.unref();try{await t.connect()}finally{clearTimeout(o),Qt(t,e,r)&&J(n(),r)}}async function Bx(t){let e=[...t.servers.values()].filter(r=>r.status==="success");e.length!==0&&await Promise.all(e.map(r=>r.probe()))}function tu(t,e){if(e.status!=="installed")return!1;let r=W(t,e.config.name);return r?.revision===e.leaseRevision&&r.host?.config===e.config}async function jq(t){let{state:e,config:r,displaced:n,retirement:o}=t;zh(e,n.config),Jo(e,r.name),n.beginDisposal?.();try{let s=Eu(n.config,r)?Promise.resolve():dt(e,r.name,n.config.id,n.config),a=(await Promise.allSettled([s,n.dispose({strict:!0})])).find(c=>c.status==="rejected");if(a)throw a.reason;we({state:e,name:r.name,retirement:o,result:{status:"retired"}})}catch(s){throw we({state:e,name:r.name,retirement:o,result:{status:"failed",error:s}}),s}}async function Fq(t){let{state:e,server:r,owner:n,leaseRevision:o}=t,s=Pt({state:e,name:r.name,owner:n,revision:o,host:r});if(s){r.beginDisposal?.();try{await r.dispose({strict:!0}),we({state:e,name:r.name,retirement:s,result:{status:"retired"}}),Pe({state:e,name:r.name,owner:n,revision:o})}catch(i){throw we({state:e,name:r.name,retirement:s,result:{status:"failed",error:i}}),i}}}async function Uq(t){let{state:e,server:r,config:n,generation:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t;return await r.connect(),Qt(r,o,e)?a?.(n)===!1?(await Fq({state:e,server:r,owner:s,leaseRevision:i}),{status:"superseded",config:n}):(r.status==="success"&&eu(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 qq(t){let{state:e,config:r,configRevision:n,pi:o,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c}=t,u=W(e,r.name);if(!Nh(e,r.name,n)||u?.revision!==i||a?.(r)===!1)return Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r};e.configRevisions.set(r.name,n);let d=Ih(e,r.name),l=Oh({state:e,config:r,generation:d});return Dh(l,d,e,o),Hi({state:e,name:r.name,owner:s,revision:i,host:l})?{connection:Uq({state:e,server:l,config:r,generation:d,owner:s,leaseRevision:i,sourceOwnership:a,activePi:c})}:(Pe({state:e,name:r.name,owner:s,revision:i}),{status:"superseded",config:r})}function Hq(t){let{intent:e,state:r,pi:n,sourceOwnership:o,sourceKind:s,activePi:i}=t,{config:a,revision:c}=e;if(o?.(a)===!1||!Nh(r,a.name,c))return{status:"superseded",config:a};let u=r.servers.get(a.name),d=u?Q(r,a.name,u):W(r,a.name),l=Fn(a,s),f=Vo({state:r,name:a.name,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return{status:"collision",config:a};let p=f.lease.revision,h=()=>qq({state:r,config:a,configRevision:c,pi:n,owner:l,leaseRevision:p,sourceOwnership:o,activePi:i}),m=async()=>(f.displacedHost&&f.retirement?await jq({state:r,config:a,displaced:f.displacedHost,retirement:f.retirement}):await xu(f.retirement),h());return f.retirement?m():h()}async function bt(t,e,r,n,o,s){let i=()=>e.currentLoad?.latestPi??r,c=t.map(d=>({config:d,revision:o?.get(d.name)??We(e,d.name)})).map(async d=>{try{let l=await Hq({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)},Fi);typeof u.unref=="function"&&u.unref();try{return await Promise.all(c)}finally{clearTimeout(u)}}async function Gq({name:t,state:e,pi:r,configRevision:n}){let o=e.servers.get(t);if(!o||e.servers.get(t)!==o||!Zx(e,t,n))return!1;let s=o.config,i=Q(e,t,o);zh(e,s),Jo(e,t);let a=Pt({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(W(e,t)?.revision!==i.revision||!Zx(e,t,n))return Pe({state:e,name:t,owner:i.owner,revision:i.revision}),!1;let c=Ih(e,t),u=Oh({state:e,config:s,generation:c});if(Dh(u,c,e,r),!Hi({state:e,name:t,owner:i.owner,revision:i.revision,host:u}))return!1;let d=()=>e.currentLoad?.latestPi??r;return await Wx(u,c,e,d),Qt(u,c,e)&&u.status==="success"&&eu(d(),e,u),!0}function Wr(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 Gq({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 Zq(t){let{state:e,name:r,existing:n,config:o,retirement:s}=t;zh(e,n.config),Jo(e,r),n.beginDisposal?.();try{let i=o!==void 0&&Eu(n.config,o)?Promise.resolve():dt(e,r,n.config.id,n.config),c=(await Promise.allSettled([i,n.dispose({strict:!0})])).find(u=>u.status==="rejected");if(c)throw c.reason;s&&we({state:e,name:r,retirement:s,result:{status:"retired"}})}catch(i){throw s&&we({state:e,name:r,retirement:s,result:{status:"failed",error:i}}),i}}async function Vx(t,e,r,n,o){let s=()=>e.currentLoad?.latestPi??r,{servers:i}=Gn(n,o,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides),a=i.find(m=>m.name===t),c=We(e,t),u=e.servers.get(t),d=u?Q(e,t,u):W(e,t),l={kind:"local",identity:a?.id??t},f=Vo({state:e,name:t,owner:l,expectedRevision:d?.revision,expectedHost:d?.host});if(!f)return;if(u&&await Zq({state:e,name:t,existing:u,config:a,retirement:f.retirement}),f.retirement&&await xu(f.retirement),W(e,t)?.revision!==f.lease.revision||!Nh(e,t,c)){Pe({state:e,name:t,owner:l,revision:f.lease.revision});return}if(e.configRevisions.set(t,c),!a){Pe({state:e,name:t,owner:l,revision:f.lease.revision}),J(s(),e);return}let p=Ih(e,t),h=Oh({state:e,config:a,generation:p});Dh(h,p,e,r),Hi({state:e,name:t,owner:l,revision:f.lease.revision,host:h})&&(await Wx(h,p,e,s),Qt(h,p,e)&&h.status==="success"&&eu(s(),e,h))}async function Oi(t,e,r){e.reconnecting=!0;try{await Promise.all(t.map(n=>Wr(n,e,r)))}finally{e.reconnecting=!1}}import{logger as Wq}from"@hermes/logger";var Lh=Wq.child({prefix:"pi-mcp"}),Bq=1e6,Vq=1e3,Kq=/^\d+$/;function Kx(t){return t.startsWith("user:")?`private:${t.slice(5)}`:t}function Dn(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t.credential_revision??t.credentialRevision,r=t.credential_revision_domain??t.credentialRevisionDomain;if(typeof e!="string"||!Kq.test(e)||typeof r!="string"||r.length===0)return;let n=Em(t);if(n.kind!=="invalid")return{revision:e.replace(/^0+(?=\d)/,""),domain:Kx(r),...n.kind==="valid"?{ownerDomain:n.ownerDomain}:{}}}function Jq(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:wr(o,n)>0?o:n}function Yq(t,e,r){if(t===void 0)return!0;let n=Kx(t);return n===e.domain||r?.kind==="domain"&&e.ownerDomain===r.domain||r?.kind==="domain"&&(n.startsWith("private:")||n.startsWith("shared:"))&&e.domain.startsWith("recipient:")&&Rr(n)===r.domain&&Rr(e.domain)===r.domain?!0:r?.kind==="domain"&&!st(n)&&st(e.domain)&&Rr(n)===r.domain}function Xq(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 Lh.warn(`Skipping MCP OAuth credentials for "${t}": invalid credential revision or domain`),"reject";let i=n?.expectedDomains?.get(t);if(r===void 0)return n?.requireRevision===!0||i!==void 0||n?.acceptedDomains?.has(t)===!0?"reject":"apply";let a=Rr(r.domain);if(i?.kind==="blocked"||i?.kind==="domain"&&r.ownerDomain!==void 0&&r.ownerDomain!==i.domain||i?.kind==="domain"&&r.ownerDomain===void 0&&!st(r.domain)&&a!==i.domain)return"reject";let c=n?.acceptedDomains?.get(t);if(!Yq(c,r,i))return"reject";let u=Jq(n?.acceptedRevisions,r.domain,s);if(u===void 0)return"apply";let d=wr(r.revision,u);return d>0||d===0&&c===void 0&&i?.kind==="domain"&&n?.equalRevisionRebindDomains?.get(t)===i.domain?"apply":d===0?"equal":"reject"}function Qq(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 eH(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)&&typeof t.access_token=="string"&&t.access_token.length>0}function tH(t){let e=t.access_token_expires_at?t.access_token_expires_at.seconds*Vq+Math.floor(t.access_token_expires_at.nanos/Bq):void 0;return{accessToken:t.access_token,refreshToken:t.refresh_token,expiresAt:e,tokenType:t.token_type,scope:t.scope,serverMetadata:{issuer:t.issuer??t.authorization_endpoint,authorization_endpoint:t.authorization_endpoint,token_endpoint:t.token_endpoint},client:{client_id:t.client_id,client_secret:t.client_secret,...t.token_endpoint_auth_method===void 0?{}:{token_endpoint_auth_method:t.token_endpoint_auth_method}}}}function ru(t,e,r){let n={applied:[],equal:[],rejected:[]};for(let[o,s]of Object.entries(e)){if(!eH(s)){Lh.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=Dn(s),a=Xq(o,s,i,r);if(a!=="apply"){n[a==="equal"?"equal":"rejected"].push(o);continue}let c=tH(s);if(Qq(t,o,c,i)){Lh.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 Jx=rH.child({prefix:"pi-mcp"});function nH(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 oH(t,e,r){let n=Object.entries(t).filter(([o,s])=>{let i=Dn(s);if(i===void 0)return!1;let a=Xr(i);return i.ownerDomain!==void 0?a===`user:${e}`:o===r&&st(i.domain)||a===`user:${e}`});return n.length===1?n[0]?.[1]:void 0}async function Yx(t){let{pi:e,state:r,update:n}=t;if(Object.keys(n.credentials).length!==1){Jx.warn(`Targeted MCP credential update for config ${n.configId} must contain exactly one entry`);return}let o=nH(r,n.configId),s=o?oH(n.credentials,n.configId,o.server.config.name):void 0;if(!o||!s)return;let i=W(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||W(r,o.name)!==i)return;let c=ru(r.tokens,{[o.name]:s},{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});if(!c.applied.includes(o.name)&&!c.equal.includes(o.name))return;if(c.applied.includes(o.name)){let f=Dn(s);f&&(r.credentialRevisions.set(o.name,f),r.hostedCredentialOwnership.set(o.name,{...f,accessTokenOnly:s.refresh_token===void 0})),r.statusFailureCategories.delete(o.name),r.authRefreshNeededReportKeys.delete(o.name),r.tokens.clearAuthRequired(o.name)}let u=r.currentLoad?.latestPi??e,d=t.reconnect??Wr,l=t.report??J;await d(o.name,r,u).catch(f=>{Jx.warn(`Targeted MCP credential restart failed for config ${n.configId}: ${f instanceof Error?f.name:"non-Error"}`)}),l(u,r),Te(r)}import{logger as yH}from"@hermes/logger";import{execFile as jh}from"node:child_process";import{win32 as Fh}from"node:path";import{logger as sH}from"@hermes/logger";var iH=5e3,aH=/^[a-z]:[\\/]/i,cH=/[<>:"|?*]/;function uH(){let t=process.env.SystemRoot??process.env.WINDIR;return!t||t!==t.trim()||!aH.test(t)||!Fh.isAbsolute(t)||t.slice(3).split(/[\\/]+/).some(n=>n==="."||n===".."||n.endsWith(".")||n.endsWith(" ")||cH.test(n)||[...n].some(o=>o.charCodeAt(0)<32))?null:Fh.join(Fh.normalize(t),"System32","WindowsPowerShell","v1.0","powershell.exe")}function dH(t){let e=t.replaceAll("'","''");return Buffer.from(`Start-Process -FilePath '${e}'`,"utf16le").toString("base64")}function lH(t,e){switch(process.platform){case"darwin":return jh("open",[t],e);case"win32":{let r=uH();return r?jh(r,["-NoProfile","-NonInteractive","-EncodedCommand",dH(t)],e):(e(new Error("Windows system root metadata is invalid")),null)}default:return jh("xdg-open",[t],e)}}function Xx(t,e=iH){let r=sH.child({prefix:"open-browser"});return new Promise(n=>{let o;try{let c=new URL(t);if(c.protocol!=="http:"&&c.protocol!=="https:"){r.warn("Refusing to open browser for a non-http(s) URL"),n(!1);return}o=c.toString()}catch{r.warn("Refusing to open browser for an unparseable URL"),n(!1);return}let s=!1,i=null,a=setTimeout(()=>{if(!s){s=!0,r.warn("Browser open timed out (no display on a remote machine?)");try{i?.kill()}catch(c){r.debug("Failed to kill browser-open child process",{error:c})}n(!1)}},e);i=lH(o,c=>{s||(s=!0,clearTimeout(a),c?(r.warn("Failed to open browser",{error:c}),n(!1)):n(!0))})})}import{createServer as fH}from"node:http";function nu(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Qx(t){let e=nu(t.title),r=nu(t.heading),n=nu(t.message),o=t.details?nu(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 Yx(t){return Jx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function ou(t,e){return Jx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var iH="127.0.0.1",ek="/callback",Xx=3e3,Qx=3010,aH="Authentication successful. You can close this window.",su={"Content-Type":"text/html; charset=utf-8"};function tk(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function rk(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:{code:r,state:e}};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}let s=n.get("code");if(!s)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{kind:"success",result:{code:s,state:o??e}}}function Uh(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function cH(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==ek){e.writeHead(404,su),e.end(ou("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){let a=c=>{e.writeHead(400,su),e.end(ou("Authentication did not complete.",`Error: ${i}`));let u=Uh(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!s){e.writeHead(400,su),e.end(ou("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,su),e.end(Yx(aH)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function uH(t){for(let e=Xx;e<=Qx;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,iH)}))return e;throw new Error(`No free port in ${Xx}-${Qx} for the OAuth callback server`)}async function nk(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,s=sH((a,c)=>{cH(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),i=await uH(s);return{port:i,redirectUri:`http://localhost:${i}${ek}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>s.close(),setErrorRetryHandler:a=>{o=a}}}var qh=dH.child({prefix:"pi-mcp"}),lH=300*1e3,ik="MCP authentication was superseded";function ok(){return tk()?"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 mr(t){if(t.aborted)throw new Error("Authentication cancelled")}function ak(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&&ck(t.credentialRevisions.get(e),r.credentialRevision)}function ck(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function sk(t,e,r){if(!ak(t,e,r))throw new Error(ik)}async function fH(t,e,r,n,o,s,i){let a=t.servers.get(e),c=t.tokens,u=c.get(e),d=t.credentialRevisions.get(e);if(c!==r.tokenStore||!a||!u||!ut(r.server.config,a.config))return;let l=a.config,f=Ut(t,a);try{let p=await c.restoreAfterSupersededAuthentication(e,o,u,n,s,f);if(p===void 0||t.tokens!==c||t.servers.get(e)?.config!==l||c.get(e)!==u||!Sr(Ut(t,a),f)||!ck(t.credentialRevisions.get(e),d)||c.reconcileCredentialIdentity?.(e,u,f)!==!0)return;Yr({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??i,t)}catch{qh.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function pH(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 hH(t,e,r,n){return new Promise((o,s)=>{let i=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=m=>{i||(i=!0,c(),m())},d=()=>u(()=>s(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>s(new Error("Authentication timed out"))),lH)},f=m=>{let y=m instanceof Error?m.message:String(m);u(()=>s(new Error(`Could not read the pasted authorization code (${y}). Restart sign-in and paste the full redirect URL.`)))},p=async(m,y)=>{let v=await n(m,l);if(!i){if(v){h(y);return}u(()=>s(Uh(m)))}},h=(m=e.waitForManualCode())=>{m.then(async y=>{if(!(i||!y))try{let v=rk(y,r());if(v.kind==="success"){u(()=>o(new URLSearchParams({code:v.result.code,state:v.result.state})));return}let b=e.waitForManualCode();await p(v.params,b)}catch(v){f(v)}}).catch(y=>u(()=>s(y instanceof Error?y:new Error(String(y)))))};if(t.setErrorRetryHandler(m=>n(m,l)),l(),e.signal.aborted){u(()=>s(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(m=>{m&&u(()=>o(new URLSearchParams({code:m.code,state:m.state})))}).catch(m=>u(()=>s(m instanceof Error?m:new Error(String(m))))),h()})}async function uk(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=Ut(r,s),d;try{mr(o.signal),d=await nk(),mr(o.signal);let l=new URL(i.url),f,p;try{f=await wd(l),mr(o.signal),p=await bd(f),mr(o.signal)}catch{throw mr(o.signal),new Error(`OAuth discovery failed for MCP server "${e}". Verify that the endpoint supports OAuth and publishes discovery metadata.`)}let h=await c.tokenStore.captureAuthenticatedIdentityVersion(u);sk(r,e,c),mr(o.signal);let m=await Rd({config:{},serverMetadata:p,redirectUris:[d.redirectUri]});mr(o.signal);let y=await pa(l,m,p,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);mr(o.signal);let v=y,b=!1,w,x,S=(Re,Kr)=>{if(b)return x&&w&&ha(Re,w)?x.then(ct=>ct.authUri.toString()):Promise.resolve(null);if(!ha(Re,v))return Promise.resolve(null);b=!0;let Jr=v;return w=Jr,Kr(),qh.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),x=Pd(Jr).then(ct=>(v=ct,o.onAuthUrl({url:ct.authUri.toString(),instructions:ok()}),ct)),x.then(ct=>ct.authUri.toString())};d.setErrorRetryHandler(Re=>S(Re,()=>{})),o.onAuthUrl({url:y.authUri.toString(),instructions:ok()}),mr(o.signal),await Kx(y.authUri.toString());let P=await hH(d,o,()=>v.state,S),I=await Cd(P,v);sk(r,e,c);let re=pH(I),fe=await c.tokenStore.persistAuthenticated(e,re,u,h);if(!ak(r,e,c))throw await fH(r,e,c,u,re,fe,n),new Error(ik);c.tokenStore.commit(e,re,u),r.preservedCredentialIdentities?.delete(e),Yr({state:r,name:e,revision:fe}),r.tokens.clearAuthRequired(e),nt(r,e),await Oi([e],r,n),J(r.currentLoad?.latestPi??n,r),Te(r),qh.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as AH}from"@augmentcode/auggie-v2";import{resolveTargetFiles as mH,SETTINGS_TARGET_ORDER as gH,SettingsManager as yH,scopeToSettingsTarget as vH,settingsTargetToScope as Hh}from"@augmentcode/auggie-v2";var _H=gH.map(t=>Hh(t)),dk=(t,e)=>yH.create(t,e);function lk(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 fk(t,e,r){let n=dk(e,r);return _H.filter(o=>lk(n,o)?.[t])}function pk(t){let e=t.map(n=>({target:vH(n),path:n,exists:!0})),r=mH({files:e});return"directTarget"in r?{scopes:t,direct:Hh(r.directTarget)}:{scopes:r.files.map(n=>Hh(n.target)),direct:null}}function SH(t,e,r){let{servers:n}=Gn(e,r);return n.find(o=>o.name===t)?.disabled===!0}function hk(t,e,r,n,o){try{let s=dk(n,o);if(!lk(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:SH(t,n,o)!==e}}function Gh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function mk(t,e,r){return Gh(t)}function gk(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as wH}from"@hermes/logger";var Wh=wH.child({prefix:"pi-mcp"}),yk="hermes:mcp:register-server-source";function bH(t,e){return t.type==="stdio"?Ht(t,e):qt(t,e)}function vk(t,e){return JSON.stringify(t)===JSON.stringify(e)}function RH(t,e){return{...t,disabled:e}}function PH(t){try{return t.getServers()}catch(e){return Wh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function CH(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function _k(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 xH(t,e,r,n){let o=new Map;if(!t)return o;for(let s of PH(t)){let i=e.servers.get(s.name),a=bH(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=RH(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=W(e,s.name),f=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,p=i!==void 0&&d===void 0&&n.has(s.name)&&vk(i.config,u);p&&(Q(e,s.name,i),ym({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(f||p||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),_k(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function kH(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=W(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){Pe({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=Pt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=dt(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),Pe({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Sk(t,e){_k(t,e)}function EH(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):W(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){Sk(e,a);continue}u===o.get(a)&&n.has(a)&&vk(u.config,c)||(i.set(a,Ze(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function TH(t,e,r){let n=r?.connect??bt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&CH(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=xH(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 kH(a,u,e);let{reservedRevisions:d,toConnect:l}=EH({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Wh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=W(e,h.name),v=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return v||Sk(e,h.name),v};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(f(),e),Te(e)}}function Zh(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>TH(t,e,r)).catch(s=>{Wh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function wk(t,e){let{name:r,disabled:n,state:o,pi:s}=t,i=o.servers.get(r),a=i?Q(o,r,i):W(o,r);return a?.owner.kind!=="plugin"||a.host!==i?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),Zh(o.currentLoad?.latestPi??s,o,e))}function bk(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Zh(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Zh(e.currentLoad?.latestPi??t,e))})}}function $H(t,e){let n=AH.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function Rk(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if($H(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:Gh(e)};if(Du(r.mcpConfigOverride).has(e))return{kind:"session"};if(_r(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=fk(e,n,o);if(i.length===0)return{kind:"blocked",message:mk(e,n,o)};let{scopes:a,direct:c}=pk(i);return{kind:"local",scopes:a,direct:c}}async function Pk(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 wk({name:e,disabled:r,state:n,pi:o});return}Du(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),s.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...s.config,disabled:r};await bt([a],n,o,void 0,void 0,i?.owner.kind),Te(n)}async function Ck(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=hk(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await Zx(e,o,s,i,a),Te(o),c.overridden?{notice:gk(e)}:{}}import{DynamicBorder as XH}from"@augmentcode/auggie-v2";import{Key as QH,matchesKey as eG,SearchableWindowedList as tG,SpinnerTimer as rG,truncateToWidth as fu,wrapTextWithAnsi as nG}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as MH,scopeToSettingsTarget as IH}from"@augmentcode/auggie-v2";import{truncateToWidth as OH,visibleWidth as Ln,wrapTextWithAnsi as zH}from"@earendil-works/pi-tui";var NH=2,DH=2,iu={name:"Name",source:"Source",status:"Status"};function Bh(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 Vh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Kh(t,e){let r=e-Ln(t);return r>0?t+" ".repeat(r):t}function au(t){return t.reduce((e,r)=>Math.max(e,Ln(r)),0)}function jo(t,e,r,n){let o=`${e}Width`,s=Math.min(Math.max(0,r-t[o]),n);return t[o]+=s,n-s}function xk(t,e){let r=Math.max(1,Math.floor(e)),n=Math.min(NH,r),o=r-n,s=Math.min(3,o),i=s<2?0:Math.min(DH,Math.floor((o-s)/(s-1))),a=o-i*Math.max(0,s-1),c=["name","source","status"].slice(0,s),u={prefixWidth:n,gapWidth:i,nameWidth:0,sourceWidth:0,statusWidth:0};for(let y of c)a=jo(u,y,1,a);for(let y=1;a>0;y++){let v=!1;for(let b of c)if(!(y>=Ln(iu[b]))&&(a=jo(u,b,y+1,a),v=!0,a===0))break;if(!v)break}let d=t.map(y=>Vh(y)),l=t.map(y=>Bh(y)),f=Math.max(Ln(iu.source),au(d)),p=Math.max(Ln(iu.status),au(l.map(y=>y.label))),h=Math.max(Ln(iu.name),au(t.map(y=>y.name))),m=Math.max(p,au(l.map(y=>y.label+(y.hint??""))));return a=jo(u,"source",f,a),a=jo(u,"status",p,a),a=jo(u,"name",h,a),jo(u,"status",m,a),u}function kk(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 Fo(t,e){let r=Math.max(1,Math.floor(e));return t.flatMap(n=>zH(n,r).map(o=>Ln(o)<=r?o:OH(o,r,"")))}function LH(t,e){return Math.max(0,t-e)}function Uo(t,e,r){return Math.max(0,Math.min(t,LH(e,r)))}function Ek(t,e,r){let n=Uo(t,e,r),o=Math.min(e,n+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Rows ${n+1}-${o} of ${e}`}}function Tk(t,e){return String(t+1).padStart(String(e).length," ")}function Jh(t){return MH(IH(t))}import{Key as jH,matchesKey as FH}from"@earendil-works/pi-tui";function cu(t){if(t.source==="plugin"&&t.disabled)return t.canAuthenticate?["authenticate","toggle"]:["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.canAuthenticate&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function Ak(){return{step:"serverList",filterQuery:"",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var $k=10,jn=15;var UH="k",qH="j";function qo(t,e){return(t%e+e)%e}function tt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function Yh(t,e,r=!0){return e.matches(t,"tui.select.up")||r&&t===UH?{kind:"up"}:e.matches(t,"tui.select.down")||r&&t===qH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:FH(t,jH.backspace)?{kind:"back"}:{kind:"ignore"}}function HH(t,e,r){if(e.kind==="filterChanged")return{state:{...t,filterQuery:e.query,selectedServer:r[0]?.name??null}};let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=qo(tt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=qo(tt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[tt(r,t.selectedServer)];return o?.status==="auth_required"&&o.canAuthenticate?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function GH(t,e,r){let n=r.snapshots[tt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=cu(n);switch(e.kind){case"up":return{state:{...t,actionIndex:qo(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:qo(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 ZH(t,e,r){let n=r.snapshots[tt(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 WH(t,e,r){let n=r.snapshots[tt(r.snapshots,t.selectedServer)]?.logLines()??[],o=Fo(n,r.logViewportWidth).length;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Uo(t.logScrollOffset-1,o,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Uo(t.logScrollOffset+1,o,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function BH(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function uu(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function VH(t,e){let r=t.targetScopes.length;if(r===0)return{state:uu(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:qo(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:qo(t.targetIndex+1,r)}};case"cancel":case"back":return{state:uu(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:uu({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:uu(t,"serverActions")}}default:return{state:t}}}function Mk(t,e,r){switch(t.step){case"serverList":return HH(t,e,r.snapshots);case"serverActions":return GH(t,e,r);case"viewTools":return ZH(t,e,r);case"viewLogs":return WH(t,e,r);case"pasteAuthCode":return BH(t,e);case"selectTarget":return VH(t,e);default:return{state:t}}}import{truncateToWidth as Lt,visibleWidth as KH,wrapTextWithAnsi as Br}from"@earendil-works/pi-tui";var Xh="\u2192 ",du=" ";function Ik(t,e,r){return e?r.bold(r.fg("accent",t)):r.fg("text",t)}function gr(t,e){return e>0?Lt(t,e,"\u2026"):""}function Ok(t,e,r,n,o,s,i){let a=Math.max(1,i),c=xk(r,a),u=" ".repeat(c.gapWidth),d=(h,m,y,v)=>{let b=[c.nameWidth>0?Kh(m,c.nameWidth):"",c.sourceWidth>0?Kh(y,c.sourceWidth):"",c.statusWidth>0?v:""].filter(w=>w.length>0);return h+b.join(u)},l=gr(du,c.prefixWidth),p=[d(l,s.bold(s.fg("accent",gr("Name",c.nameWidth))),s.bold(s.fg("accent",gr("Source",c.sourceWidth))),s.bold(s.fg("accent",gr("Status",c.statusWidth))))];if(e.length===0)p.push(Lt(s.fg("muted","No MCP servers available"),a,"\u2026"));else if(o.total===0)p.push(Lt(s.fg("muted","No matching MCP servers"),a,"\u2026"));else for(let h of n){let m=h.name===t.selectedServer,y=Bh(h),v=gr(y.label,c.statusWidth),b=c.statusWidth-KH(v),w=y.hint?gr(y.hint,b):"",x=s.fg(y.color,v)+(w?s.fg("muted",w):""),S=gr(m?Xh:du,c.prefixWidth);p.push(d(m?s.fg("accent",S):S,Ik(gr(h.name,c.nameWidth),m,s),Ik(gr(Vh(h),c.sourceWidth),m,s),x))}return o.hasOverflow&&p.push(Lt(s.fg("muted",` (${o.current}/${o.total})`),a,"\u2026")),p}var JH={authenticate:{label:"Authenticate",description:"Connect to this server"},viewTools:{label:"View tools",description:"See all tools provided by this server"},viewLogs:{label:"View logs",description:"View logs from this server"},reconnect:{label:"Reconnect",description:"Restart the server connection"},toggle:{label:"Disable",description:"Enable or disable this server"}};function YH(t,e){if(t==="authenticate")return e.status==="auth_required"?{label:"Authenticate",description:"Connect to this server"}:{label:"Reauthenticate",description:"Refresh authentication"};if(t==="toggle"){let r=e.source!=="local";return e.disabled?r?{label:"Enable for this session",description:"Re-enable this server for the current session only"}:{label:"Enable",description:"Enable this server (saved to settings.json)"}:r?{label:"Disable for this session",description:"Disable this server for the current session only"}:{label:"Disable",description:"Disable this server (saved to settings.json)"}}return JH[t]}function zk(t,e,r,n){let o=Math.max(1,n),s=e[tt(e,t.selectedServer)];if(!s)return Br(r.fg("muted","No MCP servers available"),o);let i=s.transport==="stdio"?"Command: ":"URL: ",a=Br(r.fg("muted",i+s.connectionInfo),o);s.source==="plugin"&&a.push(...Br(r.fg("muted","Source: plugin (toggles apply to this session only)"),o)),a.push("");let c=cu(s);for(let[u,d]of c.entries()){let l=u===t.actionIndex,f=YH(d,s),p=f.label,h=l?r.bold(r.fg("accent",p)):r.fg("text",p);a.push(Lt((l?Xh:du)+h+r.fg("muted",` - ${f.description}`),o,"\u2026"))}return a}function Nk(t,e,r,n){let o=Math.max(1,n),s=e[tt(e,t.selectedServer)];if(!s)return Br(r.fg("muted","No tools available."),o);if(s.disabled)return Br(r.fg("muted","Server is disabled; no tools are currently available."),o);if(s.tools.length===0)return Br(r.fg("muted","No tools available."),o);let i=s.tools.length,{start:a,end:c}=kk(t.toolIndex,i,jn),u=[];for(let d=a;d<c;d++){let l=s.tools[d];if(!l)continue;let p=d===t.toolIndex?r.bold(r.fg("accent",l.name)):r.fg("text",l.name);u.push(Lt(r.fg("muted",`${Tk(d,i)} `)+p+(l.disabled?r.fg("muted"," (disabled)"):""),o,"\u2026"))}return u}function Dk(t,e,r,n){let o=Math.max(1,n),i=e[tt(e,t.selectedServer)]?.logLines()??[];if(i.length===0)return Br(r.fg("muted","No logs available yet."),o);let a=Fo(i,o),c=a.length,u=Ek(t.logScrollOffset,c,jn),d=[];c>jn&&d.push(Lt(r.fg("muted",u.rangeLabel),o,"\u2026")),u.aboveCount>0&&d.push(Lt(r.fg("dim",`\u2191 ${u.aboveCount} more rows`),o,"\u2026"));for(let l of a.slice(u.start,u.end))d.push(Lt(r.fg("text",l),o,""));return u.belowCount>0&&d.push(Lt(r.fg("dim",`\u2193 ${u.belowCount} more rows`),o,"\u2026")),d}function Lk(t,e,r,n){let o=Math.max(1,n),s=e[tt(e,t.selectedServer)]?.name??"",i=[...Br(r.fg("muted",`Save the toggle for "${s}" to which settings file?`),o),""];for(let[a,c]of t.targetScopes.entries()){let u=a===t.targetIndex,d=u?r.bold(r.fg("accent",Jh(c))):r.fg("text",Jh(c));i.push(Lt((u?Xh:du)+d,o,"\u2026"))}return i}var lu=3;function oG(t){return t.type==="stdio"?t.command:t.url}function sG(t){let e=t.getLogHistory();if(e.length===0){let r=t.lastError;return r?r.split(`
143
+ </html>`}function ek(t){return Qx({title:"Authentication successful",heading:"Authentication successful",message:t,autoClose:!0})}function ou(t,e){return Qx({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}var pH="127.0.0.1",nk="/callback",tk=3e3,rk=3010,hH="Authentication successful. You can close this window.",su={"Content-Type":"text/html; charset=utf-8"};function ok(t=process.env){return!!(t.SSH_CONNECTION||t.SSH_TTY)}function sk(t,e){let r=t.trim();if(!r)throw new Error("No authorization code provided");let n;try{n=new URL(r).searchParams}catch{(r.includes("code=")||r.includes("error="))&&(n=new URLSearchParams(r))}if(!n)return{kind:"success",result:{code:r,state:e}};let o=n.get("state");if(n.has("error")){if(o!==e)throw new Error("OAuth state mismatch");return{kind:"error",params:n}}let s=n.get("code");if(!s)throw new Error("Could not find an authorization code in the pasted input");if(o&&o!==e)throw new Error("OAuth state mismatch");return{kind:"success",result:{code:s,state:o??e}}}function Uh(t){let e=t.get("error")??"unknown_error",r=t.get("error_description");return new Error(`Authentication did not complete: ${e}${r?`: ${r}`:""}`)}function mH(t,e,r){try{let n=new URL(t.url??"","http://localhost");if(n.pathname!==nk){e.writeHead(404,su),e.end(ou("Callback route not found."));return}let o=n.searchParams.get("code"),s=n.searchParams.get("state"),i=n.searchParams.get("error");if(i){let a=c=>{e.writeHead(400,su),e.end(ou("Authentication did not complete.",`Error: ${i}`));let u=Uh(n.searchParams);c instanceof Error?u=c:c!==void 0&&(u=new Error(String(c))),r.onError(u)};r.onErrorRetry(n.searchParams).then(c=>{c?(e.writeHead(302,{Location:c}),e.end()):a()}).catch(c=>a(c));return}if(!o||!s){e.writeHead(400,su),e.end(ou("Missing code or state parameter.")),r.onError(new Error("OAuth callback missing code or state"));return}e.writeHead(200,su),e.end(ek(hH)),r.onSuccess({code:o,state:s})}catch{e.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),e.end("Internal error")}}async function gH(t){for(let e=tk;e<=rk;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,pH)}))return e;throw new Error(`No free port in ${tk}-${rk} for the OAuth callback server`)}async function ik(){let t=!1,e,r,n=new Promise((a,c)=>{e=u=>{t||(t=!0,a(u))},r=u=>{t||(t=!0,c(u))}}),o,s=fH((a,c)=>{mH(a,c,{onSuccess:u=>e?.(u),onError:u=>r?.(u),onErrorRetry:u=>o?.(u)??Promise.resolve(null)})}),i=await gH(s);return{port:i,redirectUri:`http://localhost:${i}${nk}`,waitForCode:()=>n,cancelWait:()=>e?.(null),close:()=>s.close(),setErrorRetryHandler:a=>{o=a}}}var qh=yH.child({prefix:"pi-mcp"}),vH=300*1e3,uk="MCP authentication was superseded";function ak(){return ok()?"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 mr(t){if(t.aborted)throw new Error("Authentication cancelled")}function dk(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&&lk(t.credentialRevisions.get(e),r.credentialRevision)}function lk(t,e){return t?.revision===e?.revision&&t?.domain===e?.domain}function ck(t,e,r){if(!dk(t,e,r))throw new Error(uk)}async function _H(t,e,r,n,o,s,i){let a=t.servers.get(e),c=t.tokens,u=c.get(e),d=t.credentialRevisions.get(e);if(c!==r.tokenStore||!a||!u||!ut(r.server.config,a.config))return;let l=a.config,f=Ut(t,a);try{let p=await c.restoreAfterSupersededAuthentication(e,o,u,n,s,f);if(p===void 0||t.tokens!==c||t.servers.get(e)?.config!==l||c.get(e)!==u||!Sr(Ut(t,a),f)||!lk(t.credentialRevisions.get(e),d)||c.reconcileCredentialIdentity?.(e,u,f)!==!0)return;Yr({state:t,name:e,revision:p}),J(t.currentLoad?.latestPi??i,t)}catch{qh.error(`Failed to restore authoritative MCP OAuth token for "${e}" after superseded authentication`)}}function SH(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 wH(t,e,r,n){return new Promise((o,s)=>{let i=!1,a,c=()=>{a&&clearTimeout(a),e.signal.removeEventListener("abort",d),t.cancelWait()},u=m=>{i||(i=!0,c(),m())},d=()=>u(()=>s(new Error("Authentication cancelled"))),l=()=>{a&&clearTimeout(a),a=setTimeout(()=>u(()=>s(new Error("Authentication timed out"))),vH)},f=m=>{let y=m instanceof Error?m.message:String(m);u(()=>s(new Error(`Could not read the pasted authorization code (${y}). Restart sign-in and paste the full redirect URL.`)))},p=async(m,y)=>{let v=await n(m,l);if(!i){if(v){h(y);return}u(()=>s(Uh(m)))}},h=(m=e.waitForManualCode())=>{m.then(async y=>{if(!(i||!y))try{let v=sk(y,r());if(v.kind==="success"){u(()=>o(new URLSearchParams({code:v.result.code,state:v.result.state})));return}let b=e.waitForManualCode();await p(v.params,b)}catch(v){f(v)}}).catch(y=>u(()=>s(y instanceof Error?y:new Error(String(y)))))};if(t.setErrorRetryHandler(m=>n(m,l)),l(),e.signal.aborted){u(()=>s(new Error("Authentication cancelled")));return}e.signal.addEventListener("abort",d),t.waitForCode().then(m=>{m&&u(()=>o(new URLSearchParams({code:m.code,state:m.state})))}).catch(m=>u(()=>s(m instanceof Error?m:new Error(String(m))))),h()})}async function fk(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=Ut(r,s),d;try{mr(o.signal),d=await ik(),mr(o.signal);let l=new URL(i.url),f,p;try{f=await wd(l),mr(o.signal),p=await bd(f),mr(o.signal)}catch{throw mr(o.signal),new Error(`OAuth discovery failed for MCP server "${e}". Verify that the endpoint supports OAuth and publishes discovery metadata.`)}let h=await c.tokenStore.captureAuthenticatedIdentityVersion(u);ck(r,e,c),mr(o.signal);let m=await Rd({config:{},serverMetadata:p,redirectUris:[d.redirectUri]});mr(o.signal);let y=await pa(l,m,p,d.redirectUri,f.resourceScopes?.join(" "),f.resourceIdentifier?new URL(f.resourceIdentifier):void 0);mr(o.signal);let v=y,b=!1,w,x,S=(Re,Kr)=>{if(b)return x&&w&&ha(Re,w)?x.then(ct=>ct.authUri.toString()):Promise.resolve(null);if(!ha(Re,v))return Promise.resolve(null);b=!0;let Jr=v;return w=Jr,Kr(),qh.info(`MCP server "${e}" rejected offline_access (invalid_scope); retrying authorization without it`),x=Pd(Jr).then(ct=>(v=ct,o.onAuthUrl({url:ct.authUri.toString(),instructions:ak()}),ct)),x.then(ct=>ct.authUri.toString())};d.setErrorRetryHandler(Re=>S(Re,()=>{})),o.onAuthUrl({url:y.authUri.toString(),instructions:ak()}),mr(o.signal),await Xx(y.authUri.toString());let P=await wH(d,o,()=>v.state,S),I=await Cd(P,v);ck(r,e,c);let re=SH(I),fe=await c.tokenStore.persistAuthenticated(e,re,u,h);if(!dk(r,e,c))throw await _H(r,e,c,u,re,fe,n),new Error(uk);c.tokenStore.commit(e,re,u),r.preservedCredentialIdentities?.delete(e),Yr({state:r,name:e,revision:fe}),r.tokens.clearAuthRequired(e),nt(r,e),await Oi([e],r,n),J(r.currentLoad?.latestPi??n,r),Te(r),qh.info(`MCP server "${e}" authenticated`)}finally{d?.close(),r.authenticationGeneration===a&&(r.authenticating=!1,r.authenticatingServerName=void 0)}}import{SettingsManager as DH}from"@augmentcode/auggie-v2";import{resolveTargetFiles as bH,SETTINGS_TARGET_ORDER as RH,SettingsManager as PH,scopeToSettingsTarget as CH,settingsTargetToScope as Hh}from"@augmentcode/auggie-v2";var xH=RH.map(t=>Hh(t)),pk=(t,e)=>PH.create(t,e);function hk(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 mk(t,e,r){let n=pk(e,r);return xH.filter(o=>hk(n,o)?.[t])}function gk(t){let e=t.map(n=>({target:CH(n),path:n,exists:!0})),r=bH({files:e});return"directTarget"in r?{scopes:t,direct:Hh(r.directTarget)}:{scopes:r.files.map(n=>Hh(n.target)),direct:null}}function kH(t,e,r){let{servers:n}=Gn(e,r);return n.find(o=>o.name===t)?.disabled===!0}function yk(t,e,r,n,o){try{let s=pk(n,o);if(!hk(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:kH(t,n,o)!==e}}function Gh(t){return`Cannot toggle "${t}": server is not in any editable settings file`}function vk(t,e,r){return Gh(t)}function _k(t){return`Saved toggle for "${t}", but a higher-priority settings file overrides it`}import{logger as EH}from"@hermes/logger";var Wh=EH.child({prefix:"pi-mcp"}),Sk="hermes:mcp:register-server-source";function TH(t,e){return t.type==="stdio"?Ht(t,e):qt(t,e)}function wk(t,e){return JSON.stringify(t)===JSON.stringify(e)}function AH(t,e){return{...t,disabled:e}}function $H(t){try{return t.getServers()}catch(e){return Wh.warn(`plugin MCP server source getServers() threw: ${e instanceof Error?e.message:String(e)}`),[]}}function MH(t,e){if(t.getDiagnostics)try{for(let r of t.getDiagnostics())e.diagnostics.push({message:r.message,origin:"plugin"})}catch{}}function bk(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 IH(t,e,r,n){let o=new Map;if(!t)return o;for(let s of $H(t)){let i=e.servers.get(s.name),a=TH(s,r),c=e.sessionPluginDisabledOverrides.get(s.name),u=AH(a,c??a.disabled===!0),d=e.pluginServerHosts.get(s.name);i&&d===i&&Q(e,s.name,i);let l=W(e,s.name),f=i!==void 0&&l?.owner.kind==="plugin"&&l.host===i,p=i!==void 0&&d===void 0&&n.has(s.name)&&wk(i.config,u);p&&(Q(e,s.name,i),Sm({state:e,name:s.name,host:i}));let h=l?.owner.kind==="vfs";if(i&&!(f||p||h)){e.pluginServerNames.delete(s.name),e.pluginServerHosts.delete(s.name),bk(e,s.name);continue}o.has(s.name)||o.set(s.name,u)}return o}async function OH(t,e,r){let n=[];for(let o of e){if(t.has(o))continue;r.sessionPluginDisabledOverrides.delete(o);let s=W(r,o);if(s?.owner.kind!=="plugin")continue;let i=s.host;if(!i){Pe({state:r,name:o,owner:s.owner,revision:s.revision});continue}let a=Pt({state:r,name:o,owner:s.owner,revision:s.revision,host:i});if(!a)continue;let c=dt(r,o,i.config.id,i.config);i.beginDisposal?.(),n.push(Promise.allSettled([c,i.dispose({strict:!0})]).then(u=>{let d=u.find(l=>l.status==="rejected");if(d)throw we({state:r,name:o,retirement:a,result:{status:"failed",error:d.reason}}),d.reason;we({state:r,name:o,retirement:a,result:{status:"retired"}}),Pe({state:r,name:o,owner:s.owner,revision:s.revision})}))}await Promise.all(n)}function Rk(t,e){bk(t,e)}function zH(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):W(e,a);if(d?.owner.kind==="local"||d?.owner.kind==="registry"){Rk(e,a);continue}u===o.get(a)&&n.has(a)&&wk(u.config,c)||(i.set(a,We(e,a,"plugin")),s.push(c))}return{reservedRevisions:i,toConnect:s}}async function NH(t,e,r){let n=r?.connect??bt,o=e.pluginServerSource,s=e.workspaceRoot??process.cwd();e.diagnostics=e.diagnostics.filter(h=>h.origin!=="plugin"),o&&MH(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=IH(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 OH(a,u,e);let{reservedRevisions:d,toConnect:l}=zH({state:e,desired:a,previousNames:u,previousHosts:c});if(l.length===0)return;Wh.info(`Plugin MCP source: connecting ${l.length} server(s)`);let f=()=>e.currentLoad?.latestPi??t,p=h=>{let m=d.get(h.name);if(m===void 0||e.configDesiredRevisions.get(h.name)!==m)return!1;let y=W(e,h.name),v=y?.owner.kind!=="local"&&y?.owner.kind!=="registry";return v||Rk(e,h.name),v};try{await n(l,e,f(),p,d,"plugin");for(let h of l)p(h)}catch{}finally{e.pluginServerNames=new Set([...e.hostLeases].filter(([,h])=>h.owner.kind==="plugin").map(([h])=>h)),J(f(),e),Te(e)}}function Zh(t,e,r){e.pluginReconcileQueue??=Promise.resolve();let o=e.pluginReconcileQueue.then(()=>NH(t,e,r)).catch(s=>{Wh.warn(`Plugin MCP reconciliation failed: ${s instanceof Error?s.message:String(s)}`)});return e.pluginReconcileQueue=o,o}function Pk(t,e){let{name:r,disabled:n,state:o,pi:s}=t,i=o.servers.get(r),a=i?Q(o,r,i):W(o,r);return a?.owner.kind!=="plugin"||a.host!==i?Promise.resolve():(o.sessionPluginDisabledOverrides.set(r,n),Zh(o.currentLoad?.latestPi??s,o,e))}function Ck(t,e){return{registerServerSource:r=>(e.pluginServerSource=r,Zh(e.currentLoad?.latestPi??t,e),()=>{e.pluginServerSource===r&&(e.pluginServerSource=void 0,Zh(e.currentLoad?.latestPi??t,e))})}}function LH(t,e){let n=DH.create(t,e).getManagedSettings().mcpServers;return new Set(Object.entries(n??{}).filter(([,o])=>o!==null).map(([o])=>o))}function xk(t){let{server:e,state:r,cwd:n,agentDir:o}=t;if(LH(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:Gh(e)};if(Du(r.mcpConfigOverride).has(e))return{kind:"session"};if(_r(s,r.pluginServerHosts,r.hostLeases)!=="local")return{kind:"session"};let i=mk(e,n,o);if(i.length===0)return{kind:"blocked",message:vk(e,n,o)};let{scopes:a,direct:c}=gk(i);return{kind:"local",scopes:a,direct:c}}async function kk(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 Pk({name:e,disabled:r,state:n,pi:o});return}Du(n.mcpConfigOverride).has(e)&&n.sessionMcpConfigDisabledOverrides.set(e,r),s.config.registrySource!==void 0&&n.sessionRegistryDisabledOverrides.set(e,r);let a={...s.config,disabled:r};await bt([a],n,o,void 0,void 0,i?.owner.kind),Te(n)}async function Ek(t){let{server:e,disable:r,scope:n,state:o,pi:s,cwd:i,agentDir:a}=t,c=yk(e,r,n,i,a);if(!c.ok)throw new Error(c.error);return await Vx(e,o,s,i,a),Te(o),c.overridden?{notice:_k(e)}:{}}import{DynamicBorder as sG}from"@augmentcode/auggie-v2";import{Key as iG,matchesKey as aG,SearchableWindowedList as cG,SpinnerTimer as uG,truncateToWidth as fu,wrapTextWithAnsi as dG}from"@earendil-works/pi-tui";import{getSettingsTargetLabel as jH,scopeToSettingsTarget as FH}from"@augmentcode/auggie-v2";import{truncateToWidth as UH,visibleWidth as Ln,wrapTextWithAnsi as qH}from"@earendil-works/pi-tui";var HH=2,GH=2,iu={name:"Name",source:"Source",status:"Status"};function Bh(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 Vh(t){return t.registrySource==="tenant"?"Shared":t.registrySource==="user"?"Private registry":t.source==="plugin"?"Plugin":t.source==="vfs"?"VFS":"User-configured"}function Kh(t,e){let r=e-Ln(t);return r>0?t+" ".repeat(r):t}function au(t){return t.reduce((e,r)=>Math.max(e,Ln(r)),0)}function jo(t,e,r,n){let o=`${e}Width`,s=Math.min(Math.max(0,r-t[o]),n);return t[o]+=s,n-s}function Tk(t,e){let r=Math.max(1,Math.floor(e)),n=Math.min(HH,r),o=r-n,s=Math.min(3,o),i=s<2?0:Math.min(GH,Math.floor((o-s)/(s-1))),a=o-i*Math.max(0,s-1),c=["name","source","status"].slice(0,s),u={prefixWidth:n,gapWidth:i,nameWidth:0,sourceWidth:0,statusWidth:0};for(let y of c)a=jo(u,y,1,a);for(let y=1;a>0;y++){let v=!1;for(let b of c)if(!(y>=Ln(iu[b]))&&(a=jo(u,b,y+1,a),v=!0,a===0))break;if(!v)break}let d=t.map(y=>Vh(y)),l=t.map(y=>Bh(y)),f=Math.max(Ln(iu.source),au(d)),p=Math.max(Ln(iu.status),au(l.map(y=>y.label))),h=Math.max(Ln(iu.name),au(t.map(y=>y.name))),m=Math.max(p,au(l.map(y=>y.label+(y.hint??""))));return a=jo(u,"source",f,a),a=jo(u,"status",p,a),a=jo(u,"name",h,a),jo(u,"status",m,a),u}function Ak(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 Fo(t,e){let r=Math.max(1,Math.floor(e));return t.flatMap(n=>qH(n,r).map(o=>Ln(o)<=r?o:UH(o,r,"")))}function ZH(t,e){return Math.max(0,t-e)}function Uo(t,e,r){return Math.max(0,Math.min(t,ZH(e,r)))}function $k(t,e,r){let n=Uo(t,e,r),o=Math.min(e,n+r);return{start:n,end:o,aboveCount:n,belowCount:e-o,rangeLabel:`Rows ${n+1}-${o} of ${e}`}}function Mk(t,e){return String(t+1).padStart(String(e).length," ")}function Jh(t){return jH(FH(t))}import{Key as WH,matchesKey as BH}from"@earendil-works/pi-tui";function cu(t){if(t.source==="plugin"&&t.disabled)return t.canAuthenticate?["authenticate","toggle"]:["toggle"];let e=t.transport==="stdio"?["viewTools","viewLogs"]:["viewTools"];return t.canAuthenticate&&e.unshift("authenticate"),e.push("toggle","reconnect"),e}function Ik(){return{step:"serverList",filterQuery:"",selectedServer:null,actionIndex:0,toolIndex:0,logScrollOffset:0,authInput:"",targetScopes:[],targetIndex:0,pendingToggle:null}}var Ok=10,jn=15;var VH="k",KH="j";function qo(t,e){return(t%e+e)%e}function rt(t,e){let r=t.findIndex(n=>n.name===e);return r>=0?r:0}function Yh(t,e,r=!0){return e.matches(t,"tui.select.up")||r&&t===VH?{kind:"up"}:e.matches(t,"tui.select.down")||r&&t===KH?{kind:"down"}:e.matches(t,"tui.select.confirm")?{kind:"confirm"}:e.matches(t,"tui.select.cancel")?{kind:"cancel"}:BH(t,WH.backspace)?{kind:"back"}:{kind:"ignore"}}function JH(t,e,r){if(e.kind==="filterChanged")return{state:{...t,filterQuery:e.query,selectedServer:r[0]?.name??null}};let n=r.length;if(n===0)return e.kind==="cancel"?{state:t,effect:{kind:"close"}}:{state:t};switch(e.kind){case"up":{let o=qo(rt(r,t.selectedServer)-1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"down":{let o=qo(rt(r,t.selectedServer)+1,n);return{state:{...t,selectedServer:r[o]?.name??null}}}case"confirm":{let o=r[rt(r,t.selectedServer)];return o?.status==="auth_required"&&o.canAuthenticate?{state:t,effect:{kind:"authenticate",server:o.name}}:{state:{...t,step:"serverActions",actionIndex:0}}}case"cancel":return{state:t,effect:{kind:"close"}};default:return{state:t}}}function YH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)];if(!n)return{state:{...t,step:"serverList"}};let o=cu(n);switch(e.kind){case"up":return{state:{...t,actionIndex:qo(t.actionIndex-1,o.length)}};case"down":return{state:{...t,actionIndex:qo(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 XH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)]?.tools.length??0;switch(e.kind){case"up":return{state:{...t,toolIndex:Math.max(0,t.toolIndex-1)}};case"down":return{state:{...t,toolIndex:Math.min(Math.max(0,n-1),t.toolIndex+1)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function QH(t,e,r){let n=r.snapshots[rt(r.snapshots,t.selectedServer)]?.logLines()??[],o=Fo(n,r.logViewportWidth).length;switch(e.kind){case"up":return{state:{...t,logScrollOffset:Uo(t.logScrollOffset-1,o,r.windowSize)}};case"down":return{state:{...t,logScrollOffset:Uo(t.logScrollOffset+1,o,r.windowSize)}};case"cancel":case"back":return{state:{...t,step:"serverActions"}};default:return{state:t}}}function eG(t,e){return e.kind==="cancel"||e.kind==="back"?{state:{...t,step:"serverActions",authInput:""}}:{state:t}}function uu(t,e){return{...t,step:e,targetScopes:[],targetIndex:0,pendingToggle:null}}function tG(t,e){let r=t.targetScopes.length;if(r===0)return{state:uu(t,"serverActions")};switch(e.kind){case"up":return{state:{...t,targetIndex:qo(t.targetIndex-1,r)}};case"down":return{state:{...t,targetIndex:qo(t.targetIndex+1,r)}};case"cancel":case"back":return{state:uu(t,"serverActions")};case"confirm":{let n=t.targetScopes[t.targetIndex],o=t.pendingToggle;return n&&o?{state:uu({...t,actionIndex:0},"serverList"),effect:{kind:"toggleWrite",server:o.server,disable:o.disable,scope:n}}:{state:uu(t,"serverActions")}}default:return{state:t}}}function zk(t,e,r){switch(t.step){case"serverList":return JH(t,e,r.snapshots);case"serverActions":return YH(t,e,r);case"viewTools":return XH(t,e,r);case"viewLogs":return QH(t,e,r);case"pasteAuthCode":return eG(t,e);case"selectTarget":return tG(t,e);default:return{state:t}}}import{truncateToWidth as Lt,visibleWidth as rG,wrapTextWithAnsi as Br}from"@earendil-works/pi-tui";var Xh="\u2192 ",du=" ";function Nk(t,e,r){return e?r.bold(r.fg("accent",t)):r.fg("text",t)}function gr(t,e){return e>0?Lt(t,e,"\u2026"):""}function Dk(t,e,r,n,o,s,i){let a=Math.max(1,i),c=Tk(r,a),u=" ".repeat(c.gapWidth),d=(h,m,y,v)=>{let b=[c.nameWidth>0?Kh(m,c.nameWidth):"",c.sourceWidth>0?Kh(y,c.sourceWidth):"",c.statusWidth>0?v:""].filter(w=>w.length>0);return h+b.join(u)},l=gr(du,c.prefixWidth),p=[d(l,s.bold(s.fg("accent",gr("Name",c.nameWidth))),s.bold(s.fg("accent",gr("Source",c.sourceWidth))),s.bold(s.fg("accent",gr("Status",c.statusWidth))))];if(e.length===0)p.push(Lt(s.fg("muted","No MCP servers available"),a,"\u2026"));else if(o.total===0)p.push(Lt(s.fg("muted","No matching MCP servers"),a,"\u2026"));else for(let h of n){let m=h.name===t.selectedServer,y=Bh(h),v=gr(y.label,c.statusWidth),b=c.statusWidth-rG(v),w=y.hint?gr(y.hint,b):"",x=s.fg(y.color,v)+(w?s.fg("muted",w):""),S=gr(m?Xh:du,c.prefixWidth);p.push(d(m?s.fg("accent",S):S,Nk(gr(h.name,c.nameWidth),m,s),Nk(gr(Vh(h),c.sourceWidth),m,s),x))}return o.hasOverflow&&p.push(Lt(s.fg("muted",` (${o.current}/${o.total})`),a,"\u2026")),p}var nG={authenticate:{label:"Authenticate",description:"Connect to this server"},viewTools:{label:"View tools",description:"See all tools provided by this server"},viewLogs:{label:"View logs",description:"View logs from this server"},reconnect:{label:"Reconnect",description:"Restart the server connection"},toggle:{label:"Disable",description:"Enable or disable this server"}};function oG(t,e){if(t==="authenticate")return e.status==="auth_required"?{label:"Authenticate",description:"Connect to this server"}:{label:"Reauthenticate",description:"Refresh authentication"};if(t==="toggle"){let r=e.source!=="local";return e.disabled?r?{label:"Enable for this session",description:"Re-enable this server for the current session only"}:{label:"Enable",description:"Enable this server (saved to settings.json)"}:r?{label:"Disable for this session",description:"Disable this server for the current session only"}:{label:"Disable",description:"Disable this server (saved to settings.json)"}}return nG[t]}function Lk(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)];if(!s)return Br(r.fg("muted","No MCP servers available"),o);let i=s.transport==="stdio"?"Command: ":"URL: ",a=Br(r.fg("muted",i+s.connectionInfo),o);s.source==="plugin"&&a.push(...Br(r.fg("muted","Source: plugin (toggles apply to this session only)"),o)),a.push("");let c=cu(s);for(let[u,d]of c.entries()){let l=u===t.actionIndex,f=oG(d,s),p=f.label,h=l?r.bold(r.fg("accent",p)):r.fg("text",p);a.push(Lt((l?Xh:du)+h+r.fg("muted",` - ${f.description}`),o,"\u2026"))}return a}function jk(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)];if(!s)return Br(r.fg("muted","No tools available."),o);if(s.disabled)return Br(r.fg("muted","Server is disabled; no tools are currently available."),o);if(s.tools.length===0)return Br(r.fg("muted","No tools available."),o);let i=s.tools.length,{start:a,end:c}=Ak(t.toolIndex,i,jn),u=[];for(let d=a;d<c;d++){let l=s.tools[d];if(!l)continue;let p=d===t.toolIndex?r.bold(r.fg("accent",l.name)):r.fg("text",l.name);u.push(Lt(r.fg("muted",`${Mk(d,i)} `)+p+(l.disabled?r.fg("muted"," (disabled)"):""),o,"\u2026"))}return u}function Fk(t,e,r,n){let o=Math.max(1,n),i=e[rt(e,t.selectedServer)]?.logLines()??[];if(i.length===0)return Br(r.fg("muted","No logs available yet."),o);let a=Fo(i,o),c=a.length,u=$k(t.logScrollOffset,c,jn),d=[];c>jn&&d.push(Lt(r.fg("muted",u.rangeLabel),o,"\u2026")),u.aboveCount>0&&d.push(Lt(r.fg("dim",`\u2191 ${u.aboveCount} more rows`),o,"\u2026"));for(let l of a.slice(u.start,u.end))d.push(Lt(r.fg("text",l),o,""));return u.belowCount>0&&d.push(Lt(r.fg("dim",`\u2193 ${u.belowCount} more rows`),o,"\u2026")),d}function Uk(t,e,r,n){let o=Math.max(1,n),s=e[rt(e,t.selectedServer)]?.name??"",i=[...Br(r.fg("muted",`Save the toggle for "${s}" to which settings file?`),o),""];for(let[a,c]of t.targetScopes.entries()){let u=a===t.targetIndex,d=u?r.bold(r.fg("accent",Jh(c))):r.fg("text",Jh(c));i.push(Lt((u?Xh:du)+d,o,"\u2026"))}return i}var lu=3;function lG(t){return t.type==="stdio"?t.command:t.url}function fG(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 jk(t){return t.disabled?2:t.status==="auth_required"?0:1}function iG(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:_r(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,canAuthenticate:r.config.type!=="stdio",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:oG(r.config),logLines:()=>sG(r)});return e.sort((r,n)=>jk(r)-jk(n)),e}function aG(t,e){let r=e[tt(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 cG(t){switch(t){case"serverList":return"Type to filter \xB7 \u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function uG(t,e,r,n,o){switch(t.step){case"serverActions":return zk(t,e,n,o);case"viewTools":return Nk(t,e,n,o);case"viewLogs":return Dk(t,e,n,o);case"selectTarget":return Lk(t,e,n,o);default:return Ok(t,e,r.getMatchingItems(),r.getVisibleItems(),r.getMetadata(),n,o)}}function dG(t,e,r,n,o){let s=Math.max(1,o),i=fu(n.bold(n.fg("accent",aG(t,e))),s,"\u2026"),a=t.step==="serverList"&&s>=lu?[...r.renderInput(s),""]:[],c=uG(t,e,r,n,s);return[i,"",...a,...c,"",fu(n.fg("muted",cG(t.step)),s,"\u2026")]}function lG(t,e,r,n,o){let s=Math.max(1,o),i=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),a=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[fu(i,s,"\u2026"),"",fu(a,s,"\u2026")]}function fG(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function pG(t,e,r){let n=i=>i.flatMap(a=>nG(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 hG(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function Fk(t){return t?"Disabling":"Enabling"}function Uk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Qh=class{state=Ak();config;border;serverList;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;queuedManualCodes=[];authInPaste=!1;authPasteBuffer="";authDone;currentWidth;_focused=!1;component=this;get focused(){return this._focused}set focused(e){this._focused=e,this.syncSearchFocus()}constructor(e){this.config=e,this.border=new XH(r=>e.theme.fg("border",r)),this.serverList=new tG({items:[],getIdentity:r=>r.name,getSearchText:r=>r.name,maxVisible:$k})}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){let r=Math.max(1,e);this.currentWidth=r,this.syncSearchFocus();let n;if(this.busy)n=lG(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme,r);else if(this.authenticating)n=pG({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,r);else{let o=this.config.snapshots();this.syncServerList(o),this.clampLogScrollOffset(o,r),n=dG(this.state,o,this.serverList,this.config.theme,r)}return[...this.border.render(r),...n,...this.border.render(r)]}handleInput=e=>{this.dispatch(e)};invalidate(){}syncServerList(e){this.serverList.setItems(e);let r=this.state.selectedServer;r!==null&&this.serverList.selectIdentity(r)||(this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null})}isSearchAvailable(){return this.currentWidth===void 0||this.currentWidth>=lu}syncSearchFocus(){let e=this.currentWidth!==void 0&&this.currentWidth>=lu&&this.state.step==="serverList"&&this.busy===null&&this.authenticating===null;this.serverList.setInputFocused(this._focused&&e)}clampLogScrollOffset(e,r){if(this.state.step!=="viewLogs")return;let n=e[tt(e,this.state.selectedServer)],o=Fo(n?.logLines()??[],r).length,s=Uo(this.state.logScrollOffset,o,jn);s!==this.state.logScrollOffset&&(this.state={...this.state,logScrollOffset:s})}applyAction(e,r){let n=Mk(this.state,e,{snapshots:r,windowSize:jn,logViewportWidth:this.currentWidth??lu});this.state=n.state,n.effect&&this.runEffect(n.effect)}dispatchServerList(e,r){this.syncServerList(r);let n=this.isSearchAvailable(),o=Yh(e,this.config.keybindings,!n);if(o.kind==="up"||o.kind==="down"){o.kind==="up"?this.serverList.selectPrevious():this.serverList.selectNext(),this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null};return}if(o.kind==="confirm"||o.kind==="cancel"){this.applyAction(o,[...this.serverList.getMatchingItems()]);return}n&&this.serverList.handleInput(e)&&this.applyAction({kind:"filterChanged",query:this.serverList.getQuery()},[...this.serverList.getMatchingItems()])}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots();this.state.step==="serverList"?this.dispatchServerList(e,r):this.applyAction(Yh(e,this.config.keybindings),r),this.syncSearchFocus(),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,Fk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(Uk(e,o))}});return}if(n.direct){this.startToggleWrite(e,r,n.direct);return}this.state={...this.state,step:"selectTarget",targetScopes:n.scopes,targetIndex:0,pendingToggle:{server:e,disable:r}},this.config.tui.requestRender()}startToggleWrite(e,r,n){this.startOp(e,Fk(r),async()=>{try{let{notice:o}=await this.config.toggle.applyLocal(e,r,n);o&&this.config.toggle.notify(o)}catch(o){this.config.toggle.notify(Uk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new rG(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=fG(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth("serverActions");return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(eG(e,QH.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&hG(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}exitAuth(e="serverList"){let r=this.authenticating,n=e==="serverActions"&&r!==null&&this.config.snapshots().some(o=>o.name===r)?"serverActions":"serverList";this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:n,selectedServer:n==="serverActions"?r:this.state.selectedServer,actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function qk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new Qh({tui:s,theme:i,keybindings:a,snapshots:()=>iG(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var tm=["list"];function Hk(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 mG(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var gG="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function em(t,e){return e.length>0?[t,...e]:null}function yG(t){let e=[],r=[];for(let o of t.servers.values())(_r(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[em("MCP Server Status:",e.map(Hk)),em("Plugin MCP servers:",r.map(Hk)),em("Diagnostics:",t.diagnostics.map(mG))];return t.servers.size===0&&n.unshift([gG]),n.filter(o=>o!==null).map(o=>o.join(`
145
+ `)).map(r=>r.trimEnd()).filter(r=>r.length>0)}function qk(t){return t.disabled?2:t.status==="auth_required"?0:1}function pG(t){let e=[];for(let r of t.servers.values())e.push({name:r.name,status:r.status,transport:r.config.type,source:_r(r,t.pluginServerHosts,t.hostLeases),registrySource:r.config.registrySource,disabled:r.config.disabled===!0,canAuthenticate:r.config.type!=="stdio",tools:r.tools.map(n=>({name:n.name,disabled:!1})),connectionInfo:lG(r.config),logLines:()=>fG(r)});return e.sort((r,n)=>qk(r)-qk(n)),e}function hG(t,e){let r=e[rt(e,t.selectedServer)]?.name??"";switch(t.step){case"serverActions":return`MCP Servers \u203A ${r}`;case"viewTools":return`MCP Servers \u203A ${r} \u203A Tools`;case"viewLogs":return`MCP Servers \u203A ${r} \u203A Logs`;case"selectTarget":return`MCP Servers \u203A ${r} \u203A Settings file`;default:return"MCP Servers"}}function mG(t){switch(t){case"serverList":return"Type to filter \xB7 \u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Close";case"serverActions":case"selectTarget":return"\u2191\u2193 Navigate \xB7 Enter Select \xB7 Esc Back";default:return"\u2191\u2193 Navigate \xB7 Esc Back"}}function gG(t,e,r,n,o){switch(t.step){case"serverActions":return Lk(t,e,n,o);case"viewTools":return jk(t,e,n,o);case"viewLogs":return Fk(t,e,n,o);case"selectTarget":return Uk(t,e,n,o);default:return Dk(t,e,r.getMatchingItems(),r.getVisibleItems(),r.getMetadata(),n,o)}}function yG(t,e,r,n,o){let s=Math.max(1,o),i=fu(n.bold(n.fg("accent",hG(t,e))),s,"\u2026"),a=t.step==="serverList"&&s>=lu?[...r.renderInput(s),""]:[],c=gG(t,e,r,n,s);return[i,"",...a,...c,"",fu(n.fg("muted",mG(t.step)),s,"\u2026")]}function vG(t,e,r,n,o){let s=Math.max(1,o),i=n.bold(n.fg("accent",`MCP Servers \u203A ${t}`)),a=`${n.fg("accent",r)} ${n.fg("text",`${e} ${t}\u2026`)}`;return[fu(i,s,"\u2026"),"",fu(a,s,"\u2026")]}function _G(){let t;return{promise:new Promise(r=>{t=r}),resolve:t}}function SG(t,e,r){let n=i=>i.flatMap(a=>dG(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 wG(t){return t.length>0&&!t.startsWith("\x1B")&&t>=" "}function Hk(t){return t?"Disabling":"Enabling"}function Gk(t,e){return`Failed to toggle "${t}": ${e instanceof Error?e.message:String(e)}`}var Qh=class{state=Ik();config;border;serverList;busy=null;spinner;opDone;authenticating=null;authStatus="pending";authUrl;authInstructions;authError;authAbort;manualCode;queuedManualCodes=[];authInPaste=!1;authPasteBuffer="";authDone;currentWidth;_focused=!1;component=this;get focused(){return this._focused}set focused(e){this._focused=e,this.syncSearchFocus()}constructor(e){this.config=e,this.border=new sG(r=>e.theme.fg("border",r)),this.serverList=new cG({items:[],getIdentity:r=>r.name,getSearchText:r=>r.name,maxVisible:Ok})}get reconnectSettled(){return this.opDone}get authSettled(){return this.authDone}render(e){let r=Math.max(1,e);this.currentWidth=r,this.syncSearchFocus();let n;if(this.busy)n=vG(this.busy.server,this.busy.verb,this.spinner?.frame??"",this.config.theme,r);else if(this.authenticating)n=SG({server:this.authenticating,status:this.authStatus,url:this.authUrl,instructions:this.authInstructions,input:this.state.authInput,error:this.authError},this.config.theme,r);else{let o=this.config.snapshots();this.syncServerList(o),this.clampLogScrollOffset(o,r),n=yG(this.state,o,this.serverList,this.config.theme,r)}return[...this.border.render(r),...n,...this.border.render(r)]}handleInput=e=>{this.dispatch(e)};invalidate(){}syncServerList(e){this.serverList.setItems(e);let r=this.state.selectedServer;r!==null&&this.serverList.selectIdentity(r)||(this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null})}isSearchAvailable(){return this.currentWidth===void 0||this.currentWidth>=lu}syncSearchFocus(){let e=this.currentWidth!==void 0&&this.currentWidth>=lu&&this.state.step==="serverList"&&this.busy===null&&this.authenticating===null;this.serverList.setInputFocused(this._focused&&e)}clampLogScrollOffset(e,r){if(this.state.step!=="viewLogs")return;let n=e[rt(e,this.state.selectedServer)],o=Fo(n?.logLines()??[],r).length,s=Uo(this.state.logScrollOffset,o,jn);s!==this.state.logScrollOffset&&(this.state={...this.state,logScrollOffset:s})}applyAction(e,r){let n=zk(this.state,e,{snapshots:r,windowSize:jn,logViewportWidth:this.currentWidth??lu});this.state=n.state,n.effect&&this.runEffect(n.effect)}dispatchServerList(e,r){this.syncServerList(r);let n=this.isSearchAvailable(),o=Yh(e,this.config.keybindings,!n);if(o.kind==="up"||o.kind==="down"){o.kind==="up"?this.serverList.selectPrevious():this.serverList.selectNext(),this.state={...this.state,selectedServer:this.serverList.getSelectedIdentity()??null};return}if(o.kind==="confirm"||o.kind==="cancel"){this.applyAction(o,[...this.serverList.getMatchingItems()]);return}n&&this.serverList.handleInput(e)&&this.applyAction({kind:"filterChanged",query:this.serverList.getQuery()},[...this.serverList.getMatchingItems()])}dispatch(e){if(this.busy)return;if(this.authenticating){this.handleAuthInput(e);return}let r=this.config.snapshots();this.state.step==="serverList"?this.dispatchServerList(e,r):this.applyAction(Yh(e,this.config.keybindings),r),this.syncSearchFocus(),this.config.tui.requestRender()}runEffect(e){switch(e.kind){case"close":this.config.done();return;case"reconnect":this.startOp(e.server,"Reconnecting",()=>this.config.reconnect(e.server));return;case"authenticate":this.startAuth(e.server);return;case"toggle":this.startToggle(e.server,e.disable);return;case"toggleWrite":this.startToggleWrite(e.server,e.disable,e.scope);return;default:return}}startToggle(e,r){if(this.busy||this.config.isReconnecting())return;let n=this.config.toggle.classify(e);if(n.kind==="blocked"){this.config.toggle.notify(n.message),this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender();return}if(n.kind==="session"){this.startOp(e,Hk(r),async()=>{try{await this.config.toggle.applySession(e,r)}catch(o){this.config.toggle.notify(Gk(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,Hk(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(Gk(e,o))}})}startOp(e,r,n){this.busy||this.config.isReconnecting()||(this.busy={server:e,verb:r},this.spinner=new uG(()=>this.config.tui.requestRender()),this.opDone=n().finally(()=>{this.spinner?.stop(),this.spinner=void 0,this.busy=null,this.state={...this.state,step:"serverList",actionIndex:0},this.config.tui.requestRender()}))}startAuth(e){if(this.authenticating||this.config.isAuthenticating())return;this.authenticating=e,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.state={...this.state,step:"pasteAuthCode",authInput:""},this.authAbort=new AbortController,this.manualCode=void 0,this.queuedManualCodes.length=0;let r={onAuthUrl:n=>{this.authUrl=n.url,this.authInstructions=n.instructions,this.config.tui.requestRender()},waitForManualCode:()=>{if(this.authenticating!==e)return Promise.resolve(null);let n=this.queuedManualCodes.shift();return n!==void 0?Promise.resolve(n):(this.manualCode??=_G(),this.manualCode.promise)},signal:this.authAbort.signal};this.authDone=this.config.authenticate(e,r).then(()=>{this.authenticating===e&&this.exitAuth()}).catch(n=>{this.authenticating===e&&(this.authStatus="error",this.authError=n instanceof Error?n.message:String(n),this.config.tui.requestRender())})}handleAuthInput(e){if(this.authStatus==="error"){this.exitAuth("serverActions");return}if(this.config.keybindings.matches(e,"tui.select.cancel")){this.authAbort?.abort(),this.manualCode?.resolve(null),this.exitAuth();return}if(this.config.keybindings.matches(e,"tui.select.confirm")){let n=this.state.authInput.trim();if(n){let o=this.manualCode;this.manualCode=void 0,this.state={...this.state,authInput:""},o?o.resolve(n):this.queuedManualCodes.push(n),this.config.tui.requestRender()}return}if(aG(e,iG.backspace)){this.state={...this.state,authInput:this.state.authInput.slice(0,-1)},this.config.tui.requestRender();return}let r=this.consumeAuthPaste(e);r!==void 0&&wG(r)&&(this.state={...this.state,authInput:this.state.authInput+r},this.config.tui.requestRender())}consumeAuthPaste(e){let r=e;if(r.startsWith("\x1B[200~")&&(this.authInPaste=!0,this.authPasteBuffer="",r=r.slice(6)),!this.authInPaste)return r;this.authPasteBuffer+=r;let n=this.authPasteBuffer.indexOf("\x1B[201~");if(n===-1)return;let o=this.authPasteBuffer.slice(0,n),s=this.authPasteBuffer.slice(n+6);this.authInPaste=!1,this.authPasteBuffer="",o&&(this.state={...this.state,authInput:this.state.authInput+o},this.config.tui.requestRender()),s&&this.handleAuthInput(s)}exitAuth(e="serverList"){let r=this.authenticating,n=e==="serverActions"&&r!==null&&this.config.snapshots().some(o=>o.name===r)?"serverActions":"serverList";this.authenticating=null,this.authStatus="pending",this.authUrl=void 0,this.authInstructions=void 0,this.authError=void 0,this.authAbort=void 0,this.manualCode?.resolve(null),this.manualCode=void 0,this.queuedManualCodes.length=0,this.authInPaste=!1,this.authPasteBuffer="",this.state={...this.state,step:n,selectedServer:n==="serverActions"?r:this.state.selectedServer,actionIndex:0,authInput:""},this.config.tui.requestRender()}};async function Zk(t,e,r,n,o){await t.ui.custom((s,i,a,c)=>new Qh({tui:s,theme:i,keybindings:a,snapshots:()=>pG(e),reconnect:r,toggle:n,isReconnecting:()=>e.reconnecting,authenticate:o,isAuthenticating:()=>e.authenticating,done:()=>c(void 0)}).component)}var tm=["list"];function Wk(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 bG(t){return` ! ${t.server?`${t.server}: `:""}${t.message}`}var RG="No MCP servers configured. Add servers under the 'mcpServers' key in ~/.augment/settings.json or your project's .augment/settings.json.";function em(t,e){return e.length>0?[t,...e]:null}function PG(t){let e=[],r=[];for(let o of t.servers.values())(_r(o,t.pluginServerHosts,t.hostLeases)==="plugin"?r:e).push(o);let n=[em("MCP Server Status:",e.map(Wk)),em("Plugin MCP servers:",r.map(Wk)),em("Diagnostics:",t.diagnostics.map(bG))];return t.servers.size===0&&n.unshift([RG]),n.filter(o=>o!==null).map(o=>o.join(`
147
147
  `)).join(`
148
148
 
149
- `)}function vG(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(tm.includes(e))return e}async function _G(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=Oi([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function Gk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return tm.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 qk(n,e,i=>Oi([i],e,t),{classify:i=>Rk({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>Pk({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Ck({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)=>uk({serverName:i,state:e,pi:t,controller:a}));return}let s=vG(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${tm.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(yG(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await _G(n,e,t)}})}import{logger as SG}from"@hermes/logger";var Zk=SG.child({prefix:"pi-mcp"}),rm="augment:feature-flags";function wG(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 Wk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(rm,r=>{let n=wG(r);if(n===void 0){Zk.warn(`${rm} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,Zk.debug(`Received feature-flag snapshot via ${rm} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as bG}from"@hermes/logger";var pu=bG.child({prefix:"pi-mcp"}),nm="augment:mcp-attach-result";function Bk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(nm,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){pu.warn(`${nm} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){pu.debug(`${nm}: 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 hu(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 Qm(r);o.ok?(e.mcpCatalog=o.entries,pu.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,pu.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),Zn(e)&&nn(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as RG}from"@hermes/logger";var zi=RG.child({prefix:"pi-mcp"}),Vk=300*1e3,om=600*1e3;function PG(t){if(!t.shouldProactivelyRefreshTokens)return;let e=Date.now();for(let r of t.servers.values()){let{config:n}=r;if(n.type!=="http"&&n.type!=="sse"||n.disabled||!r.hasRefreshEligibleOAuthCredential())continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(is(o,e)||o.expiresAt>e+om||(zi.debug(`Background refresh: token for MCP server "${r.name}" expires within ${om}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&zi.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{zi.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function Kk(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{PG(t)},Vk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,zi.debug(`Started background MCP OAuth refresh loop (interval ${Vk}ms, buffer ${om}ms)`)}function Jk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,zi.debug("Stopped background MCP OAuth refresh loop"))}import{logger as LG}from"@hermes/logger";function CG(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case es.OAUTH:return"oauth";case es.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 xG(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case en.CLI:return"cli";case en.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 mu(t){if(t==null)return;if(t.length===0)return[];let e=t.map(xG).filter(r=>r!==void 0);return e.length===0?void 0:e}function gu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=CG(r.auth_type),o={name:r.name,type:r.type==="http"||r.type==="sse"||r.type==="stdio"?r.type:void 0,disabled:r.disabled,command:r.command,args:r.args,env:r.env,url:r.url,auth:n==="oauth"?"oauth":void 0,timeoutMs:r.timeout_ms,useShellInterpolation:r.use_shell_interpolation},s=qn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Hn(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof xt?i.message:String(i)}}}function kG(t){let e=t.config?.auth_type;return e===es.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function EG(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 sm(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 TG(t,e,r){if(r!==void 0&&t.added_by===r)return mu(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?mu(n):[]}function AG(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let p=sm(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let p=new Set(s),h=sm(e,r,()=>!0),m=new Set(h.map(w=>w.id)),y=h.filter(w=>p.has(w.id)),v=h.filter(w=>!p.has(w.id)).map(w=>w.id),b=s.filter(w=>!m.has(w));return{selected:y,filteredOutIds:v,missingIds:b,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=sm(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let m=!d.has(p.id)&&a.has(p.id)?TG(p,o,i):mu(p.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function $G(t){return t==null?en.CLOUD_AGENT:void 0}function MG(t){return t.map(e=>({message:`Selected MCP config id "${e}" was not returned by the registry (not opted in to the shared server, deleted, or an unknown id)`}))}function Yk(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Ht(t,n):qt(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 IG(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=gu(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`}};let d=Yk(c,e.id,i,s);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=Yk(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 OG(t){let e=[],r=[],n=[];for(let o of t)kG(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 zG(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=EG(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}function NG(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function yu(t){let e=t.client??new ea(t.creds),{tenant:r,user:n,diagnostics:o}=await lg(e,$G(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=AG({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=OG(a),f=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...MG(u));let p=[],h=new Map,m=new Set(t.localServerNames),y=[...f.filter(w=>i.has(w.id)),...f.filter(w=>!i.has(w.id))];for(let w of y){let x=IG({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:m,workspaceRoot:t.workspaceRoot});NG(x,{servers:p,retainedNames:d,diagnostics:o,nameCollisionFallbacks:h})}let v=zG(p);d.push(...v.droppedNames),o.push(...v.diagnostics);let b=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&b.set(w.id,w.config.name);return{servers:v.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:b,nameCollisionFallbacks:h}}import{logger as DG}from"@hermes/logger";var Ho=DG.child({prefix:"pi-mcp"});function Xk(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Ho.warn("Embedded MCP config is missing an id; ignoring");return}let n=gu(r,"tenant");if(!n.ok){Ho.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Ht(n.server,o):qt(n.server,o)}catch(s){Ho.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function Qk(t,e){let r;try{r=JSON.parse(t)}catch(n){Ho.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return Xk(r,e)}function vu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Ho.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Ho.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=Xk(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 Rt=LG.child({prefix:"pi-mcp"});function jG(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 er(t){We({state:t.state,domain:ot(t.configId),epoch:t.intentEpoch})}function FG(t){let e=new Set;for(let[r,n]of t.servers){let o=Q(t,r,n);(o.owner.kind==="local"||o.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 eE(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function tE(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),Rt.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function Ni(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;er(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Rt.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 UG(t,e){return e.flatMap(r=>tu(t,r)?[r.config]:[])}function qG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function HG(t,e){let r=qG(e);if(r){if(Ni(t,r.error),r.error instanceof Ct)throw r.error;return}let n=UG(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){jG(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 rE(t,e){try{HG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function GG(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 Rt.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 Rt.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 ZG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await Xo(t.state,t.configId),t.superseded()){er(t);return}if(GG(t,e)){er(t);return}try{if(!await Pr({state:t.state,config:e,pi:t.activePi})){er(t);return}}catch(r){throw Ni(t,r),r}Rt.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);rE(t,r??[])}catch(r){if(Ni(t,r),r instanceof Ct)throw r}}async function WG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){er(t),Rt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){tE(r,e),Rt.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),er(t);return}if(await Xo(r,n),o()){er(t);return}try{if((await Promise.all(e.servers.map(c=>Pr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){er(t);return}}catch(a){throw Ni(t,a),a}Rt.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()){er(t);return}tE(r,e),rE(t,i??[])}function BG(t,e){if(typeof e=="string")return Qk(e,t.workspaceRoot??process.cwd())}function nE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Rt.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();let a=BG(r,s?.embeddedConfig);if(a!==void 0&&a.id!==i)return Rt.warn(`Embedded MCP config id ${a.id??"<missing>"} does not match add target ${i}; rejecting`),Promise.resolve();if(!Vi({state:r,configId:i,generation:s?.attachmentGeneration}))return Rt.info(`Ignoring stale live MCP add-server command for config id ${i}`),Promise.resolve();r.sessionRemovedConfigIds.delete(i);let c=Gi({state:r,domain:ot(i),forceNew:!0}),u=FG(r),d=r.currentLoad?.latestPi??e,l=r.registryGeneration;r.liveEditGenerations??=new Map;let f=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,f);let p=()=>r.registryGeneration!==l||r.liveEditGenerations.get(i)!==f,h={state:r,configId:i,activePi:d,connect:o?.connect??bt,report:o?.report??J,intentEpoch:c.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>eE(r,i)},m;if(a)m=ZG(h,a);else{let y=r.credentials;y?m=(o?.discover??yu)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:u}).then(b=>WG(h,b)).catch(b=>{if(!(b instanceof Ct)){Ni(h,b);return}throw b}):(Rt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),er(h),m=Promise.resolve())}return Ki({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>eE(r,i)})}import{logger as VG}from"@hermes/logger";var jt=VG.child({prefix:"pi-mcp"});function sE(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function iE(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?Pt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(Ze(e,r),"retiring"):void 0:(Pe({state:e,name:r,owner:n.owner,revision:n.revision}),Ze(e,r),"released");let c=a.get(r),u=Vo({state:e,name:r,owner:c??n.owner,expectedRevision:n.revision,...o?{expectedHost:o}:{}});if(u)return s&&c===void 0&&e.expectedCredentialDomains.set(r,{kind:"blocked"}),{configRevision:Ze(e,r),leaseRevision:u.lease.revision}}function KG(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=iE({state:e,name:r,lease:c,host:n,isDeselected:sE({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=W(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&Pe({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function JG(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=iE({state:e,name:r,lease:n,isDeselected:sE({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function YG(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=KG({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||JG({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function aE(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=i.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){i.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&s.push(dt(t,l,f.id,f))}try{await Promise.all(s)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Ct(f)}let d=new Map;for(let[l,f]of i){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),ut(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function XG(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:f}]of t.allConfigsById)n&&!n.has(l)||u.has(f)||d.has(f)||(d.add(f),a.push(f));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function QG(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return vu(n,e.workspaceRoot??process.cwd())}async function eZ(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(ot(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(dt(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new Ct(c)}}function tZ(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 rZ(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function nZ(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 oZ(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 aE(e,r.servers,n,s,o!==void 0)}async function cE(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():Xo(t,r.id)))}async function oE(t){return await cE(t.state,t.result),t.state.registryGeneration===t.generation&&await oZ(t),t.result}function sZ(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){jt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=XG(n,r,s);return oE({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=>oE({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function iZ(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),jt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&jt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function aZ(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 uE(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 im(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=W(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&Pe({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function cZ(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){im({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),jt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await cE(e,r),e.registryGeneration!==o)return;let c=uE({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>Pr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;iZ({state:e,result:r,selection:n}),im({state:e,result:r,selection:n,slotReservations:a});let l=aZ({state:e,result:{...r,servers:u}});if(l.length===0)return;let f=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):W(e,m.name))?.owner.kind==="local")return jt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let b=a.get(m.name)?.configRevision;if(b===void 0)return!0;let w=e.configDesiredRevisions.get(m.name);return w!==b?(jt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${b} to ${w} by a concurrent operation`),!1):!0});if(f.length===0)return;jt.info(`Registry discovery: connecting ${f.length} server(s)`);let h=(await s(f,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));await uZ({state:e,pi:i,result:r,generation:o,connect:s})}async function uZ(t){let{state:e,pi:r,result:n,generation:o,connect:s}=t,i=n.nameCollisionFallbacks;if(!(!i||i.size===0))for(let[a,c]of i)for(let u of c){let d=await dZ({state:e,pi:r,generation:o,connect:s,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function dZ(t){let{state:e,pi:r,generation:n,connect:o,name:s,candidate:i}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(s);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===i.id)return"settled";if(!await Pr({state:e,config:i,pi:r})||e.registryGeneration!==n)return"abort";jt.info(`MCP auth fallback: "${s}" (id=${c}) landed ${a.status}; connecting same-named config id=${i.id} in its place`),await o([i],e,e.currentLoad?.latestPi??r,uE({state:e,generation:n}));let d=e.servers.get(s);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===i.id&&d.status==="success"?"settled":"next"}async function lZ(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;jt.warn(i),e.registryGeneration===n&&(await aE(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function fZ(t,e){for(let r of e??[]){let n=ot(r),o=t.registryCredentialIntents.get(n);o?.configName&&t.expectedCredentialDomains.set(o.configName,{kind:"blocked"}),We({state:t,domain:n,epoch:o?.epoch})}}async function pZ(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await cZ({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),im({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 Ct)throw fZ(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 lZ({...t.resultArgs,error:r})}}function dE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??yu,i=o?.connect??bt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return jt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&$m(r,new Set(a.configIds.map(ot)));let c=QG({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){jt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let v of a.configIds??[])We({state:r,domain:ot(v)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=eZ({state:r,previousSelectedIds:d,configIds:a.configIds}),f=tZ({parsedEmbedded:c,configIds:a.configIds}),p=++r.registryGeneration,h=Promise.all([YG(r,a.configIds,f),l]).then(([v])=>v);rZ(r);let m=a.configIds?[...a.configIds]:void 0,y=sZ({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:nZ(r),previousSelectedIds:d,selection:m,generation:p,discover:s});return y?pZ({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:p,connect:i,pi:e}}):Promise.resolve()}import{logger as hZ}from"@hermes/logger";var Vr=hZ.child({prefix:"pi-mcp"});function mZ(t,e){We({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 gZ(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function hE(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function yZ(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function lE(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&&(yZ({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 mE(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function fE(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 gE(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function vZ(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=W(e,r),i=n?Fn(n):void 0;if(s===void 0){Ze(e,r);return}let a=s.host===void 0&&s.owner.kind==="registry"&&i?.kind==="registry"&&s.owner.identity===i.identity,c=o?.incumbent.owner.kind==="registry"&&i?.kind==="registry"&&o.incumbent.owner.identity===i.identity;if(!a&&!c)return;(o?.settled&&s.retirement===o?vm({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):Pe({state:e,name:r,owner:s.owner,revision:s.revision}))&&W(e,r)===void 0&&(gE(e,r),Ze(e,r))}async function am(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let b=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Vr.warn(b),e.diagnostics.push({message:b,origin:"registry"}),new Error(b)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=W(e,a),u=Fn(i),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?Ze(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=W(e,a)?.retirement===d?d:void 0,v=y?.result;if(d&&v?.status==="failed"&&v.transportDisposed!==!0){let b=v.error instanceof Error?v.error:new Error(String(v.error)),w=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Vr.warn(w),e.diagnostics.push({server:a,message:w}),b}try{await Yo(e,a,r,i)}catch(b){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let w=`Live MCP remove-server failed to detach ${a}: ${b instanceof Error?b.message:String(b)}`;throw Vr.warn(w),e.diagnostics.push({server:a,message:w}),b}hE({state:e,configId:r,fence:s})&&(mE(e,r),vZ({state:e,name:a,config:i,retirement:y})),Vr.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 pE(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)}`;Vr.warn(s),e.diagnostics.push({server:r,message:s})}async function _Z(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(pE({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Yo(e,r,n,o.config)]);return pE({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 SZ(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):W(e,n);if(!a||!c||c.owner.kind!=="registry"||c.host!==a)return;e.registryConfigNamesById.set(r,n),e.registryCredentialConfigsById.set(r,{...a.config});let u=e.configDesiredRevisions.get(n),d=e.configDesiredSources.get(n),l=Ze(e,n),f=Pt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),Vr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await _Z({state:e,name:n,configId:r,server:a});if(h&&hE({state:e,configId:r,fence:i})?mE(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),we({state:e,name:n,retirement:f,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&Pe({state:e,name:n,owner:c.owner,revision:c.revision})&&gE(e,n),s(p,e),!h)throw m}function yE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Vr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Vi({state:r,configId:i,generation:s?.attachmentGeneration}))return Vr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Ki({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=fE(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?W(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(i),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(i);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(lE({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>am({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=mZ(r,i);if(u===void 0&&d===void 0)return a(am({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=gZ({state:r,configId:i,liveEditGeneration:h});return a(lE({state:r,configId:i,fence:m,operation:()=>{let y=fE(r,i);return y===void 0?am({state:r,configId:i,pi:e,report:c,sourceFence:m}):SZ({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as wZ}from"@hermes/logger";var Di=wZ.child({prefix:"pi-mcp"}),vE=3,_E=6e4,bZ=1e3,RZ=8e3;function cm(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Wr,i=o?.now??Date.now,a=o?.sleep??on,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return Di.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return Di.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),f=r.mcpRestartState.get(d),p=f&&l-f.lastRestart<_E?f.count+1:1,h=r.currentLoad?.latestPi??e;if(p>vE)return Di.warn(`augment:mcp-restart-server: ${d} exceeded ${vE} restarts within ${_E}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:p,lastRestart:l});let m=Math.min(bZ*2**(p-1),RZ);return(p>1?a(m):Promise.resolve()).then(()=>(Di.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(v=>{let b=`Live MCP restart-server failed for ${d}: ${v instanceof Error?v.message:String(v)}`;Di.warn(b),r.diagnostics.push({server:d,message:b})}).then(()=>{c(h,r)})}import{logger as PZ}from"@hermes/logger";var Li=PZ.child({prefix:"pi-mcp"}),CZ=/^\d+$/,um=1,SE="AUGMENT_ACTIVE_SPACE_ID",xZ="augment-mcp-access-token-";function _u(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function wE(t,e){return e?.["augment:encoding"]!=="base64"?t:/^[A-Za-z0-9+/]*={0,2}$/.test(t)&&t.length%4===0?Buffer.from(t,"base64").toString("utf-8"):t}var Su=class{apiKey;apiUrl;userAgent;fetchImpl;timeoutMs;cache=new Map;inflight=new Map;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??Bu}_headers(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}}lookupBody(e){let r={name:e};return!e.startsWith(xZ)&&Object.hasOwn(process.env,SE)&&(r.active_space_id=process.env[SE]??""),r}getSecret(e){let r=_u(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 sn(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=_u(e),i=(await this._callUpsert({name:o,value:r,scope:um,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!CZ.test(i))throw new Error("user secret upsert response contained an invalid persisted version");let a=BigInt(i).toString();return this.cache.set(o,r),Li.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await sn(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=_u(e);this.cache.delete(r),await this._callDelete({name:r,scope:um}),Li.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>rr?`${o.slice(0,rr)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>rr?`${o.slice(0,rr)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=_u(e);try{let n=await sn(()=>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===um||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:wE(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof lt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&Li.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await sn(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:wE(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof lt&&o.statusCode===404)return Li.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Li.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:this._headers(),body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let s=await o.text().catch(()=>""),i=s.length>rr?`${s.slice(0,rr)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}};function dm(t){return{latestPi:t}}import{randomUUID as kZ}from"node:crypto";import{setToolSource as EZ}from"@augmentcode/auggie-v2";import{logger as TZ}from"@hermes/logger";import{Type as AZ}from"@sinclair/typebox";var RE=TZ.child({prefix:"pi-mcp"}),wu="attach-mcp-server",$Z="augment:mcp-attach-request",MZ=15e3,IZ={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 OZ(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],s=o.find(l=>l.id===r);if(s)return{kind:"match",entry:s};let i=o.filter(l=>l.name.toLowerCase()===n),a=i.length===1?i[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(i.length===0)return{kind:"none"};let c=new Set(tn(t).map(l=>l.id)),u=i.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:i}}function zZ(t,e){let r=e.name.toLowerCase();return tn(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function lm(t,e){let r=zZ(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function NZ(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},MZ);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function bE(t){let e=tn(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function DZ(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return be(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${lm(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return be(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.${lm(r,e)}`)}function LZ(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return be(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,be("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return be(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return be(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return be(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return be(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${lm(n,e)}`);case"NO_ACTIVE_VM":return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return be(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function jZ(t,e,r){if(e.mcpAttachDisabled)return be("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${wu} requires a string "config_id" parameter. ${bE(e)}`);let o=OZ(e,n);if(o.kind==="none")return be(`No MCP server matching "${n}" is available to attach. ${bE(e)}`);if(o.kind==="ambiguous"){let d=o.candidates.map(l=>`"${l.name}" (id: ${l.id})`).join(", ");return be(`Multiple MCP servers match the name "${n}": ${d}. Retry with the exact id of the intended server.`)}let s=o.entry,i=DZ({entry:s,state:e});if(i!==void 0)return i;if(Gu(e,s))return be(`MCP server "${s.name}" is already attached to this session. Use find-tool to discover its tools.`);if(s.state!=="available"&&s.state!=="opt_in_required")return be(`MCP server "${s.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=kZ();RE.info(`attach-mcp-server: requesting attach of "${s.name}" (config=${s.id} request=${a})`);let c=NZ(e,a);t.events.emit($Z,{configId:s.id,requestId:a});let u=await c;return LZ({entry:s,result:u,state:e})}function fm(t,e){let r={name:wu,label:wu,description:"Attach an available MCP server to this session so its tools become usable. Only servers listed as available-but-not-attached in find-tool's description can be attached. Call this tool immediately when the user's request needs one of those servers; it attaches directly without requiring user approval.",parameters:AZ.Unsafe(IZ),execute:(n,o)=>jZ(t,e,o)};EZ(wu,"mcp"),t.registerTool(r),Cr(r),RE.debug("Registered attach-mcp-server tool")}import{logger as FZ}from"@hermes/logger";var Go=FZ.child({prefix:"pi-mcp"});async function UZ(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=Pt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;Ze(t,r);let i=dt(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),Pe({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function qZ(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),Go.warn(r.message))}function HZ(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"}),Go.warn(a);return}try{let a=Hn(r,n);return{...a.type==="stdio"?Ht(a,i):qt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof xt?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"}),Go.warn(c);return}}function GZ(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=HZ({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function ZZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function PE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??bt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return Go.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&&ZZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=UZ(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;qZ(r,i.diagnostics);let{servers:l,blockedNames:f}=GZ(r,i);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(Go.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(p??[]).some(y=>y.config===m&&tu(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;Go.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var rt=WZ.child({prefix:"pi-mcp"}),TE="augment:mcp-oauth-credentials",CE="augment:mcp-header-secrets",xE="augment:mcp-header-secret-failures",kE="augment:credentials",BZ="augment:mcp-config-ids",EE="augment:mcp-configs",VZ="augment:mcp-vfs-servers",KZ="augment:mcp-add-server",JZ="augment:mcp-restart-server",YZ="augment:mcp-remove-server";function XZ(t){if(!t.secretsClient||t.tokens instanceof ns)return;let e=t.tokens;t.tokens=new ns(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),rt.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function QZ(t){if(!t||typeof t!="object"){rt.warn(`${TE} 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 e2(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){Vx({pi:e,state:r,update:{configId:n.targetConfigId,credentials:n.credentials}});return}Object.keys(n.credentials).length>0&&(r.shouldProactivelyRefreshTokens=!1);let o=new Set;for(let i of Object.keys(n.credentials)){let a=r.servers.get(i)?.getRefreshInFlight?.();a&&o.add(a)}let s=()=>{let i=a2({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)){cm({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";rt.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function t2(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(TE,r=>{let n=QZ(r);n&&e2({pi:t,state:e,payload:n})}))}function r2(t){let{state:e,name:r,revision:n}=t,o=Xr(n);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id,u=a?.config.registrySource!==void 0&&c!==void 0&&ot(c)===o;return n.ownerDomain!==void 0?s?.kind==="domain"?s.domain===o:u:s===void 0&&i===void 0?u:s?.kind==="domain"&&(s.domain===o||st(n.domain))||i===n.domain}function n2(t){let{state:e,revision:r}=t,n=Xr(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function o2(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=Dn(i);if(a===void 0){o[s]=i;continue}if(n2({state:e,revision:a})){Mm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(r2({state:e,name:s,revision:a})){o[s]=i;continue}Am({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function s2(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=Dn(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 i2(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=W(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"&&Wr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Te(r)})}}function a2(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=o2({state:r,credentials:n,suppressReconnect:o}),i=ru(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return s2({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(rt.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),i2({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function c2(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(CE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){rt.warn(`${CE} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);my(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(xE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){rt.warn(`${xE} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);yy(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}))}function u2(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(kE,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){rt.warn(`${kE} payload missing apiKey or apiUrl`);return}e.credentials={apiKey:n.apiKey,apiUrl:n.apiUrl,...typeof n.userAgent=="string"?{userAgent:n.userAgent}:{},...typeof n.userId=="string"?{userId:n.userId}:{}},e.secretsClient=new Su(e.credentials),XZ(e)}),t.events.on(BZ,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,fm(e.currentLoad?.latestPi??t,e)),dE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{rt.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;Te(e),hu(n,e)})}))}function d2(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on(EE,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){rt.warn(`${EE} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=vu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&Pr({state:e,config:i,pi:t}).catch(a=>{rt.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}rt.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function l2(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(VZ,r=>{PE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Te(e)})}))}function f2(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(KZ,r=>{nE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{rt.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;Te(e),hu(n,e)})}))}function p2(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(JZ,r=>{cm({pi:t,state:e,data:r}).then(()=>{Te(e)})}))}function h2(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(YZ,r=>{yE({pi:t,state:e,data:r}).catch(n=>{rt.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Te(e),hu(n,e)})}))}function VX(t){return hy(t)}var AE=t=>{let e=ie();e.currentLoad=dm(t);let r=!1;Gk(t,e),t2(t,e),c2(t,e),u2(t,e),d2(t,e),l2(t,e),f2(t,e),p2(t,e),h2(t,e),Wk(t,e),Bk(t,e),e.mcpAttachCloudSignaled&&fm(t,e),t.on("session_start",(n,o)=>{e.currentLoad=dm(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,Kk(e),e.connectStarted)Zn(e)?(nn(t),Xi(t)):Km(t,e),Te(e);else{e.connectStarted=!0,Qo()&&nn(t);let{servers:i,diagnostics:a}=Gn(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),rt.warn(c.message);bt(i,e,t).then(()=>Gx(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Te(e)})}r||(r=!0,t.events.emit(yk,bk(t,e)))}),t.on("session_shutdown",()=>{Jk(e)})};Zm(AE);var KX=AE;export{KX as default,VX as setMcpErrorReporter};
149
+ `)}function CG(t){let e=t.trim().split(/\s+/)[0];if(!e)return"list";if(tm.includes(e))return e}async function xG(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=Oi([...e.servers.keys()],e,r);t.mode!=="interactive"&&await n}function Bk(t,e){t.registerCommand("mcp",{description:"List configured MCP servers and their status",getArgumentCompletions:r=>{let n=r.trim().toLowerCase();return tm.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 Zk(n,e,i=>Oi([i],e,t),{classify:i=>xk({server:i,state:e,cwd:n.cwd,agentDir:n.agentDir}),applySession:(i,a)=>kk({server:i,disable:a,state:e,pi:t}),applyLocal:(i,a,c)=>Ek({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)=>fk({serverName:i,state:e,pi:t,controller:a}));return}let s=CG(r);if(!s){n.ui.notify(`Unknown /mcp subcommand. Available: ${tm.join(", ")}.`,"warning");return}if(s==="list"){n.ui.notify(PG(e),"info");return}else return s}}),t.registerCommand("restart-mcp",{description:"Restart all configured MCP servers",handler:async(r,n)=>{await xG(n,e,t)}})}import{logger as kG}from"@hermes/logger";var Vk=kG.child({prefix:"pi-mcp"}),rm="augment:feature-flags";function EG(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 Kk(t,e){e.featureFlagsListenerBound||(e.featureFlagsListenerBound=!0,t.events.on(rm,r=>{let n=EG(r);if(n===void 0){Vk.warn(`${rm} payload missing a flags object or has a non-string errorStatus`);return}e.featureFlags=n,Vk.debug(`Received feature-flag snapshot via ${rm} event`+(n.errorStatus?` (errorStatus=${n.errorStatus})`:""))}))}import{logger as TG}from"@hermes/logger";var pu=TG.child({prefix:"pi-mcp"}),nm="augment:mcp-attach-result";function Jk(t,e){e.attachResultListenerBound||(e.attachResultListenerBound=!0,t.events.on(nm,r=>{let n=r,o=typeof n?.requestId=="string"?n.requestId:"";if(!o){pu.warn(`${nm} payload missing requestId`);return}let s=e.attachResolvers.get(o);if(!s){pu.debug(`${nm}: 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 hu(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 rg(r);o.ok?(e.mcpCatalog=o.entries,pu.debug(`MCP catalog refreshed: ${o.entries.length} entry(s)`)):o.disable&&(e.mcpAttachDisabled=!0,e.mcpCatalog=void 0,pu.debug("MCP catalog endpoint unavailable (404); disabling attach for this session")),Zn(e)&&nn(e.currentLoad?.latestPi??t)})().finally(()=>{e.catalogRefreshInFlight=void 0});return e.catalogRefreshInFlight=n,n}import{logger as AG}from"@hermes/logger";var zi=AG.child({prefix:"pi-mcp"}),Yk=300*1e3,om=600*1e3;function $G(t){if(!t.shouldProactivelyRefreshTokens)return;let e=Date.now();for(let r of t.servers.values()){let{config:n}=r;if(n.type!=="http"&&n.type!=="sse"||n.disabled||!r.hasRefreshEligibleOAuthCredential())continue;let o=t.tokens.get(r.name);o&&o.expiresAt!==void 0&&(is(o,e)||o.expiresAt>e+om||(zi.debug(`Background refresh: token for MCP server "${r.name}" expires within ${om}ms; refreshing`),r.refreshTokenIfPossible().then(s=>{s.kind!=="refreshed"&&zi.warn(`Background refresh for MCP server "${r.name}" did not complete (${s.kind})`)}).catch(()=>{zi.warn(`Background refresh for MCP server "${r.name}" rejected unexpectedly`)})))}}function Xk(t){if(t.backgroundRefreshIntervalId!==void 0||!t.shouldProactivelyRefreshTokens)return;let e=setInterval(()=>{$G(t)},Yk);typeof e.unref=="function"&&e.unref(),t.backgroundRefreshIntervalId=e,zi.debug(`Started background MCP OAuth refresh loop (interval ${Yk}ms, buffer ${om}ms)`)}function Qk(t){t.backgroundRefreshIntervalId!==void 0&&(clearInterval(t.backgroundRefreshIntervalId),t.backgroundRefreshIntervalId=void 0,zi.debug("Stopped background MCP OAuth refresh loop"))}import{logger as ZG}from"@hermes/logger";function MG(t){if(t==null)return;if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case es.OAUTH:return"oauth";case es.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 IG(t){if(typeof t=="number"||!Number.isNaN(Number(t)))switch(Number(t)){case en.CLI:return"cli";case en.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 mu(t){if(t==null)return;if(t.length===0)return[];let e=t.map(IG).filter(r=>r!==void 0);return e.length===0?void 0:e}function gu(t,e){let r=t.config;if(!r)return{ok:!1,reason:"no config payload"};let n=MG(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=qn(o);(s==="http"||s==="sse")&&r.env&&(o.headers=r.env);try{return{ok:!0,server:{...Hn(r.name??t.id,o),id:t.id,registrySource:e}}}catch(i){return{ok:!1,reason:i instanceof xt?i.message:String(i)}}}function OG(t){let e=t.config?.auth_type;return e===es.OAUTH||typeof e=="string"&&(e.toLowerCase()==="oauth"||e.toLowerCase()==="mcp_auth_type_oauth")?t.has_oauth_credentials!==!0&&t.needs_reauthentication!==!0:!1}function zG(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 sm(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 NG(t,e,r){if(r!==void 0&&t.added_by===r)return mu(t.enabled_products);let n=e[t.id]?.enabled_products;return n!==void 0?mu(n):[]}function DG(t){let{tenantConfigs:e,userConfigs:r,enabledSharedServerIds:n,serverProductPreferences:o,configIds:s,currentUserId:i}=t;if(s!=null&&s.length===0){let p=sm(e,r,()=>!0);return{selected:[],filteredOutIds:p.map(h=>h.id),missingIds:[],retainedNames:[]}}if(s!=null){let p=new Set(s),h=sm(e,r,()=>!0),m=new Set(h.map(w=>w.id)),y=h.filter(w=>p.has(w.id)),v=h.filter(w=>!p.has(w.id)).map(w=>w.id),b=s.filter(w=>!m.has(w));return{selected:y,filteredOutIds:v,missingIds:b,retainedNames:[]}}let a=new Set(n),c=[];for(let p of e)a.has(p.id)||c.push(p.id);let u=sm(e,r,p=>a.has(p)),d=new Set(r.map(p=>p.id)),l=[],f=[];for(let p of u){let m=!d.has(p.id)&&a.has(p.id)?NG(p,o,i):mu(p.enabled_products);m===void 0||m.includes("cloud_agent")?l.push(p):(c.push(p.id),p.config?.name&&f.push(p.config.name))}return{selected:l,filteredOutIds:c,missingIds:[],retainedNames:f}}function LG(t){return t==null?en.CLOUD_AGENT:void 0}function jG(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 eE(t,e,r,n){try{return{ok:!0,server:t.type==="stdio"?Ht(t,n):qt(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 FG(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=gu(e,i);if(!a.ok){let d=e.config?.name,l={server:d,message:`Skipped registry MCP server "${d??e.id}" (id=${e.id}, ${i}): ${a.reason}`};return d?{kind:"retained",name:d,diagnostic:l}:{kind:"dropped",diagnostic:l}}let c=a.server;if(o.has(c.name)){if(n.has(c.name))return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): a local server with the same name takes precedence`}};let d=eE(c,e.id,i,s);return{kind:"retained",name:c.name,diagnostic:{server:c.name,message:`Skipped registry MCP server "${c.name}" (id=${e.id}, ${i}): name collides with a higher-precedence registry server`},fallbackServer:d.ok?d.server:void 0}}let u=eE(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 UG(t){let e=[],r=[],n=[];for(let o of t)OG(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 qG(t){let e=[],r=[],n=[],o=new Set;for(let s of t){let i=zG(s);if(o.has(i)){r.push(s.name),n.push({server:s.name,message:`Skipped duplicate MCP server "${s.name}" (id=${s.id}): byte-identical to another selected server`});continue}o.add(i),e.push(s)}return{servers:e,droppedNames:r,diagnostics:n}}function HG(t,e){if(t.kind!=="connected"&&t.diagnostic&&e.diagnostics.push(t.diagnostic),t.kind==="connected")e.servers.push(t.server);else if(t.kind==="retained"&&(e.retainedNames.push(t.name),t.fallbackServer!==void 0)){let r=e.nameCollisionFallbacks.get(t.name)??[];r.push(t.fallbackServer),e.nameCollisionFallbacks.set(t.name,r)}}async function yu(t){let e=t.client??new ea(t.creds),{tenant:r,user:n,diagnostics:o}=await hg(e,LG(t.configIds)),s=n.mcp_configs??[],i=new Set(s.map(w=>w.id)),{selected:a,filteredOutIds:c,missingIds:u,retainedNames:d}=DG({tenantConfigs:r.mcp_configs??[],userConfigs:s,enabledSharedServerIds:n.enabled_shared_server_ids??[],serverProductPreferences:n.server_product_preferences??{},configIds:t.configIds,currentUserId:t.currentUserId}),l=UG(a),f=l.selected;c.push(...l.droppedIds),o.push(...l.diagnostics),o.push(...jG(u));let p=[],h=new Map,m=new Set(t.localServerNames),y=[...f.filter(w=>i.has(w.id)),...f.filter(w=>!i.has(w.id))];for(let w of y){let x=FG({payload:w,userIds:i,localServerNames:t.localServerNames,seenNames:m,workspaceRoot:t.workspaceRoot});HG(x,{servers:p,retainedNames:d,diagnostics:o,nameCollisionFallbacks:h})}let v=qG(p);d.push(...v.droppedNames),o.push(...v.diagnostics);let b=new Map;for(let w of[...r.mcp_configs??[],...s])w.config?.name&&b.set(w.id,w.config.name);return{servers:v.servers,diagnostics:o,filteredOutIds:c,retainedNames:d,namesById:b,nameCollisionFallbacks:h}}import{logger as GG}from"@hermes/logger";var Ho=GG.child({prefix:"pi-mcp"});function tE(t,e){let r=t;if(!r||typeof r!="object"||!r.id){Ho.warn("Embedded MCP config is missing an id; ignoring");return}let n=gu(r,"tenant");if(!n.ok){Ho.warn(`Embedded MCP config '${r.id}' is not convertible; ignoring: ${n.reason}`);return}let o=e??process.cwd();try{return n.server.type==="stdio"?Ht(n.server,o):qt(n.server,o)}catch(s){Ho.warn(`Embedded MCP config '${r.id}' failed expansion; ignoring: ${s instanceof Error?s.message:String(s)}`);return}}function rE(t,e){let r;try{r=JSON.parse(t)}catch(n){Ho.warn(`Failed to parse embedded MCP config: ${n instanceof Error?n.name:"non-Error thrown"}`);return}return tE(r,e)}function vu(t,e){let r=t;if(typeof r=="string")try{r=JSON.parse(r)}catch(i){Ho.warn(`Failed to parse embedded MCP configs: ${i instanceof Error?i.name:"non-Error thrown"}`);return}if(!Array.isArray(r)){Ho.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=tE(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 Rt=ZG.child({prefix:"pi-mcp"});function WG(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 er(t){Be({state:t.state,domain:ot(t.configId),epoch:t.intentEpoch})}function BG(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 nE(t,e){for(let r of t.servers.values())if(r.config.id===e)return!0;return!1}function oE(t,e){for(let r of e.diagnostics)t.diagnostics.push({...r,origin:"registry"}),Rt.warn(r.message);for(let[r,n]of e.namesById??[])t.registryConfigNamesById.set(r,n)}function Ni(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;er(t);let i=`Live MCP add-server failed for config id ${n}: ${e instanceof Error?e.message:String(e)}`;if(Rt.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 VG(t,e){return e.flatMap(r=>tu(t,r)?[r.config]:[])}function KG(t){return t.find(e=>e.status==="failed"||e.status==="unavailable")}function JG(t,e){let r=KG(e);if(r){if(Ni(t,r.error),r.error instanceof Ct)throw r.error;return}let n=VG(t.state,e).filter(o=>o.id===t.configId);if(n.length>0&&!t.superseded()){WG(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 sE(t,e){try{JG(t,e)}finally{t.superseded()||t.report(t.state.currentLoad?.latestPi??t.activePi,t.state)}}function YG(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 Rt.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 Rt.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 XG(t,e){if(t.state.missingHostRemovals.has(t.configId)&&await Xo(t.state,t.configId),t.superseded()){er(t);return}if(YG(t,e)){er(t);return}try{if(!await Pr({state:t.state,config:e,pi:t.activePi})){er(t);return}}catch(r){throw Ni(t,r),r}Rt.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);sE(t,r??[])}catch(r){if(Ni(t,r),r instanceof Ct)throw r}}async function QG(t,e){let{state:r,configId:n,superseded:o,hasLiveHostForId:s}=t;if(o()){er(t),Rt.info(`Live MCP add-server for config id ${n} superseded by a newer selection; discarding`);return}if(e.servers.length===0){oE(r,e),Rt.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),er(t);return}if(await Xo(r,n),o()){er(t);return}try{if((await Promise.all(e.servers.map(c=>Pr({state:r,config:c,pi:t.activePi})))).some(c=>!c)){er(t);return}}catch(a){throw Ni(t,a),a}Rt.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()){er(t);return}oE(r,e),sE(t,i??[])}function eZ(t,e){if(typeof e=="string")return rE(e,t.workspaceRoot??process.cwd())}function iE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Rt.warn("augment:mcp-add-server payload missing configId"),Promise.resolve();let a=eZ(r,s?.embeddedConfig);if(a!==void 0&&a.id!==i)return Rt.warn(`Embedded MCP config id ${a.id??"<missing>"} does not match add target ${i}; rejecting`),Promise.resolve();if(!Vi({state:r,configId:i,generation:s?.attachmentGeneration}))return Rt.info(`Ignoring stale live MCP add-server command for config id ${i}`),Promise.resolve();r.sessionRemovedConfigIds.delete(i);let c=Gi({state:r,domain:ot(i),forceNew:!0}),u=BG(r),d=r.currentLoad?.latestPi??e,l=r.registryGeneration;r.liveEditGenerations??=new Map;let f=(r.liveEditGenerations.get(i)??0)+1;r.liveEditGenerations.set(i,f);let p=()=>r.registryGeneration!==l||r.liveEditGenerations.get(i)!==f,h={state:r,configId:i,activePi:d,connect:o?.connect??bt,report:o?.report??J,intentEpoch:c.epoch,superseded:p,sourceOwnership:()=>!p(),hasLiveHostForId:()=>nE(r,i)},m;if(a)m=XG(h,a);else{let y=r.credentials;y?m=(o?.discover??yu)({configIds:[i],creds:y,currentUserId:y.userId,workspaceRoot:r.workspaceRoot??process.cwd(),localServerNames:u}).then(b=>QG(h,b)).catch(b=>{if(!(b instanceof Ct)){Ni(h,b);return}throw b}):(Rt.warn("augment:mcp-add-server received before credentials; cannot fetch registry config"),er(h),m=Promise.resolve())}return Ki({state:r,configId:i,generation:s?.attachmentGeneration,operation:m,wasApplied:()=>nE(r,i)})}import{logger as tZ}from"@hermes/logger";var jt=tZ.child({prefix:"pi-mcp"});function cE(t){let{selectedIds:e,config:r}=t;return e!==void 0&&(r?.id===void 0||!e.has(r.id))}function uE(t){let{state:e,name:r,lease:n,host:o,isDeselected:s,selectionIsEmpty:i,replacementOwners:a}=t;if(i)return o?Pt({state:e,name:r,owner:n.owner,revision:n.revision,host:o})?(We(e,r),"retiring"):void 0:(Pe({state:e,name:r,owner:n.owner,revision:n.revision}),We(e,r),"released");let c=a.get(r),u=Vo({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:We(e,r),leaseRevision:u.lease.revision}}function rZ(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=uE({state:e,name:r,lease:c,host:n,isDeselected:cE({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=W(e,r)?.retirement;return n.beginDisposal?.(),n.dispose({strict:!0}).then(()=>{l&&we({state:e,name:r,retirement:l,result:{status:"retired"}}),d==="retiring"&&Pe({state:e,name:r,owner:c.owner,revision:c.revision})},f=>{throw l&&we({state:e,name:r,retirement:l,result:{status:"failed",error:f}}),f})}function nZ(t){let{state:e,name:r,lease:n,selectedIds:o,replacementOwners:s,slotReservations:i}=t,a=uE({state:e,name:r,lease:n,isDeselected:cE({selectedIds:o,config:e.registryCredentialConfigs.get(r)}),selectionIsEmpty:o?.size===0,replacementOwners:s});a&&a!=="released"&&a!=="retiring"&&i.set(r,a)}async function oZ(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=rZ({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||nZ({state:t,name:a,lease:c,selectedIds:n,replacementOwners:r,slotReservations:o});return await Promise.all(s),o}async function dE(t,e,r,n,o){let s=[],i=new Map(e.map(l=>[l.name,l])),a=o?new Set(r):new Set,c=new Set([...a].flatMap(l=>{let f=t.registryConfigNamesById.get(l);return f===void 0?[]:[f]})),u=new Set(e.flatMap(l=>l.id===void 0?[]:[l.id]));for(let[l,f]of t.registryCredentialConfigs){let p=i.get(l);if(p===void 0&&f.id!==void 0&&n.has(f.id)&&!u.has(f.id)){i.set(l,f);continue}let h=f.id===void 0?c.has(l):a.has(f.id);p===void 0&&!h&&s.push(dt(t,l,f.id,f))}try{await Promise.all(s)}catch(l){let f=`Registry credential reconciliation failed: ${l instanceof Error?l.message:String(l)}`;throw new Ct(f)}let d=new Map;for(let[l,f]of i){let p=t.registryCredentialConfigs.get(l);p&&(d.set(l,{...p}),ut(p,f)&&f.id!==void 0&&t.registryCredentialConfigsById.set(f.id,{...f}))}t.registryCredentialConfigs=d}function sZ(t,e,r){let n=e!=null&&e.length>0?new Set(e):void 0,o=[],s=[],i=[],a=[],c=new Set(r);for(let l of t.servers){if(n&&l.id!==void 0&&!n.has(l.id)){i.push(l.id);continue}if(c.has(l.name)){s.push({server:l.name,message:`Skipped embedded MCP server "${l.name}" (id=${l.id}): a local server with the same name takes precedence`}),a.push(l.name);continue}c.add(l.name),o.push(l)}let u=new Set(o.map(l=>l.name)),d=new Set(a);for(let[l,{name:f}]of t.allConfigsById)n&&!n.has(l)||u.has(f)||d.has(f)||(d.add(f),a.push(f));return{servers:o,diagnostics:s,filteredOutIds:i,retainedNames:a}}function iZ(t){let{state:e,configIds:r}=t,n=e.embeddedRegistryConfigs;if(e.embeddedRegistryConfigs=void 0,!(n===void 0||r?.length===0))return vu(n,e.workspaceRoot??process.cwd())}async function aZ(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(ot(d))?.configName===c);if(c&&!u){let d=e.registryCredentialConfigs.get(c);s.push({id:a,name:c}),i.push(dt(e,c,a,d?.id===a?d:void 0))}}try{await Promise.all(i);for(let{id:a,name:c}of s)e.registryCredentialConfigs.get(c)?.id===a&&e.registryCredentialConfigs.delete(c)}catch(a){let c=`Registry credential deselection failed: ${a instanceof Error?a.message:String(a)}`;throw new Ct(c)}}function cZ(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 uZ(t){t.lastSuccessfulVfsMcpSignature=void 0,t.blockedVfsMcpNames.clear(),t.diagnostics=t.diagnostics.filter(e=>e.origin!=="registry"),t.dynamicallyAddedConfigIds.clear(),t.failedAddConfigIds.clear(),t.nameCollisionAddConfigIds.clear(),t.authFallbackDisplacedConfigIds.clear(),t.sessionRemovedConfigIds.clear(),t.selectedRegistryConfigIds=void 0}function dZ(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 lZ(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 dE(e,r.servers,n,s,o!==void 0)}async function lE(t,e){await Promise.all(e.servers.map(r=>r.id===void 0?Promise.resolve():Xo(t,r.id)))}async function aE(t){return await lE(t.state,t.result),t.state.registryGeneration===t.generation&&await lZ(t),t.result}function fZ(t){let{state:e,configIds:r,parsedEmbedded:n,credentials:o,localServerNames:s,previousSelectedIds:i,selection:a,generation:c,discover:u}=t;if(n){jt.info(`Registry selection: using ${n.servers.length} embedded config(s) (no registry fetch)`);let l=sZ(n,r,s);return aE({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=>aE({state:e,result:l,previousSelectedIds:i,selection:a,generation:c})):void 0}function pZ(t){let{state:e,result:r,selection:n}=t;e.selectedRegistryConfigIds=n;for(let o of r.diagnostics)e.diagnostics.push({...o,origin:"registry"}),jt.warn(o.message);for(let[o,s]of r.namesById??[])e.registryConfigNamesById.set(o,s);r.filteredOutIds.length>0&&jt.info(`Registry discovery filtered out ${r.filteredOutIds.length} server(s) by selection/opt-in/product`)}function hZ(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 fE(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 im(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=W(e,i);c?.owner.kind==="registry"&&c.host===void 0&&c.revision===a.leaseRevision&&Pe({state:e,name:i,owner:c.owner,revision:a.leaseRevision})}}async function mZ(t){let{state:e,result:r,selection:n,generation:o,connect:s,pi:i,slotReservations:a}=t;if(e.registryGeneration!==o){im({state:e,result:{servers:[],diagnostics:[],filteredOutIds:[]},selection:void 0,slotReservations:a}),jt.info(`Registry discovery superseded by a newer selection; skipping ${r.servers.length} server(s)`);return}if(await lE(e,r),e.registryGeneration!==o)return;let c=fE({state:e,generation:o}),u=r.servers.filter(c);if((await Promise.all(u.map(m=>Pr({state:e,config:m,pi:i})))).some(m=>!m)||e.registryGeneration!==o)return;pZ({state:e,result:r,selection:n}),im({state:e,result:r,selection:n,slotReservations:a});let l=hZ({state:e,result:{...r,servers:u}});if(l.length===0)return;let f=l.filter(m=>{let y=e.servers.get(m.name);if((y?Q(e,m.name,y):W(e,m.name))?.owner.kind==="local")return jt.info(`Registry install of "${m.name}" skipped: a local server claimed the name during discovery`),!1;let b=a.get(m.name)?.configRevision;if(b===void 0)return!0;let w=e.configDesiredRevisions.get(m.name);return w!==b?(jt.info(`Registry install of "${m.name}" skipped: slot revision advanced from ${b} to ${w} by a concurrent operation`),!1):!0});if(f.length===0)return;jt.info(`Registry discovery: connecting ${f.length} server(s)`);let h=(await s(f,e,e.currentLoad?.latestPi??i,c))?.find(m=>m.status==="failed");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));await gZ({state:e,pi:i,result:r,generation:o,connect:s})}async function gZ(t){let{state:e,pi:r,result:n,generation:o,connect:s}=t,i=n.nameCollisionFallbacks;if(!(!i||i.size===0))for(let[a,c]of i)for(let u of c){let d=await yZ({state:e,pi:r,generation:o,connect:s,name:a,candidate:u});if(d==="abort")return;if(d==="settled")break}}async function yZ(t){let{state:e,pi:r,generation:n,connect:o,name:s,candidate:i}=t;if(e.registryGeneration!==n)return"abort";let a=e.servers.get(s);if(!a||a.status!=="auth_required"&&a.status!=="failed")return"settled";let c=a.config.id;if(c===void 0||c===i.id)return"settled";if(!await Pr({state:e,config:i,pi:r})||e.registryGeneration!==n)return"abort";jt.info(`MCP auth fallback: "${s}" (id=${c}) landed ${a.status}; connecting same-named config id=${i.id} in its place`),await o([i],e,e.currentLoad?.latestPi??r,fE({state:e,generation:n}));let d=e.servers.get(s);return d?.config.id!==c&&e.authFallbackDisplacedConfigIds.add(c),d!==void 0&&d.config.id===i.id&&d.status==="success"?"settled":"next"}async function vZ(t){let{state:e,error:r,generation:n,previousSelectedIds:o,selection:s}=t,i=`Registry discovery failed: ${r instanceof Error?r.message:String(r)}`;jt.warn(i),e.registryGeneration===n&&(await dE(e,[],o,new Set(s??[]),s!==void 0),e.selectedRegistryConfigIds=s,e.diagnostics.push({message:i,origin:"registry"}))}function _Z(t,e){for(let r of e??[]){let n=ot(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 SZ(t){let e;try{let r=await Promise.all([t.disposal,t.discovery]);e=r[0],await mZ({...t.resultArgs,result:r[1],slotReservations:e})}catch(r){if(e??=await t.disposal.catch(()=>new Map),im({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 Ct)throw _Z(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 vZ({...t.resultArgs,error:r})}}function pE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.discover??yu,i=o?.connect??bt,a=n;if(!a||typeof a!="object"||Array.isArray(a))return jt.warn("augment:mcp-config-ids payload is not an object"),Promise.resolve();Array.isArray(a.configIds)&&Om(r,new Set(a.configIds.map(ot)));let c=iZ({state:r,configIds:a.configIds}),u=r.credentials;if(!(c||u)){jt.warn("augment:mcp-config-ids received before credentials; skipping registry discovery");for(let v of a.configIds??[])Be({state:r,domain:ot(v)});return Promise.resolve()}let d=r.selectedRegistryConfigIds??[],l=aZ({state:r,previousSelectedIds:d,configIds:a.configIds}),f=cZ({parsedEmbedded:c,configIds:a.configIds}),p=++r.registryGeneration,h=Promise.all([oZ(r,a.configIds,f),l]).then(([v])=>v);uZ(r);let m=a.configIds?[...a.configIds]:void 0,y=fZ({state:r,configIds:a.configIds,parsedEmbedded:c,credentials:u,localServerNames:dZ(r),previousSelectedIds:d,selection:m,generation:p,discover:s});return y?SZ({disposal:h,discovery:y,resultArgs:{state:r,previousSelectedIds:d,selection:m,generation:p,connect:i,pi:e}}):Promise.resolve()}import{logger as wZ}from"@hermes/logger";var Vr=wZ.child({prefix:"pi-mcp"});function bZ(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 RZ(t){let{state:e,configId:r,liveEditGeneration:n}=t,o={liveEditGeneration:n,registryGeneration:e.registryGeneration};return e.missingHostRemovalFences.set(r,o),o}function yE(t){let{state:e,configId:r,fence:n}=t;return e.registryGeneration===n.registryGeneration&&e.liveEditGenerations.get(r)===n.liveEditGeneration}function PZ(t){let{state:e,configId:r,fence:n}=t;e.missingHostRemovalFences.get(r)===n&&e.missingHostRemovalFences.delete(r)}function hE(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&&(PZ({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 vE(t,e){t.failedAddConfigIds.delete(e),t.nameCollisionAddConfigIds.delete(e),t.dynamicallyAddedConfigIds.delete(e),t.sessionRemovedConfigIds.add(e)}function mE(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 _E(t,e){let r=t.preservedCredentialIdentities?.get(e);r?.id&&t.expectedCredentialDomains.set(e,{kind:"domain",domain:`user:${r.id}`})}function CZ(t){let{state:e,name:r,config:n,retirement:o}=t;if(e.servers.has(r))return;let s=W(e,r),i=n?Fn(n):void 0;if(s===void 0){We(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?wm({state:e,name:r,retiredOwner:o.incumbent.owner,retirement:o}):Pe({state:e,name:r,owner:s.owner,revision:s.revision}))&&W(e,r)===void 0&&(_E(e,r),We(e,r))}async function am(t){let{state:e,configId:r,pi:n,report:o,sourceFence:s}=t,i=e.registryCredentialConfigsById.get(r),a=i?.name;if(!i||!a){let b=`Live MCP remove-server cannot retire config id ${r}: exact registry identity is unavailable`;throw Vr.warn(b),e.diagnostics.push({message:b,origin:"registry"}),new Error(b)}e.configDesiredRevisions??=new Map,e.configDesiredSources??=new Map;let c=W(e,a),u=Fn(i),d=c?.retirement?.incumbent.owner.kind==="registry"&&u.kind==="registry"&&c.retirement.incumbent.owner.identity===u.identity?c.retirement:void 0,l=c!==void 0&&c.host===void 0&&c.owner.kind==="registry"&&u.kind==="registry"&&c.owner.identity===u.identity,f=e.configDesiredRevisions.get(a),p=e.configDesiredSources.get(a),h=l&&d?.settled!==!0?We(e,a):void 0;if(d&&!d.settled&&(await d.teardown).status==="retired"&&!l)return;let y=W(e,a)?.retirement===d?d:void 0,v=y?.result;if(d&&v?.status==="failed"&&v.transportDisposed!==!0){let b=v.error instanceof Error?v.error:new Error(String(v.error)),w=`Live MCP remove-server cannot complete ${a}: strict transport disposal is unresolved`;throw Vr.warn(w),e.diagnostics.push({server:a,message:w}),b}try{await Yo(e,a,r,i)}catch(b){h!==void 0&&e.configDesiredRevisions.get(a)===h&&(f===void 0?e.configDesiredRevisions.delete(a):e.configDesiredRevisions.set(a,f),p===void 0?e.configDesiredSources.delete(a):e.configDesiredSources.set(a,p));let w=`Live MCP remove-server failed to detach ${a}: ${b instanceof Error?b.message:String(b)}`;throw Vr.warn(w),e.diagnostics.push({server:a,message:w}),b}yE({state:e,configId:r,fence:s})&&(vE(e,r),CZ({state:e,name:a,config:i,retirement:y})),Vr.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 gE(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)}`;Vr.warn(s),e.diagnostics.push({server:r,message:s})}async function xZ(t){let{state:e,name:r,configId:n,server:o}=t,[s]=await Promise.allSettled([o.dispose({strict:!0})]);if(gE({state:e,name:r,operation:"dispose",result:s}),s.status==="rejected")return{removed:!1,failure:s.reason,transportDisposed:!1};let[i]=await Promise.allSettled([Yo(e,r,n,o.config)]);return gE({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 kZ(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):W(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=We(e,n),f=Pt({state:e,name:n,owner:c.owner,revision:c.revision,host:a});if(!f)return;a.beginDisposal?.(),Vr.info(`Live MCP remove-server: disposing ${n} (config id ${r})`);let p=e.currentLoad?.latestPi??o,{removed:h,failure:m,transportDisposed:y}=await xZ({state:e,name:n,configId:r,server:a});if(h&&yE({state:e,configId:r,fence:i})?vE(e,r):!h&&e.configDesiredRevisions.get(n)===l&&(u===void 0?e.configDesiredRevisions.delete(n):e.configDesiredRevisions.set(n,u),d===void 0?e.configDesiredSources.delete(n):e.configDesiredSources.set(n,d)),we({state:e,name:n,retirement:f,result:h?{status:"retired"}:{status:"failed",error:m,transportDisposed:y}}),h&&Pe({state:e,name:n,owner:c.owner,revision:c.revision})&&_E(e,n),s(p,e),!h)throw m}function SE(t){let{pi:e,state:r,data:n,deps:o}=t,s=n,i=s&&typeof s.configId=="string"?s.configId:"";if(!i)return Vr.warn("augment:mcp-remove-server payload missing configId"),Promise.resolve();if(!Vi({state:r,configId:i,generation:s?.attachmentGeneration}))return Vr.info(`Ignoring stale live MCP remove-server command for config id ${i}`),Promise.resolve();let a=y=>Ki({state:r,configId:i,generation:s?.attachmentGeneration,operation:y,wasApplied:()=>!0}),c=o?.report??J,u=mE(r,i),d=r.registryCredentialConfigsById.get(i),l=d?.name?W(r,d.name)?.retirement:void 0,f=r.missingHostRemovals.get(i),p=f?.registryGeneration===r.registryGeneration&&f?.liveEditGeneration===r.liveEditGenerations.get(i);if(p&&l===void 0)return a(f.promise);if(p&&l!==void 0){let y=r.missingHostRemovalFences.get(i);if(y)return a(hE({state:r,configId:i,fence:y,retryPreviousFailureOnly:!0,operation:()=>am({state:r,configId:i,pi:e,report:c,sourceFence:y})}))}let h=bZ(r,i);if(u===void 0&&d===void 0)return a(am({state:r,configId:i,pi:e,report:c,sourceFence:{liveEditGeneration:h,registryGeneration:r.registryGeneration}}));let m=RZ({state:r,configId:i,liveEditGeneration:h});return a(hE({state:r,configId:i,fence:m,operation:()=>{let y=mE(r,i);return y===void 0?am({state:r,configId:i,pi:e,report:c,sourceFence:m}):kZ({state:r,configId:i,name:y,pi:e,report:c,sourceFence:m})}}))}import{logger as EZ}from"@hermes/logger";var Di=EZ.child({prefix:"pi-mcp"}),wE=3,bE=6e4,TZ=1e3,AZ=8e3;function cm(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.reconnect??Wr,i=o?.now??Date.now,a=o?.sleep??on,c=o?.report??J,u=n,d=u&&typeof u.serverName=="string"?u.serverName:"";if(!d)return Di.warn("augment:mcp-restart-server payload missing serverName"),Promise.resolve();if(!r.servers.has(d))return Di.warn(`augment:mcp-restart-server: no live MCP server named ${d}`),Promise.resolve();let l=i(),f=r.mcpRestartState.get(d),p=f&&l-f.lastRestart<bE?f.count+1:1,h=r.currentLoad?.latestPi??e;if(p>wE)return Di.warn(`augment:mcp-restart-server: ${d} exceeded ${wE} restarts within ${bE}ms; rejecting`),c(h,r),Promise.resolve();r.mcpRestartState.set(d,{count:p,lastRestart:l});let m=Math.min(TZ*2**(p-1),AZ);return(p>1?a(m):Promise.resolve()).then(()=>(Di.info(`Live MCP restart-server: reconnecting ${d}`),s(d,r,h))).catch(v=>{let b=`Live MCP restart-server failed for ${d}: ${v instanceof Error?v.message:String(v)}`;Di.warn(b),r.diagnostics.push({server:d,message:b})}).then(()=>{c(h,r)})}import{logger as $Z}from"@hermes/logger";var Li=$Z.child({prefix:"pi-mcp"}),MZ=/^\d+$/,um=1,RE="AUGMENT_ACTIVE_SPACE_ID",IZ="augment-mcp-access-token-";function _u(t){return t.replace(/[^a-zA-Z0-9_-]/g,"-")}function PE(t,e){return e?.["augment:encoding"]!=="base64"?t:/^[A-Za-z0-9+/]*={0,2}$/.test(t)&&t.length%4===0?Buffer.from(t,"base64").toString("utf-8"):t}var Su=class{apiKey;apiUrl;userAgent;fetchImpl;timeoutMs;cache=new Map;inflight=new Map;constructor(e,r,n){this.apiKey=e.apiKey,this.apiUrl=e.apiUrl.replace(/\/+$/,""),this.userAgent=e.userAgent,this.fetchImpl=r,this.timeoutMs=n??Bu}_headers(){return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",...this.userAgent?{"User-Agent":this.userAgent}:{}}}lookupBody(e){let r={name:e};return!e.startsWith(IZ)&&Object.hasOwn(process.env,RE)&&(r.active_space_id=process.env[RE]??""),r}getSecret(e){let r=_u(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 sn(()=>this.upsertUserSecretOnce(e,r,n))}async upsertUserSecretOnce(e,r,n){let o=_u(e),i=(await this._callUpsert({name:o,value:r,scope:um,...n===void 0?{}:{expected_version:n}})).secret?.version;if(typeof i!="string"||!MZ.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),Li.debug(`Upserted user secret "${o}"`),a}async deleteUserSecret(e){await sn(()=>this.deleteUserSecretOnce(e))}async deleteUserSecretOnce(e){let r=_u(e);this.cache.delete(r),await this._callDelete({name:r,scope:um}),Li.debug(`Deleted user secret "${r}"`)}async _callUpsert(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/upsert`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>rr?`${o.slice(0,rr)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}return await n.json()}async _callDelete(e){let n=await(this.fetchImpl??fetch)(`${this.apiUrl}/user-secrets/delete`,{method:"POST",headers:this._headers(),body:JSON.stringify(e),signal:AbortSignal.timeout(this.timeoutMs)});if(!n.ok){let o=await n.text().catch(()=>""),s=o.length>rr?`${o.slice(0,rr)}\u2026[truncated]`:o;throw new lt(n.status,n.statusText,s)}}async getUserSecretWithVersion(e){let r=_u(e);try{let n=await sn(()=>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===um||n.secret?.scope==="SECRET_SCOPE_PRIVATE";return{value:PE(o,n.secret?.tags),version:i?s:"0"}}catch(n){if(n instanceof lt&&n.statusCode===404)return;throw n}}async _resolve(e){let r=await this._tryGet("/mcp-secrets/get",this.lookupBody(e),e);if(r.value!==void 0)return this.cache.set(e,r.value),r.value;if(r.errored){let n=this.cache.get(e);return n!==void 0&&Li.debug(`Secret "${e}" lookup failed; using cached fallback value`),n}this.cache.delete(e)}async _tryGet(e,r,n){try{let o=await sn(()=>this._callApi(e,r)),s=o.secret?.value;return s===void 0?{errored:!1}:{value:PE(s,o.secret?.tags),errored:!1}}catch(o){if(o instanceof lt&&o.statusCode===404)return Li.debug(`Secret "${n}" not found via ${e} (404)`),{errored:!1};let s=o instanceof Error?o.message:String(o);return Li.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:this._headers(),body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeoutMs)});if(!o.ok){let s=await o.text().catch(()=>""),i=s.length>rr?`${s.slice(0,rr)}\u2026[truncated]`:s;throw new lt(o.status,o.statusText,i)}return await o.json()}};function dm(t){return{latestPi:t}}import{randomUUID as OZ}from"node:crypto";import{setToolSource as zZ}from"@augmentcode/auggie-v2";import{logger as NZ}from"@hermes/logger";import{Type as DZ}from"@sinclair/typebox";var xE=NZ.child({prefix:"pi-mcp"}),wu="attach-mcp-server",LZ="augment:mcp-attach-request",jZ=15e3,FZ={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 UZ(t,e){let r=e.trim(),n=r.toLowerCase(),o=t.mcpCatalog??[],s=o.find(l=>l.id===r);if(s)return{kind:"match",entry:s};let i=o.filter(l=>l.name.toLowerCase()===n),a=i.length===1?i[0]:void 0;if(a!==void 0)return{kind:"match",entry:a};if(i.length===0)return{kind:"none"};let c=new Set(tn(t).map(l=>l.id)),u=i.filter(l=>c.has(l.id)),d=u.length===1?u[0]:void 0;return d!==void 0?{kind:"match",entry:d}:{kind:"ambiguous",candidates:i}}function qZ(t,e){let r=e.name.toLowerCase();return tn(t).filter(n=>n.id!==e.id&&n.name.toLowerCase()===r)}function lm(t,e){let r=qZ(t,e);return r.length===0?"":` A different attachable server with the same name exists: ${r.map(o=>`"${o.name}" (id: ${o.id})`).join(", ")}. If that is the intended server, retry with its exact id.`}function HZ(t,e){return new Promise(r=>{let n=setTimeout(()=>{t.attachResolvers.delete(e),r(void 0)},jZ);t.attachResolvers.set(e,o=>{clearTimeout(n),t.attachResolvers.delete(e),r(o)})})}function CE(t){let e=tn(t).map(r=>`${r.name} (id: ${r.id})`);return e.length>0?`Available unattached servers: ${e.join(", ")}.`:"No unattached servers are currently available."}function GZ(t){let{entry:e,state:r}=t,n=[...r.servers.values()].find(o=>o.config.id===e.id);if(n?.status==="auth_required")return be(`MCP server "${e.name}" requires authentication. Ask the user to reconnect it from the session MCP panel before trying again.${lm(r,e)}`);if(n?.status==="failed"||r.failedAddConfigIds.has(e.id))return be(`MCP server "${e.name}" failed to connect after the attach was accepted. Ask the user to reconnect it from the session MCP panel before trying again.${lm(r,e)}`)}function ZZ(t){let{entry:e,result:r,state:n}=t;if(r===void 0)return be(`Timed out waiting for the attach request for "${e.name}" to be acknowledged. The server may still attach shortly; check find-tool's server list before retrying.`);if(r.error==="UNIMPLEMENTED")return n.mcpAttachDisabled=!0,be("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");if(r.error==="DENIED")return be(`The control plane denied the request to attach "${e.name}". Do not retry; ask the user to verify that the server is available for this session.`);if(r.error!==void 0)return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);switch(r.status){case"ACCEPTED":return be(`Attach accepted for "${e.name}". Connection continues in the background; use find-tool to discover its tools when ready. If its tools do not appear, call attach-mcp-server again with the same config id for connection guidance.`);case"ALREADY_ATTACHED":return be(`MCP server "${e.name}" is already attached to this session. Use find-tool to discover its tools.`);case"AUTH_REQUIRED":return be(`MCP server "${e.name}" requires authentication \u2014 the user must connect it from the session MCP panel before it can be attached.${lm(n,e)}`);case"NO_ACTIVE_VM":return be(`Could not reach the control plane to attach "${e.name}". Try again later.`);default:return be(`The attach request for "${e.name}" returned an unrecognized status. Check find-tool's server list shortly to see whether it attached.`)}}async function WZ(t,e,r){if(e.mcpAttachDisabled)return be("Attaching MCP servers is not enabled for this session. Ask the user to attach the server from the session's MCP settings instead.");let{config_id:n}=r??{};if(typeof n!="string"||n.trim().length===0)throw new Error(`${wu} requires a string "config_id" parameter. ${CE(e)}`);let o=UZ(e,n);if(o.kind==="none")return be(`No MCP server matching "${n}" is available to attach. ${CE(e)}`);if(o.kind==="ambiguous"){let d=o.candidates.map(l=>`"${l.name}" (id: ${l.id})`).join(", ");return be(`Multiple MCP servers match the name "${n}": ${d}. Retry with the exact id of the intended server.`)}let s=o.entry,i=GZ({entry:s,state:e});if(i!==void 0)return i;if(Gu(e,s))return be(`MCP server "${s.name}" is already attached to this session. Use find-tool to discover its tools.`);if(s.state!=="available"&&s.state!=="opt_in_required")return be(`MCP server "${s.name}" is not currently available to attach. Ask the user to attach it from the session's MCP settings.`);let a=OZ();xE.info(`attach-mcp-server: requesting attach of "${s.name}" (config=${s.id} request=${a})`);let c=HZ(e,a);t.events.emit(LZ,{configId:s.id,requestId:a});let u=await c;return ZZ({entry:s,result:u,state:e})}function fm(t,e){let r={name:wu,label:wu,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:DZ.Unsafe(FZ),execute:(n,o)=>WZ(t,e,o)};zZ(wu,"mcp"),t.registerTool(r),Cr(r),xE.debug("Registered attach-mcp-server tool")}import{logger as BZ}from"@hermes/logger";var Go=BZ.child({prefix:"pi-mcp"});async function VZ(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=Pt({state:t,name:r,owner:o.owner,revision:o.revision,host:n});if(!s)continue;We(t,r);let i=dt(t,r,n.config.id,n.config);n.beginDisposal?.(),e.push(Promise.allSettled([i,n.dispose({strict:!0})]).then(a=>{let c=a.find(u=>u.status==="rejected");if(c)throw we({state:t,name:r,retirement:s,result:{status:"failed",error:c.reason}}),c.reason;we({state:t,name:r,retirement:s,result:{status:"retired"}}),Pe({state:t,name:r,owner:o.owner,revision:o.revision})}))}await Promise.all(e)}function KZ(t,e){for(let r of e??[])typeof r?.message=="string"&&(t.diagnostics.push({message:r.message,origin:"vfs"}),Go.warn(r.message))}function JZ(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"}),Go.warn(a);return}try{let a=Hn(r,n);return{...a.type==="stdio"?Ht(a,i):qt(a,i),vfsSource:"vfs"}}catch(a){let c=a instanceof xt?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"}),Go.warn(c);return}}function YZ(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=JZ({state:t,name:i,stored:a,higherPriorityNames:r,blockedNames:s,workspaceRoot:n});c&&o.push(c)}return{servers:o,blockedNames:s}}function XZ(t){for(let e of t.blockedVfsMcpNames){let r=t.hostLeases.get(e);if(!r||r.owner.kind==="vfs")return!1}return!0}function kE(t){let{pi:e,state:r,data:n,deps:o}=t,s=o?.connect??bt,i=n;if(!i||typeof i!="object"||Array.isArray(i))return Go.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&&XZ(r))return Promise.resolve();let c=++r.vfsGeneration,u=new Set,d=VZ(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;KZ(r,i.diagnostics);let{servers:l,blockedNames:f}=YZ(r,i);return u=f,l.length===0?(a!==void 0&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=f),!1):(Go.info(`VFS MCP overlay: connecting ${l.length} server(s)`),s(l,r,r.currentLoad?.latestPi??e,()=>r.vfsGeneration===c).then(p=>{let h=p?.find(m=>m.status==="failed"||m.status==="unavailable");if(h)throw h.error instanceof Error?h.error:new Error(String(h.error));return l.every(m=>(p??[]).some(y=>y.config===m&&tu(r,y)))}))}).then(l=>{l&&a!==void 0&&r.vfsGeneration===c&&(r.lastSuccessfulVfsMcpSignature=a,r.blockedVfsMcpNames=u)}).catch(l=>{let f=`VFS MCP overlay connect failed: ${l instanceof Error?l.message:String(l)}`;Go.warn(f),r.vfsGeneration===c&&r.diagnostics.push({message:f,origin:"vfs"})})}var Fe=QZ.child({prefix:"pi-mcp"}),ME="augment:mcp-oauth-credentials",EE="augment:mcp-header-secrets",TE="augment:mcp-header-secret-failures",pm="augment:mcp-oauth-failures",AE="augment:credentials",e2="augment:mcp-config-ids",$E="augment:mcp-configs",t2="augment:mcp-vfs-servers",r2="augment:mcp-add-server",n2="augment:mcp-restart-server",o2="augment:mcp-remove-server";function s2(t){if(!t.secretsClient||t.tokens instanceof ns)return;let e=t.tokens;t.tokens=new ns(()=>t.secretsClient,()=>t.shouldProactivelyRefreshTokens,e.snapshot()),Fe.debug("Installed durable BackendTokenStore (durable ops gated at runtime)")}function i2(t){if(!t||typeof t!="object"){Fe.warn(`${ME} 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 a2(t){let{pi:e,state:r,payload:n}=t;if(n.targetConfigId){Yx({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=h2({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)){cm({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";Fe.warn(c),r.diagnostics.push({server:a.serverName,message:c})}}};if(o.size===0){s();return}Promise.allSettled(o).then(s)}function c2(t,e){e.credsListenerBound||(e.credsListenerBound=!0,t.events.on(ME,r=>{let n=i2(r);n&&a2({pi:t,state:e,payload:n})}))}function u2(t){let{state:e,name:r,revision:n}=t,o=Xr(n);if(e.pendingRegistryCredentialDomains.has(o)&&e.registryCredentialIntents.has(o))return!1;let s=e.expectedCredentialDomains.get(r),i=e.oauthCredentialDomains.get(r),a=e.servers.get(r),c=a?.config.id,u=a?.config.registrySource!==void 0&&c!==void 0&&ot(c)===o;return n.ownerDomain!==void 0?s?.kind==="domain"?s.domain===o:u:s===void 0&&i===void 0?u:s?.kind==="domain"&&(s.domain===o||st(n.domain))||i===n.domain}function d2(t){let{state:e,revision:r}=t,n=Xr(r);return e.pendingRegistryCredentialDomains.has(n)&&e.registryCredentialIntents.has(n)}function l2(t){let{state:e,credentials:r,suppressReconnect:n}=t,o={};for(let[s,i]of Object.entries(r)){let a=Dn(i);if(a===void 0){o[s]=i;continue}if(d2({state:e,revision:a})){zm({state:e,revision:a,credential:i,suppressReconnect:n});continue}if(u2({state:e,name:s,revision:a})){o[s]=i;continue}Im({state:e,serverName:s,revision:a,credential:i,suppressReconnect:n})}return o}function f2(t){let{state:e,applicable:r,seeded:n}=t;for(let o of n){let s=r[o],i=Dn(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 p2(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=W(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"&&Wr(i,r,s).catch(()=>{}).finally(()=>{J(s,r),Te(r)})}}function h2(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=l2({state:r,credentials:n,suppressReconnect:o}),i=ru(r.tokens,s,{acceptedRevisions:r.oauthCredentialRevisions,acceptedDomains:r.oauthCredentialDomains,expectedDomains:r.expectedCredentialDomains,equalRevisionRebindDomains:r.equalRevisionRebindDomains,requireRevision:!0});return f2({state:r,applicable:s,seeded:i.applied}),i.applied.length===0||(Fe.info(`Seeded MCP OAuth token(s) for ${i.applied.length} server(s)`),p2({pi:e,state:r,seeded:i.applied,suppressReconnect:o})),i}function m2(t,e){e.headerSecretsListenerBound||(e.headerSecretsListenerBound=!0,t.events.on(EE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){Fe.warn(`${EE} payload is not an object`);return}let n=r,o=typeof n.secrets=="object"&&n.secrets!==null&&!Array.isArray(n.secrets);vy(e,o?n.secrets:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(TE,r=>{if(!r||typeof r!="object"||Array.isArray(r)){Fe.warn(`${TE} payload is not an object`);return}let n=r,o=typeof n.entries=="object"&&n.entries!==null&&!Array.isArray(n.entries);Sy(e,o?n.entries:r,{authoritative:o&&n.authoritative===!0})}),t.events.on(pm,r=>{if(!r||typeof r!="object"||Array.isArray(r)){Fe.warn(`${pm} payload is not an object`);return}let n=r;if(typeof n.entries!="object"||n.entries===null||Array.isArray(n.entries)){Fe.warn(`${pm} entries is not an object`);return}ym(e,n.entries)}))}function g2(t,e){e.configIdsListenerBound||(e.configIdsListenerBound=!0,t.events.on(AE,r=>{let n=r;if(!n||typeof n.apiKey!="string"||typeof n.apiUrl!="string"){Fe.warn(`${AE} payload missing apiKey or apiUrl`);return}e.credentials={apiKey:n.apiKey,apiUrl:n.apiUrl,...typeof n.userAgent=="string"?{userAgent:n.userAgent}:{},...typeof n.userId=="string"?{userId:n.userId}:{}},e.secretsClient=new Su(e.credentials),s2(e)}),t.events.on(e2,r=>{e.mcpAttachCloudSignaled||(e.mcpAttachCloudSignaled=!0,fm(e.currentLoad?.latestPi??t,e)),pE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{Fe.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;Te(e),hu(n,e)})}))}function y2(t,e){e.mcpConfigsListenerBound||(e.mcpConfigsListenerBound=!0,t.events.on($E,r=>{let o=r?.configs;if(o!==void 0&&!Array.isArray(o)){Fe.warn(`${$E} payload configs is not an array`),e.embeddedRegistryConfigs=void 0;return}if(e.embeddedRegistryConfigs=o,o!==void 0){let s=vu(o,e.workspaceRoot??process.cwd());for(let{config:i}of s?.allConfigsById.values()??[])i&&Pr({state:e,config:i,pi:t}).catch(a=>{Fe.warn(`Embedded MCP credential intent did not retire durably: ${a instanceof Error?a.message:String(a)}`)})}Fe.info(`Stored ${o===void 0?0:o.length} embedded MCP config(s) for the next registry selection`)}))}function v2(t,e){e.vfsListenerBound||(e.vfsListenerBound=!0,t.events.on(t2,r=>{kE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e),Te(e)})}))}function _2(t,e){e.addServerListenerBound||(e.addServerListenerBound=!0,t.events.on(r2,r=>{iE({pi:t,state:e,data:r}).then(()=>{J(e.currentLoad?.latestPi??t,e)}).catch(n=>{Fe.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;Te(e),hu(n,e)})}))}function S2(t,e){e.restartServerListenerBound||(e.restartServerListenerBound=!0,t.events.on(n2,r=>{cm({pi:t,state:e,data:r}).then(()=>{Te(e)})}))}function w2(t,e){e.removeServerListenerBound||(e.removeServerListenerBound=!0,t.events.on(o2,r=>{SE({pi:t,state:e,data:r}).catch(n=>{Fe.warn(`Live MCP remove-server did not retire durably: ${n instanceof Error?n.message:String(n)}`)}).finally(()=>{let n=e.currentLoad?.latestPi??t;Te(e),hu(n,e)})}))}function tQ(t){return yy(t)}var IE=t=>{let e=ie();e.currentLoad=dm(t);let r=!1;Bk(t,e),c2(t,e),m2(t,e),g2(t,e),y2(t,e),v2(t,e),_2(t,e),S2(t,e),w2(t,e),Kk(t,e),Jk(t,e),e.mcpAttachCloudSignaled&&fm(t,e),t.on("session_start",(n,o)=>{e.currentLoad=dm(t),e.workspaceRoot=o.cwd;let s=o.mcpConfigOverride;if(e.mcpConfigOverride=Array.isArray(s)&&s.length>0?s:void 0,e.ui=o.ui,Xk(e),e.connectStarted)Zn(e)?(nn(t),Xi(t)):Xm(t,e),Te(e);else{e.connectStarted=!0,Qo()&&nn(t);let{servers:i,diagnostics:a}=Gn(o.cwd,o.agentDir,e.mcpConfigOverride,e.sessionMcpConfigDisabledOverrides);for(let c of a)e.diagnostics.push(c),Fe.warn(c.message);bt(i,e,t).then(()=>Bx(e)).catch(()=>{}).finally(()=>{J(e.currentLoad?.latestPi??t,e),Te(e)})}r||(r=!0,t.events.emit(Sk,Ck(t,e)))}),t.on("session_shutdown",()=>{Qk(e)})};Vm(IE);var rQ=IE;export{rQ as default,tQ as setMcpErrorReporter};
150
150
  /*! Bundled license information:
151
151
 
152
152
  content-type/index.js: