@swifty.js/swifty 0.0.8 → 0.0.10

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,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __swiftyCreateRequire } from "node:module";
3
3
  const require = __swiftyCreateRequire(import.meta.url);
4
- import{a as po,b as Ul,c as Fl,f as Hl}from"./chunk-UBV5T4TV.js";import{b as ql,c as Dl,d as Ll,j as uo}from"./chunk-A6H62GTA.js";import{a as er}from"./chunk-OXEMDMZF.js";import{a as Ue,b as Pl,c as ao,d as co}from"./chunk-LVLDD2BE.js";import{e as tr}from"./chunk-ZSJ2I5WM.js";import{a as ft}from"./chunk-7MHXMDYC.js";import{A as jl,B as Nl,C as A,D as _,I as C,L as ri,N,P as Rt,Q as Wr,R as E,S as lo,a as El,d as Rl,e as xe,f as Cl,g as Ml,h as p,i as zl,j as B,k as Z,l as Al,m as Il,n as se,o as T,p as x,q as ce,r as ee,s as Qs,t as ei,u as Y,v as ze,w as P,x as re,y as Ol,z as ti}from"./chunk-ISXLT3QN.js";import{a as mt,b as S,d as io}from"./chunk-X3UA5OZL.js";var un=S(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.regexpCode=G.getEsmExportName=G.getProperty=G.safeStringify=G.stringify=G.strConcat=G.addCodeArg=G.str=G._=G.nil=G._Code=G.Name=G.IDENTIFIER=G._CodeOrName=void 0;var cn=class{};G._CodeOrName=cn;G.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ot=class extends cn{constructor(e){if(super(),!G.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}}};G.Name=Ot;var Ne=class extends cn{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 Ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};G._Code=Ne;G.nil=new Ne("");function qd(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Xi(r,e[n]),r.push(t[++n]);return new Ne(r)}G._=qd;var Yi=new Ne("+");function Dd(t,...e){let r=[ln(t[0])],n=0;for(;n<e.length;)r.push(Yi),Xi(r,e[n]),r.push(Yi,ln(t[++n]));return dv(r),new Ne(r)}G.str=Dd;function Xi(t,e){e instanceof Ne?t.push(...e._items):e instanceof Ot?t.push(e):t.push(fv(e))}G.addCodeArg=Xi;function dv(t){let e=1;for(;e<t.length-1;){if(t[e]===Yi){let r=pv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function pv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ot||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 Ot))return`"${t}${e.slice(1)}`}function mv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Dd`${t}${e}`}G.strConcat=mv;function fv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ln(Array.isArray(t)?t.join(","):t)}function hv(t){return new Ne(ln(t))}G.stringify=hv;function ln(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}G.safeStringify=ln;function gv(t){return typeof t=="string"&&G.IDENTIFIER.test(t)?new Ne(`.${t}`):qd`[${t}]`}G.getProperty=gv;function yv(t){if(typeof t=="string"&&G.IDENTIFIER.test(t))return new Ne(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}G.getEsmExportName=yv;function _v(t){return new Ne(t.toString())}G.regexpCode=_v});var ta=S(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var Ee=un(),Qi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Bo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Bo||(Pe.UsedValueState=Bo={}));Pe.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var Go=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ee.Name?e:this.name(e)}name(e){return new Ee.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}}};Pe.Scope=Go;var Ko=class extends Ee.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ee._)`.${new Ee.Name(r)}[${n}]`}};Pe.ValueScopeName=Ko;var wv=(0,Ee._)`\n`,ea=class extends Go{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?wv:Ee.nil}}get(){return this._scope}name(e){return new Ko(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 l=a.get(i);if(l)return l}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,Ee._)`${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=Ee.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,Bo.Started);let l=r(u);if(l){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;s=(0,Ee._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ee._)`${s}${l}${this.opts._n}`;else throw new Qi(u);c.set(u,Bo.Completed)})}return s}};Pe.ValueScope=ea});var D=S(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 H=un(),Fe=ta(),wt=un();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return wt._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return wt.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return wt.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return wt.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return wt.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return wt.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return wt.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return wt.Name}});var Xo=ta();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Xo.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Xo.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Xo.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Xo.varKinds}});L.operators={GT:new H._Code(">"),GTE:new H._Code(">="),LT:new H._Code("<"),LTE:new H._Code("<="),EQ:new H._Code("==="),NEQ:new H._Code("!=="),NOT:new H._Code("!"),OR:new H._Code("||"),AND:new H._Code("&&"),ADD:new H._Code("+")};var tt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ra=class extends tt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Fe.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=pr(this.rhs,e,r)),this}get names(){return this.rhs instanceof H._CodeOrName?this.rhs.names:{}}},Zo=class extends tt{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 H.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=pr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof H.Name?{}:{...this.lhs.names};return Yo(e,this.rhs)}},na=class extends Zo{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},oa=class extends tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sa=class extends tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ia=class extends tt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},aa=class extends tt{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=pr(this.code,e,r),this}get names(){return this.code instanceof H._CodeOrName?this.code.names:{}}},dn=class extends tt{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)||(vv(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qt(e,r.names),{})}},rt=class extends dn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ca=class extends dn{},dr=class extends rt{};dr.kind="else";var jt=class t extends rt{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 dr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ld(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=pr(this.condition,e,r),this}get names(){let e=super.names;return Yo(e,this.condition),this.else&&qt(e,this.else.names),e}};jt.kind="if";var Nt=class extends rt{};Nt.kind="for";var la=class extends Nt{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=pr(this.iteration,e,r),this}get names(){return qt(super.names,this.iteration.names)}},ua=class extends Nt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Fe.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=Yo(super.names,this.from);return Yo(e,this.to)}},Jo=class extends Nt{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=pr(this.iterable,e,r),this}get names(){return qt(super.names,this.iterable.names)}},pn=class extends rt{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)}};pn.kind="func";var mn=class extends dn{render(e){return"return "+super.render(e)}};mn.kind="return";var da=class extends rt{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&&qt(e,this.catch.names),this.finally&&qt(e,this.finally.names),e}},fn=class extends rt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};fn.kind="catch";var hn=class extends rt{render(e){return"finally"+super.render(e)}};hn.kind="finally";var pa=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
- `:""},this._extScope=e,this._scope=new Fe.Scope({parent:e}),this._nodes=[new ca]}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 ra(e,s,n)),s}const(e,r,n){return this._def(Fe.varKinds.const,e,r,n)}let(e,r,n){return this._def(Fe.varKinds.let,e,r,n)}var(e,r,n){return this._def(Fe.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Zo(e,r,n))}add(e,r){return this._leafNode(new na(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==H.nil&&this._leafNode(new aa(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,H.addCodeArg)(r,o));return r.push("}"),new H._Code(r)}if(e,r,n){if(this._blockNode(new jt(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 jt(e))}else(){return this._elseNode(new dr)}endIf(){return this._endBlockNode(jt,dr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new la(e),r)}forRange(e,r,n,o,s=this.opts.es5?Fe.varKinds.var:Fe.varKinds.let){let i=this._scope.toName(e);return this._for(new ua(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Fe.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof H.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,H._)`${i}.length`,a=>{this.var(s,(0,H._)`${i}[${a}]`),n(s)})}return this._for(new Jo("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Fe.varKinds.var:Fe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,H._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Jo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Nt)}label(e){return this._leafNode(new oa(e))}break(e){return this._leafNode(new sa(e))}return(e){let r=new mn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(mn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new da;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new fn(s),r(s)}return n&&(this._currNode=o.finally=new hn,this.code(n)),this._endBlockNode(fn,hn)}throw(e){return this._leafNode(new ia(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=H.nil,n,o){return this._blockNode(new pn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(pn)}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 jt))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=pa;function qt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Yo(t,e){return e instanceof H._CodeOrName?qt(t,e.names):t}function pr(t,e,r){if(t instanceof H.Name)return n(t);if(!o(t))return t;return new H._Code(t._items.reduce((s,i)=>(i instanceof H.Name&&(i=n(i)),i instanceof H._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 H._Code&&s._items.some(i=>i instanceof H.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function vv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ld(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,H._)`!${ma(t)}`}L.not=Ld;var bv=Ud(L.operators.AND);function Sv(...t){return t.reduce(bv)}L.and=Sv;var kv=Ud(L.operators.OR);function Tv(...t){return t.reduce(kv)}L.or=Tv;function Ud(t){return(e,r)=>e===H.nil?r:r===H.nil?e:(0,H._)`${ma(e)} ${t} ${ma(r)}`}function ma(t){return t instanceof H.Name?t:(0,H._)`(${t})`}});var W=S(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.checkStrictMode=U.getErrorPath=U.Type=U.useFunc=U.setEvaluated=U.evaluatedPropsToName=U.mergeEvaluated=U.eachItem=U.unescapeJsonPointer=U.escapeJsonPointer=U.escapeFragment=U.unescapeFragment=U.schemaRefOrVal=U.schemaHasRulesButRef=U.schemaHasRules=U.checkUnknownRules=U.alwaysValidSchema=U.toHash=void 0;var J=D(),xv=un();function $v(t){let e={};for(let r of t)e[r]=!0;return e}U.toHash=$v;function Ev(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Wd(t,e),!Vd(e,t.self.RULES.all))}U.alwaysValidSchema=Ev;function Wd(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]||Kd(t,`unknown keyword: "${s}"`)}U.checkUnknownRules=Wd;function Vd(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}U.schemaHasRules=Vd;function Pv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}U.schemaHasRulesButRef=Pv;function Rv({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,J._)`${r}`}return(0,J._)`${t}${e}${(0,J.getProperty)(n)}`}U.schemaRefOrVal=Rv;function Cv(t){return Bd(decodeURIComponent(t))}U.unescapeFragment=Cv;function Mv(t){return encodeURIComponent(ha(t))}U.escapeFragment=Mv;function ha(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}U.escapeJsonPointer=ha;function Bd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}U.unescapeJsonPointer=Bd;function zv(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}U.eachItem=zv;function Fd({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof J.Name?(s instanceof J.Name?t(o,s,i):e(o,s,i),i):s instanceof J.Name?(e(o,i,s),s):r(s,i);return a===J.Name&&!(c instanceof J.Name)?n(o,c):c}}U.mergeEvaluated={props:Fd({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,J._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,J._)`${r} || {}`).code((0,J._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,J._)`${r} || {}`),ga(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Gd}),items:Fd({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,J._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,J._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Gd(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,J._)`{}`);return e!==void 0&&ga(t,r,e),r}U.evaluatedPropsToName=Gd;function ga(t,e,r){Object.keys(r).forEach(n=>t.assign((0,J._)`${e}${(0,J.getProperty)(n)}`,!0))}U.setEvaluated=ga;var Hd={};function Av(t,e){return t.scopeValue("func",{ref:e,code:Hd[e.code]||(Hd[e.code]=new xv._Code(e.code))})}U.useFunc=Av;var fa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(fa||(U.Type=fa={}));function Iv(t,e,r){if(t instanceof J.Name){let n=e===fa.Num;return r?n?(0,J._)`"[" + ${t} + "]"`:(0,J._)`"['" + ${t} + "']"`:n?(0,J._)`"/" + ${t}`:(0,J._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,J.getProperty)(t).toString():"/"+ha(t)}U.getErrorPath=Iv;function Kd(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}U.checkStrictMode=Kd});var nt=S(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var _e=D(),Ov={data:new _e.Name("data"),valCxt:new _e.Name("valCxt"),instancePath:new _e.Name("instancePath"),parentData:new _e.Name("parentData"),parentDataProperty:new _e.Name("parentDataProperty"),rootData:new _e.Name("rootData"),dynamicAnchors:new _e.Name("dynamicAnchors"),vErrors:new _e.Name("vErrors"),errors:new _e.Name("errors"),this:new _e.Name("this"),self:new _e.Name("self"),scope:new _e.Name("scope"),json:new _e.Name("json"),jsonPos:new _e.Name("jsonPos"),jsonLen:new _e.Name("jsonLen"),jsonPart:new _e.Name("jsonPart")};ya.default=Ov});var gn=S(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.extendErrors=we.resetErrorsCount=we.reportExtraError=we.reportError=we.keyword$DataError=we.keywordError=void 0;var V=D(),Qo=W(),be=nt();we.keywordError={message:({keyword:t})=>(0,V.str)`must pass "${t}" keyword validation`};we.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,V.str)`"${t}" keyword must be ${e} ($data)`:(0,V.str)`"${t}" keyword is invalid ($data)`};function jv(t,e=we.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Yd(t,e,r);n??(i||a)?Zd(s,c):Jd(o,(0,V._)`[${c}]`)}we.reportError=jv;function Nv(t,e=we.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Yd(t,e,r);Zd(o,a),s||i||Jd(n,be.default.vErrors)}we.reportExtraError=Nv;function qv(t,e){t.assign(be.default.errors,e),t.if((0,V._)`${be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,V._)`${be.default.vErrors}.length`,e),()=>t.assign(be.default.vErrors,null)))}we.resetErrorsCount=qv;function Dv({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,be.default.errors,a=>{t.const(i,(0,V._)`${be.default.vErrors}[${a}]`),t.if((0,V._)`${i}.instancePath === undefined`,()=>t.assign((0,V._)`${i}.instancePath`,(0,V.strConcat)(be.default.instancePath,s.errorPath))),t.assign((0,V._)`${i}.schemaPath`,(0,V.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,V._)`${i}.schema`,r),t.assign((0,V._)`${i}.data`,n))})}we.extendErrors=Dv;function Zd(t,e){let r=t.const("err",e);t.if((0,V._)`${be.default.vErrors} === null`,()=>t.assign(be.default.vErrors,(0,V._)`[${r}]`),(0,V._)`${be.default.vErrors}.push(${r})`),t.code((0,V._)`${be.default.errors}++`)}function Jd(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,V._)`new ${t.ValidationError}(${e})`):(r.assign((0,V._)`${n}.errors`,e),r.return(!1))}var Dt={keyword:new V.Name("keyword"),schemaPath:new V.Name("schemaPath"),params:new V.Name("params"),propertyName:new V.Name("propertyName"),message:new V.Name("message"),schema:new V.Name("schema"),parentSchema:new V.Name("parentSchema")};function Yd(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,V._)`{}`:Lv(t,e,r)}function Lv(t,e,r={}){let{gen:n,it:o}=t,s=[Uv(o,r),Fv(t,r)];return Hv(t,e,s),n.object(...s)}function Uv({errorPath:t},{instancePath:e}){let r=e?(0,V.str)`${t}${(0,Qo.getErrorPath)(e,Qo.Type.Str)}`:t;return[be.default.instancePath,(0,V.strConcat)(be.default.instancePath,r)]}function Fv({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,V.str)`${e}/${t}`;return r&&(o=(0,V.str)`${o}${(0,Qo.getErrorPath)(r,Qo.Type.Str)}`),[Dt.schemaPath,o]}function Hv(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Dt.keyword,o],[Dt.params,typeof e=="function"?e(t):e||(0,V._)`{}`]),c.messages&&n.push([Dt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Dt.schema,i],[Dt.parentSchema,(0,V._)`${l}${d}`],[be.default.data,s]),u&&n.push([Dt.propertyName,u])}});var Qd=S(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.boolOrEmptySchema=mr.topBoolOrEmptySchema=void 0;var Wv=gn(),Vv=D(),Bv=nt(),Gv={message:"boolean schema is false"};function Kv(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Xd(t,!1):typeof r=="object"&&r.$async===!0?e.return(Bv.default.data):(e.assign((0,Vv._)`${n}.errors`,null),e.return(!0))}mr.topBoolOrEmptySchema=Kv;function Zv(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Xd(t)):r.var(e,!0)}mr.boolOrEmptySchema=Zv;function Xd(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,Wv.reportError)(o,Gv,void 0,e)}});var _a=S(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.getRules=fr.isJSONType=void 0;var Jv=["string","number","integer","boolean","null","object","array"],Yv=new Set(Jv);function Xv(t){return typeof t=="string"&&Yv.has(t)}fr.isJSONType=Xv;function Qv(){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:{}}}fr.getRules=Qv});var wa=S(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.shouldUseRule=vt.shouldUseGroup=vt.schemaHasRulesForType=void 0;function eb({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ep(t,n)}vt.schemaHasRulesForType=eb;function ep(t,e){return e.rules.some(r=>tp(t,r))}vt.shouldUseGroup=ep;function tp(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))}vt.shouldUseRule=tp});var yn=S(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var tb=_a(),rb=wa(),nb=gn(),q=D(),rp=W(),hr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(hr||(ve.DataType=hr={}));function ob(t){let e=np(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}ve.getSchemaTypes=ob;function np(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(tb.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ve.getJSONTypes=np;function sb(t,e){let{gen:r,data:n,opts:o}=t,s=ib(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,rb.schemaHasRulesForType)(t,e[0]));if(i){let a=ba(e,n,o.strictNumbers,hr.Wrong);r.if(a,()=>{s.length?ab(t,e,s):Sa(t)})}return i}ve.coerceAndCheckDataType=sb;var op=new Set(["string","number","integer","boolean","null"]);function ib(t,e){return e?t.filter(r=>op.has(r)||e==="array"&&r==="array"):[]}function ab(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(ba(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(op.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Sa(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),cb(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
4
+ import{a as po,b as Ul,c as Fl,f as Hl}from"./chunk-UBV5T4TV.js";import{b as Ll,h as uo}from"./chunk-SM5OVMF6.js";import{a as er,b as Dl}from"./chunk-OKI2P5FO.js";import{a as Le,b as Pl,c as ao,d as co}from"./chunk-OZOP4GVS.js";import{e as tr}from"./chunk-2BJOFNPI.js";import{a as ft}from"./chunk-7MHXMDYC.js";import{A as jl,B as Nl,C as A,D as _,I as C,K as ri,L as ql,M as ni,O as N,Q as Rt,R as Vr,S as E,T as lo,a as El,d as Rl,e as xe,f as Cl,g as Ml,h as p,i as zl,j as B,k as Z,l as Al,m as Il,n as se,o as x,p as $,q as ce,r as ee,s as Qs,t as ei,u as Y,v as ze,w as P,x as re,y as Ol,z as ti}from"./chunk-XYSBNUNB.js";import{a as mt,b as k,d as io}from"./chunk-X3UA5OZL.js";var dn=k(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.regexpCode=G.getEsmExportName=G.getProperty=G.safeStringify=G.stringify=G.strConcat=G.addCodeArg=G.str=G._=G.nil=G._Code=G.Name=G.IDENTIFIER=G._CodeOrName=void 0;var ln=class{};G._CodeOrName=ln;G.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Ot=class extends ln{constructor(e){if(super(),!G.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}}};G.Name=Ot;var je=class extends ln{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 Ot&&(r[n.str]=(r[n.str]||0)+1),r),{})}};G._Code=je;G.nil=new je("");function Dd(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Xi(r,e[n]),r.push(t[++n]);return new je(r)}G._=Dd;var Yi=new je("+");function Ld(t,...e){let r=[un(t[0])],n=0;for(;n<e.length;)r.push(Yi),Xi(r,e[n]),r.push(Yi,un(t[++n]));return vv(r),new je(r)}G.str=Ld;function Xi(t,e){e instanceof je?t.push(...e._items):e instanceof Ot?t.push(e):t.push(kv(e))}G.addCodeArg=Xi;function vv(t){let e=1;for(;e<t.length-1;){if(t[e]===Yi){let r=bv(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function bv(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Ot||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 Ot))return`"${t}${e.slice(1)}`}function Sv(t,e){return e.emptyStr()?t:t.emptyStr()?e:Ld`${t}${e}`}G.strConcat=Sv;function kv(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:un(Array.isArray(t)?t.join(","):t)}function Tv(t){return new je(un(t))}G.stringify=Tv;function un(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}G.safeStringify=un;function xv(t){return typeof t=="string"&&G.IDENTIFIER.test(t)?new je(`.${t}`):Dd`[${t}]`}G.getProperty=xv;function $v(t){if(typeof t=="string"&&G.IDENTIFIER.test(t))return new je(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}G.getEsmExportName=$v;function Ev(t){return new je(t.toString())}G.regexpCode=Ev});var ta=k(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.ValueScope=Pe.ValueScopeName=Pe.Scope=Pe.varKinds=Pe.UsedValueState=void 0;var Ee=dn(),Qi=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Wo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Wo||(Pe.UsedValueState=Wo={}));Pe.varKinds={const:new Ee.Name("const"),let:new Ee.Name("let"),var:new Ee.Name("var")};var Bo=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ee.Name?e:this.name(e)}name(e){return new Ee.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}}};Pe.Scope=Bo;var Go=class extends Ee.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ee._)`.${new Ee.Name(r)}[${n}]`}};Pe.ValueScopeName=Go;var Pv=(0,Ee._)`\n`,ea=class extends Bo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Pv:Ee.nil}}get(){return this._scope}name(e){return new Go(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 l=a.get(i);if(l)return l}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,Ee._)`${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=Ee.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,Wo.Started);let l=r(u);if(l){let d=this.opts.es5?Pe.varKinds.var:Pe.varKinds.const;s=(0,Ee._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ee._)`${s}${l}${this.opts._n}`;else throw new Qi(u);c.set(u,Wo.Completed)})}return s}};Pe.ValueScope=ea});var D=k(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 H=dn(),Ue=ta(),wt=dn();Object.defineProperty(L,"_",{enumerable:!0,get:function(){return wt._}});Object.defineProperty(L,"str",{enumerable:!0,get:function(){return wt.str}});Object.defineProperty(L,"strConcat",{enumerable:!0,get:function(){return wt.strConcat}});Object.defineProperty(L,"nil",{enumerable:!0,get:function(){return wt.nil}});Object.defineProperty(L,"getProperty",{enumerable:!0,get:function(){return wt.getProperty}});Object.defineProperty(L,"stringify",{enumerable:!0,get:function(){return wt.stringify}});Object.defineProperty(L,"regexpCode",{enumerable:!0,get:function(){return wt.regexpCode}});Object.defineProperty(L,"Name",{enumerable:!0,get:function(){return wt.Name}});var Yo=ta();Object.defineProperty(L,"Scope",{enumerable:!0,get:function(){return Yo.Scope}});Object.defineProperty(L,"ValueScope",{enumerable:!0,get:function(){return Yo.ValueScope}});Object.defineProperty(L,"ValueScopeName",{enumerable:!0,get:function(){return Yo.ValueScopeName}});Object.defineProperty(L,"varKinds",{enumerable:!0,get:function(){return Yo.varKinds}});L.operators={GT:new H._Code(">"),GTE:new H._Code(">="),LT:new H._Code("<"),LTE:new H._Code("<="),EQ:new H._Code("==="),NEQ:new H._Code("!=="),NOT:new H._Code("!"),OR:new H._Code("||"),AND:new H._Code("&&"),ADD:new H._Code("+")};var tt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ra=class extends tt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Ue.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=pr(this.rhs,e,r)),this}get names(){return this.rhs instanceof H._CodeOrName?this.rhs.names:{}}},Ko=class extends tt{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 H.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=pr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof H.Name?{}:{...this.lhs.names};return Jo(e,this.rhs)}},na=class extends Ko{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},oa=class extends tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sa=class extends tt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ia=class extends tt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},aa=class extends tt{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=pr(this.code,e,r),this}get names(){return this.code instanceof H._CodeOrName?this.code.names:{}}},pn=class extends tt{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)||(Rv(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qt(e,r.names),{})}},rt=class extends pn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ca=class extends pn{},dr=class extends rt{};dr.kind="else";var jt=class t extends rt{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 dr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Ud(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=pr(this.condition,e,r),this}get names(){let e=super.names;return Jo(e,this.condition),this.else&&qt(e,this.else.names),e}};jt.kind="if";var Nt=class extends rt{};Nt.kind="for";var la=class extends Nt{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=pr(this.iteration,e,r),this}get names(){return qt(super.names,this.iteration.names)}},ua=class extends Nt{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Ue.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=Jo(super.names,this.from);return Jo(e,this.to)}},Zo=class extends Nt{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=pr(this.iterable,e,r),this}get names(){return qt(super.names,this.iterable.names)}},mn=class extends rt{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)}};mn.kind="func";var fn=class extends pn{render(e){return"return "+super.render(e)}};fn.kind="return";var da=class extends rt{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&&qt(e,this.catch.names),this.finally&&qt(e,this.finally.names),e}},hn=class extends rt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};hn.kind="catch";var gn=class extends rt{render(e){return"finally"+super.render(e)}};gn.kind="finally";var pa=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
5
+ `:""},this._extScope=e,this._scope=new Ue.Scope({parent:e}),this._nodes=[new ca]}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 ra(e,s,n)),s}const(e,r,n){return this._def(Ue.varKinds.const,e,r,n)}let(e,r,n){return this._def(Ue.varKinds.let,e,r,n)}var(e,r,n){return this._def(Ue.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ko(e,r,n))}add(e,r){return this._leafNode(new na(e,L.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==H.nil&&this._leafNode(new aa(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,H.addCodeArg)(r,o));return r.push("}"),new H._Code(r)}if(e,r,n){if(this._blockNode(new jt(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 jt(e))}else(){return this._elseNode(new dr)}endIf(){return this._endBlockNode(jt,dr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new la(e),r)}forRange(e,r,n,o,s=this.opts.es5?Ue.varKinds.var:Ue.varKinds.let){let i=this._scope.toName(e);return this._for(new ua(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Ue.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof H.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,H._)`${i}.length`,a=>{this.var(s,(0,H._)`${i}[${a}]`),n(s)})}return this._for(new Zo("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Ue.varKinds.var:Ue.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,H._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Zo("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Nt)}label(e){return this._leafNode(new oa(e))}break(e){return this._leafNode(new sa(e))}return(e){let r=new fn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new da;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new hn(s),r(s)}return n&&(this._currNode=o.finally=new gn,this.code(n)),this._endBlockNode(hn,gn)}throw(e){return this._leafNode(new ia(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=H.nil,n,o){return this._blockNode(new mn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(mn)}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 jt))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=pa;function qt(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Jo(t,e){return e instanceof H._CodeOrName?qt(t,e.names):t}function pr(t,e,r){if(t instanceof H.Name)return n(t);if(!o(t))return t;return new H._Code(t._items.reduce((s,i)=>(i instanceof H.Name&&(i=n(i)),i instanceof H._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 H._Code&&s._items.some(i=>i instanceof H.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Rv(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Ud(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,H._)`!${ma(t)}`}L.not=Ud;var Cv=Fd(L.operators.AND);function Mv(...t){return t.reduce(Cv)}L.and=Mv;var zv=Fd(L.operators.OR);function Av(...t){return t.reduce(zv)}L.or=Av;function Fd(t){return(e,r)=>e===H.nil?r:r===H.nil?e:(0,H._)`${ma(e)} ${t} ${ma(r)}`}function ma(t){return t instanceof H.Name?t:(0,H._)`(${t})`}});var V=k(U=>{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.checkStrictMode=U.getErrorPath=U.Type=U.useFunc=U.setEvaluated=U.evaluatedPropsToName=U.mergeEvaluated=U.eachItem=U.unescapeJsonPointer=U.escapeJsonPointer=U.escapeFragment=U.unescapeFragment=U.schemaRefOrVal=U.schemaHasRulesButRef=U.schemaHasRules=U.checkUnknownRules=U.alwaysValidSchema=U.toHash=void 0;var J=D(),Iv=dn();function Ov(t){let e={};for(let r of t)e[r]=!0;return e}U.toHash=Ov;function jv(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Wd(t,e),!Bd(e,t.self.RULES.all))}U.alwaysValidSchema=jv;function Wd(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]||Zd(t,`unknown keyword: "${s}"`)}U.checkUnknownRules=Wd;function Bd(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}U.schemaHasRules=Bd;function Nv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}U.schemaHasRulesButRef=Nv;function qv({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,J._)`${r}`}return(0,J._)`${t}${e}${(0,J.getProperty)(n)}`}U.schemaRefOrVal=qv;function Dv(t){return Gd(decodeURIComponent(t))}U.unescapeFragment=Dv;function Lv(t){return encodeURIComponent(ha(t))}U.escapeFragment=Lv;function ha(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}U.escapeJsonPointer=ha;function Gd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}U.unescapeJsonPointer=Gd;function Uv(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}U.eachItem=Uv;function Hd({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof J.Name?(s instanceof J.Name?t(o,s,i):e(o,s,i),i):s instanceof J.Name?(e(o,i,s),s):r(s,i);return a===J.Name&&!(c instanceof J.Name)?n(o,c):c}}U.mergeEvaluated={props:Hd({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,J._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,J._)`${r} || {}`).code((0,J._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,J._)`${r} || {}`),ga(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Kd}),items:Hd({mergeNames:(t,e,r)=>t.if((0,J._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,J._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,J._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,J._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Kd(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,J._)`{}`);return e!==void 0&&ga(t,r,e),r}U.evaluatedPropsToName=Kd;function ga(t,e,r){Object.keys(r).forEach(n=>t.assign((0,J._)`${e}${(0,J.getProperty)(n)}`,!0))}U.setEvaluated=ga;var Vd={};function Fv(t,e){return t.scopeValue("func",{ref:e,code:Vd[e.code]||(Vd[e.code]=new Iv._Code(e.code))})}U.useFunc=Fv;var fa;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(fa||(U.Type=fa={}));function Hv(t,e,r){if(t instanceof J.Name){let n=e===fa.Num;return r?n?(0,J._)`"[" + ${t} + "]"`:(0,J._)`"['" + ${t} + "']"`:n?(0,J._)`"/" + ${t}`:(0,J._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,J.getProperty)(t).toString():"/"+ha(t)}U.getErrorPath=Hv;function Zd(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}U.checkStrictMode=Zd});var nt=k(ya=>{"use strict";Object.defineProperty(ya,"__esModule",{value:!0});var _e=D(),Vv={data:new _e.Name("data"),valCxt:new _e.Name("valCxt"),instancePath:new _e.Name("instancePath"),parentData:new _e.Name("parentData"),parentDataProperty:new _e.Name("parentDataProperty"),rootData:new _e.Name("rootData"),dynamicAnchors:new _e.Name("dynamicAnchors"),vErrors:new _e.Name("vErrors"),errors:new _e.Name("errors"),this:new _e.Name("this"),self:new _e.Name("self"),scope:new _e.Name("scope"),json:new _e.Name("json"),jsonPos:new _e.Name("jsonPos"),jsonLen:new _e.Name("jsonLen"),jsonPart:new _e.Name("jsonPart")};ya.default=Vv});var yn=k(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.extendErrors=we.resetErrorsCount=we.reportExtraError=we.reportError=we.keyword$DataError=we.keywordError=void 0;var W=D(),Xo=V(),be=nt();we.keywordError={message:({keyword:t})=>(0,W.str)`must pass "${t}" keyword validation`};we.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,W.str)`"${t}" keyword must be ${e} ($data)`:(0,W.str)`"${t}" keyword is invalid ($data)`};function Wv(t,e=we.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Xd(t,e,r);n??(i||a)?Jd(s,c):Yd(o,(0,W._)`[${c}]`)}we.reportError=Wv;function Bv(t,e=we.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Xd(t,e,r);Jd(o,a),s||i||Yd(n,be.default.vErrors)}we.reportExtraError=Bv;function Gv(t,e){t.assign(be.default.errors,e),t.if((0,W._)`${be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,W._)`${be.default.vErrors}.length`,e),()=>t.assign(be.default.vErrors,null)))}we.resetErrorsCount=Gv;function Kv({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,be.default.errors,a=>{t.const(i,(0,W._)`${be.default.vErrors}[${a}]`),t.if((0,W._)`${i}.instancePath === undefined`,()=>t.assign((0,W._)`${i}.instancePath`,(0,W.strConcat)(be.default.instancePath,s.errorPath))),t.assign((0,W._)`${i}.schemaPath`,(0,W.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,W._)`${i}.schema`,r),t.assign((0,W._)`${i}.data`,n))})}we.extendErrors=Kv;function Jd(t,e){let r=t.const("err",e);t.if((0,W._)`${be.default.vErrors} === null`,()=>t.assign(be.default.vErrors,(0,W._)`[${r}]`),(0,W._)`${be.default.vErrors}.push(${r})`),t.code((0,W._)`${be.default.errors}++`)}function Yd(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,W._)`new ${t.ValidationError}(${e})`):(r.assign((0,W._)`${n}.errors`,e),r.return(!1))}var Dt={keyword:new W.Name("keyword"),schemaPath:new W.Name("schemaPath"),params:new W.Name("params"),propertyName:new W.Name("propertyName"),message:new W.Name("message"),schema:new W.Name("schema"),parentSchema:new W.Name("parentSchema")};function Xd(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,W._)`{}`:Zv(t,e,r)}function Zv(t,e,r={}){let{gen:n,it:o}=t,s=[Jv(o,r),Yv(t,r)];return Xv(t,e,s),n.object(...s)}function Jv({errorPath:t},{instancePath:e}){let r=e?(0,W.str)`${t}${(0,Xo.getErrorPath)(e,Xo.Type.Str)}`:t;return[be.default.instancePath,(0,W.strConcat)(be.default.instancePath,r)]}function Yv({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,W.str)`${e}/${t}`;return r&&(o=(0,W.str)`${o}${(0,Xo.getErrorPath)(r,Xo.Type.Str)}`),[Dt.schemaPath,o]}function Xv(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Dt.keyword,o],[Dt.params,typeof e=="function"?e(t):e||(0,W._)`{}`]),c.messages&&n.push([Dt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Dt.schema,i],[Dt.parentSchema,(0,W._)`${l}${d}`],[be.default.data,s]),u&&n.push([Dt.propertyName,u])}});var ep=k(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.boolOrEmptySchema=mr.topBoolOrEmptySchema=void 0;var Qv=yn(),eb=D(),tb=nt(),rb={message:"boolean schema is false"};function nb(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Qd(t,!1):typeof r=="object"&&r.$async===!0?e.return(tb.default.data):(e.assign((0,eb._)`${n}.errors`,null),e.return(!0))}mr.topBoolOrEmptySchema=nb;function ob(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Qd(t)):r.var(e,!0)}mr.boolOrEmptySchema=ob;function Qd(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,Qv.reportError)(o,rb,void 0,e)}});var _a=k(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.getRules=fr.isJSONType=void 0;var sb=["string","number","integer","boolean","null","object","array"],ib=new Set(sb);function ab(t){return typeof t=="string"&&ib.has(t)}fr.isJSONType=ab;function cb(){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:{}}}fr.getRules=cb});var wa=k(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.shouldUseRule=vt.shouldUseGroup=vt.schemaHasRulesForType=void 0;function lb({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&tp(t,n)}vt.schemaHasRulesForType=lb;function tp(t,e){return e.rules.some(r=>rp(t,r))}vt.shouldUseGroup=tp;function rp(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))}vt.shouldUseRule=rp});var _n=k(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.reportTypeError=ve.checkDataTypes=ve.checkDataType=ve.coerceAndCheckDataType=ve.getJSONTypes=ve.getSchemaTypes=ve.DataType=void 0;var ub=_a(),db=wa(),pb=yn(),q=D(),np=V(),hr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(hr||(ve.DataType=hr={}));function mb(t){let e=op(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}ve.getSchemaTypes=mb;function op(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(ub.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ve.getJSONTypes=op;function fb(t,e){let{gen:r,data:n,opts:o}=t,s=hb(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,db.schemaHasRulesForType)(t,e[0]));if(i){let a=ba(e,n,o.strictNumbers,hr.Wrong);r.if(a,()=>{s.length?gb(t,e,s):Sa(t)})}return i}ve.coerceAndCheckDataType=fb;var sp=new Set(["string","number","integer","boolean","null"]);function hb(t,e){return e?t.filter(r=>sp.has(r)||e==="array"&&r==="array"):[]}function gb(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(ba(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(sp.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Sa(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),yb(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
6
6
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
7
7
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,q._)`+${o}`);return;case"boolean":n.elseIf((0,q._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,q._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,q._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,q._)`${i} === "string" || ${i} === "number"
8
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function cb({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function va(t,e,r,n=hr.Correct){let o=n===hr.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===hr.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}ve.checkDataType=va;function ba(t,e,r,n){if(t.length===1)return va(t[0],e,r,n);let o,s=(0,rp.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,va(i,e,r,n));return o}ve.checkDataTypes=ba;var lb={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Sa(t){let e=ub(t);(0,nb.reportError)(e,lb)}ve.reportTypeError=Sa;function ub(t){let{gen:e,data:r,schema:n}=t,o=(0,rp.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ip=S(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.assignDefaults=void 0;var gr=D(),db=W();function pb(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)sp(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>sp(t,s,o.default))}es.assignDefaults=pb;function sp(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,gr._)`${s}${(0,gr.getProperty)(e)}`;if(o){(0,db.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,gr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,gr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,gr._)`${a} = ${(0,gr.stringify)(r)}`)}});var qe=S(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=D(),ka=W(),bt=nt(),mb=W();function fb(t,e){let{gen:r,data:n,it:o}=t;r.if(xa(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,X._)`${e}`},!0),t.error()})}K.checkReportMissingProp=fb;function hb({gen:t,data:e,it:{opts:r}},n,o){return(0,X.or)(...n.map(s=>(0,X.and)(xa(t,e,s,r.ownProperties),(0,X._)`${o} = ${s}`)))}K.checkMissingProp=hb;function gb(t,e){t.setParams({missingProperty:e},!0),t.error()}K.reportMissingProp=gb;function ap(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=ap;function Ta(t,e,r){return(0,X._)`${ap(t)}.call(${e}, ${r})`}K.isOwnProperty=Ta;function yb(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Ta(t,e,r)}`:o}K.propertyInData=yb;function xa(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Ta(t,e,r))):o}K.noPropertyInData=xa;function cp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}K.allSchemaProperties=cp;function _b(t,e){return cp(e).filter(r=>!(0,ka.alwaysValidSchema)(t,e[r]))}K.schemaProperties=_b;function wb({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,X._)`${t}, ${e}, ${n}${o}`:e,d=[[bt.default.instancePath,(0,X.strConcat)(bt.default.instancePath,s)],[bt.default.parentData,i.parentData],[bt.default.parentDataProperty,i.parentDataProperty],[bt.default.rootData,bt.default.rootData]];i.opts.dynamicRef&&d.push([bt.default.dynamicAnchors,bt.default.dynamicAnchors]);let m=(0,X._)`${l}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${m})`:(0,X._)`${a}(${m})`}K.callValidateCode=wb;var vb=(0,X._)`new RegExp`;function bb({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,X._)`${o.code==="new RegExp"?vb:(0,mb.useFunc)(t,o)}(${r}, ${n})`})}K.usePattern=bb;function Sb(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,X._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ka.Type.Num},s),e.if((0,X.not)(s),a)})}}K.validateArray=Sb;function kb(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,ka.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,X._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,X.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}K.validateUnion=kb});var dp=S(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.validateKeywordUsage=Ke.validSchemaType=Ke.funcKeywordCode=Ke.macroKeywordCode=void 0;var Se=D(),Lt=nt(),Tb=qe(),xb=gn();function $b(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=up(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Se.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ke.macroKeywordCode=$b;function Eb(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;Rb(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=up(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)h(),e.modifying&&lp(t),y(()=>t.error());else{let v=e.async?f():g();e.modifying&&lp(t),y(()=>Pb(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Se._)`await `),$=>n.assign(d,!1).if((0,Se._)`${$} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Se._)`${$}.errors`),()=>n.throw($))),v}function g(){let v=(0,Se._)`${l}.errors`;return n.assign(v,null),h(Se.nil),v}function h(v=e.async?(0,Se._)`await `:Se.nil){let $=c.opts.passContext?Lt.default.this:Lt.default.self,k=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Se._)`${v}${(0,Tb.callValidateCode)(t,l,$,k)}`,e.modifying)}function y(v){var $;n.if((0,Se.not)(($=e.valid)!==null&&$!==void 0?$:d),v)}}Ke.funcKeywordCode=Eb;function lp(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Se._)`${n.parentData}[${n.parentDataProperty}]`))}function Pb(t,e){let{gen:r}=t;r.if((0,Se._)`Array.isArray(${e})`,()=>{r.assign(Lt.default.vErrors,(0,Se._)`${Lt.default.vErrors} === null ? ${e} : ${Lt.default.vErrors}.concat(${e})`).assign(Lt.default.errors,(0,Se._)`${Lt.default.vErrors}.length`),(0,xb.extendErrors)(t)},()=>t.error())}function Rb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function up(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,Se.stringify)(r)})}function Cb(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")}Ke.validSchemaType=Cb;function Mb({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)}}Ke.validateKeywordUsage=Mb});var mp=S(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.extendSubschemaMode=St.extendSubschemaData=St.getSubschema=void 0;var Ze=D(),pp=W();function zb(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,Ze._)`${t.schemaPath}${(0,Ze.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ze._)`${t.schemaPath}${(0,Ze.getProperty)(e)}${(0,Ze.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pp.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')}St.getSubschema=zb;function Ab(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:l,opts:d}=e,m=a.let("data",(0,Ze._)`${e.data}${(0,Ze.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Ze.str)`${u}${(0,pp.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ze._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ze.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]}}St.extendSubschemaData=Ab;function Ib(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}St.extendSubschemaMode=Ib});var $a=S((dO,fp)=>{"use strict";fp.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 gp=S((pO,hp)=>{"use strict";var kt=hp.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(){};ts(e,n,o,t,"",t)};kt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};kt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};kt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};kt.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 ts(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 l in n){var d=n[l];if(Array.isArray(d)){if(l in kt.arrayKeywords)for(var m=0;m<d.length;m++)ts(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in kt.propsKeywords){if(d&&typeof d=="object")for(var f in d)ts(t,e,r,d[f],o+"/"+l+"/"+Ob(f),s,o,l,n,f)}else(l in kt.keywords||t.allKeys&&!(l in kt.skipKeywords))&&ts(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function Ob(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var _n=S(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getSchemaRefs=Re.resolveUrl=Re.normalizeId=Re._getFullPath=Re.getFullPath=Re.inlineRef=void 0;var jb=W(),Nb=$a(),qb=gp(),Db=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Lb(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ea(t):e?yp(t)<=e:!1}Re.inlineRef=Lb;var Ub=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ea(t){for(let e in t){if(Ub.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ea)||typeof r=="object"&&Ea(r))return!0}return!1}function yp(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Db.has(r)&&(typeof t[r]=="object"&&(0,jb.eachItem)(t[r],n=>e+=yp(n)),e===1/0))return 1/0}return e}function _p(t,e="",r){r!==!1&&(e=yr(e));let n=t.parse(e);return wp(t,n)}Re.getFullPath=_p;function wp(t,e){return t.serialize(e).split("#")[0]+"#"}Re._getFullPath=wp;var Fb=/#\/?$/;function yr(t){return t?t.replace(Fb,""):""}Re.normalizeId=yr;function Hb(t,e,r){return r=yr(r),t.resolve(e,r)}Re.resolveUrl=Hb;var Wb=/^[a-z_][-a-z0-9._]*$/i;function Vb(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=yr(t[r]||e),s={"":o},i=_p(n,o,!1),a={},c=new Set;return qb(t,{allKeys:!0},(d,m,f,g)=>{if(g===void 0)return;let h=i+m,y=s[g];typeof d[r]=="string"&&(y=v.call(this,d[r])),$.call(this,d.$anchor),$.call(this,d.$dynamicAnchor),s[m]=y;function v(k){let z=this.opts.uriResolver.resolve;if(k=yr(y?z(y,k):k),c.has(k))throw l(k);c.add(k);let w=this.refs[k];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(d,w.schema,k):k!==yr(h)&&(k[0]==="#"?(u(d,a[k],k),a[k]=d):this.refs[k]=h),k}function $(k){if(typeof k=="string"){if(!Wb.test(k))throw new Error(`invalid anchor "${k}"`);v.call(this,`#${k}`)}}}),a;function u(d,m,f){if(m!==void 0&&!Nb(d,m))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Re.getSchemaRefs=Vb});var bn=S(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var Tp=Qd(),vp=yn(),Ra=wa(),rs=yn(),Bb=ip(),vn=dp(),Pa=mp(),R=D(),O=nt(),Gb=_n(),ot=W(),wn=gn();function Kb(t){if(Ep(t)&&(Pp(t),$p(t))){Yb(t);return}xp(t,()=>(0,Tp.topBoolOrEmptySchema)(t))}Tt.validateFunctionCode=Kb;function xp({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,R._)`${O.default.data}, ${O.default.valCxt}`,n.$async,()=>{t.code((0,R._)`"use strict"; ${bp(r,o)}`),Jb(t,o),t.code(s)}):t.func(e,(0,R._)`${O.default.data}, ${Zb(o)}`,n.$async,()=>t.code(bp(r,o)).code(s))}function Zb(t){return(0,R._)`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${t.dynamicRef?(0,R._)`, ${O.default.dynamicAnchors}={}`:R.nil}}={}`}function Jb(t,e){t.if(O.default.valCxt,()=>{t.var(O.default.instancePath,(0,R._)`${O.default.valCxt}.${O.default.instancePath}`),t.var(O.default.parentData,(0,R._)`${O.default.valCxt}.${O.default.parentData}`),t.var(O.default.parentDataProperty,(0,R._)`${O.default.valCxt}.${O.default.parentDataProperty}`),t.var(O.default.rootData,(0,R._)`${O.default.valCxt}.${O.default.rootData}`),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,R._)`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{t.var(O.default.instancePath,(0,R._)`""`),t.var(O.default.parentData,(0,R._)`undefined`),t.var(O.default.parentDataProperty,(0,R._)`undefined`),t.var(O.default.rootData,O.default.data),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,R._)`{}`)})}function Yb(t){let{schema:e,opts:r,gen:n}=t;xp(t,()=>{r.$comment&&e.$comment&&Cp(t),rS(t),n.let(O.default.vErrors,null),n.let(O.default.errors,0),r.unevaluated&&Xb(t),Rp(t),sS(t)})}function Xb(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,R._)`${r}.evaluated`),e.if((0,R._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,R._)`${t.evaluated}.props`,(0,R._)`undefined`)),e.if((0,R._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,R._)`${t.evaluated}.items`,(0,R._)`undefined`))}function bp(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,R._)`/*# sourceURL=${r} */`:R.nil}function Qb(t,e){if(Ep(t)&&(Pp(t),$p(t))){eS(t,e);return}(0,Tp.boolOrEmptySchema)(t,e)}function $p({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 Ep(t){return typeof t.schema!="boolean"}function eS(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Cp(t),nS(t),oS(t);let s=n.const("_errs",O.default.errors);Rp(t,s),n.var(e,(0,R._)`${s} === ${O.default.errors}`)}function Pp(t){(0,ot.checkUnknownRules)(t),tS(t)}function Rp(t,e){if(t.opts.jtd)return Sp(t,[],!1,e);let r=(0,vp.getSchemaTypes)(t.schema),n=(0,vp.coerceAndCheckDataType)(t,r);Sp(t,r,!n,e)}function tS(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function rS(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ot.checkStrictMode)(t,"default is ignored in the schema root")}function nS(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Gb.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function oS(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cp({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,R._)`${O.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,R.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,R._)`${O.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function sS(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,R._)`${O.default.errors} === 0`,()=>e.return(O.default.data),()=>e.throw((0,R._)`new ${o}(${O.default.vErrors})`)):(e.assign((0,R._)`${n}.errors`,O.default.vErrors),s.unevaluated&&iS(t),e.return((0,R._)`${O.default.errors} === 0`))}function iS({gen:t,evaluated:e,props:r,items:n}){r instanceof R.Name&&t.assign((0,R._)`${e}.props`,r),n instanceof R.Name&&t.assign((0,R._)`${e}.items`,n)}function Sp(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(s,l))){o.block(()=>zp(t,"$ref",l.all.$ref.definition));return}c.jtd||aS(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ra.shouldUseGroup)(s,m)&&(m.type?(o.if((0,rs.checkDataType)(m.type,i,c.strictNumbers)),kp(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,rs.reportTypeError)(t)),o.endIf()):kp(t,m),a||o.if((0,R._)`${O.default.errors} === ${n||0}`))}}function kp(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,Bb.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ra.shouldUseRule)(n,s)&&zp(t,s.keyword,s.definition,e.type)})}function aS(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(cS(t,e),t.opts.allowUnionTypes||lS(t,e),uS(t,t.dataTypes))}function cS(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Mp(t.dataTypes,r)||Ca(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),pS(t,e)}}function lS(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ca(t,"use allowUnionTypes to allow union type keyword")}function uS(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ra.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>dS(e,i))&&Ca(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function dS(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Mp(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function pS(t,e){let r=[];for(let n of t.dataTypes)Mp(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ca(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ot.checkStrictMode)(t,e,t.opts.strictTypes)}var ns=class{constructor(e,r,n){if((0,vn.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,ot.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",Ap(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,vn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",O.default.errors))}result(e,r,n){this.failResult((0,R.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,R.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,R._)`${r} !== undefined && (${(0,R.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?wn.reportExtraError:wn.reportError)(this,this.def.error,r)}$dataError(){(0,wn.reportError)(this,this.def.$dataError||wn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,wn.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=R.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=R.nil,r=R.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,R.or)((0,R._)`${o} === undefined`,r)),e!==R.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==R.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(n.length){if(!(r instanceof R.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,R._)`${(0,rs.checkDataTypes)(c,r,s.opts.strictNumbers,rs.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${r})`}return R.nil}}subschema(e,r){let n=(0,Pa.getSubschema)(this.it,e);(0,Pa.extendSubschemaData)(n,this.it,e),(0,Pa.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return Qb(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ot.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ot.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,R.Name)),!0}};Tt.KeywordCxt=ns;function zp(t,e,r,n){let o=new ns(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,vn.funcKeywordCode)(o,r):"macro"in r?(0,vn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,vn.funcKeywordCode)(o,r)}var mS=/^\/(?:[^~]|~0|~1)*$/,fS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ap(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return O.default.rootData;if(t[0]==="/"){if(!mS.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=O.default.rootData}else{let u=fS.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,ot.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Tt.getData=Ap});var os=S(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var Ma=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};za.default=Ma});var Sn=S(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Aa=_n(),Ia=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Aa.resolveUrl)(e,r,n),this.missingSchema=(0,Aa.normalizeId)((0,Aa.getFullPath)(e,this.missingRef))}};Oa.default=Ia});var is=S(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.resolveSchema=De.getCompilingSchema=De.resolveRef=De.compileSchema=De.SchemaEnv=void 0;var He=D(),hS=os(),Ut=nt(),We=_n(),Ip=W(),gS=bn(),_r=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,We.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};De.SchemaEnv=_r;function Na(t){let e=Op.call(this,t);if(e)return e;let r=(0,We.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new He.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:hS.default,code:(0,He._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Ut.default.data,parentData:Ut.default.parentData,parentDataProperty:Ut.default.parentDataProperty,dataNames:[Ut.default.data],dataPathArr:[He.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,He.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:He.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,He._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,gS.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Ut.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Ut.default.self}`,`${Ut.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:g,items:h}=u;f.evaluated={props:g instanceof He.Name?void 0:g,items:h instanceof He.Name?void 0:h,dynamicProps:g instanceof He.Name,dynamicItems:h instanceof He.Name},f.source&&(f.source.evaluated=(0,He.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}De.compileSchema=Na;function yS(t,e,r){var n;r=(0,We.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=vS.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 _r({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=_S.call(this,s)}De.resolveRef=yS;function _S(t){return(0,We.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Na.call(this,t)}function Op(t){for(let e of this._compilations)if(wS(e,t))return e}De.getCompilingSchema=Op;function wS(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function vS(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ss.call(this,t,e)}function ss(t,e){let r=this.opts.uriResolver.parse(e),n=(0,We._getFullPath)(this.opts.uriResolver,r),o=(0,We.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ja.call(this,r,t);let s=(0,We.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ss.call(this,t,i);return typeof a?.schema!="object"?void 0:ja.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Na.call(this,i),s===(0,We.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,We.resolveUrl)(this.opts.uriResolver,o,u)),new _r({schema:a,schemaId:c,root:t,baseId:o})}return ja.call(this,r,i)}}De.resolveSchema=ss;var bS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ja(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,Ip.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!bS.has(a)&&u&&(e=(0,We.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Ip.schemaHasRulesButRef)(r,this.RULES)){let a=(0,We.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ss.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new _r({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var jp=S((_O,SS)=>{SS.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 La=S((wO,Fp)=>{"use strict";var kS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),qp=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),qa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Dp=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),TS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Da(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 xS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Np(t){return t.length=0,!0}function $S(t,e,r){if(t.length){let n=Da(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function ES(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=$S;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=Np}else{o.push(u);continue}}return o.length&&(a===Np?r.zone=o.join(""):i?n.push(o.join("")):n.push(Da(o))),r.address=n.join(""),r}function Lp(t){if(PS(t,":")<2)return{host:t,isIPV6:!1};let e=ES(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 PS(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function RS(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 CS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},MS=/[@/?#:]/g,zS=/[@/?#]/g;function Up(t,e){let r=e?zS:MS;return r.lastIndex=0,t.replace(r,n=>CS[n])}function AS(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(qa(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Dp(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function IS(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(qa(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Dp(s)?e+=s:e+="%"+o,r+=2;continue}}TS(t[r])?e+=t[r]:e+=escape(t[r])}return e}function OS(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(qa(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function jS(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!qp(r)){let n=Lp(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Up(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}Fp.exports={nonSimpleDomain:xS,recomposeAuthority:jS,reescapeHostDelimiters:Up,normalizePercentEncoding:AS,normalizePathEncoding:IS,escapePreservingEscapes:OS,removeDotSegments:RS,isIPv4:qp,isUUID:kS,normalizeIPv6:Lp,stringArrayToHexStripped:Da}});var Gp=S((vO,Bp)=>{"use strict";var{isUUID:NS}=La(),qS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,DS=["http","https","ws","wss","urn","urn:uuid"];function LS(t){return DS.indexOf(t)!==-1}function Ua(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 Hp(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Wp(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 US(t){return t.secure=Ua(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function FS(t){if((t.port===(Ua(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 HS(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(qS);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=Fa(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function WS(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=Fa(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 VS(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!NS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function BS(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Vp={scheme:"http",domainHost:!0,parse:Hp,serialize:Wp},GS={scheme:"https",domainHost:Vp.domainHost,parse:Hp,serialize:Wp},as={scheme:"ws",domainHost:!0,parse:US,serialize:FS},KS={scheme:"wss",domainHost:as.domainHost,parse:as.parse,serialize:as.serialize},ZS={scheme:"urn",parse:HS,serialize:WS,skipNormalize:!0},JS={scheme:"urn:uuid",parse:VS,serialize:BS,skipNormalize:!0},cs={http:Vp,https:GS,ws:as,wss:KS,urn:ZS,"urn:uuid":JS};Object.setPrototypeOf(cs,null);function Fa(t){return t&&(cs[t]||cs[t.toLowerCase()])||void 0}Bp.exports={wsIsSecure:Ua,SCHEMES:cs,isValidSchemeName:LS,getSchemeHandler:Fa}});var Qp=S((bO,ls)=>{"use strict";var{normalizeIPv6:YS,removeDotSegments:kn,recomposeAuthority:XS,normalizePercentEncoding:QS,normalizePathEncoding:ek,escapePreservingEscapes:tk,reescapeHostDelimiters:rk,isIPv4:nk,nonSimpleDomain:ok}=La(),{SCHEMES:sk,getSchemeHandler:Zp}=Gp();function ik(t,e){return typeof t=="string"?t=pk(t,e):typeof t=="object"&&(t=wr(Ft(t,e),e)),t}function ak(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Jp(wr(t,n),wr(e,n),n,!0);return n.skipEscape=!0,Ft(o,n)}function Jp(t,e,r,n){let o={};return n||(t=wr(Ft(t,r),r),e=wr(Ft(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=kn(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=kn(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=kn(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=kn(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 ck(t,e,r){let n=Kp(t,r),o=Kp(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ft(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=Zp(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=QS(r.path):(r.path=tk(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=XS(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=kn(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 lk=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,uk=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function dk(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 Yp(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(uk);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(lk);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=dk(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(nk(n.host)===!1){let d=YS(n.host);n.host=d.host.toLowerCase(),s=d.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 u=Zp(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&ok(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((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=rk(unescape(n.host),s))),n.path&&(n.path=ek(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function wr(t,e){return Yp(t,e).parsed}function pk(t,e){return Xp(t,e).normalized}function Xp(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Yp(t,e);return{normalized:n?t:Ft(r,e),malformedAuthorityOrPort:n}}function Kp(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Xp(t,e);return n?void 0:r}if(typeof t=="object")return Ft(t,e)}var Ha={SCHEMES:sk,normalize:ik,resolve:ak,resolveComponent:Jp,equal:ck,serialize:Ft,parse:wr};ls.exports=Ha;ls.exports.default=Ha;ls.exports.fastUri=Ha});var tm=S(Wa=>{"use strict";Object.defineProperty(Wa,"__esModule",{value:!0});var em=Qp();em.code='require("ajv/dist/runtime/uri").default';Wa.default=em});var lm=S(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=void 0;var mk=bn();Object.defineProperty(he,"KeywordCxt",{enumerable:!0,get:function(){return mk.KeywordCxt}});var vr=D();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(he,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var fk=os(),im=Sn(),hk=_a(),Tn=is(),gk=D(),xn=_n(),us=yn(),Ba=W(),rm=jp(),yk=tm(),am=(t,e)=>new RegExp(t,e);am.code="new RegExp";var _k=["removeAdditional","useDefaults","coerceTypes"],wk=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),vk={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."},bk={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},nm=200;function Sk(t){var e,r,n,o,s,i,a,c,u,l,d,m,f,g,h,y,v,$,k,z,w,b,j,ne,oe;let Te=t.strict,Hr=(e=t.code)===null||e===void 0?void 0:e.optimize,oo=Hr===!0||Hr===void 0?1:Hr||0,so=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:am,pt=(o=t.uriResolver)!==null&&o!==void 0?o:yk.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Te)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&m!==void 0?m:"log",strictRequired:(g=(f=t.strictRequired)!==null&&f!==void 0?f:Te)!==null&&g!==void 0?g:!1,code:t.code?{...t.code,optimize:oo,regExp:so}:{optimize:oo,regExp:so},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:nm,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:nm,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:($=t.messages)!==null&&$!==void 0?$:!0,inlineRefs:(k=t.inlineRefs)!==null&&k!==void 0?k:!0,schemaId:(z=t.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(b=t.validateSchema)!==null&&b!==void 0?b:!0,validateFormats:(j=t.validateFormats)!==null&&j!==void 0?j:!0,unicodeRegExp:(ne=t.unicodeRegExp)!==null&&ne!==void 0?ne:!0,int32range:(oe=t.int32range)!==null&&oe!==void 0?oe:!0,uriResolver:pt}}var $n=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,...Sk(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new gk.ValueScope({scope:{},prefixes:wk,es5:r,lines:n}),this.logger=Pk(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hk.getRules)(),om.call(this,vk,e,"NOT SUPPORTED"),om.call(this,bk,e,"DEPRECATED","warn"),this._metaOpts=$k.call(this),e.formats&&Tk.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&xk.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),kk.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=rm;n==="id"&&(o={...rm},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(l,d){await s.call(this,l.$schema);let m=this._addSchema(l,d);return m.validate||i.call(this,m)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof im.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}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,xn.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=sm.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Tn.SchemaEnv({schema:{},schemaId:n});if(r=Tn.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=sm.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,xn.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(Ck.call(this,n,r),!r)return(0,Ba.eachItem)(n,s=>Va.call(this,s)),this;zk.call(this,r);let o={...r,type:(0,us.getJSONTypes)(r.type),schemaType:(0,us.getJSONTypes)(r.schemaType)};return(0,Ba.eachItem)(n,o.type.length===0?s=>Va.call(this,s,o):s=>o.type.forEach(i=>Va.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,l=i[a];u&&l&&(i[a]=cm(l))}}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,xn.normalizeId)(i||n);let u=xn.getSchemaRefs.call(this,e,n);return c=new Tn.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):Tn.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{Tn.compileSchema.call(this,e)}finally{this.opts=r}}};$n.ValidationError=fk.default;$n.MissingRefError=im.default;he.default=$n;function om(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 sm(t){return t=(0,xn.normalizeId)(t),this.schemas[t]||this.refs[t]}function kk(){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 Tk(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function xk(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 $k(){let t={...this.opts};for(let e of _k)delete t[e];return t}var Ek={log(){},warn(){},error(){}};function Pk(t){if(t===!1)return Ek;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 Rk=/^[a-z_$][a-z0-9_$:-]*$/i;function Ck(t,e){let{RULES:r}=this;if((0,Ba.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Rk.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 Va(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,us.getJSONTypes)(e.type),schemaType:(0,us.getJSONTypes)(e.schemaType)}};e.before?Mk.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 Mk(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 zk(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=cm(e)),t.validateSchema=this.compile(e,!0))}var Ak={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function cm(t){return{anyOf:[t,Ak]}}});var um=S(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var Ik={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ga.default=Ik});var fm=S(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.callRef=Ht.getValidate=void 0;var Ok=Sn(),dm=qe(),Ce=D(),br=nt(),pm=is(),ds=W(),jk={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 d();let l=pm.resolveRef.call(c,u,o,r);if(l===void 0)throw new Ok.default(n.opts.uriResolver,o,r);if(l instanceof pm.SchemaEnv)return m(l);return f(l);function d(){if(s===u)return ps(t,i,s,s.$async);let g=e.scopeValue("root",{ref:u});return ps(t,(0,Ce._)`${g}.validate`,u,u.$async)}function m(g){let h=mm(t,g);ps(t,h,g,g.$async)}function f(g){let h=e.scopeValue("schema",a.code.source===!0?{ref:g,code:(0,Ce.stringify)(g)}:{ref:g}),y=e.name("valid"),v=t.subschema({schema:g,dataTypes:[],schemaPath:Ce.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function mm(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ce._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ht.getValidate=mm;function ps(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?br.default.this:Ce.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let g=o.let("valid");o.try(()=>{o.code((0,Ce._)`await ${(0,dm.callValidateCode)(t,e,u)}`),f(e),i||o.assign(g,!0)},h=>{o.if((0,Ce._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(g,!1)}),t.ok(g)}function d(){t.result((0,dm.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(g){let h=(0,Ce._)`${g}.errors`;o.assign(br.default.vErrors,(0,Ce._)`${br.default.vErrors} === null ? ${h} : ${br.default.vErrors}.concat(${h})`),o.assign(br.default.errors,(0,Ce._)`${br.default.vErrors}.length`)}function f(g){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ds.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Ce._)`${g}.evaluated.props`);s.props=ds.mergeEvaluated.props(o,v,s.props,Ce.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ds.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Ce._)`${g}.evaluated.items`);s.items=ds.mergeEvaluated.items(o,v,s.items,Ce.Name)}}}Ht.callRef=ps;Ht.default=jk});var hm=S(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var Nk=um(),qk=fm(),Dk=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Nk.default,qk.default];Ka.default=Dk});var gm=S(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var ms=D(),xt=ms.operators,fs={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},Lk={message:({keyword:t,schemaCode:e})=>(0,ms.str)`must be ${fs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ms._)`{comparison: ${fs[t].okStr}, limit: ${e}}`},Uk={keyword:Object.keys(fs),type:"number",schemaType:"number",$data:!0,error:Lk,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ms._)`${r} ${fs[e].fail} ${n} || isNaN(${r})`)}};Za.default=Uk});var ym=S(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var En=D(),Fk={message:({schemaCode:t})=>(0,En.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,En._)`{multipleOf: ${t}}`},Hk={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Fk,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,En._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,En._)`${i} !== parseInt(${i})`;t.fail$data((0,En._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ja.default=Hk});var wm=S(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});function _m(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}Ya.default=_m;_m.code='require("ajv/dist/runtime/ucs2length").default'});var vm=S(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var Wt=D(),Wk=W(),Vk=wm(),Bk={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Wt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Wt._)`{limit: ${t}}`},Gk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Bk,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Wt.operators.GT:Wt.operators.LT,i=o.opts.unicode===!1?(0,Wt._)`${r}.length`:(0,Wt._)`${(0,Wk.useFunc)(t.gen,Vk.default)}(${r})`;t.fail$data((0,Wt._)`${i} ${s} ${n}`)}};Xa.default=Gk});var bm=S(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Kk=qe(),Zk=W(),Sr=D(),Jk={message:({schemaCode:t})=>(0,Sr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Sr._)`{pattern: ${t}}`},Yk={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Jk,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,Sr._)`new RegExp`:(0,Zk.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Sr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Sr._)`!${l}`)}else{let c=(0,Kk.usePattern)(t,o);t.fail$data((0,Sr._)`!${c}.test(${r})`)}}};Qa.default=Yk});var Sm=S(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Pn=D(),Xk={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Pn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Pn._)`{limit: ${t}}`},Qk={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Xk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Pn.operators.GT:Pn.operators.LT;t.fail$data((0,Pn._)`Object.keys(${r}).length ${o} ${n}`)}};ec.default=Qk});var km=S(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Rn=qe(),Cn=D(),e0=W(),t0={message:({params:{missingProperty:t}})=>(0,Cn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Cn._)`{missingProperty: ${t}}`},r0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:t0,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():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:g}=t.it;for(let h of r)if(f?.[h]===void 0&&!g.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,e0.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Cn.nil,d);else for(let f of r)(0,Rn.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let g=e.let("valid",!0);t.block$data(g,()=>m(f,g)),t.ok(g)}else e.if((0,Rn.checkMissingProp)(t,r,f)),(0,Rn.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Rn.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function m(f,g){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(g,(0,Rn.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Cn.not)(g),()=>{t.error(),e.break()})},Cn.nil)}}};tc.default=r0});var Tm=S(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var Mn=D(),n0={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Mn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Mn._)`{limit: ${t}}`},o0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n0,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Mn.operators.GT:Mn.operators.LT;t.fail$data((0,Mn._)`${r}.length ${o} ${n}`)}};rc.default=o0});var hs=S(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var xm=$a();xm.code='require("ajv/dist/runtime/equal").default';nc.default=xm});var $m=S(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var oc=yn(),ge=D(),s0=W(),i0=hs(),a0={message:({params:{i:t,j:e}})=>(0,ge.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ge._)`{i: ${t}, j: ${e}}`},c0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a0,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,oc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ge._)`${i} === false`),t.ok(c);function l(){let g=e.let("i",(0,ge._)`${r}.length`),h=e.let("j");t.setParams({i:g,j:h}),e.assign(c,!0),e.if((0,ge._)`${g} > 1`,()=>(d()?m:f)(g,h))}function d(){return u.length>0&&!u.some(g=>g==="object"||g==="array")}function m(g,h){let y=e.name("item"),v=(0,oc.checkDataTypes)(u,y,a.opts.strictNumbers,oc.DataType.Wrong),$=e.const("indices",(0,ge._)`{}`);e.for((0,ge._)`;${g}--;`,()=>{e.let(y,(0,ge._)`${r}[${g}]`),e.if(v,(0,ge._)`continue`),u.length>1&&e.if((0,ge._)`typeof ${y} == "string"`,(0,ge._)`${y} += "_"`),e.if((0,ge._)`typeof ${$}[${y}] == "number"`,()=>{e.assign(h,(0,ge._)`${$}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,ge._)`${$}[${y}] = ${g}`)})}function f(g,h){let y=(0,s0.useFunc)(e,i0.default),v=e.name("outer");e.label(v).for((0,ge._)`;${g}--;`,()=>e.for((0,ge._)`${h} = ${g}; ${h}--;`,()=>e.if((0,ge._)`${y}(${r}[${g}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};sc.default=c0});var Em=S(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var ic=D(),l0=W(),u0=hs(),d0={message:"must be equal to constant",params:({schemaCode:t})=>(0,ic._)`{allowedValue: ${t}}`},p0={keyword:"const",$data:!0,error:d0,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,ic._)`!${(0,l0.useFunc)(e,u0.default)}(${r}, ${o})`):t.fail((0,ic._)`${s} !== ${r}`)}};ac.default=p0});var Pm=S(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var zn=D(),m0=W(),f0=hs(),h0={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,zn._)`{allowedValues: ${t}}`},g0={keyword:"enum",schemaType:"array",$data:!0,error:h0,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,m0.useFunc)(e,f0.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,zn.or)(...o.map((g,h)=>m(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,zn._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function m(f,g){let h=o[g];return typeof h=="object"&&h!==null?(0,zn._)`${u()}(${r}, ${f}[${g}])`:(0,zn._)`${r} === ${h}`}}};cc.default=g0});var Rm=S(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var y0=gm(),_0=ym(),w0=vm(),v0=bm(),b0=Sm(),S0=km(),k0=Tm(),T0=$m(),x0=Em(),$0=Pm(),E0=[y0.default,_0.default,w0.default,v0.default,b0.default,S0.default,k0.default,T0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},x0.default,$0.default];lc.default=E0});var dc=S(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.validateAdditionalItems=void 0;var Vt=D(),uc=W(),P0={message:({params:{len:t}})=>(0,Vt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vt._)`{limit: ${t}}`},R0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:P0,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,uc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Cm(t,n)}};function Cm(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Vt._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Vt._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,uc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Vt._)`${a} <= ${e.length}`);r.if((0,Vt.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:uc.Type.Num},u),i.allErrors||r.if((0,Vt.not)(u),()=>r.break())})}}An.validateAdditionalItems=Cm;An.default=R0});var pc=S(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.validateTuple=void 0;var Mm=D(),gs=W(),C0=qe(),M0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return zm(t,"additionalItems",e);r.items=!0,!(0,gs.alwaysValidSchema)(r,e)&&t.ok((0,C0.validateArray)(t))}};function zm(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=gs.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Mm._)`${s}.length`);r.forEach((d,m)=>{(0,gs.alwaysValidSchema)(a,d)||(n.if((0,Mm._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:f}=a,g=r.length,h=g===d.minItems&&(g===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let y=`"${i}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,gs.checkStrictMode)(a,y,m.strictTuples)}}}In.validateTuple=zm;In.default=M0});var Am=S(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var z0=pc(),A0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,z0.validateTuple)(t,"items")};mc.default=A0});var Om=S(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Im=D(),I0=W(),O0=qe(),j0=dc(),N0={message:({params:{len:t}})=>(0,Im.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Im._)`{limit: ${t}}`},q0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:N0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,I0.alwaysValidSchema)(n,e)&&(o?(0,j0.validateAdditionalItems)(t,o):t.ok((0,O0.validateArray)(t)))}};fc.default=q0});var jm=S(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var Le=D(),ys=W(),D0={message:({params:{min:t,max:e}})=>e===void 0?(0,Le.str)`must contain at least ${t} valid item(s)`:(0,Le.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Le._)`{minContains: ${t}}`:(0,Le._)`{minContains: ${t}, maxContains: ${e}}`},L0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:D0,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 l=e.const("len",(0,Le._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ys.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ys.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ys.alwaysValidSchema)(s,r)){let h=(0,Le._)`${l} >= ${i}`;a!==void 0&&(h=(0,Le._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Le._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>g(y)))}function f(h,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:ys.Type.Num,compositeRule:!0},h),y()})}function g(h){e.code((0,Le._)`${h}++`),a===void 0?e.if((0,Le._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Le._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Le._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};hc.default=L0});var Dm=S(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateSchemaDeps=Je.validatePropertyDeps=Je.error=void 0;var gc=D(),U0=W(),On=qe();Je.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,gc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,gc._)`{property: ${t},
8
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function yb({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function va(t,e,r,n=hr.Correct){let o=n===hr.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===hr.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}ve.checkDataType=va;function ba(t,e,r,n){if(t.length===1)return va(t[0],e,r,n);let o,s=(0,np.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,va(i,e,r,n));return o}ve.checkDataTypes=ba;var _b={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Sa(t){let e=wb(t);(0,pb.reportError)(e,_b)}ve.reportTypeError=Sa;function wb(t){let{gen:e,data:r,schema:n}=t,o=(0,np.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var ap=k(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.assignDefaults=void 0;var gr=D(),vb=V();function bb(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)ip(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>ip(t,s,o.default))}Qo.assignDefaults=bb;function ip(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,gr._)`${s}${(0,gr.getProperty)(e)}`;if(o){(0,vb.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,gr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,gr._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,gr._)`${a} = ${(0,gr.stringify)(r)}`)}});var Ne=k(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;var X=D(),ka=V(),bt=nt(),Sb=V();function kb(t,e){let{gen:r,data:n,it:o}=t;r.if(xa(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,X._)`${e}`},!0),t.error()})}K.checkReportMissingProp=kb;function Tb({gen:t,data:e,it:{opts:r}},n,o){return(0,X.or)(...n.map(s=>(0,X.and)(xa(t,e,s,r.ownProperties),(0,X._)`${o} = ${s}`)))}K.checkMissingProp=Tb;function xb(t,e){t.setParams({missingProperty:e},!0),t.error()}K.reportMissingProp=xb;function cp(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,X._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=cp;function Ta(t,e,r){return(0,X._)`${cp(t)}.call(${e}, ${r})`}K.isOwnProperty=Ta;function $b(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} !== undefined`;return n?(0,X._)`${o} && ${Ta(t,e,r)}`:o}K.propertyInData=$b;function xa(t,e,r,n){let o=(0,X._)`${e}${(0,X.getProperty)(r)} === undefined`;return n?(0,X.or)(o,(0,X.not)(Ta(t,e,r))):o}K.noPropertyInData=xa;function lp(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}K.allSchemaProperties=lp;function Eb(t,e){return lp(e).filter(r=>!(0,ka.alwaysValidSchema)(t,e[r]))}K.schemaProperties=Eb;function Pb({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,X._)`${t}, ${e}, ${n}${o}`:e,d=[[bt.default.instancePath,(0,X.strConcat)(bt.default.instancePath,s)],[bt.default.parentData,i.parentData],[bt.default.parentDataProperty,i.parentDataProperty],[bt.default.rootData,bt.default.rootData]];i.opts.dynamicRef&&d.push([bt.default.dynamicAnchors,bt.default.dynamicAnchors]);let m=(0,X._)`${l}, ${r.object(...d)}`;return c!==X.nil?(0,X._)`${a}.call(${c}, ${m})`:(0,X._)`${a}(${m})`}K.callValidateCode=Pb;var Rb=(0,X._)`new RegExp`;function Cb({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,X._)`${o.code==="new RegExp"?Rb:(0,Sb.useFunc)(t,o)}(${r}, ${n})`})}K.usePattern=Cb;function Mb(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,X._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ka.Type.Num},s),e.if((0,X.not)(s),a)})}}K.validateArray=Mb;function zb(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,ka.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,X._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,X.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}K.validateUnion=zb});var pp=k(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.validateKeywordUsage=Ke.validSchemaType=Ke.funcKeywordCode=Ke.macroKeywordCode=void 0;var Se=D(),Lt=nt(),Ab=Ne(),Ib=yn();function Ob(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=dp(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Se.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ke.macroKeywordCode=Ob;function jb(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;qb(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=dp(n,o,u),d=n.let("valid");t.block$data(d,m),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function m(){if(e.errors===!1)h(),e.modifying&&up(t),y(()=>t.error());else{let v=e.async?f():g();e.modifying&&up(t),y(()=>Nb(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Se._)`await `),S=>n.assign(d,!1).if((0,Se._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Se._)`${S}.errors`),()=>n.throw(S))),v}function g(){let v=(0,Se._)`${l}.errors`;return n.assign(v,null),h(Se.nil),v}function h(v=e.async?(0,Se._)`await `:Se.nil){let S=c.opts.passContext?Lt.default.this:Lt.default.self,T=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Se._)`${v}${(0,Ab.callValidateCode)(t,l,S,T)}`,e.modifying)}function y(v){var S;n.if((0,Se.not)((S=e.valid)!==null&&S!==void 0?S:d),v)}}Ke.funcKeywordCode=jb;function up(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Se._)`${n.parentData}[${n.parentDataProperty}]`))}function Nb(t,e){let{gen:r}=t;r.if((0,Se._)`Array.isArray(${e})`,()=>{r.assign(Lt.default.vErrors,(0,Se._)`${Lt.default.vErrors} === null ? ${e} : ${Lt.default.vErrors}.concat(${e})`).assign(Lt.default.errors,(0,Se._)`${Lt.default.vErrors}.length`),(0,Ib.extendErrors)(t)},()=>t.error())}function qb({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function dp(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,Se.stringify)(r)})}function Db(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")}Ke.validSchemaType=Db;function Lb({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)}}Ke.validateKeywordUsage=Lb});var fp=k(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.extendSubschemaMode=St.extendSubschemaData=St.getSubschema=void 0;var Ze=D(),mp=V();function Ub(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,Ze._)`${t.schemaPath}${(0,Ze.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ze._)`${t.schemaPath}${(0,Ze.getProperty)(e)}${(0,Ze.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,mp.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')}St.getSubschema=Ub;function Fb(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:l,opts:d}=e,m=a.let("data",(0,Ze._)`${e.data}${(0,Ze.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Ze.str)`${u}${(0,mp.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Ze._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ze.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]}}St.extendSubschemaData=Fb;function Hb(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}St.extendSubschemaMode=Hb});var $a=k((xO,hp)=>{"use strict";hp.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 yp=k(($O,gp)=>{"use strict";var kt=gp.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(){};es(e,n,o,t,"",t)};kt.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};kt.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};kt.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};kt.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 es(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 l in n){var d=n[l];if(Array.isArray(d)){if(l in kt.arrayKeywords)for(var m=0;m<d.length;m++)es(t,e,r,d[m],o+"/"+l+"/"+m,s,o,l,n,m)}else if(l in kt.propsKeywords){if(d&&typeof d=="object")for(var f in d)es(t,e,r,d[f],o+"/"+l+"/"+Vb(f),s,o,l,n,f)}else(l in kt.keywords||t.allKeys&&!(l in kt.skipKeywords))&&es(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function Vb(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var wn=k(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.getSchemaRefs=Re.resolveUrl=Re.normalizeId=Re._getFullPath=Re.getFullPath=Re.inlineRef=void 0;var Wb=V(),Bb=$a(),Gb=yp(),Kb=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Zb(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ea(t):e?_p(t)<=e:!1}Re.inlineRef=Zb;var Jb=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ea(t){for(let e in t){if(Jb.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ea)||typeof r=="object"&&Ea(r))return!0}return!1}function _p(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Kb.has(r)&&(typeof t[r]=="object"&&(0,Wb.eachItem)(t[r],n=>e+=_p(n)),e===1/0))return 1/0}return e}function wp(t,e="",r){r!==!1&&(e=yr(e));let n=t.parse(e);return vp(t,n)}Re.getFullPath=wp;function vp(t,e){return t.serialize(e).split("#")[0]+"#"}Re._getFullPath=vp;var Yb=/#\/?$/;function yr(t){return t?t.replace(Yb,""):""}Re.normalizeId=yr;function Xb(t,e,r){return r=yr(r),t.resolve(e,r)}Re.resolveUrl=Xb;var Qb=/^[a-z_][-a-z0-9._]*$/i;function eS(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=yr(t[r]||e),s={"":o},i=wp(n,o,!1),a={},c=new Set;return Gb(t,{allKeys:!0},(d,m,f,g)=>{if(g===void 0)return;let h=i+m,y=s[g];typeof d[r]=="string"&&(y=v.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[m]=y;function v(T){let z=this.opts.uriResolver.resolve;if(T=yr(y?z(y,T):T),c.has(T))throw l(T);c.add(T);let w=this.refs[T];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(d,w.schema,T):T!==yr(h)&&(T[0]==="#"?(u(d,a[T],T),a[T]=d):this.refs[T]=h),T}function S(T){if(typeof T=="string"){if(!Qb.test(T))throw new Error(`invalid anchor "${T}"`);v.call(this,`#${T}`)}}}),a;function u(d,m,f){if(m!==void 0&&!Bb(d,m))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Re.getSchemaRefs=eS});var Sn=k(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getData=Tt.KeywordCxt=Tt.validateFunctionCode=void 0;var xp=ep(),bp=_n(),Ra=wa(),ts=_n(),tS=ap(),bn=pp(),Pa=fp(),R=D(),O=nt(),rS=wn(),ot=V(),vn=yn();function nS(t){if(Pp(t)&&(Rp(t),Ep(t))){iS(t);return}$p(t,()=>(0,xp.topBoolOrEmptySchema)(t))}Tt.validateFunctionCode=nS;function $p({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,R._)`${O.default.data}, ${O.default.valCxt}`,n.$async,()=>{t.code((0,R._)`"use strict"; ${Sp(r,o)}`),sS(t,o),t.code(s)}):t.func(e,(0,R._)`${O.default.data}, ${oS(o)}`,n.$async,()=>t.code(Sp(r,o)).code(s))}function oS(t){return(0,R._)`{${O.default.instancePath}="", ${O.default.parentData}, ${O.default.parentDataProperty}, ${O.default.rootData}=${O.default.data}${t.dynamicRef?(0,R._)`, ${O.default.dynamicAnchors}={}`:R.nil}}={}`}function sS(t,e){t.if(O.default.valCxt,()=>{t.var(O.default.instancePath,(0,R._)`${O.default.valCxt}.${O.default.instancePath}`),t.var(O.default.parentData,(0,R._)`${O.default.valCxt}.${O.default.parentData}`),t.var(O.default.parentDataProperty,(0,R._)`${O.default.valCxt}.${O.default.parentDataProperty}`),t.var(O.default.rootData,(0,R._)`${O.default.valCxt}.${O.default.rootData}`),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,R._)`${O.default.valCxt}.${O.default.dynamicAnchors}`)},()=>{t.var(O.default.instancePath,(0,R._)`""`),t.var(O.default.parentData,(0,R._)`undefined`),t.var(O.default.parentDataProperty,(0,R._)`undefined`),t.var(O.default.rootData,O.default.data),e.dynamicRef&&t.var(O.default.dynamicAnchors,(0,R._)`{}`)})}function iS(t){let{schema:e,opts:r,gen:n}=t;$p(t,()=>{r.$comment&&e.$comment&&Mp(t),dS(t),n.let(O.default.vErrors,null),n.let(O.default.errors,0),r.unevaluated&&aS(t),Cp(t),fS(t)})}function aS(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,R._)`${r}.evaluated`),e.if((0,R._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,R._)`${t.evaluated}.props`,(0,R._)`undefined`)),e.if((0,R._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,R._)`${t.evaluated}.items`,(0,R._)`undefined`))}function Sp(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,R._)`/*# sourceURL=${r} */`:R.nil}function cS(t,e){if(Pp(t)&&(Rp(t),Ep(t))){lS(t,e);return}(0,xp.boolOrEmptySchema)(t,e)}function Ep({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 Pp(t){return typeof t.schema!="boolean"}function lS(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Mp(t),pS(t),mS(t);let s=n.const("_errs",O.default.errors);Cp(t,s),n.var(e,(0,R._)`${s} === ${O.default.errors}`)}function Rp(t){(0,ot.checkUnknownRules)(t),uS(t)}function Cp(t,e){if(t.opts.jtd)return kp(t,[],!1,e);let r=(0,bp.getSchemaTypes)(t.schema),n=(0,bp.coerceAndCheckDataType)(t,r);kp(t,r,!n,e)}function uS(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ot.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function dS(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ot.checkStrictMode)(t,"default is ignored in the schema root")}function pS(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,rS.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function mS(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Mp({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,R._)`${O.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,R.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,R._)`${O.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function fS(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,R._)`${O.default.errors} === 0`,()=>e.return(O.default.data),()=>e.throw((0,R._)`new ${o}(${O.default.vErrors})`)):(e.assign((0,R._)`${n}.errors`,O.default.vErrors),s.unevaluated&&hS(t),e.return((0,R._)`${O.default.errors} === 0`))}function hS({gen:t,evaluated:e,props:r,items:n}){r instanceof R.Name&&t.assign((0,R._)`${e}.props`,r),n instanceof R.Name&&t.assign((0,R._)`${e}.items`,n)}function kp(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ot.schemaHasRulesButRef)(s,l))){o.block(()=>Ap(t,"$ref",l.all.$ref.definition));return}c.jtd||gS(t,e),o.block(()=>{for(let m of l.rules)d(m);d(l.post)});function d(m){(0,Ra.shouldUseGroup)(s,m)&&(m.type?(o.if((0,ts.checkDataType)(m.type,i,c.strictNumbers)),Tp(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,ts.reportTypeError)(t)),o.endIf()):Tp(t,m),a||o.if((0,R._)`${O.default.errors} === ${n||0}`))}}function Tp(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,tS.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Ra.shouldUseRule)(n,s)&&Ap(t,s.keyword,s.definition,e.type)})}function gS(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(yS(t,e),t.opts.allowUnionTypes||_S(t,e),wS(t,t.dataTypes))}function yS(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{zp(t.dataTypes,r)||Ca(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),bS(t,e)}}function _S(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ca(t,"use allowUnionTypes to allow union type keyword")}function wS(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Ra.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>vS(e,i))&&Ca(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function vS(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function zp(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function bS(t,e){let r=[];for(let n of t.dataTypes)zp(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ca(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ot.checkStrictMode)(t,e,t.opts.strictTypes)}var rs=class{constructor(e,r,n){if((0,bn.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,ot.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",Ip(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,bn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",O.default.errors))}result(e,r,n){this.failResult((0,R.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,R.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,R._)`${r} !== undefined && (${(0,R.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?vn.reportExtraError:vn.reportError)(this,this.def.error,r)}$dataError(){(0,vn.reportError)(this,this.def.$dataError||vn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,vn.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=R.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=R.nil,r=R.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,R.or)((0,R._)`${o} === undefined`,r)),e!==R.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==R.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(n.length){if(!(r instanceof R.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,R._)`${(0,ts.checkDataTypes)(c,r,s.opts.strictNumbers,ts.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${r})`}return R.nil}}subschema(e,r){let n=(0,Pa.getSubschema)(this.it,e);(0,Pa.extendSubschemaData)(n,this.it,e),(0,Pa.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return cS(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ot.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ot.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,R.Name)),!0}};Tt.KeywordCxt=rs;function Ap(t,e,r,n){let o=new rs(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,bn.funcKeywordCode)(o,r):"macro"in r?(0,bn.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,bn.funcKeywordCode)(o,r)}var SS=/^\/(?:[^~]|~0|~1)*$/,kS=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ip(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return O.default.rootData;if(t[0]==="/"){if(!SS.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=O.default.rootData}else{let u=kS.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,ot.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Tt.getData=Ip});var ns=k(za=>{"use strict";Object.defineProperty(za,"__esModule",{value:!0});var Ma=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};za.default=Ma});var kn=k(Oa=>{"use strict";Object.defineProperty(Oa,"__esModule",{value:!0});var Aa=wn(),Ia=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Aa.resolveUrl)(e,r,n),this.missingSchema=(0,Aa.normalizeId)((0,Aa.getFullPath)(e,this.missingRef))}};Oa.default=Ia});var ss=k(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.resolveSchema=qe.getCompilingSchema=qe.resolveRef=qe.compileSchema=qe.SchemaEnv=void 0;var Fe=D(),TS=ns(),Ut=nt(),He=wn(),Op=V(),xS=Sn(),_r=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,He.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};qe.SchemaEnv=_r;function Na(t){let e=jp.call(this,t);if(e)return e;let r=(0,He.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Fe.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:TS.default,code:(0,Fe._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Ut.default.data,parentData:Ut.default.parentData,parentDataProperty:Ut.default.parentDataProperty,dataNames:[Ut.default.data],dataPathArr:[Fe.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Fe.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Fe.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Fe._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,xS.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Ut.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Ut.default.self}`,`${Ut.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:g,items:h}=u;f.evaluated={props:g instanceof Fe.Name?void 0:g,items:h instanceof Fe.Name?void 0:h,dynamicProps:g instanceof Fe.Name,dynamicItems:h instanceof Fe.Name},f.source&&(f.source.evaluated=(0,Fe.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}qe.compileSchema=Na;function $S(t,e,r){var n;r=(0,He.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=RS.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 _r({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=ES.call(this,s)}qe.resolveRef=$S;function ES(t){return(0,He.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Na.call(this,t)}function jp(t){for(let e of this._compilations)if(PS(e,t))return e}qe.getCompilingSchema=jp;function PS(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function RS(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||os.call(this,t,e)}function os(t,e){let r=this.opts.uriResolver.parse(e),n=(0,He._getFullPath)(this.opts.uriResolver,r),o=(0,He.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return ja.call(this,r,t);let s=(0,He.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=os.call(this,t,i);return typeof a?.schema!="object"?void 0:ja.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Na.call(this,i),s===(0,He.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,He.resolveUrl)(this.opts.uriResolver,o,u)),new _r({schema:a,schemaId:c,root:t,baseId:o})}return ja.call(this,r,i)}}qe.resolveSchema=os;var CS=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ja(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,Op.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!CS.has(a)&&u&&(e=(0,He.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Op.schemaHasRulesButRef)(r,this.RULES)){let a=(0,He.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=os.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new _r({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Np=k((zO,MS)=>{MS.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 La=k((AO,Hp)=>{"use strict";var zS=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dp=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),qa=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Lp=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),AS=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Da(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 IS=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function qp(t){return t.length=0,!0}function OS(t,e,r){if(t.length){let n=Da(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function jS(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=OS;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=qp}else{o.push(u);continue}}return o.length&&(a===qp?r.zone=o.join(""):i?n.push(o.join("")):n.push(Da(o))),r.address=n.join(""),r}function Up(t){if(NS(t,":")<2)return{host:t,isIPV6:!1};let e=jS(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 NS(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function qS(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 DS={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},LS=/[@/?#:]/g,US=/[@/?#]/g;function Fp(t,e){let r=e?US:LS;return r.lastIndex=0,t.replace(r,n=>DS[n])}function FS(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(qa(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Lp(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function HS(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(qa(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Lp(s)?e+=s:e+="%"+o,r+=2;continue}}AS(t[r])?e+=t[r]:e+=escape(t[r])}return e}function VS(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(qa(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function WS(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Dp(r)){let n=Up(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Fp(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}Hp.exports={nonSimpleDomain:IS,recomposeAuthority:WS,reescapeHostDelimiters:Fp,normalizePercentEncoding:FS,normalizePathEncoding:HS,escapePreservingEscapes:VS,removeDotSegments:qS,isIPv4:Dp,isUUID:zS,normalizeIPv6:Up,stringArrayToHexStripped:Da}});var Kp=k((IO,Gp)=>{"use strict";var{isUUID:BS}=La(),GS=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,KS=["http","https","ws","wss","urn","urn:uuid"];function ZS(t){return KS.indexOf(t)!==-1}function Ua(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 Vp(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Wp(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 JS(t){return t.secure=Ua(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function YS(t){if((t.port===(Ua(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 XS(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(GS);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=Fa(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function QS(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=Fa(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 e0(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!BS(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function t0(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Bp={scheme:"http",domainHost:!0,parse:Vp,serialize:Wp},r0={scheme:"https",domainHost:Bp.domainHost,parse:Vp,serialize:Wp},is={scheme:"ws",domainHost:!0,parse:JS,serialize:YS},n0={scheme:"wss",domainHost:is.domainHost,parse:is.parse,serialize:is.serialize},o0={scheme:"urn",parse:XS,serialize:QS,skipNormalize:!0},s0={scheme:"urn:uuid",parse:e0,serialize:t0,skipNormalize:!0},as={http:Bp,https:r0,ws:is,wss:n0,urn:o0,"urn:uuid":s0};Object.setPrototypeOf(as,null);function Fa(t){return t&&(as[t]||as[t.toLowerCase()])||void 0}Gp.exports={wsIsSecure:Ua,SCHEMES:as,isValidSchemeName:ZS,getSchemeHandler:Fa}});var em=k((OO,cs)=>{"use strict";var{normalizeIPv6:i0,removeDotSegments:Tn,recomposeAuthority:a0,normalizePercentEncoding:c0,normalizePathEncoding:l0,escapePreservingEscapes:u0,reescapeHostDelimiters:d0,isIPv4:p0,nonSimpleDomain:m0}=La(),{SCHEMES:f0,getSchemeHandler:Jp}=Kp();function h0(t,e){return typeof t=="string"?t=b0(t,e):typeof t=="object"&&(t=wr(Ft(t,e),e)),t}function g0(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Yp(wr(t,n),wr(e,n),n,!0);return n.skipEscape=!0,Ft(o,n)}function Yp(t,e,r,n){let o={};return n||(t=wr(Ft(t,r),r),e=wr(Ft(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=Tn(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=Tn(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Tn(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=Tn(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 y0(t,e,r){let n=Zp(t,r),o=Zp(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Ft(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=Jp(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=c0(r.path):(r.path=u0(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=a0(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=Tn(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 _0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,w0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function v0(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 Xp(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(w0);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(_0);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=v0(n,a);if(c!==void 0&&(n.error=n.error||c,o=!0),n.host)if(p0(n.host)===!1){let d=i0(n.host);n.host=d.host.toLowerCase(),s=d.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 u=Jp(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&m0(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((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=d0(unescape(n.host),s))),n.path&&(n.path=l0(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function wr(t,e){return Xp(t,e).parsed}function b0(t,e){return Qp(t,e).normalized}function Qp(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Xp(t,e);return{normalized:n?t:Ft(r,e),malformedAuthorityOrPort:n}}function Zp(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Qp(t,e);return n?void 0:r}if(typeof t=="object")return Ft(t,e)}var Ha={SCHEMES:f0,normalize:h0,resolve:g0,resolveComponent:Yp,equal:y0,serialize:Ft,parse:wr};cs.exports=Ha;cs.exports.default=Ha;cs.exports.fastUri=Ha});var rm=k(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var tm=em();tm.code='require("ajv/dist/runtime/uri").default';Va.default=tm});var um=k(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.CodeGen=he.Name=he.nil=he.stringify=he.str=he._=he.KeywordCxt=void 0;var S0=Sn();Object.defineProperty(he,"KeywordCxt",{enumerable:!0,get:function(){return S0.KeywordCxt}});var vr=D();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return vr.Name}});Object.defineProperty(he,"CodeGen",{enumerable:!0,get:function(){return vr.CodeGen}});var k0=ns(),am=kn(),T0=_a(),xn=ss(),x0=D(),$n=wn(),ls=_n(),Ba=V(),nm=Np(),$0=rm(),cm=(t,e)=>new RegExp(t,e);cm.code="new RegExp";var E0=["removeAdditional","useDefaults","coerceTypes"],P0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),R0={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."},C0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},om=200;function M0(t){var e,r,n,o,s,i,a,c,u,l,d,m,f,g,h,y,v,S,T,z,w,b,j,ne,oe;let Te=t.strict,Hr=(e=t.code)===null||e===void 0?void 0:e.optimize,oo=Hr===!0||Hr===void 0?1:Hr||0,so=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:cm,pt=(o=t.uriResolver)!==null&&o!==void 0?o:$0.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Te)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Te)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Te)!==null&&l!==void 0?l:"log",strictTuples:(m=(d=t.strictTuples)!==null&&d!==void 0?d:Te)!==null&&m!==void 0?m:"log",strictRequired:(g=(f=t.strictRequired)!==null&&f!==void 0?f:Te)!==null&&g!==void 0?g:!1,code:t.code?{...t.code,optimize:oo,regExp:so}:{optimize:oo,regExp:so},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:om,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:om,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(T=t.inlineRefs)!==null&&T!==void 0?T:!0,schemaId:(z=t.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(b=t.validateSchema)!==null&&b!==void 0?b:!0,validateFormats:(j=t.validateFormats)!==null&&j!==void 0?j:!0,unicodeRegExp:(ne=t.unicodeRegExp)!==null&&ne!==void 0?ne:!0,int32range:(oe=t.int32range)!==null&&oe!==void 0?oe:!0,uriResolver:pt}}var En=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,...M0(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new x0.ValueScope({scope:{},prefixes:P0,es5:r,lines:n}),this.logger=N0(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,T0.getRules)(),sm.call(this,R0,e,"NOT SUPPORTED"),sm.call(this,C0,e,"DEPRECATED","warn"),this._metaOpts=O0.call(this),e.formats&&A0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&I0.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),z0.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=nm;n==="id"&&(o={...nm},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(l,d){await s.call(this,l.$schema);let m=this._addSchema(l,d);return m.validate||i.call(this,m)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof am.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}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,$n.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=im.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xn.SchemaEnv({schema:{},schemaId:n});if(r=xn.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=im.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,$n.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(D0.call(this,n,r),!r)return(0,Ba.eachItem)(n,s=>Wa.call(this,s)),this;U0.call(this,r);let o={...r,type:(0,ls.getJSONTypes)(r.type),schemaType:(0,ls.getJSONTypes)(r.schemaType)};return(0,Ba.eachItem)(n,o.type.length===0?s=>Wa.call(this,s,o):s=>o.type.forEach(i=>Wa.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,l=i[a];u&&l&&(i[a]=lm(l))}}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,$n.normalizeId)(i||n);let u=$n.getSchemaRefs.call(this,e,n);return c=new xn.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):xn.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{xn.compileSchema.call(this,e)}finally{this.opts=r}}};En.ValidationError=k0.default;En.MissingRefError=am.default;he.default=En;function sm(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 im(t){return t=(0,$n.normalizeId)(t),this.schemas[t]||this.refs[t]}function z0(){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 A0(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function I0(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 O0(){let t={...this.opts};for(let e of E0)delete t[e];return t}var j0={log(){},warn(){},error(){}};function N0(t){if(t===!1)return j0;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 q0=/^[a-z_$][a-z0-9_$:-]*$/i;function D0(t,e){let{RULES:r}=this;if((0,Ba.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!q0.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 Wa(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,ls.getJSONTypes)(e.type),schemaType:(0,ls.getJSONTypes)(e.schemaType)}};e.before?L0.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 L0(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 U0(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=lm(e)),t.validateSchema=this.compile(e,!0))}var F0={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function lm(t){return{anyOf:[t,F0]}}});var dm=k(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});var H0={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ga.default=H0});var hm=k(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.callRef=Ht.getValidate=void 0;var V0=kn(),pm=Ne(),Ce=D(),br=nt(),mm=ss(),us=V(),W0={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 d();let l=mm.resolveRef.call(c,u,o,r);if(l===void 0)throw new V0.default(n.opts.uriResolver,o,r);if(l instanceof mm.SchemaEnv)return m(l);return f(l);function d(){if(s===u)return ds(t,i,s,s.$async);let g=e.scopeValue("root",{ref:u});return ds(t,(0,Ce._)`${g}.validate`,u,u.$async)}function m(g){let h=fm(t,g);ds(t,h,g,g.$async)}function f(g){let h=e.scopeValue("schema",a.code.source===!0?{ref:g,code:(0,Ce.stringify)(g)}:{ref:g}),y=e.name("valid"),v=t.subschema({schema:g,dataTypes:[],schemaPath:Ce.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function fm(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ce._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ht.getValidate=fm;function ds(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?br.default.this:Ce.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let g=o.let("valid");o.try(()=>{o.code((0,Ce._)`await ${(0,pm.callValidateCode)(t,e,u)}`),f(e),i||o.assign(g,!0)},h=>{o.if((0,Ce._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(g,!1)}),t.ok(g)}function d(){t.result((0,pm.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(g){let h=(0,Ce._)`${g}.errors`;o.assign(br.default.vErrors,(0,Ce._)`${br.default.vErrors} === null ? ${h} : ${br.default.vErrors}.concat(${h})`),o.assign(br.default.errors,(0,Ce._)`${br.default.vErrors}.length`)}function f(g){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=us.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Ce._)`${g}.evaluated.props`);s.props=us.mergeEvaluated.props(o,v,s.props,Ce.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=us.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Ce._)`${g}.evaluated.items`);s.items=us.mergeEvaluated.items(o,v,s.items,Ce.Name)}}}Ht.callRef=ds;Ht.default=W0});var gm=k(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});var B0=dm(),G0=hm(),K0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",B0.default,G0.default];Ka.default=K0});var ym=k(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});var ps=D(),xt=ps.operators,ms={maximum:{okStr:"<=",ok:xt.LTE,fail:xt.GT},minimum:{okStr:">=",ok:xt.GTE,fail:xt.LT},exclusiveMaximum:{okStr:"<",ok:xt.LT,fail:xt.GTE},exclusiveMinimum:{okStr:">",ok:xt.GT,fail:xt.LTE}},Z0={message:({keyword:t,schemaCode:e})=>(0,ps.str)`must be ${ms[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ps._)`{comparison: ${ms[t].okStr}, limit: ${e}}`},J0={keyword:Object.keys(ms),type:"number",schemaType:"number",$data:!0,error:Z0,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ps._)`${r} ${ms[e].fail} ${n} || isNaN(${r})`)}};Za.default=J0});var _m=k(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});var Pn=D(),Y0={message:({schemaCode:t})=>(0,Pn.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Pn._)`{multipleOf: ${t}}`},X0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Y0,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Pn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Pn._)`${i} !== parseInt(${i})`;t.fail$data((0,Pn._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Ja.default=X0});var vm=k(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});function wm(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}Ya.default=wm;wm.code='require("ajv/dist/runtime/ucs2length").default'});var bm=k(Xa=>{"use strict";Object.defineProperty(Xa,"__esModule",{value:!0});var Vt=D(),Q0=V(),ek=vm(),tk={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Vt.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Vt._)`{limit: ${t}}`},rk={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tk,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Vt.operators.GT:Vt.operators.LT,i=o.opts.unicode===!1?(0,Vt._)`${r}.length`:(0,Vt._)`${(0,Q0.useFunc)(t.gen,ek.default)}(${r})`;t.fail$data((0,Vt._)`${i} ${s} ${n}`)}};Xa.default=rk});var Sm=k(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var nk=Ne(),ok=V(),Sr=D(),sk={message:({schemaCode:t})=>(0,Sr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Sr._)`{pattern: ${t}}`},ik={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:sk,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,Sr._)`new RegExp`:(0,ok.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Sr._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Sr._)`!${l}`)}else{let c=(0,nk.usePattern)(t,o);t.fail$data((0,Sr._)`!${c}.test(${r})`)}}};Qa.default=ik});var km=k(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Rn=D(),ak={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Rn.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Rn._)`{limit: ${t}}`},ck={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ak,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Rn.operators.GT:Rn.operators.LT;t.fail$data((0,Rn._)`Object.keys(${r}).length ${o} ${n}`)}};ec.default=ck});var Tm=k(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});var Cn=Ne(),Mn=D(),lk=V(),uk={message:({params:{missingProperty:t}})=>(0,Mn.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Mn._)`{missingProperty: ${t}}`},dk={keyword:"required",type:"object",schemaType:"array",$data:!0,error:uk,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():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:g}=t.it;for(let h of r)if(f?.[h]===void 0&&!g.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,lk.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Mn.nil,d);else for(let f of r)(0,Cn.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let g=e.let("valid",!0);t.block$data(g,()=>m(f,g)),t.ok(g)}else e.if((0,Cn.checkMissingProp)(t,r,f)),(0,Cn.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Cn.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function m(f,g){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(g,(0,Cn.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Mn.not)(g),()=>{t.error(),e.break()})},Mn.nil)}}};tc.default=dk});var xm=k(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var zn=D(),pk={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,zn.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,zn._)`{limit: ${t}}`},mk={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pk,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?zn.operators.GT:zn.operators.LT;t.fail$data((0,zn._)`${r}.length ${o} ${n}`)}};rc.default=mk});var fs=k(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var $m=$a();$m.code='require("ajv/dist/runtime/equal").default';nc.default=$m});var Em=k(sc=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var oc=_n(),ge=D(),fk=V(),hk=fs(),gk={message:({params:{i:t,j:e}})=>(0,ge.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ge._)`{i: ${t}, j: ${e}}`},yk={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gk,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,oc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,ge._)`${i} === false`),t.ok(c);function l(){let g=e.let("i",(0,ge._)`${r}.length`),h=e.let("j");t.setParams({i:g,j:h}),e.assign(c,!0),e.if((0,ge._)`${g} > 1`,()=>(d()?m:f)(g,h))}function d(){return u.length>0&&!u.some(g=>g==="object"||g==="array")}function m(g,h){let y=e.name("item"),v=(0,oc.checkDataTypes)(u,y,a.opts.strictNumbers,oc.DataType.Wrong),S=e.const("indices",(0,ge._)`{}`);e.for((0,ge._)`;${g}--;`,()=>{e.let(y,(0,ge._)`${r}[${g}]`),e.if(v,(0,ge._)`continue`),u.length>1&&e.if((0,ge._)`typeof ${y} == "string"`,(0,ge._)`${y} += "_"`),e.if((0,ge._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(h,(0,ge._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,ge._)`${S}[${y}] = ${g}`)})}function f(g,h){let y=(0,fk.useFunc)(e,hk.default),v=e.name("outer");e.label(v).for((0,ge._)`;${g}--;`,()=>e.for((0,ge._)`${h} = ${g}; ${h}--;`,()=>e.if((0,ge._)`${y}(${r}[${g}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};sc.default=yk});var Pm=k(ac=>{"use strict";Object.defineProperty(ac,"__esModule",{value:!0});var ic=D(),_k=V(),wk=fs(),vk={message:"must be equal to constant",params:({schemaCode:t})=>(0,ic._)`{allowedValue: ${t}}`},bk={keyword:"const",$data:!0,error:vk,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,ic._)`!${(0,_k.useFunc)(e,wk.default)}(${r}, ${o})`):t.fail((0,ic._)`${s} !== ${r}`)}};ac.default=bk});var Rm=k(cc=>{"use strict";Object.defineProperty(cc,"__esModule",{value:!0});var An=D(),Sk=V(),kk=fs(),Tk={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,An._)`{allowedValues: ${t}}`},xk={keyword:"enum",schemaType:"array",$data:!0,error:Tk,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,Sk.useFunc)(e,kk.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,An.or)(...o.map((g,h)=>m(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,An._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function m(f,g){let h=o[g];return typeof h=="object"&&h!==null?(0,An._)`${u()}(${r}, ${f}[${g}])`:(0,An._)`${r} === ${h}`}}};cc.default=xk});var Cm=k(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});var $k=ym(),Ek=_m(),Pk=bm(),Rk=Sm(),Ck=km(),Mk=Tm(),zk=xm(),Ak=Em(),Ik=Pm(),Ok=Rm(),jk=[$k.default,Ek.default,Pk.default,Rk.default,Ck.default,Mk.default,zk.default,Ak.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Ik.default,Ok.default];lc.default=jk});var dc=k(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.validateAdditionalItems=void 0;var Wt=D(),uc=V(),Nk={message:({params:{len:t}})=>(0,Wt.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wt._)`{limit: ${t}}`},qk={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Nk,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,uc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Mm(t,n)}};function Mm(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Wt._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Wt._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,uc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Wt._)`${a} <= ${e.length}`);r.if((0,Wt.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:uc.Type.Num},u),i.allErrors||r.if((0,Wt.not)(u),()=>r.break())})}}In.validateAdditionalItems=Mm;In.default=qk});var pc=k(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.validateTuple=void 0;var zm=D(),hs=V(),Dk=Ne(),Lk={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Am(t,"additionalItems",e);r.items=!0,!(0,hs.alwaysValidSchema)(r,e)&&t.ok((0,Dk.validateArray)(t))}};function Am(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=hs.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,zm._)`${s}.length`);r.forEach((d,m)=>{(0,hs.alwaysValidSchema)(a,d)||(n.if((0,zm._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function l(d){let{opts:m,errSchemaPath:f}=a,g=r.length,h=g===d.minItems&&(g===d.maxItems||d[e]===!1);if(m.strictTuples&&!h){let y=`"${i}" is ${g}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,hs.checkStrictMode)(a,y,m.strictTuples)}}}On.validateTuple=Am;On.default=Lk});var Im=k(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var Uk=pc(),Fk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Uk.validateTuple)(t,"items")};mc.default=Fk});var jm=k(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var Om=D(),Hk=V(),Vk=Ne(),Wk=dc(),Bk={message:({params:{len:t}})=>(0,Om.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Om._)`{limit: ${t}}`},Gk={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Bk,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,Hk.alwaysValidSchema)(n,e)&&(o?(0,Wk.validateAdditionalItems)(t,o):t.ok((0,Vk.validateArray)(t)))}};fc.default=Gk});var Nm=k(hc=>{"use strict";Object.defineProperty(hc,"__esModule",{value:!0});var De=D(),gs=V(),Kk={message:({params:{min:t,max:e}})=>e===void 0?(0,De.str)`must contain at least ${t} valid item(s)`:(0,De.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,De._)`{minContains: ${t}}`:(0,De._)`{minContains: ${t}, maxContains: ${e}}`},Zk={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Kk,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 l=e.const("len",(0,De._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,gs.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,gs.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,gs.alwaysValidSchema)(s,r)){let h=(0,De._)`${l} >= ${i}`;a!==void 0&&(h=(0,De._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,De._)`${o}.length > 0`,m)):(e.let(d,!1),m()),t.result(d,()=>t.reset());function m(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>g(y)))}function f(h,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:gs.Type.Num,compositeRule:!0},h),y()})}function g(h){e.code((0,De._)`${h}++`),a===void 0?e.if((0,De._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,De._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,De._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};hc.default=Zk});var Lm=k(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.validateSchemaDeps=Je.validatePropertyDeps=Je.error=void 0;var gc=D(),Jk=V(),jn=Ne();Je.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,gc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,gc._)`{property: ${t},
9
9
  missingProperty: ${n},
10
10
  depsCount: ${e},
11
- deps: ${r}}`};var F0={keyword:"dependencies",type:"object",schemaType:"object",error:Je.error,code(t){let[e,r]=H0(t);Nm(t,e),qm(t,r)}};function H0({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 Nm(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,On.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,On.checkReportMissingProp)(t,u)}):(r.if((0,gc._)`${c} && (${(0,On.checkMissingProp)(t,a,s)})`),(0,On.reportMissingProp)(t,s),r.else())}}Je.validatePropertyDeps=Nm;function qm(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,U0.alwaysValidSchema)(s,e[a])||(r.if((0,On.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))}Je.validateSchemaDeps=qm;Je.default=F0});var Um=S(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Lm=D(),W0=W(),V0={message:"property name must be valid",params:({params:t})=>(0,Lm._)`{propertyName: ${t.propertyName}}`},B0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:V0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,W0.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,Lm.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};yc.default=B0});var wc=S(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var _s=qe(),Ve=D(),G0=nt(),ws=W(),K0={message:"must NOT have additional properties",params:({params:t})=>(0,Ve._)`{additionalProperty: ${t.additionalProperty}}`},Z0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:K0,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,ws.alwaysValidSchema)(i,r))return;let u=(0,_s.allSchemaProperties)(n.properties),l=(0,_s.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Ve._)`${s} === ${G0.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?g(y):e.if(m(y),()=>g(y))})}function m(y){let v;if(u.length>8){let $=(0,ws.schemaRefOrVal)(i,n.properties,"properties");v=(0,_s.isOwnProperty)(e,$,y)}else u.length?v=(0,Ve.or)(...u.map($=>(0,Ve._)`${y} === ${$}`)):v=Ve.nil;return l.length&&(v=(0,Ve.or)(v,...l.map($=>(0,Ve._)`${(0,_s.usePattern)(t,$)}.test(${y})`))),(0,Ve.not)(v)}function f(y){e.code((0,Ve._)`delete ${o}[${y}]`)}function g(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ws.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,Ve.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,Ve.not)(v),()=>e.break()))}}function h(y,v,$){let k={keyword:"additionalProperties",dataProp:y,dataPropType:ws.Type.Str};$===!1&&Object.assign(k,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(k,v)}}};_c.default=Z0});var Wm=S(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var J0=bn(),Fm=qe(),vc=W(),Hm=wc(),Y0={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&&Hm.default.code(new J0.KeywordCxt(s,Hm.default,"additionalProperties"));let i=(0,Fm.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(i),s.props));let a=i.filter(d=>!(0,vc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Fm.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};bc.default=Y0});var Km=S(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Vm=qe(),vs=D(),Bm=W(),Gm=W(),X0={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,Vm.allSchemaProperties)(r),c=a.filter(h=>(0,Bm.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof vs.Name)&&(s.props=(0,Gm.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let h of a)u&&f(h),s.allErrors?g(h):(e.var(l,!0),g(h),e.if(l))}function f(h){for(let y in u)new RegExp(h).test(y)&&(0,Bm.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function g(h){e.forIn("key",n,y=>{e.if((0,vs._)`${(0,Vm.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:Gm.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,vs._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,vs.not)(l),()=>e.break())})})}}};Sc.default=X0});var Zm=S(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var Q0=W(),eT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Q0.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"}};kc.default=eT});var Jm=S(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var tT=qe(),rT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tT.validateUnion,error:{message:"must match a schema in anyOf"}};Tc.default=rT});var Ym=S(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var bs=D(),nT=W(),oT={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,bs._)`{passingSchemas: ${t.passing}}`},sT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oT,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((l,d)=>{let m;(0,nT.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,bs._)`${c} && ${i}`).assign(i,!1).assign(a,(0,bs._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,bs.Name)})})}}};xc.default=sT});var Xm=S($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var iT=W(),aT={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,iT.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};$c.default=aT});var tf=S(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Ss=D(),ef=W(),cT={message:({params:t})=>(0,Ss.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ss._)`{failingKeyword: ${t.ifClause}}`},lT={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cT,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ef.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Qm(n,"then"),s=Qm(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ss.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,Ss._)`${l}`):t.setParams({ifClause:l})}}}};function Qm(t,e){let r=t.schema[e];return r!==void 0&&!(0,ef.alwaysValidSchema)(t,r)}Ec.default=lT});var rf=S(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var uT=W(),dT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,uT.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Pc.default=dT});var nf=S(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var pT=dc(),mT=Am(),fT=pc(),hT=Om(),gT=jm(),yT=Dm(),_T=Um(),wT=wc(),vT=Wm(),bT=Km(),ST=Zm(),kT=Jm(),TT=Ym(),xT=Xm(),$T=tf(),ET=rf();function PT(t=!1){let e=[ST.default,kT.default,TT.default,xT.default,$T.default,ET.default,_T.default,wT.default,yT.default,vT.default,bT.default];return t?e.push(mT.default,hT.default):e.push(pT.default,fT.default),e.push(gT.default),e}Rc.default=PT});var of=S(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var ie=D(),RT={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},CT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RT,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?m():f();function m(){let g=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${g}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ie._)`${h}.type || "string"`).assign(v,(0,ie._)`${h}.validate`),()=>r.assign(y,(0,ie._)`"string"`).assign(v,h)),t.fail$data((0,ie.or)($(),k()));function $(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${v}`}function k(){let z=l.$async?(0,ie._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ie._)`${v}(${n})`,w=(0,ie._)`(typeof ${v} == "function" ? ${z} : ${v}.test(${n}))`;return(0,ie._)`${v} && ${v} !== true && ${y} === ${e} && !${w}`}}function f(){let g=d.formats[s];if(!g){$();return}if(g===!0)return;let[h,y,v]=k(g);h===e&&t.pass(z());function $(){if(c.strictSchema===!1){d.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function k(w){let b=w instanceof RegExp?(0,ie.regexpCode)(w):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,j=r.scopeValue("formats",{key:s,ref:w,code:b});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,ie._)`${j}.validate`]:["string",w,j]}function z(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${v}(${n})`}return typeof y=="function"?(0,ie._)`${v}(${n})`:(0,ie._)`${v}.test(${n})`}}}};Cc.default=CT});var sf=S(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var MT=of(),zT=[MT.default];Mc.default=zT});var af=S(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.contentVocabulary=kr.metadataVocabulary=void 0;kr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var lf=S(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var AT=hm(),IT=Rm(),OT=nf(),jT=sf(),cf=af(),NT=[AT.default,IT.default,(0,OT.default)(),jT.default,cf.metadataVocabulary,cf.contentVocabulary];zc.default=NT});var df=S(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.DiscrError=void 0;var uf;(function(t){t.Tag="tag",t.Mapping="mapping"})(uf||(ks.DiscrError=uf={}))});var mf=S(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Tr=D(),Ac=df(),pf=is(),qT=Sn(),DT=W(),LT={message:({params:{discrError:t,tagName:e}})=>t===Ac.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Tr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},UT={keyword:"discriminator",type:"object",schemaType:"object",error:LT,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,Tr._)`${r}${(0,Tr.getProperty)(a)}`);e.if((0,Tr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Ac.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=m();e.if(!1);for(let g in f)e.elseIf((0,Tr._)`${u} === ${g}`),e.assign(c,d(f[g]));e.else(),t.error(!1,{discrError:Ac.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let g=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},g);return t.mergeEvaluated(h,Tr.Name),g}function m(){var f;let g={},h=v(o),y=!0;for(let z=0;z<i.length;z++){let w=i[z];if(w?.$ref&&!(0,DT.schemaHasRulesButRef)(w,s.self.RULES)){let j=w.$ref;if(w=pf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,j),w instanceof pf.SchemaEnv&&(w=w.schema),w===void 0)throw new qT.default(s.opts.uriResolver,s.baseId,j)}let b=(f=w?.properties)===null||f===void 0?void 0:f[a];if(typeof b!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(w)),$(b,z)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return g;function v({required:z}){return Array.isArray(z)&&z.includes(a)}function $(z,w){if(z.const)k(z.const,w);else if(z.enum)for(let b of z.enum)k(b,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function k(z,w){if(typeof z!="string"||z in g)throw new Error(`discriminator: "${a}" values must be unique strings`);g[z]=w}}}};Ic.default=UT});var ff=S((l1,FT)=>{FT.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 jc=S((Q,Oc)=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.MissingRefError=Q.ValidationError=Q.CodeGen=Q.Name=Q.nil=Q.stringify=Q.str=Q._=Q.KeywordCxt=Q.Ajv=void 0;var HT=lm(),WT=lf(),VT=mf(),hf=ff(),BT=["/properties"],Ts="http://json-schema.org/draft-07/schema",xr=class extends HT.default{_addVocabularies(){super._addVocabularies(),WT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(VT.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(hf,BT):hf;this.addMetaSchema(e,Ts,!1),this.refs["http://json-schema.org/schema"]=Ts}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ts)?Ts:void 0)}};Q.Ajv=xr;Oc.exports=Q=xr;Oc.exports.Ajv=xr;Object.defineProperty(Q,"__esModule",{value:!0});Q.default=xr;var GT=bn();Object.defineProperty(Q,"KeywordCxt",{enumerable:!0,get:function(){return GT.KeywordCxt}});var $r=D();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return $r._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return $r.str}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return $r.stringify}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return $r.nil}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return $r.Name}});Object.defineProperty(Q,"CodeGen",{enumerable:!0,get:function(){return $r.CodeGen}});var KT=os();Object.defineProperty(Q,"ValidationError",{enumerable:!0,get:function(){return KT.default}});var ZT=Sn();Object.defineProperty(Q,"MissingRefError",{enumerable:!0,get:function(){return ZT.default}})});var kf=S(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.formatNames=Xe.fastFormats=Xe.fullFormats=void 0;function Ye(t,e){return{validate:t,compare:e}}Xe.fullFormats={date:Ye(wf,Lc),time:Ye(qc(!0),Uc),"date-time":Ye(gf(!0),bf),"iso-time":Ye(qc(),vf),"iso-date-time":Ye(gf(),Sf),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:tx,"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:cx,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:rx,int32:{type:"number",validate:sx},int64:{type:"number",validate:ix},float:{type:"number",validate:_f},double:{type:"number",validate:_f},password:!0,binary:!0};Xe.fastFormats={...Xe.fullFormats,date:Ye(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Lc),time:Ye(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Uc),"date-time":Ye(/^\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,bf),"iso-time":Ye(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vf),"iso-date-time":Ye(/^\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,Sf),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};Xe.formatNames=Object.keys(Xe.fullFormats);function JT(t){return t%4===0&&(t%100!==0||t%400===0)}var YT=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,XT=[0,31,28,31,30,31,30,31,31,30,31,30,31];function wf(t){let e=YT.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&&JT(r)?29:XT[n])}function Lc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Nc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function qc(t){return function(r){let n=Nc.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),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function Uc(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 vf(t,e){if(!(t&&e))return;let r=Nc.exec(t),n=Nc.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 Dc=/t|\s/i;function gf(t){let e=qc(t);return function(n){let o=n.split(Dc);return o.length===2&&wf(o[0])&&e(o[1])}}function bf(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Sf(t,e){if(!(t&&e))return;let[r,n]=t.split(Dc),[o,s]=e.split(Dc),i=Lc(r,o);if(i!==void 0)return i||Uc(n,s)}var QT=/\/|:/,ex=/^(?:[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 tx(t){return QT.test(t)&&ex.test(t)}var yf=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function rx(t){return yf.lastIndex=0,yf.test(t)}var nx=-(2**31),ox=2**31-1;function sx(t){return Number.isInteger(t)&&t<=ox&&t>=nx}function ix(t){return Number.isInteger(t)}function _f(){return!0}var ax=/[^\\]\\Z/;function cx(t){if(ax.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Tf=S(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.formatLimitDefinition=void 0;var lx=jc(),Be=D(),$t=Be.operators,xs={formatMaximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},formatMinimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},formatExclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},formatExclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},ux={message:({keyword:t,schemaCode:e})=>(0,Be.str)`should be ${xs[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Be._)`{comparison: ${xs[t].okStr}, limit: ${e}}`};Er.formatLimitDefinition={keyword:Object.keys(xs),type:"string",schemaType:"string",$data:!0,error:ux,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 lx.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Be._)`${m}[${c.schemaCode}]`);t.fail$data((0,Be.or)((0,Be._)`typeof ${f} != "object"`,(0,Be._)`${f} instanceof RegExp`,(0,Be._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let g=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,Be._)`${i.code.formats}${(0,Be.getProperty)(m)}`:void 0});t.fail$data(d(g))}function d(m){return(0,Be._)`${m}.compare(${r}, ${n}) ${xs[o].fail} 0`}},dependencies:["format"]};var dx=t=>(t.addKeyword(Er.formatLimitDefinition),t);Er.default=dx});var Pf=S((jn,Ef)=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});var Pr=kf(),px=Tf(),Fc=D(),xf=new Fc.Name("fullFormats"),mx=new Fc.Name("fastFormats"),Hc=(t,e={keywords:!0})=>{if(Array.isArray(e))return $f(t,e,Pr.fullFormats,xf),t;let[r,n]=e.mode==="fast"?[Pr.fastFormats,mx]:[Pr.fullFormats,xf],o=e.formats||Pr.formatNames;return $f(t,o,r,n),e.keywords&&(0,px.default)(t),t};Hc.get=(t,e="full")=>{let n=(e==="fast"?Pr.fastFormats:Pr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function $f(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Fc._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Ef.exports=jn=Hc;Object.defineProperty(jn,"__esModule",{value:!0});jn.default=Hc});var nh=S((V1,rh)=>{"use strict";rh.exports=th;th.sync=Vx;var Qf=mt("fs");function Wx(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 eh(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:Wx(e,r)}function th(t,e,r){Qf.stat(t,function(n,o){r(n,n?!1:eh(o,t,e))})}function Vx(t,e){return eh(Qf.statSync(t),t,e)}});var ch=S((B1,ah)=>{"use strict";ah.exports=sh;sh.sync=Bx;var oh=mt("fs");function sh(t,e,r){oh.stat(t,function(n,o){r(n,n?!1:ih(o,e))})}function Bx(t,e){return ih(oh.statSync(t),e)}function ih(t,e){return t.isFile()&&Gx(t,e)}function Gx(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),l=a|c,d=r&u||r&c&&o===i||r&a&&n===s||r&l&&s===0;return d}});var uh=S((K1,lh)=>{"use strict";var G1=mt("fs"),js;process.platform==="win32"||global.TESTING_WINDOWS?js=nh():js=ch();lh.exports=ll;ll.sync=Kx;function ll(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){ll(t,e||{},function(s,i){s?o(s):n(i)})})}js(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function Kx(t,e){try{return js.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var yh=S((Z1,gh)=>{"use strict";var jr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",dh=mt("path"),Zx=jr?";":":",ph=uh(),mh=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),fh=(t,e)=>{let r=e.colon||Zx,n=t.match(/\//)||jr&&t.match(/\\/)?[""]:[...jr?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=jr?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=jr?o.split(r):[""];return jr&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},hh=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=fh(t,e),i=[],a=u=>new Promise((l,d)=>{if(u===n.length)return e.all&&i.length?l(i):d(mh(t));let m=n[u],f=/^".*"$/.test(m)?m.slice(1,-1):m,g=dh.join(f,t),h=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+g:g;l(c(h,u,0))}),c=(u,l,d)=>new Promise((m,f)=>{if(d===o.length)return m(a(l+1));let g=o[d];ph(u+g,{pathExt:s},(h,y)=>{if(!h&&y)if(e.all)i.push(u+g);else return m(u+g);return m(c(u,l,d+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},Jx=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=fh(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=dh.join(c,t),l=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let d=0;d<n.length;d++){let m=l+n[d];try{if(ph.sync(m,{pathExt:o}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw mh(t)};gh.exports=hh;hh.sync=Jx});var wh=S((J1,ul)=>{"use strict";var _h=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};ul.exports=_h;ul.exports.default=_h});var kh=S((Y1,Sh)=>{"use strict";var vh=mt("path"),Yx=yh(),Xx=wh();function bh(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=Yx.sync(t.command,{path:r[Xx({env:r})],pathExt:e?vh.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=vh.resolve(o?t.options.cwd:"",i)),i}function Qx(t){return bh(t)||bh(t,!0)}Sh.exports=Qx});var Th=S((X1,pl)=>{"use strict";var dl=/([()\][%!^"`<>&|;, *?])/g;function e$(t){return t=t.replace(dl,"^$1"),t}function t$(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(dl,"^$1"),e&&(t=t.replace(dl,"^$1")),t}pl.exports.command=e$;pl.exports.argument=t$});var $h=S((Q1,xh)=>{"use strict";xh.exports=/^#!(.*)/});var Ph=S((ej,Eh)=>{"use strict";var r$=$h();Eh.exports=(t="")=>{let e=t.match(r$);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Ch=S((tj,Rh)=>{"use strict";var ml=mt("fs"),n$=Ph();function o$(t){let r=Buffer.alloc(150),n;try{n=ml.openSync(t,"r"),ml.readSync(n,r,0,150,0),ml.closeSync(n)}catch{}return n$(r.toString())}Rh.exports=o$});var Ih=S((rj,Ah)=>{"use strict";var s$=mt("path"),Mh=kh(),zh=Th(),i$=Ch(),a$=process.platform==="win32",c$=/\.(?:com|exe)$/i,l$=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function u$(t){t.file=Mh(t);let e=t.file&&i$(t.file);return e?(t.args.unshift(t.file),t.command=e,Mh(t)):t.file}function d$(t){if(!a$)return t;let e=u$(t),r=!c$.test(e);if(t.options.forceShell||r){let n=l$.test(e);t.command=s$.normalize(t.command),t.command=zh.command(t.command),t.args=t.args.map(s=>zh.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 p$(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:d$(n)}Ah.exports=p$});var Nh=S((nj,jh)=>{"use strict";var fl=process.platform==="win32";function hl(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 m$(t,e){if(!fl)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=Oh(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function Oh(t,e){return fl&&t===1&&!e.file?hl(e.original,"spawn"):null}function f$(t,e){return fl&&t===1&&!e.file?hl(e.original,"spawnSync"):null}jh.exports={hookChildProcess:m$,verifyENOENT:Oh,verifyENOENTSync:f$,notFoundError:hl}});var Lh=S((oj,Nr)=>{"use strict";var qh=mt("child_process"),gl=Ih(),yl=Nh();function Dh(t,e,r){let n=gl(t,e,r),o=qh.spawn(n.command,n.args,n.options);return yl.hookChildProcess(o,n),o}function h$(t,e,r){let n=gl(t,e,r),o=qh.spawnSync(n.command,n.args,n.options);return o.error=o.error||yl.verifyENOENTSync(o.status,n),o}Nr.exports=Dh;Nr.exports.spawn=Dh;Nr.exports.sync=h$;Nr.exports._parse=gl;Nr.exports._enoent=yl});var Bh=S(wl=>{"use strict";var Hh=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,b$=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Wh=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,S$=/\\([\u000b\u0020-\u00ff])/g,k$=/([\\"])/g,Vh=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;wl.format=T$;wl.parse=x$;function T$(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Vh.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],!Wh.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+E$(e[o])}return n}function x$(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?$$(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(!Vh.test(n))throw new TypeError("invalid media type");var o=new P$(n.toLowerCase());if(r!==-1){var s,i,a;for(Hh.lastIndex=r;i=Hh.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(S$,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function $$(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 E$(t){var e=String(t);if(Wh.test(e))return e;if(e.length>0&&!b$.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(k$,"\\$1")+'"'}function P$(t){this.parameters=Object.create(null),this.type=t}});async function ni(t,e){switch(t.protocol){case"anthropic":{let{AnthropicClient:r}=await import("./anthropic-GAI75HYJ.js");return new r(t,e)}case"openai":{let{OpenAIClient:r}=await import("./openai-SMJX34AX.js");return new r(t,e)}case"openai-compat":{let{OpenAICompatClient:r}=await import("./openai-SMJX34AX.js");return new r(t,e)}default:throw new Error(`Unknown protocol: ${String(t.protocol)}`)}}import{execSync as Xl}from"child_process";import{platform as Ig,arch as Og}from"os";function Wl(){return{name:"Identity",priority:0,content:`You are Swifty, an AI programming assistant running in a terminal.
11
+ deps: ${r}}`};var Yk={keyword:"dependencies",type:"object",schemaType:"object",error:Je.error,code(t){let[e,r]=Xk(t);qm(t,e),Dm(t,r)}};function Xk({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 qm(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,jn.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,jn.checkReportMissingProp)(t,u)}):(r.if((0,gc._)`${c} && (${(0,jn.checkMissingProp)(t,a,s)})`),(0,jn.reportMissingProp)(t,s),r.else())}}Je.validatePropertyDeps=qm;function Dm(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Jk.alwaysValidSchema)(s,e[a])||(r.if((0,jn.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))}Je.validateSchemaDeps=Dm;Je.default=Yk});var Fm=k(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var Um=D(),Qk=V(),eT={message:"property name must be valid",params:({params:t})=>(0,Um._)`{propertyName: ${t.propertyName}}`},tT={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:eT,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Qk.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,Um.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};yc.default=tT});var wc=k(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var ys=Ne(),Ve=D(),rT=nt(),_s=V(),nT={message:"must NOT have additional properties",params:({params:t})=>(0,Ve._)`{additionalProperty: ${t.additionalProperty}}`},oT={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nT,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,_s.alwaysValidSchema)(i,r))return;let u=(0,ys.allSchemaProperties)(n.properties),l=(0,ys.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Ve._)`${s} === ${rT.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?g(y):e.if(m(y),()=>g(y))})}function m(y){let v;if(u.length>8){let S=(0,_s.schemaRefOrVal)(i,n.properties,"properties");v=(0,ys.isOwnProperty)(e,S,y)}else u.length?v=(0,Ve.or)(...u.map(S=>(0,Ve._)`${y} === ${S}`)):v=Ve.nil;return l.length&&(v=(0,Ve.or)(v,...l.map(S=>(0,Ve._)`${(0,ys.usePattern)(t,S)}.test(${y})`))),(0,Ve.not)(v)}function f(y){e.code((0,Ve._)`delete ${o}[${y}]`)}function g(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,_s.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,Ve.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,Ve.not)(v),()=>e.break()))}}function h(y,v,S){let T={keyword:"additionalProperties",dataProp:y,dataPropType:_s.Type.Str};S===!1&&Object.assign(T,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(T,v)}}};_c.default=oT});var Wm=k(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var sT=Sn(),Hm=Ne(),vc=V(),Vm=wc(),iT={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&&Vm.default.code(new sT.KeywordCxt(s,Vm.default,"additionalProperties"));let i=(0,Hm.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(i),s.props));let a=i.filter(d=>!(0,vc.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Hm.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};bc.default=iT});var Zm=k(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var Bm=Ne(),ws=D(),Gm=V(),Km=V(),aT={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,Bm.allSchemaProperties)(r),c=a.filter(h=>(0,Gm.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ws.Name)&&(s.props=(0,Km.evaluatedPropsToName)(e,s.props));let{props:d}=s;m();function m(){for(let h of a)u&&f(h),s.allErrors?g(h):(e.var(l,!0),g(h),e.if(l))}function f(h){for(let y in u)new RegExp(h).test(y)&&(0,Gm.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function g(h){e.forIn("key",n,y=>{e.if((0,ws._)`${(0,Bm.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:Km.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ws._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,ws.not)(l),()=>e.break())})})}}};Sc.default=aT});var Jm=k(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var cT=V(),lT={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,cT.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"}};kc.default=lT});var Ym=k(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var uT=Ne(),dT={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:uT.validateUnion,error:{message:"must match a schema in anyOf"}};Tc.default=dT});var Xm=k(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var vs=D(),pT=V(),mT={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,vs._)`{passingSchemas: ${t.passing}}`},fT={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mT,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((l,d)=>{let m;(0,pT.alwaysValidSchema)(o,l)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,vs._)`${c} && ${i}`).assign(i,!1).assign(a,(0,vs._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),m&&t.mergeEvaluated(m,vs.Name)})})}}};xc.default=fT});var Qm=k($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var hT=V(),gT={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,hT.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};$c.default=gT});var rf=k(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var bs=D(),tf=V(),yT={message:({params:t})=>(0,bs.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,bs._)`{failingKeyword: ${t.ifClause}}`},_T={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yT,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,tf.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=ef(n,"then"),s=ef(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,bs.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let m=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(m,i),d?e.assign(d,(0,bs._)`${l}`):t.setParams({ifClause:l})}}}};function ef(t,e){let r=t.schema[e];return r!==void 0&&!(0,tf.alwaysValidSchema)(t,r)}Ec.default=_T});var nf=k(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var wT=V(),vT={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,wT.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Pc.default=vT});var of=k(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var bT=dc(),ST=Im(),kT=pc(),TT=jm(),xT=Nm(),$T=Lm(),ET=Fm(),PT=wc(),RT=Wm(),CT=Zm(),MT=Jm(),zT=Ym(),AT=Xm(),IT=Qm(),OT=rf(),jT=nf();function NT(t=!1){let e=[MT.default,zT.default,AT.default,IT.default,OT.default,jT.default,ET.default,PT.default,$T.default,RT.default,CT.default];return t?e.push(ST.default,TT.default):e.push(bT.default,kT.default),e.push(xT.default),e}Rc.default=NT});var sf=k(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var ie=D(),qT={message:({schemaCode:t})=>(0,ie.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ie._)`{format: ${t}}`},DT={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qT,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?m():f();function m(){let g=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,ie._)`${g}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,ie._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ie._)`${h}.type || "string"`).assign(v,(0,ie._)`${h}.validate`),()=>r.assign(y,(0,ie._)`"string"`).assign(v,h)),t.fail$data((0,ie.or)(S(),T()));function S(){return c.strictSchema===!1?ie.nil:(0,ie._)`${i} && !${v}`}function T(){let z=l.$async?(0,ie._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ie._)`${v}(${n})`,w=(0,ie._)`(typeof ${v} == "function" ? ${z} : ${v}.test(${n}))`;return(0,ie._)`${v} && ${v} !== true && ${y} === ${e} && !${w}`}}function f(){let g=d.formats[s];if(!g){S();return}if(g===!0)return;let[h,y,v]=T(g);h===e&&t.pass(z());function S(){if(c.strictSchema===!1){d.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function T(w){let b=w instanceof RegExp?(0,ie.regexpCode)(w):c.code.formats?(0,ie._)`${c.code.formats}${(0,ie.getProperty)(s)}`:void 0,j=r.scopeValue("formats",{key:s,ref:w,code:b});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,ie._)`${j}.validate`]:["string",w,j]}function z(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ie._)`await ${v}(${n})`}return typeof y=="function"?(0,ie._)`${v}(${n})`:(0,ie._)`${v}.test(${n})`}}}};Cc.default=DT});var af=k(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var LT=sf(),UT=[LT.default];Mc.default=UT});var cf=k(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.contentVocabulary=kr.metadataVocabulary=void 0;kr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];kr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var uf=k(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var FT=gm(),HT=Cm(),VT=of(),WT=af(),lf=cf(),BT=[FT.default,HT.default,(0,VT.default)(),WT.default,lf.metadataVocabulary,lf.contentVocabulary];zc.default=BT});var pf=k(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.DiscrError=void 0;var df;(function(t){t.Tag="tag",t.Mapping="mapping"})(df||(Ss.DiscrError=df={}))});var ff=k(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Tr=D(),Ac=pf(),mf=ss(),GT=kn(),KT=V(),ZT={message:({params:{discrError:t,tagName:e}})=>t===Ac.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Tr._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},JT={keyword:"discriminator",type:"object",schemaType:"object",error:ZT,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,Tr._)`${r}${(0,Tr.getProperty)(a)}`);e.if((0,Tr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Ac.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=m();e.if(!1);for(let g in f)e.elseIf((0,Tr._)`${u} === ${g}`),e.assign(c,d(f[g]));e.else(),t.error(!1,{discrError:Ac.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let g=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},g);return t.mergeEvaluated(h,Tr.Name),g}function m(){var f;let g={},h=v(o),y=!0;for(let z=0;z<i.length;z++){let w=i[z];if(w?.$ref&&!(0,KT.schemaHasRulesButRef)(w,s.self.RULES)){let j=w.$ref;if(w=mf.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,j),w instanceof mf.SchemaEnv&&(w=w.schema),w===void 0)throw new GT.default(s.opts.uriResolver,s.baseId,j)}let b=(f=w?.properties)===null||f===void 0?void 0:f[a];if(typeof b!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(w)),S(b,z)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return g;function v({required:z}){return Array.isArray(z)&&z.includes(a)}function S(z,w){if(z.const)T(z.const,w);else if(z.enum)for(let b of z.enum)T(b,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function T(z,w){if(typeof z!="string"||z in g)throw new Error(`discriminator: "${a}" values must be unique strings`);g[z]=w}}}};Ic.default=JT});var hf=k((kj,YT)=>{YT.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 jc=k((Q,Oc)=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.MissingRefError=Q.ValidationError=Q.CodeGen=Q.Name=Q.nil=Q.stringify=Q.str=Q._=Q.KeywordCxt=Q.Ajv=void 0;var XT=um(),QT=uf(),ex=ff(),gf=hf(),tx=["/properties"],ks="http://json-schema.org/draft-07/schema",xr=class extends XT.default{_addVocabularies(){super._addVocabularies(),QT.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(ex.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(gf,tx):gf;this.addMetaSchema(e,ks,!1),this.refs["http://json-schema.org/schema"]=ks}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ks)?ks:void 0)}};Q.Ajv=xr;Oc.exports=Q=xr;Oc.exports.Ajv=xr;Object.defineProperty(Q,"__esModule",{value:!0});Q.default=xr;var rx=Sn();Object.defineProperty(Q,"KeywordCxt",{enumerable:!0,get:function(){return rx.KeywordCxt}});var $r=D();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return $r._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return $r.str}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return $r.stringify}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return $r.nil}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return $r.Name}});Object.defineProperty(Q,"CodeGen",{enumerable:!0,get:function(){return $r.CodeGen}});var nx=ns();Object.defineProperty(Q,"ValidationError",{enumerable:!0,get:function(){return nx.default}});var ox=kn();Object.defineProperty(Q,"MissingRefError",{enumerable:!0,get:function(){return ox.default}})});var Tf=k(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.formatNames=Xe.fastFormats=Xe.fullFormats=void 0;function Ye(t,e){return{validate:t,compare:e}}Xe.fullFormats={date:Ye(vf,Lc),time:Ye(qc(!0),Uc),"date-time":Ye(yf(!0),Sf),"iso-time":Ye(qc(),bf),"iso-date-time":Ye(yf(),kf),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:ux,"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:yx,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:dx,int32:{type:"number",validate:fx},int64:{type:"number",validate:hx},float:{type:"number",validate:wf},double:{type:"number",validate:wf},password:!0,binary:!0};Xe.fastFormats={...Xe.fullFormats,date:Ye(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Lc),time:Ye(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Uc),"date-time":Ye(/^\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,Sf),"iso-time":Ye(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,bf),"iso-date-time":Ye(/^\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,kf),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};Xe.formatNames=Object.keys(Xe.fullFormats);function sx(t){return t%4===0&&(t%100!==0||t%400===0)}var ix=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ax=[0,31,28,31,30,31,30,31,31,30,31,30,31];function vf(t){let e=ix.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&&sx(r)?29:ax[n])}function Lc(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Nc=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function qc(t){return function(r){let n=Nc.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),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,m=o-u*c-(d<0?1:0);return(m===23||m===-1)&&(d===59||d===-1)&&i<61}}function Uc(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 bf(t,e){if(!(t&&e))return;let r=Nc.exec(t),n=Nc.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 Dc=/t|\s/i;function yf(t){let e=qc(t);return function(n){let o=n.split(Dc);return o.length===2&&vf(o[0])&&e(o[1])}}function Sf(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function kf(t,e){if(!(t&&e))return;let[r,n]=t.split(Dc),[o,s]=e.split(Dc),i=Lc(r,o);if(i!==void 0)return i||Uc(n,s)}var cx=/\/|:/,lx=/^(?:[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 ux(t){return cx.test(t)&&lx.test(t)}var _f=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function dx(t){return _f.lastIndex=0,_f.test(t)}var px=-(2**31),mx=2**31-1;function fx(t){return Number.isInteger(t)&&t<=mx&&t>=px}function hx(t){return Number.isInteger(t)}function wf(){return!0}var gx=/[^\\]\\Z/;function yx(t){if(gx.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var xf=k(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.formatLimitDefinition=void 0;var _x=jc(),We=D(),$t=We.operators,Ts={formatMaximum:{okStr:"<=",ok:$t.LTE,fail:$t.GT},formatMinimum:{okStr:">=",ok:$t.GTE,fail:$t.LT},formatExclusiveMaximum:{okStr:"<",ok:$t.LT,fail:$t.GTE},formatExclusiveMinimum:{okStr:">",ok:$t.GT,fail:$t.LTE}},wx={message:({keyword:t,schemaCode:e})=>(0,We.str)`should be ${Ts[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,We._)`{comparison: ${Ts[t].okStr}, limit: ${e}}`};Er.formatLimitDefinition={keyword:Object.keys(Ts),type:"string",schemaType:"string",$data:!0,error:wx,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 _x.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,We._)`${m}[${c.schemaCode}]`);t.fail$data((0,We.or)((0,We._)`typeof ${f} != "object"`,(0,We._)`${f} instanceof RegExp`,(0,We._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let g=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,We._)`${i.code.formats}${(0,We.getProperty)(m)}`:void 0});t.fail$data(d(g))}function d(m){return(0,We._)`${m}.compare(${r}, ${n}) ${Ts[o].fail} 0`}},dependencies:["format"]};var vx=t=>(t.addKeyword(Er.formatLimitDefinition),t);Er.default=vx});var Rf=k((Nn,Pf)=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});var Pr=Tf(),bx=xf(),Fc=D(),$f=new Fc.Name("fullFormats"),Sx=new Fc.Name("fastFormats"),Hc=(t,e={keywords:!0})=>{if(Array.isArray(e))return Ef(t,e,Pr.fullFormats,$f),t;let[r,n]=e.mode==="fast"?[Pr.fastFormats,Sx]:[Pr.fullFormats,$f],o=e.formats||Pr.formatNames;return Ef(t,o,r,n),e.keywords&&(0,bx.default)(t),t};Hc.get=(t,e="full")=>{let n=(e==="fast"?Pr.fastFormats:Pr.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Ef(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Fc._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Pf.exports=Nn=Hc;Object.defineProperty(Nn,"__esModule",{value:!0});Nn.default=Hc});var oh=k((s1,nh)=>{"use strict";nh.exports=rh;rh.sync=e$;var eh=mt("fs");function Qx(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 th(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:Qx(e,r)}function rh(t,e,r){eh.stat(t,function(n,o){r(n,n?!1:th(o,t,e))})}function e$(t,e){return th(eh.statSync(t),t,e)}});var lh=k((i1,ch)=>{"use strict";ch.exports=ih;ih.sync=t$;var sh=mt("fs");function ih(t,e,r){sh.stat(t,function(n,o){r(n,n?!1:ah(o,e))})}function t$(t,e){return ah(sh.statSync(t),e)}function ah(t,e){return t.isFile()&&r$(t,e)}function r$(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),l=a|c,d=r&u||r&c&&o===i||r&a&&n===s||r&l&&s===0;return d}});var dh=k((c1,uh)=>{"use strict";var a1=mt("fs"),Os;process.platform==="win32"||global.TESTING_WINDOWS?Os=oh():Os=lh();uh.exports=ll;ll.sync=n$;function ll(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){ll(t,e||{},function(s,i){s?o(s):n(i)})})}Os(t,e||{},function(n,o){n&&(n.code==="EACCES"||e&&e.ignoreErrors)&&(n=null,o=!1),r(n,o)})}function n$(t,e){try{return Os.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var _h=k((l1,yh)=>{"use strict";var jr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",ph=mt("path"),o$=jr?";":":",mh=dh(),fh=t=>Object.assign(new Error(`not found: ${t}`),{code:"ENOENT"}),hh=(t,e)=>{let r=e.colon||o$,n=t.match(/\//)||jr&&t.match(/\\/)?[""]:[...jr?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],o=jr?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",s=jr?o.split(r):[""];return jr&&t.indexOf(".")!==-1&&s[0]!==""&&s.unshift(""),{pathEnv:n,pathExt:s,pathExtExe:o}},gh=(t,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:n,pathExt:o,pathExtExe:s}=hh(t,e),i=[],a=u=>new Promise((l,d)=>{if(u===n.length)return e.all&&i.length?l(i):d(fh(t));let m=n[u],f=/^".*"$/.test(m)?m.slice(1,-1):m,g=ph.join(f,t),h=!f&&/^\.[\\\/]/.test(t)?t.slice(0,2)+g:g;l(c(h,u,0))}),c=(u,l,d)=>new Promise((m,f)=>{if(d===o.length)return m(a(l+1));let g=o[d];mh(u+g,{pathExt:s},(h,y)=>{if(!h&&y)if(e.all)i.push(u+g);else return m(u+g);return m(c(u,l,d+1))})});return r?a(0).then(u=>r(null,u),r):a(0)},s$=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:n,pathExtExe:o}=hh(t,e),s=[];for(let i=0;i<r.length;i++){let a=r[i],c=/^".*"$/.test(a)?a.slice(1,-1):a,u=ph.join(c,t),l=!c&&/^\.[\\\/]/.test(t)?t.slice(0,2)+u:u;for(let d=0;d<n.length;d++){let m=l+n[d];try{if(mh.sync(m,{pathExt:o}))if(e.all)s.push(m);else return m}catch{}}}if(e.all&&s.length)return s;if(e.nothrow)return null;throw fh(t)};yh.exports=gh;gh.sync=s$});var vh=k((u1,ul)=>{"use strict";var wh=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(n=>n.toUpperCase()==="PATH")||"Path"};ul.exports=wh;ul.exports.default=wh});var Th=k((d1,kh)=>{"use strict";var bh=mt("path"),i$=_h(),a$=vh();function Sh(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=i$.sync(t.command,{path:r[a$({env:r})],pathExt:e?bh.delimiter:void 0})}catch{}finally{s&&process.chdir(n)}return i&&(i=bh.resolve(o?t.options.cwd:"",i)),i}function c$(t){return Sh(t)||Sh(t,!0)}kh.exports=c$});var xh=k((p1,pl)=>{"use strict";var dl=/([()\][%!^"`<>&|;, *?])/g;function l$(t){return t=t.replace(dl,"^$1"),t}function u$(t,e){return t=`${t}`,t=t.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),t=t.replace(/(?=(\\+?)?)\1$/,"$1$1"),t=`"${t}"`,t=t.replace(dl,"^$1"),e&&(t=t.replace(dl,"^$1")),t}pl.exports.command=l$;pl.exports.argument=u$});var Eh=k((m1,$h)=>{"use strict";$h.exports=/^#!(.*)/});var Rh=k((f1,Ph)=>{"use strict";var d$=Eh();Ph.exports=(t="")=>{let e=t.match(d$);if(!e)return null;let[r,n]=e[0].replace(/#! ?/,"").split(" "),o=r.split("/").pop();return o==="env"?n:n?`${o} ${n}`:o}});var Mh=k((h1,Ch)=>{"use strict";var ml=mt("fs"),p$=Rh();function m$(t){let r=Buffer.alloc(150),n;try{n=ml.openSync(t,"r"),ml.readSync(n,r,0,150,0),ml.closeSync(n)}catch{}return p$(r.toString())}Ch.exports=m$});var Oh=k((g1,Ih)=>{"use strict";var f$=mt("path"),zh=Th(),Ah=xh(),h$=Mh(),g$=process.platform==="win32",y$=/\.(?:com|exe)$/i,_$=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function w$(t){t.file=zh(t);let e=t.file&&h$(t.file);return e?(t.args.unshift(t.file),t.command=e,zh(t)):t.file}function v$(t){if(!g$)return t;let e=w$(t),r=!y$.test(e);if(t.options.forceShell||r){let n=_$.test(e);t.command=f$.normalize(t.command),t.command=Ah.command(t.command),t.args=t.args.map(s=>Ah.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 b$(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:v$(n)}Ih.exports=b$});var qh=k((y1,Nh)=>{"use strict";var fl=process.platform==="win32";function hl(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 S$(t,e){if(!fl)return;let r=t.emit;t.emit=function(n,o){if(n==="exit"){let s=jh(o,e);if(s)return r.call(t,"error",s)}return r.apply(t,arguments)}}function jh(t,e){return fl&&t===1&&!e.file?hl(e.original,"spawn"):null}function k$(t,e){return fl&&t===1&&!e.file?hl(e.original,"spawnSync"):null}Nh.exports={hookChildProcess:S$,verifyENOENT:jh,verifyENOENTSync:k$,notFoundError:hl}});var Uh=k((_1,Nr)=>{"use strict";var Dh=mt("child_process"),gl=Oh(),yl=qh();function Lh(t,e,r){let n=gl(t,e,r),o=Dh.spawn(n.command,n.args,n.options);return yl.hookChildProcess(o,n),o}function T$(t,e,r){let n=gl(t,e,r),o=Dh.spawnSync(n.command,n.args,n.options);return o.error=o.error||yl.verifyENOENTSync(o.status,n),o}Nr.exports=Lh;Nr.exports.spawn=Lh;Nr.exports.sync=T$;Nr.exports._parse=gl;Nr.exports._enoent=yl});var Gh=k(wl=>{"use strict";var Vh=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,C$=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,Wh=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,M$=/\\([\u000b\u0020-\u00ff])/g,z$=/([\\"])/g,Bh=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;wl.format=A$;wl.parse=I$;function A$(t){if(!t||typeof t!="object")throw new TypeError("argument obj is required");var e=t.parameters,r=t.type;if(!r||!Bh.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],!Wh.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+j$(e[o])}return n}function I$(t){if(!t)throw new TypeError("argument string is required");var e=typeof t=="object"?O$(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(!Bh.test(n))throw new TypeError("invalid media type");var o=new N$(n.toLowerCase());if(r!==-1){var s,i,a;for(Vh.lastIndex=r;i=Vh.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(M$,"$1"))),o.parameters[s]=a}if(r!==e.length)throw new TypeError("invalid parameter format")}return o}function O$(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 j$(t){var e=String(t);if(Wh.test(e))return e;if(e.length>0&&!C$.test(e))throw new TypeError("invalid parameter value");return'"'+e.replace(z$,"\\$1")+'"'}function N$(t){this.parameters=Object.create(null),this.type=t}});async function oi(t,e){switch(t.protocol){case"anthropic":{let{AnthropicClient:r}=await import("./anthropic-DFGYPMNW.js");return new r(t,e)}case"openai":{let{OpenAIClient:r}=await import("./openai-NMDB34GN.js");return new r(t,e)}case"openai-compat":{let{OpenAICompatClient:r}=await import("./openai-NMDB34GN.js");return new r(t,e)}default:throw new Error(`Unknown protocol: ${String(t.protocol)}`)}}import{execSync as Xl}from"child_process";import{platform as jg,arch as Ng}from"os";function Vl(){return{name:"Identity",priority:0,content:`You are Swifty, an AI programming assistant running in a terminal.
12
12
  You assist users with software engineering tasks, including writing code, debugging, refactoring, explaining code, and executing commands.
13
13
 
14
14
  IMPORTANT: Avoid introducing security vulnerabilities such as command injection, XSS, SQL injection, and other common exploits. Prioritize writing secure, correct code.
15
- IMPORTANT: Never generate or fabricate URLs unless you are confident they are directly helpful to the user's programming task. URLs provided by the user may be used.`}}function Vl(){return{name:"System",priority:10,content:`# System
15
+ IMPORTANT: Never generate or fabricate URLs unless you are confident they are directly helpful to the user's programming task. URLs provided by the user may be used.`}}function Wl(){return{name:"System",priority:10,content:`# System
16
16
  - All text output outside of tool calls is displayed to the user. Communicate using Github-flavored Markdown.
17
17
  - Tools execute according to permission settings. If a tool call is denied, adjust your approach rather than retrying the identical call.
18
18
  - Tool results and user messages may contain <system-reminder> tags. These are system-level information and are not directly related to the tool result or message they appear in.
@@ -73,9 +73,9 @@ End-of-turn summary: one to two sentences. What changed, what is next. No more.
73
73
  Match the response style to the task: for simple questions, give a direct answer without headings or sections.
74
74
 
75
75
  In code: do not write comments by default. Never write multi-paragraph docstring or multi-line comment blocks \u2014 at most one short comment line. Do not create planning, decision, or analysis documents unless the user requests them \u2014 work from the conversation context and do not produce intermediate files.`}}function Yl(t){let e=["# Environment",` - Working directory: ${t.workDir}`,` - Platform: ${t.os}/${t.arch}`,` - Shell: ${t.shell}`,` - Git repository: ${t.isGitRepo?"true":"false"}`];return t.isGitRepo&&t.gitBranch&&e.push(` - Git branch: ${t.gitBranch}`),t.model&&e.push(` - Model: ${t.model}`),e.push(` - Date: ${t.date}`),{name:"Environment",priority:70,content:e.join(`
76
- `)}}var jg=C({module:"prompt"}),oi=class{sections=[];add(e){return this.sections.push(e),this}build(){return[...this.sections].sort((r,n)=>r.priority-n.priority).map(r=>r.content.trim()).filter(Boolean).join(`
76
+ `)}}var qg=C({module:"prompt"}),si=class{sections=[];add(e){return this.sections.push(e),this}build(){return[...this.sections].sort((r,n)=>r.priority-n.priority).map(r=>r.content.trim()).filter(Boolean).join(`
77
77
 
78
- `)}};function Ql(t){let e={workDir:t,os:Ig(),arch:Og(),shell:process.env.SHELL??"bash",isGitRepo:!1,gitBranch:"",model:"",date:new Date().toISOString().split("T")[0]};try{Xl("git rev-parse --is-inside-work-tree",{cwd:t,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim()==="true"&&(e.isGitRepo=!0,e.gitBranch=Xl("git rev-parse --abbrev-ref HEAD",{cwd:t,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim())}catch(r){jg.error({err:r},"prompt operation failed")}return e}function eu(t){let e=new oi;return e.add(Wl()),e.add(Vl()),e.add(Bl()),e.add(Gl()),e.add(Kl()),e.add(Zl()),e.add(Jl()),e.add(Yl(t)),e.build()}import{randomBytes as Ng}from"crypto";var mo="text",Ct="shutdown_request",fo="shutdown_response",qg="plan_approval_request",rr="plan_approval_response",tu="[shutdown]";function ru(){return`req-${Ng(8).toString("hex")}`}function ho(t,e,r,n,o){return{from:t,text:n,timestamp:new Date().toISOString(),type:e,requestId:r,...o===void 0?{}:{approve:o}}}function go(t,e=""){let r=e||"team is wrapping up";return ho(t,Ct,ru(),`${tu} ${r}`)}function yo(t,e,r,n=""){return ho(t,fo,e,n,r)}function nu(t,e){return ho(t,qg,ru(),e)}function ou(t,e,r,n=""){return ho(t,rr,e,n,r)}function su(t){return t.type===Ct?!0:(t.text??"").trim().startsWith(tu)}function si(t){return t.approve===!0}var ii=class{names=new Map;register(e,r){this.names.set(e,r)}resolve(e){let r=this.names.get(e);if(r!==void 0)return r;for(let n of this.names.values())if(n===e)return e}unregister(e){this.names.delete(e)}clear(){this.names.clear()}},iu;function nr(){return iu??=new ii,iu}var Dg=C({module:"teams"}),au=class{constructor(e){this.mgr=e}mgr;name="TeamCreate";description="Create a team for coordinating multiple agents.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{team_name:{type:"string",description:"Name for the team"},description:{type:"string",description:"What this team will work on"}},required:["team_name"]}}}async execute(e,r){let n=E(r,"team_name");if(!n)return Promise.resolve({output:"Error: team_name is required",isError:!0});let o=n;for(let a=2;this.mgr.get(o);a++)o=`${n}-${String(a)}`;let s=E(r,"description"),i=this.mgr.create(o,void 0,{leadAgentId:"lead",description:s});return{output:`Team '${i.name}' created (mode: ${i.mode}). Use Agent tool with team_name='${i.name}' to add teammates.`,isError:!1}}},cu=class{constructor(e,r){this.mgr=e;this.runAgent=r}mgr;runAgent;name="SpawnTeammate";description="Spawn a teammate in a team to work on a task in the background. Its result is delivered back to you on the team channel when it finishes.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{team:{type:"string",description:"Team name (created if missing)"},name:{type:"string",description:"Teammate name"},task:{type:"string",description:"The task for the teammate"}},required:["team","name","task"]}}}async execute(e,r){let n=E(r,"team"),o=E(r,"name"),s=E(r,"task");return!n||!o||!s?Promise.resolve({output:"Error: team, name and task are required",isError:!0}):((this.mgr.get(n)??this.mgr.create(n)).spawnTeammate(o,s,this.runAgent),Promise.resolve({output:`Teammate '${o}' spawned in team '${n}'. Its result will arrive on the team channel; keep working and watch for it.`,isError:!1}))}},_o=class{constructor(e,r="lead"){this.mgr=e;this.senderName=r}mgr;senderName;name="SendMessage";description="Send a message to a teammate's mailbox. Use to='*' to broadcast to all teammates.";category="read";senderTeam(){let e=this.mgr.list();for(let r of e)if(r.getMember(this.senderName))return r;return e[0]}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{to:{type:"string",description:"Teammate name, or '*' to broadcast"},content:{type:"string",description:"Message content. For shutdown_request this is the reason; for plan_approval_response this is your feedback when rejecting."},type:{type:"string",enum:[mo,Ct,fo,rr],description:"Message kind, defaults to 'text'. Use 'shutdown_request' to ask a teammate to wrap up (it replies with shutdown_response). Use 'plan_approval_response' to answer a teammate's plan, together with 'approve' and, when rejecting, feedback in 'content'."},request_id:{type:"string",description:"Required for plan_approval_response: copy the requestId from the teammate's plan approval request so it knows which plan you are answering."},approve:{type:"boolean",description:"Required for plan_approval_response: true to let the teammate start executing, false to send it back to revise."}},required:["to","content"]}}}async execute(e,r){let n=E(r,"to"),o=E(r,"content"),s=this.senderTeam();if(!s)return{output:"No active team found for this sender.",isError:!0};let i=typeof r.type=="string"?r.type:mo;if(i!==mo){let c=typeof r.request_id=="string"?r.request_id:"",u=typeof r.approve=="boolean"?r.approve:void 0,l;switch(i){case Ct:l=go(this.senderName,o);break;case fo:if(u===void 0)return{output:"shutdown_response requires 'approve'.",isError:!0};l=yo(this.senderName,c,u,o);break;case rr:if(!c||u===void 0)return{output:"plan_approval_response requires both 'request_id' and 'approve'.",isError:!0};l=ou(this.senderName,c,u,o);break;default:return{output:`Unsupported message type ${i}.`,isError:!0}}let d=n==="lead"?s.leadMailbox:s.getMember(n)?.mailbox;return d?(await d.send(this.senderName,l.text,l),{output:`${i} sent to '${n}'.`,isError:!1}):{output:`Teammate '${n}' not found.`,isError:!0}}if(n==="*"){let c=0;for(let u of s.listMembers())u.name!==this.senderName&&(await s.sendMessage(this.senderName,u.name,o),c++);return{output:`Message broadcast to ${String(c)} teammate(s).`,isError:!1}}let a=nr().resolve(n)??n;try{await s.sendMessage(this.senderName,a,o)}catch(c){return Dg.error({err:c},"teams operation failed"),{output:`Error: ${N(c)}`,isError:!0}}return{output:`Message sent to '${n}'.`,isError:!1}}},lu=class{constructor(e){this.mgr=e}mgr;name="ListTeams";description="List teams and their members.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{},required:[]}}}execute(){let e=this.mgr.list();if(e.length===0)return Promise.resolve({output:"No teams.",isError:!1});let r=e.map(n=>{let o=n.listMembers().map(s=>`${s.name}${s.active?" (active)":""}`).join(", ")||"(no members)";return`${n.name} [${n.mode}]: ${o}`});return Promise.resolve({output:r.join(`
78
+ `)}};function Ql(t){let e={workDir:t,os:jg(),arch:Ng(),shell:process.env.SHELL??"bash",isGitRepo:!1,gitBranch:"",model:"",date:new Date().toISOString().split("T")[0]};try{Xl("git rev-parse --is-inside-work-tree",{cwd:t,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim()==="true"&&(e.isGitRepo=!0,e.gitBranch=Xl("git rev-parse --abbrev-ref HEAD",{cwd:t,stdio:["pipe","pipe","pipe"],encoding:"utf-8"}).trim())}catch(r){qg.error({err:r},"prompt operation failed")}return e}function eu(t){let e=new si;return e.add(Vl()),e.add(Wl()),e.add(Bl()),e.add(Gl()),e.add(Kl()),e.add(Zl()),e.add(Jl()),e.add(Yl(t)),e.build()}import{randomBytes as Dg}from"crypto";var mo="text",Ct="shutdown_request",fo="shutdown_response",Lg="plan_approval_request",rr="plan_approval_response",tu="[shutdown]";function ru(){return`req-${Dg(8).toString("hex")}`}function ho(t,e,r,n,o){return{from:t,text:n,timestamp:new Date().toISOString(),type:e,requestId:r,...o===void 0?{}:{approve:o}}}function go(t,e=""){let r=e||"team is wrapping up";return ho(t,Ct,ru(),`${tu} ${r}`)}function yo(t,e,r,n=""){return ho(t,fo,e,n,r)}function nu(t,e){return ho(t,Lg,ru(),e)}function ou(t,e,r,n=""){return ho(t,rr,e,n,r)}function su(t){return t.type===Ct?!0:(t.text??"").trim().startsWith(tu)}function ii(t){return t.approve===!0}var ai=class{names=new Map;register(e,r){this.names.set(e,r)}resolve(e){let r=this.names.get(e);if(r!==void 0)return r;for(let n of this.names.values())if(n===e)return e}unregister(e){this.names.delete(e)}clear(){this.names.clear()}},iu;function nr(){return iu??=new ai,iu}var Ug=C({module:"teams"}),au=class{constructor(e){this.mgr=e}mgr;name="TeamCreate";description="Create a team for coordinating multiple agents.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{team_name:{type:"string",description:"Name for the team"},description:{type:"string",description:"What this team will work on"}},required:["team_name"]}}}async execute(e,r){let n=E(r,"team_name");if(!n)return Promise.resolve({output:"Error: team_name is required",isError:!0});let o=n;for(let a=2;this.mgr.get(o);a++)o=`${n}-${String(a)}`;let s=E(r,"description"),i=this.mgr.create(o,void 0,{leadAgentId:"lead",description:s});return{output:`Team '${i.name}' created (mode: ${i.mode}). Use Agent tool with team_name='${i.name}' to add teammates.`,isError:!1}}},cu=class{constructor(e,r){this.mgr=e;this.runAgent=r}mgr;runAgent;name="SpawnTeammate";description="Spawn a teammate in a team to work on a task in the background. Its result is delivered back to you on the team channel when it finishes.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{team:{type:"string",description:"Team name (created if missing)"},name:{type:"string",description:"Teammate name"},task:{type:"string",description:"The task for the teammate"}},required:["team","name","task"]}}}async execute(e,r){let n=E(r,"team"),o=E(r,"name"),s=E(r,"task");return!n||!o||!s?Promise.resolve({output:"Error: team, name and task are required",isError:!0}):((this.mgr.get(n)??this.mgr.create(n)).spawnTeammate(o,s,this.runAgent),Promise.resolve({output:`Teammate '${o}' spawned in team '${n}'. Its result will arrive on the team channel; keep working and watch for it.`,isError:!1}))}},_o=class{constructor(e,r="lead"){this.mgr=e;this.senderName=r}mgr;senderName;name="SendMessage";description="Send a message to a teammate's mailbox. Use to='*' to broadcast to all teammates.";category="read";senderTeam(){let e=this.mgr.list();for(let r of e)if(r.getMember(this.senderName))return r;return e[0]}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{to:{type:"string",description:"Teammate name, or '*' to broadcast"},content:{type:"string",description:"Message content. For shutdown_request this is the reason; for plan_approval_response this is your feedback when rejecting."},type:{type:"string",enum:[mo,Ct,fo,rr],description:"Message kind, defaults to 'text'. Use 'shutdown_request' to ask a teammate to wrap up (it replies with shutdown_response). Use 'plan_approval_response' to answer a teammate's plan, together with 'approve' and, when rejecting, feedback in 'content'."},request_id:{type:"string",description:"Required for plan_approval_response: copy the requestId from the teammate's plan approval request so it knows which plan you are answering."},approve:{type:"boolean",description:"Required for plan_approval_response: true to let the teammate start executing, false to send it back to revise."}},required:["to","content"]}}}async execute(e,r){let n=E(r,"to"),o=E(r,"content"),s=this.senderTeam();if(!s)return{output:"No active team found for this sender.",isError:!0};let i=typeof r.type=="string"?r.type:mo;if(i!==mo){let c=typeof r.request_id=="string"?r.request_id:"",u=typeof r.approve=="boolean"?r.approve:void 0,l;switch(i){case Ct:l=go(this.senderName,o);break;case fo:if(u===void 0)return{output:"shutdown_response requires 'approve'.",isError:!0};l=yo(this.senderName,c,u,o);break;case rr:if(!c||u===void 0)return{output:"plan_approval_response requires both 'request_id' and 'approve'.",isError:!0};l=ou(this.senderName,c,u,o);break;default:return{output:`Unsupported message type ${i}.`,isError:!0}}let d=n==="lead"?s.leadMailbox:s.getMember(n)?.mailbox;return d?(await d.send(this.senderName,l.text,l),{output:`${i} sent to '${n}'.`,isError:!1}):{output:`Teammate '${n}' not found.`,isError:!0}}if(n==="*"){let c=0;for(let u of s.listMembers())u.name!==this.senderName&&(await s.sendMessage(this.senderName,u.name,o),c++);return{output:`Message broadcast to ${String(c)} teammate(s).`,isError:!1}}let a=nr().resolve(n)??n;try{await s.sendMessage(this.senderName,a,o)}catch(c){return Ug.error({err:c},"teams operation failed"),{output:`Error: ${N(c)}`,isError:!0}}return{output:`Message sent to '${n}'.`,isError:!1}}},lu=class{constructor(e){this.mgr=e}mgr;name="ListTeams";description="List teams and their members.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{},required:[]}}}execute(){let e=this.mgr.list();if(e.length===0)return Promise.resolve({output:"No teams.",isError:!1});let r=e.map(n=>{let o=n.listMembers().map(s=>`${s.name}${s.active?" (active)":""}`).join(", ")||"(no members)";return`${n.name} [${n.mode}]: ${o}`});return Promise.resolve({output:r.join(`
79
79
  `),isError:!1})}},uu=class{constructor(e){this.mgr=e}mgr;name="TeamDelete";description="Delete a team and stop its members.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{name:{type:"string"}},required:["name"]}}}async execute(e,r){let n=E(r,"name");return await this.mgr.delete(n),{output:`Team '${n}' deleted.`,isError:!1}}};var du=[{name:"general-purpose",description:"General-purpose agent for researching complex questions, exploring codebase, and executing multi-step tasks."},{name:"plan",description:`You are a software architect. This is a read-only planning task.
80
80
  Prohibited actions:
81
81
  Creating, modifying, or deleting files, Asking questions
@@ -93,17 +93,17 @@ Tool invocation strategy:
93
93
  - Use ReadFile to read files at specified paths
94
94
  - Only execute read-only Bash commands
95
95
  - Invoke multiple tools in parallel whenever possible to maximize efficiency
96
- `,disallowedTools:["EditFile","WriteFile"],permissionMode:"plan",model:"haiku"}];import{randomBytes as ay}from"crypto";var Lg=new Set(["pending","in_progress","completed","blocked"]),wo=class{constructor(e,r,n=""){this.mgr=e;this.teamName=r;this.agentName=n}mgr;teamName;agentName;name="TaskCreate";description="Create a shared task in the team's task board. Supports dependency tracking with blocks/blocked_by fields.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{title:{type:"string",description:"Short task title"},description:{type:"string",description:"Optional task details"},assignee:{type:"string",description:"Teammate name to assign this task to"},blocks:{type:"array",items:{type:"string"},description:"IDs of tasks that this task blocks"},blocked_by:{type:"array",items:{type:"string"},description:"IDs of tasks that block this task"}},required:["title"]}}}execute(e,r){let n=E(r,"title");if(!n)return Promise.resolve({output:"Error: 'title' is required",isError:!0});let o=this.mgr.getTaskStore(this.teamName);if(!o)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let s=o.create(n,E(r,"description"),E(r,"assignee"),Wr(r.blocks),Wr(r.blocked_by),this.agentName);return Promise.resolve({output:`Task created:
96
+ `,disallowedTools:["EditFile","WriteFile"],permissionMode:"plan",model:"haiku"}];import{randomBytes as ly}from"crypto";var Fg=new Set(["pending","in_progress","completed","blocked"]),wo=class{constructor(e,r,n=""){this.mgr=e;this.teamName=r;this.agentName=n}mgr;teamName;agentName;name="TaskCreate";description="Create a shared task in the team's task board. Supports dependency tracking with blocks/blocked_by fields.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{title:{type:"string",description:"Short task title"},description:{type:"string",description:"Optional task details"},assignee:{type:"string",description:"Teammate name to assign this task to"},blocks:{type:"array",items:{type:"string"},description:"IDs of tasks that this task blocks"},blocked_by:{type:"array",items:{type:"string"},description:"IDs of tasks that block this task"}},required:["title"]}}}execute(e,r){let n=E(r,"title");if(!n)return Promise.resolve({output:"Error: 'title' is required",isError:!0});let o=this.mgr.getTaskStore(this.teamName);if(!o)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let s=o.create(n,E(r,"description"),E(r,"assignee"),Vr(r.blocks),Vr(r.blocked_by),this.agentName);return Promise.resolve({output:`Task created:
97
97
  ID: ${s.id}
98
98
  Title: ${s.title}
99
99
  Status: ${s.status}
100
100
  Assignee: ${s.assignee||"(unassigned)"}`,isError:!1})}},vo=class{constructor(e,r){this.mgr=e;this.teamName=r}mgr;teamName;name="TaskGet";description="Get details of a shared task by ID, including dependency information.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{task_id:{type:"string",description:"ID of the task to fetch"}},required:["task_id"]}}}execute(e,r){let n=E(r,"task_id");if(!n)return Promise.resolve({output:"Error: 'task_id' is required",isError:!0});let o=this.mgr.getTaskStore(this.teamName);if(!o)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let s=o.get(n);if(!s)return Promise.resolve({output:`Task '${n}' not found`,isError:!0});let i=[`Task ${s.id}:`,` Title: ${s.title}`,` Status: ${s.status}`,` Assignee: ${s.assignee||"(unassigned)"}`,` Created by: ${s.createdBy||"(unknown)"}`];return s.description&&i.push(` Description: ${s.description}`),s.blocks.length&&i.push(` Blocks: ${s.blocks.join(", ")}`),s.blockedBy.length&&i.push(` Blocked by: ${s.blockedBy.join(", ")}`),Promise.resolve({output:i.join(`
101
101
  `),isError:!1})}},bo=class{constructor(e,r){this.mgr=e;this.teamName=r}mgr;teamName;name="TaskList";description="List all shared tasks in the team's task board. Optionally filter by status (pending/in_progress/completed/blocked) or assignee.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{status:{type:"string",description:"Filter by status"},assignee:{type:"string",description:"Filter by assignee name"}},required:[]}}}execute(e,r){let n=this.mgr.getTaskStore(this.teamName);if(!n)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let o=E(r,"status")||void 0,s=E(r,"assignee")||void 0,i=n.listTasks(o,s);if(i.length===0){let u=[];o&&u.push(`status=${o}`),s&&u.push(`assignee=${s}`);let l=u.length?` (filters: ${u.join(", ")})`:"";return Promise.resolve({output:`No tasks found${l}`,isError:!1})}let a={pending:"\u25CB",in_progress:"\u25D0",completed:"\u25CF",blocked:"\u2715"},c=[`Tasks (${String(i.length)}):`];for(let u of i){let l=a[u.status]??"?",d=u.assignee?` [${u.assignee}]`:"",m=u.blockedBy.length?` (blocked by: ${u.blockedBy.join(", ")})`:"";c.push(` ${l} [${u.id}] ${u.title}${d}${m}`)}return Promise.resolve({output:c.join(`
102
- `),isError:!1})}},So=class{constructor(e,r){this.mgr=e;this.teamName=r}mgr;teamName;name="TaskUpdate";description="Update a shared task's status, assignee, description, or dependencies. Use add_blocks/add_blocked_by to add dependency relations.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{task_id:{type:"string",description:"ID of the task to update"},status:{type:"string",description:"New status: pending/in_progress/completed/blocked"},assignee:{type:"string",description:"Teammate name to assign"},description:{type:"string",description:"New description"},add_blocks:{type:"array",items:{type:"string"},description:"Task IDs to add to the blocks list"},add_blocked_by:{type:"array",items:{type:"string"},description:"Task IDs to add to the blocked_by list"}},required:["task_id"]}}}execute(e,r){let n=E(r,"task_id");if(!n)return Promise.resolve({output:"Error: 'task_id' is required",isError:!0});let o=E(r,"status");if(o&&!Lg.has(o))return Promise.resolve({output:`Invalid status '${o}'. Must be one of: blocked, completed, in_progress, pending`,isError:!0});let s=this.mgr.getTaskStore(this.teamName);if(!s)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let i=[],a={};o&&(a.status=o,i.push(`status \u2192 ${o}`)),typeof r.assignee=="string"&&(a.assignee=r.assignee,i.push(`assignee \u2192 ${a.assignee||"(unassigned)"}`)),typeof r.description=="string"&&(a.description=r.description,i.push("description updated"));let c=Wr(r.add_blocks);c.length&&(a.addBlocks=c,i.push(`blocks += ${c.join(", ")}`));let u=Wr(r.add_blocked_by);u.length&&(a.addBlockedBy=u,i.push(`blocked_by += ${u.join(", ")}`));let l=s.update(n,a);return l?Promise.resolve({output:`Task ${l.id} updated: ${i.length?i.join("; "):"no changes"}`,isError:!1}):Promise.resolve({output:`Task '${n}' not found`,isError:!0})}};import{exec as Ug}from"child_process";import{access as Fg,cp as ai,mkdir as Hg,readFile as or,stat as mu,symlink as Wg}from"fs/promises";import{dirname as Vg,isAbsolute as fu,join as de}from"path";import{promisify as Bg}from"util";var $e=C({module:"worktree"}),Qe=Bg(Ug),Gg=/^[a-zA-Z0-9/._+@-]+$/,ci=/^[0-9a-f]{40}([0-9a-f]{24})?$/;function li(t){if(!t||t.startsWith("-")||t.startsWith("/")||t.includes(".."))return!1;let e=t.split("/");for(let r of e)if(r==="."||r==="")return!1;return Gg.test(t)}async function sr(t){try{return await Fg(t),!0}catch(e){return $e.error({err:e},"worktree operation failed"),!1}}async function Kg(t){try{let e=de(t,"commondir"),r=(await or(e,"utf-8")).trim();return fu(r)?r:de(t,r)}catch(e){return $e.error({err:e},"worktree operation failed"),""}}async function Zg(t){let e;try{e=(await or(de(t,"HEAD"),"utf-8")).trim()}catch(r){return $e.error({err:r},"worktree operation failed"),null}if(e.startsWith("ref:")){let r=e.slice(4).trim();if(r.startsWith("refs/heads/")){let o=r.slice(11);return li(o)?{branch:o}:null}if(!li(r))return null;let n=await di(t,r);return n?{sha:n}:null}return ci.test(e)?{sha:e}:null}async function pu(t,e){try{let r=(await or(de(t,e),"utf-8")).trim();if(r.startsWith("ref:")){let n=r.slice(4).trim();return li(n)?await di(t,n):""}return ci.test(r)?r:""}catch(r){$e.error({err:r},"worktree operation failed")}try{let r=await or(de(t,"packed-refs"),"utf-8");for(let n of r.split(`
103
- `)){if(!n||n.startsWith("#")||n.startsWith("^"))continue;let o=n.indexOf(" ");if(o!==-1&&n.slice(o+1)===e){let s=n.slice(0,o);return ci.test(s)?s:""}}}catch(r){$e.error({err:r},"worktree operation failed")}return""}async function di(t,e){let r=await pu(t,e);if(r)return r;let n=await Kg(t);return n&&n!==t?pu(n,e):""}async function ui(t){let e;try{e=(await or(de(t,".git"),"utf-8")).trim()}catch(s){return $e.error({err:s},"worktree operation failed"),""}if(!e.startsWith("gitdir:"))return"";let r=e.slice(7).trim(),n=fu(r)?r:de(t,r),o=await Zg(n);return o?o.branch?di(n,"refs/heads/"+o.branch):o.sha??"":""}async function Vr(t,e){let r=e??(await Qe("git rev-parse --show-toplevel")).stdout.trim(),n=de(r,".swifty","worktrees",t),o=`worktree-${t}`;if(await sr(n)){let a=await ui(n);if(a)return{path:n,branch:o,headCommit:a,gitRoot:r};let{stdout:c}=await Qe("git rev-parse HEAD",{cwd:n});return{path:n,branch:o,headCommit:c.trim(),gitRoot:r}}await Qe(`git worktree add -B "${o}" "${n}"`,{cwd:r}),await Jg(r,n);let s=await ui(n);if(s)return{path:n,branch:o,headCommit:s,gitRoot:r};let{stdout:i}=await Qe("git rev-parse HEAD",{cwd:n});return{path:n,branch:o,headCommit:i.trim(),gitRoot:r}}async function hu(t,e,r){try{await Qe(`git worktree remove "${t}" --force`,{cwd:r})}catch(n){$e.error({err:n},"worktree operation failed")}try{await Qe(`git branch -D "${e}"`,{cwd:r})}catch(n){$e.error({err:n},"worktree operation failed")}}async function gu(t,e){try{let{stdout:r}=await Qe("git status --porcelain",{cwd:t});return r.trim()?!0:(await ui(t)||(await Qe("git rev-parse HEAD",{cwd:t})).stdout.trim())!==e}catch(r){return $e.error({err:r},"worktree operation failed"),!0}}function pi(t,e){return`You are working in a git worktree at: ${e}
102
+ `),isError:!1})}},So=class{constructor(e,r){this.mgr=e;this.teamName=r}mgr;teamName;name="TaskUpdate";description="Update a shared task's status, assignee, description, or dependencies. Use add_blocks/add_blocked_by to add dependency relations.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{task_id:{type:"string",description:"ID of the task to update"},status:{type:"string",description:"New status: pending/in_progress/completed/blocked"},assignee:{type:"string",description:"Teammate name to assign"},description:{type:"string",description:"New description"},add_blocks:{type:"array",items:{type:"string"},description:"Task IDs to add to the blocks list"},add_blocked_by:{type:"array",items:{type:"string"},description:"Task IDs to add to the blocked_by list"}},required:["task_id"]}}}execute(e,r){let n=E(r,"task_id");if(!n)return Promise.resolve({output:"Error: 'task_id' is required",isError:!0});let o=E(r,"status");if(o&&!Fg.has(o))return Promise.resolve({output:`Invalid status '${o}'. Must be one of: blocked, completed, in_progress, pending`,isError:!0});let s=this.mgr.getTaskStore(this.teamName);if(!s)return Promise.resolve({output:`Task store not found for team '${this.teamName}'`,isError:!0});let i=[],a={};o&&(a.status=o,i.push(`status \u2192 ${o}`)),typeof r.assignee=="string"&&(a.assignee=r.assignee,i.push(`assignee \u2192 ${a.assignee||"(unassigned)"}`)),typeof r.description=="string"&&(a.description=r.description,i.push("description updated"));let c=Vr(r.add_blocks);c.length&&(a.addBlocks=c,i.push(`blocks += ${c.join(", ")}`));let u=Vr(r.add_blocked_by);u.length&&(a.addBlockedBy=u,i.push(`blocked_by += ${u.join(", ")}`));let l=s.update(n,a);return l?Promise.resolve({output:`Task ${l.id} updated: ${i.length?i.join("; "):"no changes"}`,isError:!1}):Promise.resolve({output:`Task '${n}' not found`,isError:!0})}};import{exec as Hg}from"child_process";import{access as Vg,cp as ci,mkdir as Wg,readFile as or,stat as mu,symlink as Bg}from"fs/promises";import{dirname as Gg,isAbsolute as fu,join as de}from"path";import{promisify as Kg}from"util";var $e=C({module:"worktree"}),Qe=Kg(Hg),Zg=/^[a-zA-Z0-9/._+@-]+$/,li=/^[0-9a-f]{40}([0-9a-f]{24})?$/;function ui(t){if(!t||t.startsWith("-")||t.startsWith("/")||t.includes(".."))return!1;let e=t.split("/");for(let r of e)if(r==="."||r==="")return!1;return Zg.test(t)}async function sr(t){try{return await Vg(t),!0}catch(e){return $e.error({err:e},"worktree operation failed"),!1}}async function Jg(t){try{let e=de(t,"commondir"),r=(await or(e,"utf-8")).trim();return fu(r)?r:de(t,r)}catch(e){return $e.error({err:e},"worktree operation failed"),""}}async function Yg(t){let e;try{e=(await or(de(t,"HEAD"),"utf-8")).trim()}catch(r){return $e.error({err:r},"worktree operation failed"),null}if(e.startsWith("ref:")){let r=e.slice(4).trim();if(r.startsWith("refs/heads/")){let o=r.slice(11);return ui(o)?{branch:o}:null}if(!ui(r))return null;let n=await pi(t,r);return n?{sha:n}:null}return li.test(e)?{sha:e}:null}async function pu(t,e){try{let r=(await or(de(t,e),"utf-8")).trim();if(r.startsWith("ref:")){let n=r.slice(4).trim();return ui(n)?await pi(t,n):""}return li.test(r)?r:""}catch(r){$e.error({err:r},"worktree operation failed")}try{let r=await or(de(t,"packed-refs"),"utf-8");for(let n of r.split(`
103
+ `)){if(!n||n.startsWith("#")||n.startsWith("^"))continue;let o=n.indexOf(" ");if(o!==-1&&n.slice(o+1)===e){let s=n.slice(0,o);return li.test(s)?s:""}}}catch(r){$e.error({err:r},"worktree operation failed")}return""}async function pi(t,e){let r=await pu(t,e);if(r)return r;let n=await Jg(t);return n&&n!==t?pu(n,e):""}async function di(t){let e;try{e=(await or(de(t,".git"),"utf-8")).trim()}catch(s){return $e.error({err:s},"worktree operation failed"),""}if(!e.startsWith("gitdir:"))return"";let r=e.slice(7).trim(),n=fu(r)?r:de(t,r),o=await Yg(n);return o?o.branch?pi(n,"refs/heads/"+o.branch):o.sha??"":""}async function Wr(t,e){let r=e??(await Qe("git rev-parse --show-toplevel")).stdout.trim(),n=de(r,".swifty","worktrees",t),o=`worktree-${t}`;if(await sr(n)){let a=await di(n);if(a)return{path:n,branch:o,headCommit:a,gitRoot:r};let{stdout:c}=await Qe("git rev-parse HEAD",{cwd:n});return{path:n,branch:o,headCommit:c.trim(),gitRoot:r}}await Qe(`git worktree add -B "${o}" "${n}"`,{cwd:r}),await Xg(r,n);let s=await di(n);if(s)return{path:n,branch:o,headCommit:s,gitRoot:r};let{stdout:i}=await Qe("git rev-parse HEAD",{cwd:n});return{path:n,branch:o,headCommit:i.trim(),gitRoot:r}}async function hu(t,e,r){try{await Qe(`git worktree remove "${t}" --force`,{cwd:r})}catch(n){$e.error({err:n},"worktree operation failed")}try{await Qe(`git branch -D "${e}"`,{cwd:r})}catch(n){$e.error({err:n},"worktree operation failed")}}async function gu(t,e){try{let{stdout:r}=await Qe("git status --porcelain",{cwd:t});return r.trim()?!0:(await di(t)||(await Qe("git rev-parse HEAD",{cwd:t})).stdout.trim())!==e}catch(r){return $e.error({err:r},"worktree operation failed"),!0}}function mi(t,e){return`You are working in a git worktree at: ${e}
104
104
  The parent project is at: ${t}
105
- Changes made here are isolated from the parent working tree.`}async function Jg(t,e){await Yg(t,e),await Xg(t,e),await Qg(t,e),await ey(t,e)}async function Yg(t,e){try{let r=de(t,".swifty");if(!await sr(r))return;let n=de(e,".swifty");await ai(r,n,{recursive:!0})}catch(r){$e.error({err:r},"failed to copy .swifty/ to worktree")}}async function Xg(t,e){try{let r=[de(t,".husky"),de(t,".git","hooks")],n;for(let o of r)try{if((await mu(o)).isDirectory()){n=o;break}}catch(s){$e.error({err:s},"worktree operation failed")}if(!n)return;await Qe(`git config core.hooksPath "${n}"`,{cwd:e})}catch(r){$e.error({err:r},"failed to configure hooks path in worktree")}}async function Qg(t,e){try{let r=de(t,"node_modules");if(!await sr(r))return;let n=de(e,"node_modules");if(await sr(n))return;await Wg(r,n)}catch(r){console.error(`Warning: failed to symlink node_modules in worktree: ${N(r)}`)}}async function ey(t,e){try{let r=de(t,".worktreeinclude");if(!await sr(r))return;let o=(await or(r,"utf-8")).split(`
106
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));for(let s of o)if(!s.includes(".."))try{let i=de(t,s);if(!await sr(i))continue;let a=de(e,s);await Hg(Vg(a),{recursive:!0}),(await mu(i)).isDirectory()?await ai(i,a,{recursive:!0}):await ai(i,a)}catch(i){$e.error({err:i},"worktree operation failed")}}catch(r){$e.error({err:r},"failed to process .worktreeinclude")}}import{readdirSync as ty,readFileSync as ry,existsSync as ny}from"fs";import{homedir as oy}from"os";import{join as mi}from"path";var _u=C({module:"subagent"});function wu(t){let e=[...du],r=oy();r&&yu(mi(r,".swifty","agents"),e);let n=[mi(t,".swifty","agents")];for(let o of n)yu(o,e);return e}function yu(t,e){if(!ny(t))return;let r=ty(t).filter(n=>n.endsWith(".md"));for(let n of r)try{let o=ry(mi(t,n),"utf-8"),s=iy(o);if(s){let i=e.findIndex(a=>a.name===s.name);i>=0?e[i]=s:e.push(s)}}catch(o){_u.error({err:o},"subagent operation failed");continue}}var sy=_.looseObject({name:_.string(),description:_.string().optional(),tools:_.array(_.string()).optional(),disallowed_tools:_.array(_.string()).optional(),system_prompt:_.string().optional(),max_turns:_.number().optional(),model:_.string().optional(),background:_.boolean().optional(),isolation:_.literal("worktree").optional()});function iy(t){if(!t.startsWith("---"))return null;let e=t.indexOf("---",3);if(e===-1)return null;let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(sy,o);return{name:s.name,description:s.description??n.slice(0,200),tools:s.tools,disallowedTools:s.disallowed_tools,systemPromptOverride:s.system_prompt,maxTurns:s.max_turns,model:s.model,background:s.background,isolation:s.isolation,initialPrompt:n}}catch(o){return _u.error({err:o},"subagent operation failed"),null}}var cy=C({module:"subagent"}),ly="general-purpose";function vu(){return`agent-a${ay(4).toString("hex").slice(0,7)}`}var Su="<fork_boilerplate>",uy="agent:builtin:fork",dy=`${Su}
105
+ Changes made here are isolated from the parent working tree.`}async function Xg(t,e){await Qg(t,e),await ey(t,e),await ty(t,e),await ry(t,e)}async function Qg(t,e){try{let r=de(t,".swifty");if(!await sr(r))return;let n=de(e,".swifty");await ci(r,n,{recursive:!0})}catch(r){$e.error({err:r},"failed to copy .swifty/ to worktree")}}async function ey(t,e){try{let r=[de(t,".husky"),de(t,".git","hooks")],n;for(let o of r)try{if((await mu(o)).isDirectory()){n=o;break}}catch(s){$e.error({err:s},"worktree operation failed")}if(!n)return;await Qe(`git config core.hooksPath "${n}"`,{cwd:e})}catch(r){$e.error({err:r},"failed to configure hooks path in worktree")}}async function ty(t,e){try{let r=de(t,"node_modules");if(!await sr(r))return;let n=de(e,"node_modules");if(await sr(n))return;await Bg(r,n)}catch(r){console.error(`Warning: failed to symlink node_modules in worktree: ${N(r)}`)}}async function ry(t,e){try{let r=de(t,".worktreeinclude");if(!await sr(r))return;let o=(await or(r,"utf-8")).split(`
106
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));for(let s of o)if(!s.includes(".."))try{let i=de(t,s);if(!await sr(i))continue;let a=de(e,s);await Wg(Gg(a),{recursive:!0}),(await mu(i)).isDirectory()?await ci(i,a,{recursive:!0}):await ci(i,a)}catch(i){$e.error({err:i},"worktree operation failed")}}catch(r){$e.error({err:r},"failed to process .worktreeinclude")}}import{readdirSync as ny,readFileSync as oy,existsSync as sy}from"fs";import{homedir as iy}from"os";import{join as fi}from"path";var _u=C({module:"subagent"});function wu(t){let e=[...du],r=iy();r&&yu(fi(r,".swifty","agents"),e);let n=[fi(t,".swifty","agents")];for(let o of n)yu(o,e);return e}function yu(t,e){if(!sy(t))return;let r=ny(t).filter(n=>n.endsWith(".md"));for(let n of r)try{let o=oy(fi(t,n),"utf-8"),s=cy(o);if(s){let i=e.findIndex(a=>a.name===s.name);i>=0?e[i]=s:e.push(s)}}catch(o){_u.error({err:o},"subagent operation failed");continue}}var ay=_.looseObject({name:_.string(),description:_.string().optional(),tools:_.array(_.string()).optional(),disallowed_tools:_.array(_.string()).optional(),system_prompt:_.string().optional(),max_turns:_.number().optional(),model:_.string().optional(),background:_.boolean().optional(),isolation:_.literal("worktree").optional()});function cy(t){if(!t.startsWith("---"))return null;let e=t.indexOf("---",3);if(e===-1)return null;let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(ay,o);return{name:s.name,description:s.description??n.slice(0,200),tools:s.tools,disallowedTools:s.disallowed_tools,systemPromptOverride:s.system_prompt,maxTurns:s.max_turns,model:s.model,background:s.background,isolation:s.isolation,initialPrompt:n}}catch(o){return _u.error({err:o},"subagent operation failed"),null}}var uy=C({module:"subagent"}),dy="general-purpose";function vu(){return`agent-a${ly(4).toString("hex").slice(0,7)}`}var Su="<fork_boilerplate>",py="agent:builtin:fork",my=`${Su}
107
107
  You are a forked worker process. You are NOT the main agent.
108
108
  Rules (non-negotiable):
109
109
  1. Do NOT fork again.
@@ -129,23 +129,23 @@ Example call shape:
129
129
  }
130
130
 
131
131
  Write a detailed prompt explaining what the subagent should do and why \u2014 it has no prior context.
132
- When tasks are independent, launch multiple subagents in parallel by making multiple Agent tool calls in a single response.`,e}async execute(e,r){let n=E(r,"description"),o=E(r,"prompt");if(!n||!o)return{output:"Error: description and prompt are required",isError:!0};let s=E(r,"subagent_type")||(this.forkDisabled?ly:""),i=E(r,"model"),a=lo(r,"run_in_background"),c=E(r,"team_name"),u=E(r,"isolation");if(c&&this.teamManager&&this.teamRunAgentFactory)return await this.runAsTeammate(c,n,o,r.plan_mode_required===!0,u==="worktree");if(!s)return this.runFork(o,n,i);let l=this.definitions.find(f=>f.name===s);if(!l)return{output:`Error: unknown agent type '${s}'. Available: ${this.definitions.map(f=>f.name).join(", ")}`,isError:!0};let d=o,m;if(u==="worktree"||l.isolation==="worktree")try{let f=await Vr(vu());m=f.path,d=`${pi(this.workDir,f.path)}
132
+ When tasks are independent, launch multiple subagents in parallel by making multiple Agent tool calls in a single response.`,e}async execute(e,r){let n=E(r,"description"),o=E(r,"prompt");if(!n||!o)return{output:"Error: description and prompt are required",isError:!0};let s=E(r,"subagent_type")||(this.forkDisabled?dy:""),i=E(r,"model"),a=lo(r,"run_in_background"),c=E(r,"team_name"),u=E(r,"isolation");if(c&&this.teamManager&&this.teamRunAgentFactory)return await this.runAsTeammate(c,n,o,r.plan_mode_required===!0,u==="worktree");if(!s)return this.runFork(o,n,i);let l=this.definitions.find(f=>f.name===s);if(!l)return{output:`Error: unknown agent type '${s}'. Available: ${this.definitions.map(f=>f.name).join(", ")}`,isError:!0};let d=o,m;if(u==="worktree"||l.isolation==="worktree")try{let f=await Wr(vu());m=f.path,d=`${mi(this.workDir,f.path)}
133
133
 
134
- ${o}`}catch(f){return{output:`Error creating agent worktree: ${N(f)}`,isError:!0}}try{return{output:await this.spawnHandler(l,d,a||!!l.background,i,m),isError:!1}}catch(f){return{output:`Agent error: ${N(f)}`,isError:!0}}}async runAsTeammate(e,r,n,o,s){if(!this.teamManager)return{output:`Error: team manager '${e}' not found.`,isError:!0};let i=this.teamManager.get(e)??this.teamManager.create(e,void 0,{leadAgentId:"lead",description:r}),a=r.replace(/\s+/g,"-").toLowerCase().slice(0,30),c=2,u=a;for(;i.getMember(a);)a=`${u}-${String(c++)}`;let l=new po;for(let g of this.registry.listTools())Ul.has(g.name)||Fl.has(g.name)||l.register(g);l.register(new _o(this.teamManager,a)),l.register(new wo(this.teamManager,e,a)),l.register(new vo(this.teamManager,e)),l.register(new bo(this.teamManager,e)),l.register(new So(this.teamManager,e));let d=o?new tr(this.workDir,"plan"):void 0,m=n;if(s)try{let g=await Vr(vu());i.setMemberMeta(a,{worktreePath:g.path}),m=`${pi(this.workDir,g.path)}
134
+ ${o}`}catch(f){return{output:`Error creating agent worktree: ${N(f)}`,isError:!0}}try{return{output:await this.spawnHandler(l,d,a||!!l.background,i,m),isError:!1}}catch(f){return{output:`Agent error: ${N(f)}`,isError:!0}}}async runAsTeammate(e,r,n,o,s){if(!this.teamManager)return{output:`Error: team manager '${e}' not found.`,isError:!0};let i=this.teamManager.get(e)??this.teamManager.create(e,void 0,{leadAgentId:"lead",description:r}),a=r.replace(/\s+/g,"-").toLowerCase().slice(0,30),c=2,u=a;for(;i.getMember(a);)a=`${u}-${String(c++)}`;let l=new po;for(let g of this.registry.listTools())Ul.has(g.name)||Fl.has(g.name)||l.register(g);l.register(new _o(this.teamManager,a)),l.register(new wo(this.teamManager,e,a)),l.register(new vo(this.teamManager,e)),l.register(new bo(this.teamManager,e)),l.register(new So(this.teamManager,e));let d=o?new tr(this.workDir,"plan"):void 0,m=n;if(s)try{let g=await Wr(vu());i.setMemberMeta(a,{worktreePath:g.path}),m=`${mi(this.workDir,g.path)}
135
135
 
136
136
  ${n}`}catch(g){return{output:`Error creating teammate worktree: ${N(g)}`,isError:!0}}let f=this.teamRunAgentFactory?.(l,d);return f&&i.spawnTeammate(a,m,f,d),{output:`Teammate '${a}' spawned in team '${e}' (mode: ${i.mode})${o?", starting in plan mode":""}.
137
- The teammate is now working on the assigned task.`,isError:!1}}async runFork(e,r,n){if(!this.conversation||!this.forkHandler)return{output:"Error: fork requires parent conversation context",isError:!0};if(this.querySource===uy)return{output:"Error: cannot fork from a forked agent. Use subagent_type to spawn a definition-based agent instead.",isError:!0};for(let o of this.conversation.getMessages())if(o.content.includes(Su))return{output:"Error: cannot fork from a forked agent. Use subagent_type to spawn a definition-based agent instead.",isError:!0};try{let{cloneRegistryForFork:o}=await import("./tool-filter-ERUPKZYV.js"),s=o(this.registry);return await this.forkHandler(`${dy}
137
+ The teammate is now working on the assigned task.`,isError:!1}}async runFork(e,r,n){if(!this.conversation||!this.forkHandler)return{output:"Error: fork requires parent conversation context",isError:!0};if(this.querySource===py)return{output:"Error: cannot fork from a forked agent. Use subagent_type to spawn a definition-based agent instead.",isError:!0};for(let o of this.conversation.getMessages())if(typeof o.content=="string"&&o.content.includes(Su))return{output:"Error: cannot fork from a forked agent. Use subagent_type to spawn a definition-based agent instead.",isError:!0};try{let{cloneRegistryForFork:o}=await import("./tool-filter-ERUPKZYV.js"),s=o(this.registry);return await this.forkHandler(`${my}
138
138
 
139
139
  Your task:
140
- ${e}`,this.conversation,s,n),{output:`Forked agent "${r}" launched in background. Results will arrive via task-notification.`,isError:!1}}catch(o){return cy.error({err:o},"subagent operation failed"),{output:`Fork error: ${N(o)}`,isError:!0}}}};var py={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6-20250514",opus:"claude-opus-4-6-20250514"};function ku(t){return py[t]??t}async function HP(t,e,r,n,o,s,i,a,c,u){let l=c??t.model,d=l?ku(l):o.model,m=Ql(s);m.model=d;let f=t.systemPromptOverride??eu(m),g=l?await ni({...o,model:d},f):r,h=Hl(n,t.tools,t.disallowedTools,!1),y=t.permissionMode??"acceptEdits",v=u??new tr(s,y),$=new er;$.addUserMessage(e);let k=new uo({client:g,registry:h,checker:v,conversation:$,workDir:s,maxIterations:t.maxTurns??200}),z="",w=0;for await(let b of k.run())switch(b.type){case"stream_text":z+=b.text;break;case"tool_use":i?.({lastTool:b.toolName}),a?.({type:"tool_use",toolName:b.toolName,args:b.args});break;case"usage":a?.({type:"usage",usage:{inputTokens:b.usage.inputTokens,outputTokens:b.usage.outputTokens}});break;case"turn_complete":i?.({turn:++w});break;case"loop_complete":return z||"[No output]";case"error":return z?`${z}
140
+ ${e}`,this.conversation,s,n),{output:`Forked agent "${r}" launched in background. Results will arrive via task-notification.`,isError:!1}}catch(o){return uy.error({err:o},"subagent operation failed"),{output:`Fork error: ${N(o)}`,isError:!0}}}};var fy={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6-20250514",opus:"claude-opus-4-6-20250514"};function ku(t){return fy[t]??t}async function QP(t,e,r,n,o,s,i,a,c,u){let l=c??t.model,d=l?ku(l):o.model,m=Ql(s);m.model=d;let f=t.systemPromptOverride??eu(m),g=l?await oi({...o,model:d},f):r,h=Hl(n,t.tools,t.disallowedTools,!1),y=t.permissionMode??"acceptEdits",v=u??new tr(s,y),S=new er;S.addUserMessage(e);let T=new uo({client:g,registry:h,checker:v,conversation:S,workDir:s,maxIterations:t.maxTurns??200}),z="",w=0;for await(let b of T.run())switch(b.type){case"stream_text":z+=b.text;break;case"tool_use":i?.({lastTool:b.toolName}),a?.({type:"tool_use",toolName:b.toolName,args:b.args});break;case"usage":a?.({type:"usage",usage:{inputTokens:b.usage.inputTokens,outputTokens:b.usage.outputTokens}});break;case"turn_complete":i?.({turn:++w});break;case"loop_complete":return z||"[No output]";case"error":return z?`${z}
141
141
 
142
- [Error: ${b.error.message}]`:`Error: ${b.error.message}`}return z||"[No output]"}var my=new Set(["Agent","SendMessage","TaskStop","SyntheticOutput","TeamDelete"]);function fy(t){return my.has(t)}function VP(t=!1){return t?fy:()=>!0}function BP(t=!1){return t}var Tu=class{constructor(e){this.teamManager=e}teamManager;name="TaskStop";description="Stop a running teammate. Pass the teammate name as it appears in the from= field of a team-notification. Use this when you sent a teammate in the wrong direction \u2014 for example when the user changes requirements after you launched it.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{teammate:{type:"string",description:"Name of the teammate to stop, exactly as it appears in the from= field of a team-notification"}},required:["teammate"]}}}async execute(e,r){let n=E(r,"teammate","");if(!n)return{output:"Error: teammate is required",isError:!0};for(let o of this.teamManager.list()){let s=o.members.get(n);if(s)return s.active?(await o.stopMember(n),{output:`Teammate '${n}' in team '${o.name}' stopped.`,isError:!1}):{output:`Teammate '${n}' in team '${o.name}' is not running, nothing to stop`,isError:!1}}return{output:`Error: teammate '${n}' not found. Known teammates: ${this.knownMembers()}`,isError:!0}}knownMembers(){let e=[];for(let r of this.teamManager.list())for(let n of r.members.keys())e.push(n);return e.length>0?e.join(", "):"(none)"}};import{mkdirSync as o_,readFileSync as s_,rmSync as i_}from"fs";import{join as _i}from"path";var xu=["Accomplishing","Architecting","Baking","Be-bopping'","Befuddling","Boogieing","Boondoggling","Bootstrapping","Brewing","Calculating","Canoodling","Caramelizing","Cascading","Cerebrating","Choreographing","Churning","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Dilly-dallying","Discombobulating","Doodling","Elucidating","Enchanting","Envisioning","Fermenting","Finagling","Flamb\xE9ing","Flummoxing","Forging","Frolicking","Gallivanting","Garnishing","Generating","Germinating","Grooving","Harmonizing","Hatching","Honking","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Kneading","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Mewing","Moonwalking","Moseying","Mulling","Musing","Noodling","Orbiting","Orchestrating","Percolating","Philosophizing","Pondering","Pontificating","Pouncing","Purring","Puzzling","Razzle-dazzling","Ruminating","Scampering","Simmering","Sketching","Spelunking","Spinning","Sprouting","Synthesizing","Thinking","Tinkering","Transfiguring","Transmuting","Undulating","Unfurling","Unravelling","Vibing","Wandering","Whisking","Working","Wrangling","Zigzagging"];function fi(){return xu[Math.floor(Math.random()*xu.length)]}var $u=["Accomplished","Baked","Brewed","Cooked","Crafted","Crunched","Forged","Hatched","Pondered","Synthesized","Tinkered","Worked","Wrangled","Computed","Created","Composed","Conjured","Concocted","Cultivated","Deciphered"];function JP(){return $u[Math.floor(Math.random()*$u.length)]}import{execSync as ko,spawn as hy}from"child_process";var Eu=C({module:"teams"});function Ru(){return process.platform==="win32"?"in-process":gy()}function gy(){return process.env.TMUX?"tmux":process.env.ITERM_SESSION_ID?"iterm":"in-process"}function Cu(t){return/^[A-Za-z0-9_/.:=-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Pu(t){return[t.command,...t.args].map(Cu).join(" ")}function Mu(t){switch(t.mode){case"in-process":{let e=hy(t.command,t.args,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:{...process.env,...t.env}});return{cancel:()=>e.kill("SIGTERM")}}case"tmux":{let e=`swifty-${Date.now().toString(36)}`,r=Pu(t);try{ko(`tmux new-window -t "${e}" -n teammate "${r}"`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(n){Eu.error({err:n},"teams operation failed"),ko(`tmux new-session -d -s "${e}" -n teammate "${r}"`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}return{cancel:()=>{try{ko(`tmux kill-session -t "${e}"`,{stdio:["pipe","pipe","pipe"]})}catch(n){Eu.error({err:n},"teams operation failed")}},paneId:e}}case"iterm":{let e=Pu(t),s=['tell application "iTerm2"'," tell current window"," create tab with default profile",` tell current session to write text "${`cd ${Cu(t.cwd)} && ${e}`.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`," end tell","end tell"].map(i=>`-e '${i.replace(/'/g,"'\\''")}'`).join(" ");return ko(`osascript ${s}`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),{cancel:()=>{}}}default:throw new Error(`Unknown team mode: ${String(t.mode)}`)}}import{readFileSync as yy,writeFileSync as _y,mkdirSync as wy,existsSync as vy,unlinkSync as Au,statSync as by,openSync as Sy,closeSync as ky}from"fs";import{join as Ty}from"path";var Br=C({module:"teams"}),xy=_.object({from:_.string(),text:_.string(),timestamp:_.string(),read:_.boolean().optional(),type:_.string().optional(),requestId:_.string().optional(),approve:_.boolean().optional()}),zu=5e3,$y=1e4,Ey=5,Py=80,Ry=_.looseObject({errno:_.number().optional(),code:_.string().optional(),path:_.string().optional(),syscall:_.string().optional()});function Cy(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function My(t){let e=Date.now()+zu,r=Ey;for(;;)try{let n=Sy(t,"wx");ky(n);return}catch(n){Br.error({err:n},"teams operation failed");let{data:o,success:s}=Cl(Ry,n),i="";if(s&&o.code&&(i=o.code),i!=="EEXIST")throw n;try{let a=by(t);if(Date.now()-a.mtimeMs>$y)try{Au(t);continue}catch(c){Br.error({err:c},"teams operation failed")}}catch(a){Br.error({err:a},"teams operation failed")}if(Date.now()>=e)throw new Error(`mailbox lock ${t}: timed out after ${String(zu)}ms, message not written`);Cy(r+Math.floor(Math.random()*r)),r=Math.min(r*2,Py)}}function zy(t){try{Au(t)}catch(e){Br.error({err:e},"teams operation failed")}}function hi(t,e){let r=t+".lock";My(r);try{return e()}finally{zy(r)}}var Gr=class{filePath;constructor(e,r){wy(e,{recursive:!0}),this.filePath=Ty(e,`${r}.json`)}readAll(){if(!vy(this.filePath))return[];try{let e=JSON.parse(yy(this.filePath,"utf-8")),r=[];if(Array.isArray(e))for(let n of e){let o=xy.safeParse(n);o.success&&r.push(o.data)}return r}catch(e){return Br.error({err:e},"teams operation failed"),[]}}writeAll(e){_y(this.filePath,JSON.stringify(e,null,2),"utf-8")}async send(e,r,n){let o=n??{from:e,text:r,timestamp:new Date().toISOString()};return o.read=!1,hi(this.filePath,()=>{let s=this.readAll();s.push(o),this.writeAll(s)}),Promise.resolve()}receiveSync(){return hi(this.filePath,()=>{let e=this.readAll(),r=e.filter(n=>!n.read);if(r.length>0){for(let n of e)n.read=!0;this.writeAll(e)}return r})}async receive(){return Promise.resolve(this.receiveSync())}unreadCount(){return this.readAll().filter(e=>!e.read).length}markAllRead(){hi(this.filePath,()=>{let e=this.readAll(),r=!1;for(let n of e)n.read||(n.read=!0,r=!0);r&&this.writeAll(e)})}async*poll(e=1e3){for(;;){let r=await this.receive();for(let n of r)yield n;await new Promise(n=>setTimeout(n,e))}}};var Iu=A.object({toolName:A.string(),input:A.record(A.string(),A.unknown()),activityDescription:A.string()}),Ay=A.object({toolUseCount:A.number(),tokenCount:A.number(),lastActivity:Iu.optional(),recentActivities:A.array(Iu)}),cR=A.object({name:A.string(),teamName:A.string(),status:A.enum(["running","idle","completed","failed","stopped"]),progress:Ay,startTime:A.number(),spinnerVerb:A.string(),lastMessage:A.string().optional()});function gi(){return{toolUseCount:0,tokenCount:0,lastActivity:void 0,recentActivities:[]}}function Ou(t,e,r){t.toolUseCount++;let n=Iy(e,r),o={toolName:e,input:r,activityDescription:n};t.lastActivity=o,t.recentActivities.push(o),t.recentActivities.length>5&&t.recentActivities.shift()}function ju(t,e,r){t.tokenCount=e+r}function Iy(t,e){switch(t){case"ReadFile":return`Reading ${E(e,"file_path","file")}`;case"EditFile":return`Editing ${E(e,"file_path","file")}`;case"WriteFile":return`Writing ${E(e,"file_path","file")}`;case"Bash":{let r=E(e,"command","");return`Running ${r.length>40?r.slice(0,40)+"...":r}`}case"Glob":return`Searching ${E(e,"pattern","files")}`;case"Grep":return`Grepping ${E(e,"pattern","pattern")}`;default:return t}}function lR(t){return t.length?t[t.length-1].activityDescription:""}function uR(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}import{readFileSync as Oy,writeFileSync as jy,mkdirSync as Ny,existsSync as qy}from"fs";import{dirname as Dy}from"path";var Ly=_.object({id:_.string(),title:_.string(),description:_.string().default(""),status:_.string().default("pending"),assignee:_.string().default(""),blocks:_.array(_.string()).default([]),blocked_by:_.array(_.string()).default([]),created_by:_.string().default("")}),Uy=_.object({next_id:_.number().int().positive().default(1),tasks:_.array(Ly).default([])}),Kr=class{path;nextId=1;tasks=[];constructor(e){this.path=e,this.load()}load(){if(qy(this.path))try{let e=JSON.parse(Oy(this.path,"utf-8")),r=xe(Uy,e);this.nextId=r.next_id,this.tasks=r.tasks.map(n=>({id:n.id,title:n.title,description:n.description,status:n.status,assignee:n.assignee,blocks:n.blocks,blockedBy:n.blocked_by,createdBy:n.created_by}))}catch{}}save(){Ny(Dy(this.path),{recursive:!0});let e={next_id:this.nextId,tasks:this.tasks.map(r=>({id:r.id,title:r.title,description:r.description,status:r.status,assignee:r.assignee,blocks:r.blocks,blocked_by:r.blockedBy,created_by:r.createdBy}))};jy(this.path,JSON.stringify(e,null,2),"utf-8")}create(e,r="",n="",o=[],s=[],i=""){let a={id:String(this.nextId++),title:e,description:r,status:"pending",assignee:n,blocks:[...o],blockedBy:[...s],createdBy:i};return this.tasks.push(a),this.save(),a}get(e){return this.load(),this.tasks.find(r=>r.id===e)}listTasks(e,r){return this.load(),this.tasks.filter(n=>!(e&&n.status!==e||r&&n.assignee!==r))}update(e,r){this.load();let n=this.tasks.find(o=>o.id===e);if(n){r.status!==void 0&&(n.status=r.status),r.assignee!==void 0&&(n.assignee=r.assignee),r.description!==void 0&&(n.description=r.description);for(let o of r.addBlocks??[])n.blocks.includes(o)||n.blocks.push(o);for(let o of r.addBlockedBy??[])n.blockedBy.includes(o)||n.blockedBy.push(o);return this.save(),n}}initEmpty(){this.tasks=[],this.nextId=1,this.save()}};import{existsSync as Fy,mkdirSync as Hy,readFileSync as Wy,writeFileSync as Vy}from"fs";import{homedir as By}from"os";import{dirname as Gy,join as yi}from"path";var Ky=_.object({agentId:_.string(),name:_.string(),agentType:_.string().optional(),model:_.string().optional(),joinedAt:_.number(),worktreePath:_.string().optional(),backendType:_.string().optional(),isActive:_.boolean().optional()}),Zy=_.object({name:_.string(),description:_.string().optional(),createdAt:_.number(),leadAgentId:_.string(),members:_.array(Ky)});function Jy(){return yi(By(),".swifty","teams")}function Yy(t){return t.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}function Zr(t){return yi(Jy(),Yy(t))}function Nu(t){return yi(Zr(t),"config.json")}function qu(t){let e=Nu(t);if(!Fy(e))return null;try{let r=JSON.parse(Wy(e,"utf-8"));return Zy.parse(r)}catch{return null}}function Du(t,e){try{let r=Nu(t);Hy(Gy(r),{recursive:!0}),Vy(r,JSON.stringify(e,null,2),"utf-8")}catch{}}import{mkdirSync as Xy,readFileSync as SR,writeFileSync as Qy,existsSync as kR}from"fs";import{join as Lu}from"path";var ER=C({module:"teams"}),e_=_.object({tool_use_id:_.string(),tool_name:_.string(),arguments:_.record(_.string(),_.unknown())}),t_=_.object({tool_use_id:_.string(),content:_.string(),is_error:_.boolean().optional()}),PR=_.object({role:_.string(),content:_.string().optional(),tool_uses:_.array(e_).optional(),tool_results:_.array(t_).optional()});function r_(t){let e=[];for(let r of t.getMessages()){let n={role:r.role,content:r.content};r.toolUses&&r.toolUses.length>0&&(n.tool_uses=r.toolUses.map(o=>({tool_use_id:o.toolUseId,tool_name:o.toolName,arguments:o.arguments}))),r.toolResults&&r.toolResults.length>0&&(n.tool_results=r.toolResults.map(o=>({tool_use_id:o.toolUseId,content:o.content,is_error:o.isError||void 0}))),e.push(n)}return e}function n_(t,e){return Lu(t,".swifty","teams",e,"transcripts")}function Uu(t,e,r,n){let o=n_(t,e);Xy(o,{recursive:!0});let s=Lu(o,`${r}.json`),i=r_(n);return Qy(s,JSON.stringify(i,null,2),"utf-8"),s}var Fu=C({module:"teams"}),To=class t{name;mode;members=new Map;leadMailbox;mailboxDir;workDir;leadAgentId="";description;createdAt=Math.floor(Date.now()/1e3);constructor(e,r,n){this.name=e,this.mode=r,this.workDir=n,this.mailboxDir=_i(Zr(e),"inboxes"),o_(this.mailboxDir,{recursive:!0}),this.leadMailbox=new Gr(this.mailboxDir,"lead")}addMember(e){let r=new Gr(this.mailboxDir,e),n={name:e,active:!1,mailbox:r,agentId:e,joinedAt:Math.floor(Date.now()/1e3)};return this.members.set(e,n),this.persist(),n}setMemberMeta(e,r){let n=this.members.get(e);n&&(n.agentType=r.agentType,n.model=r.model,n.worktreePath=r.worktreePath,this.persist())}snapshot(){return{name:this.name,description:this.description,createdAt:this.createdAt,leadAgentId:this.leadAgentId,members:[...this.members.values()].map(e=>({agentId:e.agentId??e.name,name:e.name,agentType:e.agentType,model:e.model,joinedAt:e.joinedAt??0,worktreePath:e.worktreePath,backendType:this.mode,isActive:e.active}))}}persist(){Du(this.name,this.snapshot())}static IDLE_POLL_INTERVAL_MS=500;static SHUTDOWN_PREFIX="[shutdown]";spawnTeammate(e,r,n,o){if(this.mode==="in-process"){this.spawnInProcess(e,r,n,o);return}try{this.spawnExternal(e,r)}catch{this.spawnInProcess(e,r,n,o)}}spawnExternal(e,r){let n=this.addMember(e);n.active=!0,nr().register(e,e),n.uiState={name:e,teamName:this.name,status:"running",progress:gi(),startTime:Date.now(),spinnerVerb:fi()};let o=process.argv[1]??"src/main.tsx",s={mode:this.mode,command:"bun",args:["run",o,"--teammate","--team-dir",this.mailboxDir,"--team-name",this.name,"--member-name",e,"--task",r],cwd:this.workDir},{cancel:i,paneId:a}=Mu(s);n.cancel=i,n.paneId=a,n.external=!0}spawnInProcess(e,r,n,o){let s=this.addMember(e);s.active=!0,s.checker=o,nr().register(e,e);let i={name:e,teamName:this.name,status:"running",progress:gi(),startTime:Date.now(),spinnerVerb:fi()};s.uiState=i;let a=c=>{switch(c.type){case"tool_use":c.toolName&&c.args&&Ou(i.progress,c.toolName,c.args);break;case"usage":c.usage&&ju(i.progress,c.usage.inputTokens,c.usage.outputTokens);break;case"stream_text":c.text&&(i.lastMessage=c.text);break}};(async()=>{let c=r,u="available";try{for(;s.active;){i.status="running";let l=await n(c,a);if(i.lastMessage=l.length>200?l.slice(0,200)+"...":l,s.checker?.mode==="plan"){i.status="idle";let m=await this.runPlanApproval(s,this.readPlanForReview());if(m===null)break;c=m;continue}i.status="idle",await this.leadMailbox.send(e,`[idle] ${e} (reason: ${u})`),u="available";let d=await this.waitForNextPromptOrShutdown(s);if(d.shutdown||!s.active){let m=d.shutdown;if(m?.type===Ct){let f=yo(s.name,m.requestId??"",!0,"acknowledged, shutting down");await this.leadMailbox.send(s.name,f.text,f)}break}c=d.prompt}i.status="completed"}catch(l){Fu.error({err:l},"teams operation failed"),i.status="failed",i.lastMessage=N(l),await this.leadMailbox.send(e,`[idle] ${e} (reason: failed)`)}finally{if(s.active=!1,i.status==="running"&&(i.status="idle"),s.conversation)try{Uu(this.workDir,this.name,e,s.conversation)}catch(l){Fu.error({err:l},"teams operation failed")}}})()}async waitForNextPromptOrShutdown(e){for(;e.active;){await new Promise(s=>setTimeout(s,t.IDLE_POLL_INTERVAL_MS));let r=e.mailbox.receiveSync();if(r.length===0)continue;let n=r.find(s=>su(s));return n?{prompt:"",shutdown:n}:{prompt:`You have new messages from your team:
142
+ [Error: ${b.error.message}]`:`Error: ${b.error.message}`}return z||"[No output]"}var hy=new Set(["Agent","SendMessage","TaskStop","SyntheticOutput","TeamDelete"]);function gy(t){return hy.has(t)}function tR(t=!1){return t?gy:()=>!0}function rR(t=!1){return t}var Tu=class{constructor(e){this.teamManager=e}teamManager;name="TaskStop";description="Stop a running teammate. Pass the teammate name as it appears in the from= field of a team-notification. Use this when you sent a teammate in the wrong direction \u2014 for example when the user changes requirements after you launched it.";category="command";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{teammate:{type:"string",description:"Name of the teammate to stop, exactly as it appears in the from= field of a team-notification"}},required:["teammate"]}}}async execute(e,r){let n=E(r,"teammate","");if(!n)return{output:"Error: teammate is required",isError:!0};for(let o of this.teamManager.list()){let s=o.members.get(n);if(s)return s.active?(await o.stopMember(n),{output:`Teammate '${n}' in team '${o.name}' stopped.`,isError:!1}):{output:`Teammate '${n}' in team '${o.name}' is not running, nothing to stop`,isError:!1}}return{output:`Error: teammate '${n}' not found. Known teammates: ${this.knownMembers()}`,isError:!0}}knownMembers(){let e=[];for(let r of this.teamManager.list())for(let n of r.members.keys())e.push(n);return e.length>0?e.join(", "):"(none)"}};import{mkdirSync as i_,readFileSync as a_,rmSync as c_}from"fs";import{join as wi}from"path";var xu=["Accomplishing","Architecting","Baking","Be-bopping'","Befuddling","Boogieing","Boondoggling","Bootstrapping","Brewing","Calculating","Canoodling","Caramelizing","Cascading","Cerebrating","Choreographing","Churning","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Dilly-dallying","Discombobulating","Doodling","Elucidating","Enchanting","Envisioning","Fermenting","Finagling","Flamb\xE9ing","Flummoxing","Forging","Frolicking","Gallivanting","Garnishing","Generating","Germinating","Grooving","Harmonizing","Hatching","Honking","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Kneading","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Mewing","Moonwalking","Moseying","Mulling","Musing","Noodling","Orbiting","Orchestrating","Percolating","Philosophizing","Pondering","Pontificating","Pouncing","Purring","Puzzling","Razzle-dazzling","Ruminating","Scampering","Simmering","Sketching","Spelunking","Spinning","Sprouting","Synthesizing","Thinking","Tinkering","Transfiguring","Transmuting","Undulating","Unfurling","Unravelling","Vibing","Wandering","Whisking","Working","Wrangling","Zigzagging"];function hi(){return xu[Math.floor(Math.random()*xu.length)]}var $u=["Accomplished","Baked","Brewed","Cooked","Crafted","Crunched","Forged","Hatched","Pondered","Synthesized","Tinkered","Worked","Wrangled","Computed","Created","Composed","Conjured","Concocted","Cultivated","Deciphered"];function iR(){return $u[Math.floor(Math.random()*$u.length)]}import{execSync as ko,spawn as yy}from"child_process";var Eu=C({module:"teams"});function Ru(){return process.platform==="win32"?"in-process":_y()}function _y(){return process.env.TMUX?"tmux":process.env.ITERM_SESSION_ID?"iterm":"in-process"}function Cu(t){return/^[A-Za-z0-9_/.:=-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Pu(t){return[t.command,...t.args].map(Cu).join(" ")}function Mu(t){switch(t.mode){case"in-process":{let e=yy(t.command,t.args,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:{...process.env,...t.env}});return{cancel:()=>e.kill("SIGTERM")}}case"tmux":{let e=`swifty-${Date.now().toString(36)}`,r=Pu(t);try{ko(`tmux new-window -t "${e}" -n teammate "${r}"`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(n){Eu.error({err:n},"teams operation failed"),ko(`tmux new-session -d -s "${e}" -n teammate "${r}"`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}return{cancel:()=>{try{ko(`tmux kill-session -t "${e}"`,{stdio:["pipe","pipe","pipe"]})}catch(n){Eu.error({err:n},"teams operation failed")}},paneId:e}}case"iterm":{let e=Pu(t),s=['tell application "iTerm2"'," tell current window"," create tab with default profile",` tell current session to write text "${`cd ${Cu(t.cwd)} && ${e}`.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`," end tell","end tell"].map(i=>`-e '${i.replace(/'/g,"'\\''")}'`).join(" ");return ko(`osascript ${s}`,{cwd:t.cwd,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),{cancel:()=>{}}}default:throw new Error(`Unknown team mode: ${String(t.mode)}`)}}import{readFileSync as wy,writeFileSync as vy,mkdirSync as by,existsSync as Sy,unlinkSync as Au,statSync as ky,openSync as Ty,closeSync as xy}from"fs";import{join as $y}from"path";var Br=C({module:"teams"}),Ey=_.object({from:_.string(),text:_.string(),timestamp:_.string(),read:_.boolean().optional(),type:_.string().optional(),requestId:_.string().optional(),approve:_.boolean().optional()}),zu=5e3,Py=1e4,Ry=5,Cy=80,My=_.looseObject({errno:_.number().optional(),code:_.string().optional(),path:_.string().optional(),syscall:_.string().optional()});function zy(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Ay(t){let e=Date.now()+zu,r=Ry;for(;;)try{let n=Ty(t,"wx");xy(n);return}catch(n){Br.error({err:n},"teams operation failed");let{data:o,success:s}=Cl(My,n),i="";if(s&&o.code&&(i=o.code),i!=="EEXIST")throw n;try{let a=ky(t);if(Date.now()-a.mtimeMs>Py)try{Au(t);continue}catch(c){Br.error({err:c},"teams operation failed")}}catch(a){Br.error({err:a},"teams operation failed")}if(Date.now()>=e)throw new Error(`mailbox lock ${t}: timed out after ${String(zu)}ms, message not written`);zy(r+Math.floor(Math.random()*r)),r=Math.min(r*2,Cy)}}function Iy(t){try{Au(t)}catch(e){Br.error({err:e},"teams operation failed")}}function gi(t,e){let r=t+".lock";Ay(r);try{return e()}finally{Iy(r)}}var Gr=class{filePath;constructor(e,r){by(e,{recursive:!0}),this.filePath=$y(e,`${r}.json`)}readAll(){if(!Sy(this.filePath))return[];try{let e=JSON.parse(wy(this.filePath,"utf-8")),r=[];if(Array.isArray(e))for(let n of e){let o=Ey.safeParse(n);o.success&&r.push(o.data)}return r}catch(e){return Br.error({err:e},"teams operation failed"),[]}}writeAll(e){vy(this.filePath,JSON.stringify(e,null,2),"utf-8")}async send(e,r,n){let o=n??{from:e,text:r,timestamp:new Date().toISOString()};return o.read=!1,gi(this.filePath,()=>{let s=this.readAll();s.push(o),this.writeAll(s)}),Promise.resolve()}receiveSync(){return gi(this.filePath,()=>{let e=this.readAll(),r=e.filter(n=>!n.read);if(r.length>0){for(let n of e)n.read=!0;this.writeAll(e)}return r})}async receive(){return Promise.resolve(this.receiveSync())}unreadCount(){return this.readAll().filter(e=>!e.read).length}markAllRead(){gi(this.filePath,()=>{let e=this.readAll(),r=!1;for(let n of e)n.read||(n.read=!0,r=!0);r&&this.writeAll(e)})}async*poll(e=1e3){for(;;){let r=await this.receive();for(let n of r)yield n;await new Promise(n=>setTimeout(n,e))}}};var Iu=A.object({toolName:A.string(),input:A.record(A.string(),A.unknown()),activityDescription:A.string()}),Oy=A.object({toolUseCount:A.number(),tokenCount:A.number(),lastActivity:Iu.optional(),recentActivities:A.array(Iu)}),_R=A.object({name:A.string(),teamName:A.string(),status:A.enum(["running","idle","completed","failed","stopped"]),progress:Oy,startTime:A.number(),spinnerVerb:A.string(),lastMessage:A.string().optional()});function yi(){return{toolUseCount:0,tokenCount:0,lastActivity:void 0,recentActivities:[]}}function Ou(t,e,r){t.toolUseCount++;let n=jy(e,r),o={toolName:e,input:r,activityDescription:n};t.lastActivity=o,t.recentActivities.push(o),t.recentActivities.length>5&&t.recentActivities.shift()}function ju(t,e,r){t.tokenCount=e+r}function jy(t,e){switch(t){case"ReadFile":return`Reading ${E(e,"file_path","file")}`;case"EditFile":return`Editing ${E(e,"file_path","file")}`;case"WriteFile":return`Writing ${E(e,"file_path","file")}`;case"Bash":{let r=E(e,"command","");return`Running ${r.length>40?r.slice(0,40)+"...":r}`}case"Glob":return`Searching ${E(e,"pattern","files")}`;case"Grep":return`Grepping ${E(e,"pattern","pattern")}`;default:return t}}function wR(t){return t.length?t[t.length-1].activityDescription:""}function vR(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":String(t)}import{readFileSync as Ny,writeFileSync as qy,mkdirSync as Dy,existsSync as Ly}from"fs";import{dirname as Uy}from"path";var Fy=_.object({id:_.string(),title:_.string(),description:_.string().default(""),status:_.string().default("pending"),assignee:_.string().default(""),blocks:_.array(_.string()).default([]),blocked_by:_.array(_.string()).default([]),created_by:_.string().default("")}),Hy=_.object({next_id:_.number().int().positive().default(1),tasks:_.array(Fy).default([])}),Kr=class{path;nextId=1;tasks=[];constructor(e){this.path=e,this.load()}load(){if(Ly(this.path))try{let e=JSON.parse(Ny(this.path,"utf-8")),r=xe(Hy,e);this.nextId=r.next_id,this.tasks=r.tasks.map(n=>({id:n.id,title:n.title,description:n.description,status:n.status,assignee:n.assignee,blocks:n.blocks,blockedBy:n.blocked_by,createdBy:n.created_by}))}catch{}}save(){Dy(Uy(this.path),{recursive:!0});let e={next_id:this.nextId,tasks:this.tasks.map(r=>({id:r.id,title:r.title,description:r.description,status:r.status,assignee:r.assignee,blocks:r.blocks,blocked_by:r.blockedBy,created_by:r.createdBy}))};qy(this.path,JSON.stringify(e,null,2),"utf-8")}create(e,r="",n="",o=[],s=[],i=""){let a={id:String(this.nextId++),title:e,description:r,status:"pending",assignee:n,blocks:[...o],blockedBy:[...s],createdBy:i};return this.tasks.push(a),this.save(),a}get(e){return this.load(),this.tasks.find(r=>r.id===e)}listTasks(e,r){return this.load(),this.tasks.filter(n=>!(e&&n.status!==e||r&&n.assignee!==r))}update(e,r){this.load();let n=this.tasks.find(o=>o.id===e);if(n){r.status!==void 0&&(n.status=r.status),r.assignee!==void 0&&(n.assignee=r.assignee),r.description!==void 0&&(n.description=r.description);for(let o of r.addBlocks??[])n.blocks.includes(o)||n.blocks.push(o);for(let o of r.addBlockedBy??[])n.blockedBy.includes(o)||n.blockedBy.push(o);return this.save(),n}}initEmpty(){this.tasks=[],this.nextId=1,this.save()}};import{existsSync as Vy,mkdirSync as Wy,readFileSync as By,writeFileSync as Gy}from"fs";import{homedir as Ky}from"os";import{dirname as Zy,join as _i}from"path";var Jy=_.object({agentId:_.string(),name:_.string(),agentType:_.string().optional(),model:_.string().optional(),joinedAt:_.number(),worktreePath:_.string().optional(),backendType:_.string().optional(),isActive:_.boolean().optional()}),Yy=_.object({name:_.string(),description:_.string().optional(),createdAt:_.number(),leadAgentId:_.string(),members:_.array(Jy)});function Xy(){return _i(Ky(),".swifty","teams")}function Qy(t){return t.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}function Zr(t){return _i(Xy(),Qy(t))}function Nu(t){return _i(Zr(t),"config.json")}function qu(t){let e=Nu(t);if(!Vy(e))return null;try{let r=JSON.parse(By(e,"utf-8"));return Yy.parse(r)}catch{return null}}function Du(t,e){try{let r=Nu(t);Wy(Zy(r),{recursive:!0}),Gy(r,JSON.stringify(e,null,2),"utf-8")}catch{}}import{mkdirSync as e_,readFileSync as zR,writeFileSync as t_,existsSync as AR}from"fs";import{join as Lu}from"path";var qR=C({module:"teams"}),r_=_.object({tool_use_id:_.string(),tool_name:_.string(),arguments:_.record(_.string(),_.unknown())}),n_=_.object({tool_use_id:_.string(),content:_.string(),is_error:_.boolean().optional()}),DR=_.object({role:_.string(),content:_.string().optional(),tool_uses:_.array(r_).optional(),tool_results:_.array(n_).optional()});function o_(t){let e=[];for(let r of t.getMessages()){let n={role:r.role,content:ri(r.content)};r.toolUses&&r.toolUses.length>0&&(n.tool_uses=r.toolUses.map(o=>({tool_use_id:o.toolUseId,tool_name:o.toolName,arguments:o.arguments}))),r.toolResults&&r.toolResults.length>0&&(n.tool_results=r.toolResults.map(o=>({tool_use_id:o.toolUseId,content:ri(o.content),is_error:o.isError||void 0}))),e.push(n)}return e}function s_(t,e){return Lu(t,".swifty","teams",e,"transcripts")}function Uu(t,e,r,n){let o=s_(t,e);e_(o,{recursive:!0});let s=Lu(o,`${r}.json`),i=o_(n);return t_(s,JSON.stringify(i,null,2),"utf-8"),s}var Fu=C({module:"teams"}),To=class t{name;mode;members=new Map;leadMailbox;mailboxDir;workDir;leadAgentId="";description;createdAt=Math.floor(Date.now()/1e3);constructor(e,r,n){this.name=e,this.mode=r,this.workDir=n,this.mailboxDir=wi(Zr(e),"inboxes"),i_(this.mailboxDir,{recursive:!0}),this.leadMailbox=new Gr(this.mailboxDir,"lead")}addMember(e){let r=new Gr(this.mailboxDir,e),n={name:e,active:!1,mailbox:r,agentId:e,joinedAt:Math.floor(Date.now()/1e3)};return this.members.set(e,n),this.persist(),n}setMemberMeta(e,r){let n=this.members.get(e);n&&(n.agentType=r.agentType,n.model=r.model,n.worktreePath=r.worktreePath,this.persist())}snapshot(){return{name:this.name,description:this.description,createdAt:this.createdAt,leadAgentId:this.leadAgentId,members:[...this.members.values()].map(e=>({agentId:e.agentId??e.name,name:e.name,agentType:e.agentType,model:e.model,joinedAt:e.joinedAt??0,worktreePath:e.worktreePath,backendType:this.mode,isActive:e.active}))}}persist(){Du(this.name,this.snapshot())}static IDLE_POLL_INTERVAL_MS=500;static SHUTDOWN_PREFIX="[shutdown]";spawnTeammate(e,r,n,o){if(this.mode==="in-process"){this.spawnInProcess(e,r,n,o);return}try{this.spawnExternal(e,r)}catch{this.spawnInProcess(e,r,n,o)}}spawnExternal(e,r){let n=this.addMember(e);n.active=!0,nr().register(e,e),n.uiState={name:e,teamName:this.name,status:"running",progress:yi(),startTime:Date.now(),spinnerVerb:hi()};let o=process.argv[1]??"src/main.tsx",s={mode:this.mode,command:"bun",args:["run",o,"--teammate","--team-dir",this.mailboxDir,"--team-name",this.name,"--member-name",e,"--task",r],cwd:this.workDir},{cancel:i,paneId:a}=Mu(s);n.cancel=i,n.paneId=a,n.external=!0}spawnInProcess(e,r,n,o){let s=this.addMember(e);s.active=!0,s.checker=o,nr().register(e,e);let i={name:e,teamName:this.name,status:"running",progress:yi(),startTime:Date.now(),spinnerVerb:hi()};s.uiState=i;let a=c=>{switch(c.type){case"tool_use":c.toolName&&c.args&&Ou(i.progress,c.toolName,c.args);break;case"usage":c.usage&&ju(i.progress,c.usage.inputTokens,c.usage.outputTokens);break;case"stream_text":c.text&&(i.lastMessage=c.text);break}};(async()=>{let c=r,u="available";try{for(;s.active;){i.status="running";let l=await n(c,a);if(i.lastMessage=l.length>200?l.slice(0,200)+"...":l,s.checker?.mode==="plan"){i.status="idle";let m=await this.runPlanApproval(s,this.readPlanForReview());if(m===null)break;c=m;continue}i.status="idle",await this.leadMailbox.send(e,`[idle] ${e} (reason: ${u})`),u="available";let d=await this.waitForNextPromptOrShutdown(s);if(d.shutdown||!s.active){let m=d.shutdown;if(m?.type===Ct){let f=yo(s.name,m.requestId??"",!0,"acknowledged, shutting down");await this.leadMailbox.send(s.name,f.text,f)}break}c=d.prompt}i.status="completed"}catch(l){Fu.error({err:l},"teams operation failed"),i.status="failed",i.lastMessage=N(l),await this.leadMailbox.send(e,`[idle] ${e} (reason: failed)`)}finally{if(s.active=!1,i.status==="running"&&(i.status="idle"),s.conversation)try{Uu(this.workDir,this.name,e,s.conversation)}catch(l){Fu.error({err:l},"teams operation failed")}}})()}async waitForNextPromptOrShutdown(e){for(;e.active;){await new Promise(s=>setTimeout(s,t.IDLE_POLL_INTERVAL_MS));let r=e.mailbox.receiveSync();if(r.length===0)continue;let n=r.find(s=>su(s));return n?{prompt:"",shutdown:n}:{prompt:`You have new messages from your team:
143
143
 
144
144
  ${r.map(s=>`From ${s.from}: ${s.text}`).join(`
145
145
 
146
- `)}`}}return{prompt:"",shutdown:go("lead","member deactivated")}}readPlanForReview(){try{let e=s_(Ll(this.workDir),"utf-8");if(e.trim())return e}catch{}return"(Plan file is empty \u2014 the teammate may not have written the plan as expected)"}async runPlanApproval(e,r){let n=nu(e.name,r);for(await this.leadMailbox.send(e.name,n.text,n);e.active;){await new Promise(o=>setTimeout(o,t.IDLE_POLL_INTERVAL_MS));for(let o of e.mailbox.receiveSync())if(o.type===rr&&o.requestId===n.requestId)return si(o)&&e.checker&&(e.checker.mode="default"),si(o)?"The Lead has approved your plan. Begin execution now.":`The Lead rejected your plan. Feedback: ${o.text}
147
- Please revise the plan accordingly and resubmit.`}return null}getMember(e){return this.members.get(e)}async sendMessage(e,r,n){let o=this.members.get(r);if(!o)throw new Error(`Member '${r}' not found in team '${this.name}'`);await o.mailbox.send(e,n)}async stopMember(e){let r=this.members.get(e);r&&(await this.stopOne(r),this.persist())}async stopAll(){for(let e of this.members.values())await this.stopOne(e)}async stopOne(e){if(e.active=!1,e.uiState?.status==="running"&&(e.uiState.status="stopped"),e.external)try{await e.mailbox.send("lead",`${t.SHUTDOWN_PREFIX} stop`)}catch{}e.cancel?.()}listMembers(){return[...this.members.values()]}getTeammateStates(){return this.listMembers().filter(e=>e.uiState).map(e=>e.uiState)}},Hu=class{teams=new Map;workDir;taskStores=new Map;constructor(e){this.workDir=e}teamDir(e){return Zr(e)}create(e,r=Ru(),n={}){let o=new To(e,r,this.workDir);o.leadAgentId=n.leadAgentId??"",o.description=n.description,this.teams.set(e,o);let s=new Kr(_i(this.teamDir(e),"tasks.json"));return s.initEmpty(),this.taskStores.set(e,s),o.persist(),o}get(e){let r=this.teams.get(e);if(r)return r;let n=qu(e);if(!n)return;let o=n.members.find(i=>i.backendType)?.backendType,s=new To(n.name,a_(o)?o:"in-process",this.workDir);s.leadAgentId=n.leadAgentId,s.description=n.description,s.createdAt=n.createdAt;for(let i of n.members){let a=s.addMember(i.name);a.agentId=i.agentId,a.agentType=i.agentType,a.model=i.model,a.worktreePath=i.worktreePath,a.joinedAt=i.joinedAt,a.active=i.isActive===!0}return this.teams.set(e,s),s}getTaskStore(e){let r=this.taskStores.get(e);if(r)return r;let n=new Kr(_i(this.teamDir(e),"tasks.json"));return this.taskStores.set(e,n),n}list(){return[...this.teams.values()]}async delete(e){let r=this.teams.get(e);if(r){let n=nr();for(let o of r.listMembers())n.unregister(o.name);await r.stopAll(),this.teams.delete(e)}this.taskStores.delete(e),i_(Zr(e),{recursive:!0,force:!0})}getAllTeammateStates(){return this.list().flatMap(e=>e.getTeammateStates())}drainLeads(){let e=[];for(let r of this.teams.values()){let n=r.leadMailbox.receiveSync();if(n.length===0)continue;let o=[];o.push(`<task-notification team="${r.name}">`);for(let s of n)o.push(`from=${s.from}: ${s.text}`);o.push("</task-notification>"),e.push(o.join(`
148
- `))}return e}};function a_(t){return t==="in-process"||t==="tmux"||t==="iterm"}import{spawnSync as c_}from"child_process";var Wu=`
146
+ `)}`}}return{prompt:"",shutdown:go("lead","member deactivated")}}readPlanForReview(){try{let e=a_(Ll(this.workDir),"utf-8");if(e.trim())return e}catch{}return"(Plan file is empty \u2014 the teammate may not have written the plan as expected)"}async runPlanApproval(e,r){let n=nu(e.name,r);for(await this.leadMailbox.send(e.name,n.text,n);e.active;){await new Promise(o=>setTimeout(o,t.IDLE_POLL_INTERVAL_MS));for(let o of e.mailbox.receiveSync())if(o.type===rr&&o.requestId===n.requestId)return ii(o)&&e.checker&&(e.checker.mode="default"),ii(o)?"The Lead has approved your plan. Begin execution now.":`The Lead rejected your plan. Feedback: ${o.text}
147
+ Please revise the plan accordingly and resubmit.`}return null}getMember(e){return this.members.get(e)}async sendMessage(e,r,n){let o=this.members.get(r);if(!o)throw new Error(`Member '${r}' not found in team '${this.name}'`);await o.mailbox.send(e,n)}async stopMember(e){let r=this.members.get(e);r&&(await this.stopOne(r),this.persist())}async stopAll(){for(let e of this.members.values())await this.stopOne(e)}async stopOne(e){if(e.active=!1,e.uiState?.status==="running"&&(e.uiState.status="stopped"),e.external)try{await e.mailbox.send("lead",`${t.SHUTDOWN_PREFIX} stop`)}catch{}e.cancel?.()}listMembers(){return[...this.members.values()]}getTeammateStates(){return this.listMembers().filter(e=>e.uiState).map(e=>e.uiState)}},Hu=class{teams=new Map;workDir;taskStores=new Map;constructor(e){this.workDir=e}teamDir(e){return Zr(e)}create(e,r=Ru(),n={}){let o=new To(e,r,this.workDir);o.leadAgentId=n.leadAgentId??"",o.description=n.description,this.teams.set(e,o);let s=new Kr(wi(this.teamDir(e),"tasks.json"));return s.initEmpty(),this.taskStores.set(e,s),o.persist(),o}get(e){let r=this.teams.get(e);if(r)return r;let n=qu(e);if(!n)return;let o=n.members.find(i=>i.backendType)?.backendType,s=new To(n.name,l_(o)?o:"in-process",this.workDir);s.leadAgentId=n.leadAgentId,s.description=n.description,s.createdAt=n.createdAt;for(let i of n.members){let a=s.addMember(i.name);a.agentId=i.agentId,a.agentType=i.agentType,a.model=i.model,a.worktreePath=i.worktreePath,a.joinedAt=i.joinedAt,a.active=i.isActive===!0}return this.teams.set(e,s),s}getTaskStore(e){let r=this.taskStores.get(e);if(r)return r;let n=new Kr(wi(this.teamDir(e),"tasks.json"));return this.taskStores.set(e,n),n}list(){return[...this.teams.values()]}async delete(e){let r=this.teams.get(e);if(r){let n=nr();for(let o of r.listMembers())n.unregister(o.name);await r.stopAll(),this.teams.delete(e)}this.taskStores.delete(e),c_(Zr(e),{recursive:!0,force:!0})}getAllTeammateStates(){return this.list().flatMap(e=>e.getTeammateStates())}drainLeads(){let e=[];for(let r of this.teams.values()){let n=r.leadMailbox.receiveSync();if(n.length===0)continue;let o=[];o.push(`<task-notification team="${r.name}">`);for(let s of n)o.push(`from=${s.from}: ${s.text}`);o.push("</task-notification>"),e.push(o.join(`
148
+ `))}return e}};function l_(t){return t==="in-process"||t==="tmux"||t==="iterm"}import{statSync as f_}from"fs";import{join as h_,resolve as g_}from"path";import{existsSync as u_}from"fs";import{createRequire as d_}from"module";import{fileURLToPath as Vu}from"url";var p_=d_(import.meta.url);function m_(){let t=[new URL("../build/Release/glob_addon.node",import.meta.url),new URL("./glob_addon.node",import.meta.url)];for(let e of t){let r=Vu(e);if(u_(r))return p_(r)}throw new Error(`@swifty.js/glob-addon: glob_addon.node not found (searched: ${t.map(e=>Vu(e)).join(", ")})`)}var Wu=m_(),ir=class{pattern;dot;constructor(e,r){this.pattern=e,this.dot=r?.dot??!1}match(e){return Wu.globMatch(this.pattern,e)}scan(e){return Wu.globScan(this.pattern,e?.cwd??null,e?.exclude??null,e?.dot??this.dot,e?.maxResults??null)}};var Bu=`
149
149
  Execute a shell command and return stdout and stderr.
150
150
 
151
151
  IMPORTANT: Avoid using this tool to run cat, head, tail, sed, awk or echo commands. Instead use the dedicated ReadFile, EditFile, or WriteFile tools which provide a better experience.
@@ -167,7 +167,7 @@ Git Safety Protocol
167
167
 
168
168
  Avoiding unnecessary sleep commands. Do NOT retry failing commands in a sleep loop -- diagnose the root cause instead.
169
169
  When using find, search from "." or a specific path, not "/" -- scanning the full filesystem is too expensive.
170
- `,Vu=`
170
+ `,Gu=`
171
171
  Read a file and return its contents with line numbers.
172
172
 
173
173
  Usage Notes
@@ -178,8 +178,8 @@ Usage Notes
178
178
  - Results are returned with line numbers (1-based) for easy reference.
179
179
  - This tool can only read files, not directories. Use glob to list directory contents.
180
180
  - Do NOT re-read a file you just edited to verify -- EditFile would have errored if the change failed.
181
- - This tool can read image files, supported types: image/png, image/jpeg, image/gif, and image/webp. The image contents are returned visually, so line numbers do NOT apply.
182
- `,Bu=`
181
+ - This tool can read image files (png, jpg, jpeg, gif, webp). Image contents are returned as visual content for multimodal analysis. Line numbers and offset/limit parameters do NOT apply to image files.
182
+ `,Ku=`
183
183
  Replace an extract string in a file, The old_string MUST appear exactly once in the file.
184
184
 
185
185
  Usage Notes
@@ -190,7 +190,7 @@ Usage Notes
190
190
  - The edit will FAIL if old_string is not unique in the file, provide more surrounding context to make it unique.
191
191
  - Use the smallest old_string that is clearly unique -- 2-4 adjacent lines is usually sufficient.
192
192
  - The new_string MUST be different from old_string.
193
- `,Gu=`
193
+ `,Zu=`
194
194
  Write content to a file, creating parent directories if needed. Overwrites existing files.
195
195
 
196
196
  Usage Notes
@@ -199,64 +199,66 @@ Usage Notes
199
199
  - Use this tool only to create new files or for complete rewrites.
200
200
  - You MUST read existing files with ReadFile before overwriting them.
201
201
  - NEVER create documentation files (*.md) or README files unless explicitly requested.
202
- `,Ku=`
203
- File files matching a glob pattern, returning relative paths sorted alphabetically.
202
+ `,Ju=`
203
+ Find files matching a glob pattern, returning relative paths sorted by modification time (newest first).
204
204
 
205
205
  Usage Notes
206
206
 
207
- - Supports patterns like "**/*.ts", "**/*.go".
207
+ - Supports patterns like "**/*.ts", "src/js/*.js", "*.{ts,tsx}".
208
208
  - Search from "." or a specific path, never from "/".
209
209
  - Automatically skips .git, node_modules, __pycache__, and similar directories.
210
210
  - Use this instead of find or ls command via Bash.
211
- `,Zu=`
212
- Search file content using a regex pattern, returning file:line:content matches.
211
+ `,Yu=`
212
+ Search file content using a regex pattern (case-insensitive), returning file:line:content matches.
213
213
 
214
214
  Usage Notes
215
215
 
216
216
  - Supports full regex syntax (e.g., "log.*Error", "func\\s+\\w+").
217
- - Filter files with the include parameter (e.g., "*.ts", "*.go").
218
- - Search from ". or a specific path, never from "/".
217
+ - Filter files with the include parameter (e.g., "*.ts", "*.{ts,tsx}", "src/**/*.js").
218
+ - Include patterns containing "/" match the path relative to the working directory; bare patterns like "*.ts" match file names at any depth.
219
+ - Search from "." or a specific path, never from "/".
219
220
  - Automatically skips .git, node_modules, __pycache__, and similar directories.
220
221
  - Use this instead of grep or rg commands via Bash.
221
- `;var xo=new Set([".claude",".git",".swifty",".next",".venv",".mypy_cache",".tox","__pycache__","build","dist","node_modules","vendor","venv"]);var Ju=600;function l_(t){let r=(t.split("|").pop()?.trim()??t).split(/\s+/);for(let n of r)if(!(n.includes("=")&&!n.startsWith("-")))return n.split("/").pop()??n;return""}var u_=new Map([["grep",new Map([[1,"no matches found"]])],["egrep",new Map([[1,"no matches found"]])],["fgrep",new Map([[1,"no matches found"]])],["rg",new Map([[1,"no matches found"]])],["diff",new Map([[1,"files differ"]])],["test",new Map([[1,"condition is false"]])],["[",new Map([[1,"condition is false"]])],["find",new Map([[1,"partial success"]])]]);function d_(t,e){let r=l_(t);return u_.get(r)?.get(e)??""}var Yu=class{name="Bash";description=Wu;category="command";sandbox=null;sandboxConfig={allowWrite:[],denyWrite:[],networkEnabled:!0};schema(){let e={type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"integer",description:"Timeout in seconds (max 600)",default:120}},required:["command"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"command");if(!n)return Promise.resolve({output:"Error: command is required",isError:!0});let o=Rt(r,"timeout",120);o>Ju&&(o=Ju);let s=n;this.sandbox?.available()&&(s=this.sandbox.wrap(n,this.sandboxConfig));let i=c_("bash",["-c",s],{cwd:e.workDir,timeout:o*1e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"],maxBuffer:10*1024*1024});if(i.error&&i.signal==="SIGTERM")return Promise.resolve({output:`Error: command timed out after ${String(o)}s`,isError:!0});if(i.error&&!i.stdout&&!i.stderr)return Promise.resolve({output:`Error executing command: ${i.error.message}`,isError:!0});let a=i.status??0,c=`$ ${n}
222
- `;if(i.stdout&&(c+=i.stdout),i.stderr&&(c+=i.stderr),a!==0){let u=d_(n,a);c+=u?`
223
- Exit code ${String(a)} (${u})`:`
224
- Exit code ${String(a)}`}return Promise.resolve({output:c,isError:!1})}};import{readFile as p_,writeFile as m_}from"fs/promises";function Xu(t,e){let r=t.split(`
222
+ `;var xo=new Set([".claude",".git",".swifty",".next",".venv",".mypy_cache",".tox","__pycache__","build","dist","node_modules","vendor","venv"]);var Xu=C({module:"tools"}),$o=class{name="Glob";description=Ju;category="read";schema(){let e={type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g., '**/*.ts', '**/*.go')"},path:{type:"string",description:"Base directory to search from",default:"."}},required:["pattern"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"pattern");if(!n)return Promise.resolve({output:"Error: pattern is required",isError:!0});let o=g_(e.workDir,E(r,"path",e.workDir)),s=1e3;try{let a=new ir(n).scan({cwd:o,exclude:[...xo],maxResults:s});if(a.length===0)return Promise.resolve({output:"No files matched the pattern.",isError:!1});let c=new Map;for(let l of a){let d=0;try{d=f_(h_(o,l)).mtimeMs}catch(m){Xu.debug({err:m,match:l},"stat failed while sorting glob results")}c.set(l,d)}a.sort((l,d)=>(c.get(d)??0)-(c.get(l)??0)||l.localeCompare(d));let u=a.join(`
223
+ `);return a.length>=s&&(u+=`
224
+ (Results limited to ${s} files. Use a more specific pattern.)`),Promise.resolve({output:u,isError:!1})}catch(i){return Xu.error({err:i},"tool operation failed"),Promise.resolve({output:`Error: ${N(i)}`,isError:!0})}}};import{readdir as y_,readFile as __,stat as Qu}from"fs/promises";import{join as w_,relative as ed,resolve as v_,sep as b_}from"path";var Jr=C({module:"tools"}),Yr=500,Eo=class{name="Grep";description=Yu;category="read";schema(){let e={type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search"},path:{type:"string",description:"Directory or file to search",default:"."},include:{type:"string",description:"File pattern filter (e.g., '*.ts', 'src/**/*.js')"}},required:["pattern"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"pattern");if(!n)return{output:"Error: pattern is required",isError:!0};let o=v_(e.workDir,E(r,"path",e.workDir)),s=E(r,"include"),i;try{i=new RegExp(n,"i")}catch(g){return Jr.error({err:g},"tool operation failed"),{output:`Error: invalid regex pattern: ${n}`,isError:!0}}let a=s?new ir(s):null,c=s.includes("/"),u=(g,h)=>{if(!a)return!0;let y=c?ed(e.workDir,g).split(b_).join("/"):h;return a.match(y)},l=[],d=async g=>{if(l.length>=Yr)return;let h;try{h=await y_(g)}catch(y){Jr.error({err:y},"tool operation failed");return}for(let y of h){if(l.length>=Yr)return;if(xo.has(y))continue;let v=w_(g,y),S;try{S=await Qu(v)}catch(T){Jr.error({err:T},"tool operation failed");continue}if(S.isDirectory())await d(v);else if(S.isFile()){if(!u(v,y))continue;await m(v)}}},m=async g=>{try{let y=(await __(g,"utf-8")).split(`
225
+ `),v=ed(e.workDir,g);for(let S=0;S<y.length&&l.length<Yr;S++)i.test(y[S])&&l.push(`${v}:${String(S+1)}:${y[S]}`)}catch(h){Jr.error({err:h},"tool operation failed")}};try{(await Qu(o)).isFile()?await m(o):await d(o)}catch(g){return Jr.error({err:g},"tool operation failed"),{output:`Error: ${N(g)}`,isError:!0}}if(l.length===0)return{output:"No matches found.",isError:!1};let f=l.join(`
226
+ `);return l.length>=Yr&&(f+=`
227
+
228
+ (results truncated at ${String(Yr)} matches)`),{output:f,isError:!1}}};import{execFile as S_}from"child_process";var td=600;function k_(t){let r=(t.split("|").pop()?.trim()??t).split(/\s+/);for(let n of r)if(!(n.includes("=")&&!n.startsWith("-")))return n.split("/").pop()??n;return""}var T_=new Map([["grep",new Map([[1,"no matches found"]])],["egrep",new Map([[1,"no matches found"]])],["fgrep",new Map([[1,"no matches found"]])],["rg",new Map([[1,"no matches found"]])],["diff",new Map([[1,"files differ"]])],["test",new Map([[1,"condition is false"]])],["[",new Map([[1,"condition is false"]])],["find",new Map([[1,"partial success"]])]]);function x_(t,e){let r=k_(t);return T_.get(r)?.get(e)??""}var rd=class{name="Bash";description=Bu;category="command";sandbox=null;sandboxConfig={allowWrite:[],denyWrite:[],networkEnabled:!0};schema(){let e={type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"integer",description:"Timeout in seconds (max 600)",default:120}},required:["command"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"command");if(!n)return Promise.resolve({output:"Error: command is required",isError:!0});let o=Rt(r,"timeout",120);o>td&&(o=td);let s=n;return this.sandbox?.available()&&(s=this.sandbox.wrap(n,this.sandboxConfig)),new Promise(i=>{S_("bash",["-c",s],{cwd:e.workDir,timeout:o*1e3,killSignal:"SIGTERM",encoding:"utf-8",maxBuffer:10*1024*1024,...e.abortSignal?{signal:e.abortSignal}:{}},(a,c,u)=>{if(a?.name==="AbortError"){i({output:"Error: command interrupted",isError:!0});return}if(a&&a.killed&&a.signal==="SIGTERM"){i({output:`Error: command timed out after ${String(o)}s`,isError:!0});return}if(a&&typeof a.code!="number"&&!c&&!u){i({output:`Error executing command: ${a.message}`,isError:!0});return}let l=a&&typeof a.code=="number"?a.code:0,d=`$ ${n}
229
+ `;if(c&&(d+=c),u&&(d+=u),l!==0){let m=x_(n,l);d+=m?`
230
+ Exit code ${String(l)} (${m})`:`
231
+ Exit code ${String(l)}`}i({output:d,isError:!1})})})}};import{readFile as $_,writeFile as E_}from"fs/promises";function nd(t,e){let r=t.split(`
225
232
  `),n=e.split(`
226
- `),o=0,s=Math.min(r.length,n.length);for(;o<s&&r[o]===n[o];)o++;let i=0,a=s-o;for(;i<a&&r[r.length-1-i]===n[n.length-1-i];)i++;let c=r.slice(o,r.length-i),u=n.slice(o,n.length-i),l=Math.max(0,o-3),d=r.slice(l,o),m=Math.min(r.length,r.length-i+3),f=r.slice(r.length-i,m),g=[],h=l+1,y=l+1,v=!1,$=(k,z,w)=>{if(g.length>=200){v=!0;return}g.push(`${k} ${String(z).padStart(4)} ${w}`)};for(let k of d)$(" ",h,k),h++,y++;for(let k of c)$("-",h,k),h++;for(let k of u)$("+",y,k),y++;for(let k of f)$(" ",h,k),h++,y++;return v&&g.push(` ... (diff truncated at ${String(200)} lines)`),{text:g.join(`
227
- `),additions:u.length,removals:c.length}}var Qu=C({module:"tools"}),$o=class{name="EditFile";description=Bu;category="write";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file"},old_string:{type:"string",description:"Exact string to find and replace"},new_string:{type:"string",description:"Replacement string"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"file_path"),o=E(r,"old_string"),s=E(r,"new_string"),i=lo(r,"replace_all");if(!n)return{output:"Error: file_path is required",isError:!0};if(!o)return{output:"Error: old_string is required",isError:!0};if(o===s)return{output:"Error: old_string and new_string MUST be different",isError:!0};if(e.fileStateCache){let l=e.fileStateCache.check(n);if(!l.ok)return{output:l.error,isError:!0}}e.fileHistory?.trackEdit(n);let a;try{a=await p_(n,"utf-8")}catch(l){return Qu.error({err:l},"tool operation failed"),{output:`Error reading file: ${N(l)}`,isError:!0}}let c=a.split(o).length-1;if(c===0)return{output:"Error: old_string not found in file",isError:!0};if(!i&&c>1)return{output:`Error: old_string found ${String(c)} times in file. It must be unique. Add more surrounding context, or set replace_all to true`,isError:!0};let u=i?a.replaceAll(o,s):a.replace(o,s);try{await m_(n,u,"utf-8"),e.fileStateCache?.update(n);let{text:l,additions:d,removals:m}=Xu(a,u);return{output:`${i&&c>1?`Updated ${n} with ${String(d)} addition${d===1?"":"s"} and ${String(m)} removal${m===1?"":"s"} (${String(c)} replacements)`:`Updated ${n} with ${String(d)} addition${d===1?"":"s"} and ${String(m)} removal${m===1?"":"s"}`}
228
- ${l}`,isError:!1}}catch(l){return Qu.error({err:l},"tool operation failed"),{output:`Error writing file: ${N(l)}`,isError:!0}}}};import{statSync as ed}from"fs";var td=C({module:"file-state-cache"}),rd=class{cache=new Map;record(e,r){this.cache.set(e,r)}check(e){let r=this.cache.get(e);if(r===void 0)return{ok:!1,error:"Error: file has not been read yet, read it first before editing."};let n;try{n=ed(e).mtimeMs}catch(o){return td.error({err:o},"file state cache operation failed"),{ok:!0}}return n>r?{ok:!1,error:"Error: file has been modified since last read, read it again before editing."}:{ok:!0}}update(e){let r;try{r=ed(e).mtimeMs}catch(n){td.error({err:n},"file state cache operation failed"),this.cache.delete(e);return}this.cache.set(e,r)}};import{statSync as sd}from"fs";import{join as id}from"path";import{readdir as f_}from"fs/promises";import{join as nd,relative as h_}from"path";var Eo=null,wi=null;async function od(){return Eo||(wi||(wi=import("./release-OQD3IZ5W.js").then(t=>(Eo=t.match,Eo))),wi)}var ir=class{pattern;dot;isFilenameOnly;constructor(e,r){this.pattern=e,this.dot=r?.dot??!1,this.isFilenameOnly=!e.includes("/")}async match(e){return(await od())(this.pattern,e)}async*scan(e){let r=e?.cwd??".",n=e?.exclude,o=await od();yield*this.walkDir(r,r,o,n)}async*walkDir(e,r,n,o){let s;try{s=await f_(e,{withFileTypes:!0})}catch{return}s.sort((i,a)=>i.name.localeCompare(a.name));for(let i of s){let a=i.name;if(i.isDirectory()){if(a.startsWith(".")||o&&o(a))continue;yield*this.walkDir(nd(e,a),r,n,o)}else if(i.isFile()){if(!this.dot&&a.startsWith("."))continue;let c=h_(r,nd(e,a)),u=this.isFilenameOnly?a:c;n(this.pattern,u)&&(yield c)}}}};var ad=C({module:"tools"}),Po=class{name="Glob";description=Ku;category="read";schema(){let e={type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g., '**/*.ts', '**/*.go')"},path:{type:"string",description:"Base directory to search from",default:"."}},required:["pattern"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"pattern");if(!n)return{output:"Error: pattern is required",isError:!0};let o=E(r,"path",e.workDir);try{let s=[],i=new ir(n);for await(let a of i.scan({cwd:o,exclude:c=>c.startsWith(".")||xo.has(c)}))if(s.push(a),s.length>=1e3)break;return s.sort((a,c)=>{try{let u=sd(id(o,a)).mtimeMs;return sd(id(o,c)).mtimeMs-u}catch(u){return ad.error({err:u},"tool operation failed"),a.localeCompare(c)}}),s.length===0?{output:"No files matched the pattern.",isError:!1}:{output:s.join(`
229
- `),isError:!1}}catch(s){return ad.error({err:s},"tool operation failed"),{output:`Error: ${N(s)}`,isError:!0}}}};import{readdir as g_,readFile as y_,stat as cd}from"fs/promises";import{join as __,relative as w_}from"path";var Ro=C({module:"tools"}),Jr=500,Co=class{name="Grep";description=Zu;category="read";schema(){let e={type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search"},path:{type:"string",description:"Directory or file to search",default:"."},include:{type:"string",description:"File pattern filter (e.g., '*.ts')"}},required:["pattern"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"pattern");if(!n)return{output:"Error: pattern is required",isError:!0};let o=E(r,"path",e.workDir),s=E(r,"include"),i;try{i=new RegExp(n)}catch(m){return Ro.error({err:m},"tool operation failed"),{output:`Error: invalid regex pattern: ${n}`,isError:!0}}let a=s?new ir(s):null,c=[],u=async m=>{if(c.length>=Jr)return;let f;try{f=await g_(m)}catch(g){Ro.error({err:g},"tool operation failed");return}for(let g of f){if(c.length>=Jr)return;if(xo.has(g))continue;let h=__(m,g),y;try{y=await cd(h)}catch(v){Ro.error({err:v},"tool operation failed");continue}if(y.isDirectory())await u(h);else if(y.isFile()){if(a&&!await a.match(g))continue;await l(h)}}},l=async m=>{try{let g=(await y_(m,"utf-8")).split(`
230
- `),h=w_(e.workDir,m);for(let y=0;y<g.length&&c.length<Jr;y++)i.test(g[y])&&c.push(`${h}:${String(y+1)}:${g[y]}`)}catch(f){Ro.error({err:f},"tool operation failed")}};try{(await cd(o)).isFile()?await l(o):await u(o)}catch(m){return{output:`Error: ${N(m)}`,isError:!0}}if(c.length===0)return{output:"No matches found.",isError:!1};let d=c.join(`
231
- `);return c.length>=Jr&&(d+=`
232
-
233
- (results truncated at ${String(Jr)} matches)`),{output:d,isError:!1}}};import{existsSync as $_,readFileSync as E_,statSync as P_}from"fs";import{readFileSync as S_,statSync as k_}from"fs";import{basename as T_}from"path";import vi from"sharp";var ld=[80,60,40,20],CC=10,Mt=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}};var v_=C({module:"images"});function Si(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Yr(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function dd(t,e){if(t.length===0)throw new Mt("Image file is empty (0 bytes)");if(t.length<=3932160)return Si(t,e);try{return await b_(t,e)}catch(r){throw r instanceof Mt?r:(v_.warn({err:r},"sharp compression failed"),new Mt(`Image is ${Yr(t.length)} raw (${Yr(t.length*4/3)} base64-encoded, API limit ${Yr(5242880)}) and compression failed. Please provide a smaller image.`))}}async function b_(t,e){let r=await vi(t).metadata(),n=r.width??2e3,o=r.height??2e3;n>2e3&&(o=Math.max(1,Math.round(o*2e3/n)),n=2e3),o>2e3&&(n=Math.max(1,Math.round(n*2e3/o)),o=2e3);let s=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(s){let a=await vi(t).resize(n,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:9,palette:!0}).toBuffer();if(a.length<=3932160)return Si(a,"image/png")}for(let a of ld){let c=await vi(t).resize(n,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=3932160)return Si(c,"image/jpeg")}n=Math.max(1,Math.round(n/2)),o=Math.max(1,Math.round(o/2))}throw new Mt(`Unable to compress image (${Yr(t.length)} raw) under the ${Yr(5242880)} API limit. Please provide a smaller image.`)}async function pd(t){if(!k_(t).isFile())throw new Error(`Not a file: ${t}`);let r=S_(t),n=Dl(r);if(!n)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await dd(r,n);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}function x_(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${String(Math.round(t/1024))}KB`:`${String(t)}B`}function md(t){return`[image: ${t.sourcePath?T_(t.sourcePath):"image"} \xB7 ${t.mediaType} \xB7 ${x_(t.byteLength)}]`}var fd=C({module:"tools"}),Mo=class{name="ReadFile";description=Vu;category="read";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file"},offset:{type:"integer",description:"Line number to start from (0-based)",default:0},limit:{type:"integer",description:"Max lines to read",default:2e3}},required:["file_path"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"file_path");if(!n)return{output:"Error: file_path is required",isError:!0};if(!$_(n))return{output:`Error: file not found: ${n}`,isError:!0};let o=P_(n);if(o.isDirectory())return{output:`Error: ${n} is a directory, not a file. Use Glob to list directory contents.`,isError:!0};if(ql(n))try{let a=await pd(n);return e.fileStateCache?.record(n,o.mtimeMs),{output:md(a),isError:!1,images:[a]}}catch(a){return fd.error({err:a},"tool operation failed"),{output:`Error reading image: ${N(a)}`,isError:!0}}let s=Rt(r,"offset",0),i=Rt(r,"limit",2e3);try{let u=E_(n,"utf-8").split(`
234
- `).slice(s,s+i);return e.fileStateCache?.record(n,o.mtimeMs),{output:u.map((d,m)=>`${String(s+m+1)} ${d}`).join(`
235
- `),isError:!1}}catch(a){return fd.error({err:a},"tool operation failed"),{output:`Error reading file: ${N(a)}`,isError:!0}}}};var hd=class{constructor(e){this.jsonSchema=e}jsonSchema;name="SyntheticOutput";description="Return structured output in JSON format. Use this tool to return your final response as structured data in non-interactive or coordinator mode sessions.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{output:{description:"The structured result: an object, an array, or a plain string"}},required:["output"]}}}execute(e,r){if(!("output"in r))return Promise.resolve({output:"Error: output is required",isError:!0});let n=r.output,o=this.validateSchema(n);if(o)return Promise.resolve({output:`Output does not match required schema: ${o}`,isError:!0});if(typeof n=="string")return Promise.resolve({output:n,isError:!1});try{return Promise.resolve({output:JSON.stringify(n,null,2),isError:!1})}catch(s){return Promise.resolve({output:`Error: output is not serializable: ${N(s)}`,isError:!0})}}validateSchema(e){if(!this.jsonSchema)return"";let r=this.jsonSchema.type;if(typeof r=="string"){let o=Array.isArray(e);if(r==="object"&&!(typeof e=="object"&&e!==null&&!o))return`Expected object, got ${o?"array":typeof e}`;if(r==="array"&&!o)return`Expected array, got ${typeof e}`;if(r==="string"&&typeof e!="string")return`Expected string, got ${o?"array":typeof e}`}let n=this.jsonSchema.required;if(Array.isArray(n)&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let o=n.filter(s=>typeof s=="string"&&!(s in e));if(o.length>0)return`Missing required fields: ${o.join(", ")}`}return""}};var gd=class{name="ToolSearch";description="Search for and load deferred tools by name or keyword.";category="read";registry;constructor(e){this.registry=e}schema(){let e={type:"object",properties:{query:{type:"string",description:'Search query. Use "select:name1,name2" to load specific tools by name, or keywords to search.'},max_results:{type:"integer",description:"Max results to return",default:5}},required:["query"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"query"),o=Rt(r,"max_results",5);if(!n)return Promise.resolve({output:"Error: query is required",isError:!0});if(n.startsWith("select:")){let a=n.slice(7).split(",").map(l=>l.trim()),c=this.registry.findDeferredByNames(a);for(let l of c)this.registry.markDiscovered(l.name);if(c.length===0)return Promise.resolve({output:`No deferred tools found matching: ${a.join(", ")}`,isError:!1});let u=c.map(l=>JSON.stringify(l.schema(),null,2));return Promise.resolve({output:u.join(`
233
+ `),o=0,s=Math.min(r.length,n.length);for(;o<s&&r[o]===n[o];)o++;let i=0,a=s-o;for(;i<a&&r[r.length-1-i]===n[n.length-1-i];)i++;let c=r.slice(o,r.length-i),u=n.slice(o,n.length-i),l=Math.max(0,o-3),d=r.slice(l,o),m=Math.min(r.length,r.length-i+3),f=r.slice(r.length-i,m),g=[],h=l+1,y=l+1,v=!1,S=(T,z,w)=>{if(g.length>=200){v=!0;return}g.push(`${T} ${String(z).padStart(4)} ${w}`)};for(let T of d)S(" ",h,T),h++,y++;for(let T of c)S("-",h,T),h++;for(let T of u)S("+",y,T),y++;for(let T of f)S(" ",h,T),h++,y++;return v&&g.push(` ... (diff truncated at ${String(200)} lines)`),{text:g.join(`
234
+ `),additions:u.length,removals:c.length}}var od=C({module:"tools"}),Po=class{name="EditFile";description=Ku;category="write";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file"},old_string:{type:"string",description:"Exact string to find and replace"},new_string:{type:"string",description:"Replacement string"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)",default:!1}},required:["file_path","old_string","new_string"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"file_path"),o=E(r,"old_string"),s=E(r,"new_string"),i=lo(r,"replace_all");if(!n)return{output:"Error: file_path is required",isError:!0};if(!o)return{output:"Error: old_string is required",isError:!0};if(o===s)return{output:"Error: old_string and new_string MUST be different",isError:!0};if(e.fileStateCache){let l=e.fileStateCache.check(n);if(!l.ok)return{output:l.error,isError:!0}}e.fileHistory?.trackEdit(n);let a;try{a=await $_(n,"utf-8")}catch(l){return od.error({err:l},"tool operation failed"),{output:`Error reading file: ${N(l)}`,isError:!0}}let c=a.split(o).length-1;if(c===0)return{output:"Error: old_string not found in file",isError:!0};if(!i&&c>1)return{output:`Error: old_string found ${String(c)} times in file. It must be unique. Add more surrounding context, or set replace_all to true`,isError:!0};let u=i?a.replaceAll(o,s):a.replace(o,s);try{await E_(n,u,"utf-8"),e.fileStateCache?.update(n);let{text:l,additions:d,removals:m}=nd(a,u);return{output:`${i&&c>1?`Updated ${n} with ${String(d)} addition${d===1?"":"s"} and ${String(m)} removal${m===1?"":"s"} (${String(c)} replacements)`:`Updated ${n} with ${String(d)} addition${d===1?"":"s"} and ${String(m)} removal${m===1?"":"s"}`}
235
+ ${l}`,isError:!1}}catch(l){return od.error({err:l},"tool operation failed"),{output:`Error writing file: ${N(l)}`,isError:!0}}}};import{statSync as sd}from"fs";var id=C({module:"file-state-cache"}),ad=class{cache=new Map;record(e,r){this.cache.set(e,r)}check(e){let r=this.cache.get(e);if(r===void 0)return{ok:!1,error:"Error: file has not been read yet, read it first before editing."};let n;try{n=sd(e).mtimeMs}catch(o){return id.error({err:o},"file state cache operation failed"),{ok:!0}}return n>r?{ok:!1,error:"Error: file has been modified since last read, read it again before editing."}:{ok:!0}}update(e){let r;try{r=sd(e).mtimeMs}catch(n){id.error({err:n},"file state cache operation failed"),this.cache.delete(e);return}this.cache.set(e,r)}};import{existsSync as I_,readFileSync as O_,statSync as j_}from"fs";import{basename as fd}from"path";import{extname as P_}from"path";var cd={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"},FC=new Set(Object.keys(cd));function R_(t){return cd[P_(t).toLowerCase()]??null}function ld(t){return R_(t)!==null}function ud(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":null}import{readFileSync as z_,statSync as A_}from"fs";import vi from"sharp";var dd=[80,60,40,20],VC=10,Mt=class extends Error{constructor(e){super(e),this.name="ImageTooLargeError"}};var C_=C({module:"images"});function Si(t,e){return{data:t.toString("base64"),mediaType:e,byteLength:t.length}}function Xr(t){return`${(t/(1024*1024)).toFixed(1)}MB`}async function Ro(t,e){if(t.length===0)throw new Mt("Image file is empty (0 bytes)");if(t.length<=3932160)return Si(t,e);try{return await M_(t,e)}catch(r){throw r instanceof Mt?r:(C_.warn({err:r},"sharp compression failed"),new Mt(`Image is ${Xr(t.length)} raw (${Xr(t.length*4/3)} base64-encoded, API limit ${Xr(5242880)}) and compression failed. Please provide a smaller image.`))}}async function M_(t,e){let r=await vi(t).metadata(),n=r.width??2e3,o=r.height??2e3;n>2e3&&(o=Math.max(1,Math.round(o*2e3/n)),n=2e3),o>2e3&&(n=Math.max(1,Math.round(n*2e3/o)),o=2e3);let s=e==="image/png"||e==="image/gif";for(let i=0;i<3;i++){if(s){let a=await vi(t).resize(n,o,{fit:"inside",withoutEnlargement:!0}).png({compressionLevel:8,palette:!0}).toBuffer();if(a.length<=3932160)return Si(a,"image/png")}for(let a of dd){let c=await vi(t).resize(n,o,{fit:"inside",withoutEnlargement:!0}).jpeg({quality:a}).toBuffer();if(c.length<=3932160)return Si(c,"image/jpeg")}n=Math.max(1,Math.round(n/2)),o=Math.max(1,Math.round(o/2))}throw new Mt(`Unable to compress image (${Xr(t.length)} raw) under the ${Xr(5242880)} API limit. Please provide a smaller image.`)}async function md(t){if(!A_(t).isFile())throw new Error(`Not a file: ${t}`);let r=z_(t),n=ud(r);if(!n)throw new Error(`File ${t} has an image extension but its contents are not a supported image format (png/jpeg/gif/webp)`);let o=await Ro(r,n);return{mediaType:o.mediaType,data:o.data,sourcePath:t,byteLength:o.byteLength}}var hd=C({module:"tools"}),Co=class{name="ReadFile";description=Gu;category="read";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file"},offset:{type:"integer",description:"Line number to start from (0-based)",default:0},limit:{type:"integer",description:"Max lines to read",default:2e3}},required:["file_path"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"file_path");if(!n)return Promise.resolve({output:"Error: file_path is required",isError:!0});if(!I_(n))return Promise.resolve({output:`Error: file not found: ${n}`,isError:!0});let o=j_(n);if(o.isDirectory())return Promise.resolve({output:`Error: ${n} is a directory, not a file. Use Glob to list directory contents.`,isError:!0});if(ld(n))return this.readImage(e,n,o.mtimeMs);let s=Rt(r,"offset",0),i=Rt(r,"limit",2e3);try{let u=O_(n,"utf-8").split(`
236
+ `).slice(s,s+i);e.fileStateCache?.record(n,o.mtimeMs);let l=u.map((d,m)=>`${String(s+m+1)} ${d}`);return Promise.resolve({output:l.join(`
237
+ `),isError:!1})}catch(a){return hd.error({err:a},"tool operation failed"),Promise.resolve({output:`Error reading file: ${N(a)}`,isError:!0})}}async readImage(e,r,n){try{let o=await md(r);e.fileStateCache?.record(r,n);let s={type:"text",text:`[image: ${fd(r)} \xB7 ${o.mediaType} \xB7 ${N_(o.byteLength)}]`},i={type:"image",source:{type:"base64",media_type:o.mediaType,data:o.data}};return{output:[s,i],isError:!1}}catch(o){return hd.error({err:o},"image read failed"),{output:`Error reading image ${fd(r)}: ${N(o)}`,isError:!0}}}};function N_(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)}MB`:t>=1024?`${String(Math.round(t/1024))}KB`:`${String(t)}B`}var gd=class{constructor(e){this.jsonSchema=e}jsonSchema;name="SyntheticOutput";description="Return structured output in JSON format. Use this tool to return your final response as structured data in non-interactive or coordinator mode sessions.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{output:{description:"The structured result: an object, an array, or a plain string"}},required:["output"]}}}execute(e,r){if(!("output"in r))return Promise.resolve({output:"Error: output is required",isError:!0});let n=r.output,o=this.validateSchema(n);if(o)return Promise.resolve({output:`Output does not match required schema: ${o}`,isError:!0});if(typeof n=="string")return Promise.resolve({output:n,isError:!1});try{return Promise.resolve({output:JSON.stringify(n,null,2),isError:!1})}catch(s){return Promise.resolve({output:`Error: output is not serializable: ${N(s)}`,isError:!0})}}validateSchema(e){if(!this.jsonSchema)return"";let r=this.jsonSchema.type;if(typeof r=="string"){let o=Array.isArray(e);if(r==="object"&&!(typeof e=="object"&&e!==null&&!o))return`Expected object, got ${o?"array":typeof e}`;if(r==="array"&&!o)return`Expected array, got ${typeof e}`;if(r==="string"&&typeof e!="string")return`Expected string, got ${o?"array":typeof e}`}let n=this.jsonSchema.required;if(Array.isArray(n)&&typeof e=="object"&&e!==null&&!Array.isArray(e)){let o=n.filter(s=>typeof s=="string"&&!(s in e));if(o.length>0)return`Missing required fields: ${o.join(", ")}`}return""}};var yd=class{name="ToolSearch";description="Search for and load deferred tools by name or keyword.";category="read";registry;constructor(e){this.registry=e}schema(){let e={type:"object",properties:{query:{type:"string",description:'Search query. Use "select:name1,name2" to load specific tools by name, or keywords to search.'},max_results:{type:"integer",description:"Max results to return",default:5}},required:["query"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"query"),o=Rt(r,"max_results",5);if(!n)return Promise.resolve({output:"Error: query is required",isError:!0});if(n.startsWith("select:")){let a=n.slice(7).split(",").map(l=>l.trim()),c=this.registry.findDeferredByNames(a);for(let l of c)this.registry.markDiscovered(l.name);if(c.length===0)return Promise.resolve({output:`No deferred tools found matching: ${a.join(", ")}`,isError:!1});let u=c.map(l=>JSON.stringify(l.schema(),null,2));return Promise.resolve({output:u.join(`
236
238
 
237
239
  `),isError:!1})}let s=this.registry.searchDeferred(n,o);if(s.length===0)return Promise.resolve({output:"No deferred tools matched the query.",isError:!1});let i=s.map(a=>JSON.stringify(a.schema(),null,2));return Promise.resolve({output:i.join(`
238
240
 
239
- `),isError:!1})}};import{existsSync as R_,mkdirSync as C_,writeFileSync as M_}from"fs";import{dirname as z_}from"path";var A_=C({module:"tools"}),zo=class{name="WriteFile";description=Gu;category="write";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to write"},content:{type:"string",description:"Content to write"}},required:["file_path","content"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"file_path"),o=E(r,"content");if(!n)return Promise.resolve({output:"Error: file_path is required",isError:!0});if(e.fileStateCache&&R_(n)){let s=e.fileStateCache.check(n);if(!s.ok)return Promise.resolve({output:s.error,isError:!0})}try{e.fileHistory?.trackEdit(n),C_(z_(n),{recursive:!0}),M_(n,o,"utf-8"),e.fileStateCache?.update(n);let s=o.split(`
240
- `).length;return Promise.resolve({output:`Successfully wrote to ${n} (${String(s)} lines)`,isError:!1})}catch(s){return A_.error({err:s},"tool operation failed"),Promise.resolve({output:`Error writing file: ${N(s)}`,isError:!0})}}};var cr="2025-11-25";var yd=[cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gt="io.modelcontextprotocol/related-task",Io="2.0",le=Ol(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_d=ee([p(),B().int()]),wd=p(),lM=ce({ttl:B().optional(),pollInterval:B().optional()}),O_=x({ttl:B().optional()}),j_=x({taskId:p()}),Ti=ce({progressToken:_d.optional(),[gt]:j_.optional()}),Ae=x({_meta:Ti.optional()}),Xr=Ae.extend({task:O_.optional()}),vd=t=>Xr.safeParse(t).success,pe=x({method:p(),params:Ae.loose().optional()}),Oe=x({_meta:Ti.optional()}),je=x({method:p(),params:Oe.loose().optional()}),me=ce({_meta:Ti.optional()}),Oo=ee([p(),B().int()]),bd=x({jsonrpc:P(Io),id:Oo,...pe.shape}).strict(),Qr=t=>bd.safeParse(t).success,Sd=x({jsonrpc:P(Io),...je.shape}).strict(),kd=t=>Sd.safeParse(t).success,xi=x({jsonrpc:P(Io),id:Oo,result:me}).strict(),zt=t=>xi.safeParse(t).success;var I;(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"})(I||(I={}));var $i=x({jsonrpc:P(Io),id:Oo.optional(),error:x({code:B().int(),message:p(),data:se().optional()})}).strict();var Td=t=>$i.safeParse(t).success;var yt=ee([bd,Sd,xi,$i]),uM=ee([xi,$i]),At=me.strict(),N_=Oe.extend({requestId:Oo.optional(),reason:p().optional()}),jo=je.extend({method:P("notifications/cancelled"),params:N_}),q_=x({src:p(),mimeType:p().optional(),sizes:T(p()).optional(),theme:ze(["light","dark"]).optional()}),en=x({icons:T(q_).optional()}),ar=x({name:p(),title:p().optional()}),xd=ar.extend({...ar.shape,...en.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),D_=ei(x({applyDefaults:Z().optional()}),Y(p(),se())),L_=ti(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ei(x({form:D_.optional(),url:le.optional()}),Y(p(),se()).optional())),U_=ce({list:le.optional(),cancel:le.optional(),requests:ce({sampling:ce({createMessage:le.optional()}).optional(),elicitation:ce({create:le.optional()}).optional()}).optional()}),F_=ce({list:le.optional(),cancel:le.optional(),requests:ce({tools:ce({call:le.optional()}).optional()}).optional()}),H_=x({experimental:Y(p(),le).optional(),sampling:x({context:le.optional(),tools:le.optional()}).optional(),elicitation:L_.optional(),roots:x({listChanged:Z().optional()}).optional(),tasks:U_.optional(),extensions:Y(p(),le).optional()}),W_=Ae.extend({protocolVersion:p(),capabilities:H_,clientInfo:xd}),V_=pe.extend({method:P("initialize"),params:W_});var B_=x({experimental:Y(p(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:x({listChanged:Z().optional()}).optional(),resources:x({subscribe:Z().optional(),listChanged:Z().optional()}).optional(),tools:x({listChanged:Z().optional()}).optional(),tasks:F_.optional(),extensions:Y(p(),le).optional()}),Ei=me.extend({protocolVersion:p(),capabilities:B_,serverInfo:xd,instructions:p().optional()}),$d=je.extend({method:P("notifications/initialized"),params:Oe.optional()}),Ed=t=>$d.safeParse(t).success,No=pe.extend({method:P("ping"),params:Ae.optional()}),G_=x({progress:B(),total:re(B()),message:re(p())}),K_=x({...Oe.shape,...G_.shape,progressToken:_d}),qo=je.extend({method:P("notifications/progress"),params:K_}),Z_=Ae.extend({cursor:wd.optional()}),tn=pe.extend({params:Z_.optional()}),rn=me.extend({nextCursor:wd.optional()}),J_=ze(["working","input_required","completed","failed","cancelled"]),nn=x({taskId:p(),status:J_,ttl:ee([B(),Al()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:re(B()),statusMessage:re(p())}),It=me.extend({task:nn}),Y_=Oe.merge(nn),on=je.extend({method:P("notifications/tasks/status"),params:Y_}),Do=pe.extend({method:P("tasks/get"),params:Ae.extend({taskId:p()})}),Lo=me.merge(nn),Uo=pe.extend({method:P("tasks/result"),params:Ae.extend({taskId:p()})}),dM=me.loose(),Fo=tn.extend({method:P("tasks/list")}),Ho=rn.extend({tasks:T(nn)}),Wo=pe.extend({method:P("tasks/cancel"),params:Ae.extend({taskId:p()})}),Pd=me.merge(nn),Rd=x({uri:p(),mimeType:re(p()),_meta:Y(p(),se()).optional()}),Cd=Rd.extend({text:p()}),Pi=p().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Md=Rd.extend({blob:Pi}),sn=ze(["user","assistant"]),lr=x({audience:T(sn).optional(),priority:B().min(0).max(1).optional(),lastModified:Rl.datetime({offset:!0}).optional()}),zd=x({...ar.shape,...en.shape,uri:p(),description:re(p()),mimeType:re(p()),size:re(B()),annotations:lr.optional(),_meta:re(ce({}))}),X_=x({...ar.shape,...en.shape,uriTemplate:p(),description:re(p()),mimeType:re(p()),annotations:lr.optional(),_meta:re(ce({}))}),Q_=tn.extend({method:P("resources/list")}),Ri=rn.extend({resources:T(zd)}),ew=tn.extend({method:P("resources/templates/list")}),Ci=rn.extend({resourceTemplates:T(X_)}),Mi=Ae.extend({uri:p()}),tw=Mi,rw=pe.extend({method:P("resources/read"),params:tw}),zi=me.extend({contents:T(ee([Cd,Md]))}),Ai=je.extend({method:P("notifications/resources/list_changed"),params:Oe.optional()}),nw=Mi,ow=pe.extend({method:P("resources/subscribe"),params:nw}),sw=Mi,iw=pe.extend({method:P("resources/unsubscribe"),params:sw}),aw=Oe.extend({uri:p()}),cw=je.extend({method:P("notifications/resources/updated"),params:aw}),lw=x({name:p(),description:re(p()),required:re(Z())}),uw=x({...ar.shape,...en.shape,description:re(p()),arguments:re(T(lw)),_meta:re(ce({}))}),dw=tn.extend({method:P("prompts/list")}),Ii=rn.extend({prompts:T(uw)}),pw=Ae.extend({name:p(),arguments:Y(p(),p()).optional()}),mw=pe.extend({method:P("prompts/get"),params:pw}),Oi=x({type:P("text"),text:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),ji=x({type:P("image"),data:Pi,mimeType:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),Ni=x({type:P("audio"),data:Pi,mimeType:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),fw=x({type:P("tool_use"),name:p(),id:p(),input:Y(p(),se()),_meta:Y(p(),se()).optional()}),hw=x({type:P("resource"),resource:ee([Cd,Md]),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),gw=zd.extend({type:P("resource_link")}),qi=ee([Oi,ji,Ni,gw,hw]),yw=x({role:sn,content:qi}),Di=me.extend({description:p().optional(),messages:T(yw)}),Li=je.extend({method:P("notifications/prompts/list_changed"),params:Oe.optional()}),_w=x({title:p().optional(),readOnlyHint:Z().optional(),destructiveHint:Z().optional(),idempotentHint:Z().optional(),openWorldHint:Z().optional()}),ww=x({taskSupport:ze(["required","optional","forbidden"]).optional()}),Ad=x({...ar.shape,...en.shape,description:p().optional(),inputSchema:x({type:P("object"),properties:Y(p(),le).optional(),required:T(p()).optional()}).catchall(se()),outputSchema:x({type:P("object"),properties:Y(p(),le).optional(),required:T(p()).optional()}).catchall(se()).optional(),annotations:_w.optional(),execution:ww.optional(),_meta:Y(p(),se()).optional()}),vw=tn.extend({method:P("tools/list")}),Ui=rn.extend({tools:T(Ad)}),ur=me.extend({content:T(qi).default([]),structuredContent:Y(p(),se()).optional(),isError:Z().optional()}),pM=ur.or(me.extend({toolResult:se()})),bw=Xr.extend({name:p(),arguments:Y(p(),se()).optional()}),Sw=pe.extend({method:P("tools/call"),params:bw}),Fi=je.extend({method:P("notifications/tools/list_changed"),params:Oe.optional()}),Id=x({autoRefresh:Z().default(!0),debounceMs:B().int().nonnegative().default(300)}),Od=ze(["debug","info","notice","warning","error","critical","alert","emergency"]),kw=Ae.extend({level:Od}),Tw=pe.extend({method:P("logging/setLevel"),params:kw}),xw=Oe.extend({level:Od,logger:p().optional(),data:se()}),$w=je.extend({method:P("notifications/message"),params:xw}),Ew=x({name:p().optional()}),Pw=x({hints:T(Ew).optional(),costPriority:B().min(0).max(1).optional(),speedPriority:B().min(0).max(1).optional(),intelligencePriority:B().min(0).max(1).optional()}),Rw=x({mode:ze(["auto","required","none"]).optional()}),Cw=x({type:P("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:T(qi).default([]),structuredContent:x({}).loose().optional(),isError:Z().optional(),_meta:Y(p(),se()).optional()}),Mw=Qs("type",[Oi,ji,Ni]),Ao=Qs("type",[Oi,ji,Ni,fw,Cw]),zw=x({role:sn,content:ee([Ao,T(Ao)]),_meta:Y(p(),se()).optional()}),Aw=Xr.extend({messages:T(zw),modelPreferences:Pw.optional(),systemPrompt:p().optional(),includeContext:ze(["none","thisServer","allServers"]).optional(),temperature:B().optional(),maxTokens:B().int(),stopSequences:T(p()).optional(),metadata:le.optional(),tools:T(Ad).optional(),toolChoice:Rw.optional()}),Hi=pe.extend({method:P("sampling/createMessage"),params:Aw}),Wi=me.extend({model:p(),stopReason:re(ze(["endTurn","stopSequence","maxTokens"]).or(p())),role:sn,content:Mw}),Vi=me.extend({model:p(),stopReason:re(ze(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:sn,content:ee([Ao,T(Ao)])}),Iw=x({type:P("boolean"),title:p().optional(),description:p().optional(),default:Z().optional()}),Ow=x({type:P("string"),title:p().optional(),description:p().optional(),minLength:B().optional(),maxLength:B().optional(),format:ze(["email","uri","date","date-time"]).optional(),default:p().optional()}),jw=x({type:ze(["number","integer"]),title:p().optional(),description:p().optional(),minimum:B().optional(),maximum:B().optional(),default:B().optional()}),Nw=x({type:P("string"),title:p().optional(),description:p().optional(),enum:T(p()),default:p().optional()}),qw=x({type:P("string"),title:p().optional(),description:p().optional(),oneOf:T(x({const:p(),title:p()})),default:p().optional()}),Dw=x({type:P("string"),title:p().optional(),description:p().optional(),enum:T(p()),enumNames:T(p()).optional(),default:p().optional()}),Lw=ee([Nw,qw]),Uw=x({type:P("array"),title:p().optional(),description:p().optional(),minItems:B().optional(),maxItems:B().optional(),items:x({type:P("string"),enum:T(p())}),default:T(p()).optional()}),Fw=x({type:P("array"),title:p().optional(),description:p().optional(),minItems:B().optional(),maxItems:B().optional(),items:x({anyOf:T(x({const:p(),title:p()}))}),default:T(p()).optional()}),Hw=ee([Uw,Fw]),Ww=ee([Dw,Lw,Hw]),Vw=ee([Ww,Iw,Ow,jw]),Bw=Xr.extend({mode:P("form").optional(),message:p(),requestedSchema:x({type:P("object"),properties:Y(p(),Vw),required:T(p()).optional()})}),Gw=Xr.extend({mode:P("url"),message:p(),elicitationId:p(),url:p().url()}),Kw=ee([Bw,Gw]),Bi=pe.extend({method:P("elicitation/create"),params:Kw}),Zw=Oe.extend({elicitationId:p()}),Jw=je.extend({method:P("notifications/elicitation/complete"),params:Zw}),Gi=me.extend({action:ze(["accept","decline","cancel"]),content:ti(t=>t===null?void 0:t,Y(p(),ee([p(),B(),Z(),T(p())])).optional())}),Yw=x({type:P("ref/resource"),uri:p()});var Xw=x({type:P("ref/prompt"),name:p()}),Qw=Ae.extend({ref:ee([Xw,Yw]),argument:x({name:p(),value:p()}),context:x({arguments:Y(p(),p()).optional()}).optional()}),ev=pe.extend({method:P("completion/complete"),params:Qw});var Ki=me.extend({completion:ce({values:T(p()).max(100),total:re(B().int()),hasMore:re(Z())})}),tv=x({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),se()).optional()}),rv=pe.extend({method:P("roots/list"),params:Ae.optional()}),nv=me.extend({roots:T(tv)}),ov=je.extend({method:P("notifications/roots/list_changed"),params:Oe.optional()}),mM=ee([No,V_,ev,Tw,mw,dw,Q_,ew,rw,ow,iw,Sw,vw,Do,Uo,Fo,Wo]),fM=ee([jo,qo,$d,ov,on]),hM=ee([At,Wi,Vi,Gi,nv,Lo,Ho,It]),gM=ee([No,Hi,Bi,rv,Do,Uo,Fo,Wo]),yM=ee([jo,qo,$w,cw,Ai,Fi,Li,on,Jw]),_M=ee([At,Ei,Ki,Di,Ii,Ri,Ci,zi,ur,Ui,Lo,Ho,It]),M=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ki(o.elicitations,r)}return new t(e,r,n)}},ki=class extends M{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function _t(t){return t==="completed"||t==="failed"||t==="cancelled"}var YM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zi(t){let r=ao(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=co(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ji(t,e){let r=Ue(t,e);if(!r.success)throw r.error;return r.data}var uv=6e4,Vo=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(jo,r=>{this._oncancel(r)}),this.setNotificationHandler(qo,r=>{this._onprogress(r)}),this.setRequestHandler(No,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Do,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Uo,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,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,m=new M(d.error.code,d.error.message,d.error.data);l(m)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} 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(I.InvalidParams,`Task not found: ${s}`);if(!_t(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(_t(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Fo,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(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Wo,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(_t(o.status))throw new M(I.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(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof M?o:new M(I.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),M.fromError(I.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),zt(s)||Td(s)?this._onresponse(s):Qr(s)?this._onrequest(s,i):kd(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=M.fromError(I.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?.[gt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:I.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=vd(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 l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(i.signal.aborted)throw new M(I.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let g=f.relatedTask?.taskId??s;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:I.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).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),zt(e))n(e);else{let i=new M(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(zt(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),zt(e))o(e);else{let i=M.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 M?i:new M(I.InternalError,String(i))}}return}let s;try{let i=await this.request(e,It,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new M(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},_t(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(I.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new M(I.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 M?i:new M(I.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=$=>{l($)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch($){d($);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gt]:c}});let g=$=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String($)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));let k=$ instanceof M?$:new M(I.RequestTimeout,String($));l(k)};this._responseHandlers.set(m,$=>{if(!n?.signal?.aborted){if($ instanceof Error)return l($);try{let k=Ue(r,$.result);k.success?u(k.data):l(k.error)}catch(k){l(k)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let h=n?.timeout??uv,y=()=>g(M.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let $=k=>{let z=this._responseHandlers.get(m);z?z(k):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,$),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(k=>{this._cleanupTimeout(m),l(k)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>{this._cleanupTimeout(m),l($)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Lo,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},Ho,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Pd,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||{},[gt]: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||{},[gt]: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||{},[gt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Zi(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ji(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=Zi(e);this._notificationHandlers.set(n,o=>{let s=Ji(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"&&Qr(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new M(I.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(I.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new M(I.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(I.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=on.parse({method:"notifications/tasks/status",params:a});await this.notification(c),_t(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(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(_t(a.status))throw new M(I.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=on.parse({method:"notifications/tasks/status",params:c});await this.notification(u),_t(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function jd(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Nd(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];jd(i)&&jd(s)?r[o]={...i,...s}:r[o]=s}return r}var Rf=io(jc(),1),Cf=io(Pf(),1);function fx(){let t=new Rf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Cf.default)(t),t}var $s=class{constructor(e){this._ajv=e??fx()}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 Es=class{constructor(e){this._client=e}async*callToolStream(e,r=ur,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(I.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new M(I.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof M){yield{type:"error",error:l};return}yield{type:"error",error:new M(I.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};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 Mf(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 zf(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 Ps(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&&Ps(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Ps(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Ps(r,e)}}function hx(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 Rs=class extends Vo{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 $s,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Fi,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Li,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ai,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Es(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Nd(this._capabilities,e)}setRequestHandler(e,r){let o=ao(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=co(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 l=Ue(Bi,c);if(!l.success){let $=l.error instanceof Error?l.error.message:String(l.error);throw new M(I.InvalidParams,`Invalid elicitation request: ${$}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:m,supportsUrlMode:f}=hx(this._capabilities.elicitation);if(d.mode==="form"&&!m)throw new M(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new M(I.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(r(c,u));if(d.task){let $=Ue(It,g);if(!$.success){let k=$.error instanceof Error?$.error.message:String($.error);throw new M(I.InvalidParams,`Invalid task creation result: ${k}`)}return $.data}let h=Ue(Gi,g);if(!h.success){let $=h.error instanceof Error?h.error.message:String(h.error);throw new M(I.InvalidParams,`Invalid elicitation result: ${$}`)}let y=h.data,v=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Ps(v,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Ue(Hi,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new M(I.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let y=Ue(It,m);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new M(I.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let g=d.tools||d.toolChoice?Vi:Wi,h=Ue(g,m);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new M(I.InvalidParams,`Invalid sampling result: ${y}`)}return h.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:cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ei,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!yd.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){Mf(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&zf(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},At,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ki,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},At,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Di,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Ii,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ri,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Ci,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},zi,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},At,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},At,r)}async callTool(e,r=ur,n){if(this.isToolTaskRequired(e.name))throw new M(I.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(I.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(I.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof M?i:new M(I.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},Ui,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Id.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 d=await o();c(null,d)}catch(d){let m=d instanceof Error?d:new Error(String(d));c(m,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let m=setTimeout(u,a);this._listChangedDebounceTimers.set(e,m)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Nn=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}},Af=10,gx=13,Bt=32;function Wc(t){}function Cs(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=Wc,onError:r=Wc,onRetry:n=Wc,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,l="",d=0,m,f=!1;function g(w){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,w.charCodeAt(0)===239&&w.charCodeAt(1)===187&&w.charCodeAt(2)===191&&(w=w.slice(3))),i.length===0){let ne=y(w);ne!==""&&(i.push(ne),a=ne.length),h();return}if(w.indexOf(`
241
- `)===-1&&w.indexOf("\r")===-1){i.push(w),a+=w.length,h();return}i.push(w);let b=i.join("");i.length=0,a=0;let j=y(b);j!==""&&(i.push(j),a=j.length),h()}function h(){s!==void 0&&(a+l.length<=s||(f=!0,i.length=0,a=0,u=void 0,l="",d=0,m=void 0,r(new Nn(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(w){let b=0;if(w.indexOf("\r")===-1){let j=w.indexOf(`
241
+ `),isError:!1})}};import{existsSync as q_,mkdirSync as D_,writeFileSync as L_}from"fs";import{dirname as U_}from"path";var F_=C({module:"tools"}),Mo=class{name="WriteFile";description=Zu;category="write";schema(){let e={type:"object",properties:{file_path:{type:"string",description:"Absolute path to write"},content:{type:"string",description:"Content to write"}},required:["file_path","content"]};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){let n=E(r,"file_path"),o=E(r,"content");if(!n)return Promise.resolve({output:"Error: file_path is required",isError:!0});if(e.fileStateCache&&q_(n)){let s=e.fileStateCache.check(n);if(!s.ok)return Promise.resolve({output:s.error,isError:!0})}try{e.fileHistory?.trackEdit(n),D_(U_(n),{recursive:!0}),L_(n,o,"utf-8"),e.fileStateCache?.update(n);let s=o.split(`
242
+ `).length;return Promise.resolve({output:`Successfully wrote to ${n} (${String(s)} lines)`,isError:!1})}catch(s){return F_.error({err:s},"tool operation failed"),Promise.resolve({output:`Error writing file: ${N(s)}`,isError:!0})}}};var cr="2025-11-25";var _d=[cr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gt="io.modelcontextprotocol/related-task",Ao="2.0",le=Ol(t=>t!==null&&(typeof t=="object"||typeof t=="function")),wd=ee([p(),B().int()]),vd=p(),kM=ce({ttl:B().optional(),pollInterval:B().optional()}),V_=$({ttl:B().optional()}),W_=$({taskId:p()}),Ti=ce({progressToken:wd.optional(),[gt]:W_.optional()}),Ae=$({_meta:Ti.optional()}),Qr=Ae.extend({task:V_.optional()}),bd=t=>Qr.safeParse(t).success,pe=$({method:p(),params:Ae.loose().optional()}),Ie=$({_meta:Ti.optional()}),Oe=$({method:p(),params:Ie.loose().optional()}),me=ce({_meta:Ti.optional()}),Io=ee([p(),B().int()]),Sd=$({jsonrpc:P(Ao),id:Io,...pe.shape}).strict(),en=t=>Sd.safeParse(t).success,kd=$({jsonrpc:P(Ao),...Oe.shape}).strict(),Td=t=>kd.safeParse(t).success,xi=$({jsonrpc:P(Ao),id:Io,result:me}).strict(),zt=t=>xi.safeParse(t).success;var I;(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"})(I||(I={}));var $i=$({jsonrpc:P(Ao),id:Io.optional(),error:$({code:B().int(),message:p(),data:se().optional()})}).strict();var xd=t=>$i.safeParse(t).success;var yt=ee([Sd,kd,xi,$i]),TM=ee([xi,$i]),At=me.strict(),B_=Ie.extend({requestId:Io.optional(),reason:p().optional()}),Oo=Oe.extend({method:P("notifications/cancelled"),params:B_}),G_=$({src:p(),mimeType:p().optional(),sizes:x(p()).optional(),theme:ze(["light","dark"]).optional()}),tn=$({icons:x(G_).optional()}),ar=$({name:p(),title:p().optional()}),$d=ar.extend({...ar.shape,...tn.shape,version:p(),websiteUrl:p().optional(),description:p().optional()}),K_=ei($({applyDefaults:Z().optional()}),Y(p(),se())),Z_=ti(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ei($({form:K_.optional(),url:le.optional()}),Y(p(),se()).optional())),J_=ce({list:le.optional(),cancel:le.optional(),requests:ce({sampling:ce({createMessage:le.optional()}).optional(),elicitation:ce({create:le.optional()}).optional()}).optional()}),Y_=ce({list:le.optional(),cancel:le.optional(),requests:ce({tools:ce({call:le.optional()}).optional()}).optional()}),X_=$({experimental:Y(p(),le).optional(),sampling:$({context:le.optional(),tools:le.optional()}).optional(),elicitation:Z_.optional(),roots:$({listChanged:Z().optional()}).optional(),tasks:J_.optional(),extensions:Y(p(),le).optional()}),Q_=Ae.extend({protocolVersion:p(),capabilities:X_,clientInfo:$d}),ew=pe.extend({method:P("initialize"),params:Q_});var tw=$({experimental:Y(p(),le).optional(),logging:le.optional(),completions:le.optional(),prompts:$({listChanged:Z().optional()}).optional(),resources:$({subscribe:Z().optional(),listChanged:Z().optional()}).optional(),tools:$({listChanged:Z().optional()}).optional(),tasks:Y_.optional(),extensions:Y(p(),le).optional()}),Ei=me.extend({protocolVersion:p(),capabilities:tw,serverInfo:$d,instructions:p().optional()}),Ed=Oe.extend({method:P("notifications/initialized"),params:Ie.optional()}),Pd=t=>Ed.safeParse(t).success,jo=pe.extend({method:P("ping"),params:Ae.optional()}),rw=$({progress:B(),total:re(B()),message:re(p())}),nw=$({...Ie.shape,...rw.shape,progressToken:wd}),No=Oe.extend({method:P("notifications/progress"),params:nw}),ow=Ae.extend({cursor:vd.optional()}),rn=pe.extend({params:ow.optional()}),nn=me.extend({nextCursor:vd.optional()}),sw=ze(["working","input_required","completed","failed","cancelled"]),on=$({taskId:p(),status:sw,ttl:ee([B(),Al()]),createdAt:p(),lastUpdatedAt:p(),pollInterval:re(B()),statusMessage:re(p())}),It=me.extend({task:on}),iw=Ie.merge(on),sn=Oe.extend({method:P("notifications/tasks/status"),params:iw}),qo=pe.extend({method:P("tasks/get"),params:Ae.extend({taskId:p()})}),Do=me.merge(on),Lo=pe.extend({method:P("tasks/result"),params:Ae.extend({taskId:p()})}),xM=me.loose(),Uo=rn.extend({method:P("tasks/list")}),Fo=nn.extend({tasks:x(on)}),Ho=pe.extend({method:P("tasks/cancel"),params:Ae.extend({taskId:p()})}),Rd=me.merge(on),Cd=$({uri:p(),mimeType:re(p()),_meta:Y(p(),se()).optional()}),Md=Cd.extend({text:p()}),Pi=p().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),zd=Cd.extend({blob:Pi}),an=ze(["user","assistant"]),lr=$({audience:x(an).optional(),priority:B().min(0).max(1).optional(),lastModified:Rl.datetime({offset:!0}).optional()}),Ad=$({...ar.shape,...tn.shape,uri:p(),description:re(p()),mimeType:re(p()),size:re(B()),annotations:lr.optional(),_meta:re(ce({}))}),aw=$({...ar.shape,...tn.shape,uriTemplate:p(),description:re(p()),mimeType:re(p()),annotations:lr.optional(),_meta:re(ce({}))}),cw=rn.extend({method:P("resources/list")}),Ri=nn.extend({resources:x(Ad)}),lw=rn.extend({method:P("resources/templates/list")}),Ci=nn.extend({resourceTemplates:x(aw)}),Mi=Ae.extend({uri:p()}),uw=Mi,dw=pe.extend({method:P("resources/read"),params:uw}),zi=me.extend({contents:x(ee([Md,zd]))}),Ai=Oe.extend({method:P("notifications/resources/list_changed"),params:Ie.optional()}),pw=Mi,mw=pe.extend({method:P("resources/subscribe"),params:pw}),fw=Mi,hw=pe.extend({method:P("resources/unsubscribe"),params:fw}),gw=Ie.extend({uri:p()}),yw=Oe.extend({method:P("notifications/resources/updated"),params:gw}),_w=$({name:p(),description:re(p()),required:re(Z())}),ww=$({...ar.shape,...tn.shape,description:re(p()),arguments:re(x(_w)),_meta:re(ce({}))}),vw=rn.extend({method:P("prompts/list")}),Ii=nn.extend({prompts:x(ww)}),bw=Ae.extend({name:p(),arguments:Y(p(),p()).optional()}),Sw=pe.extend({method:P("prompts/get"),params:bw}),Oi=$({type:P("text"),text:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),ji=$({type:P("image"),data:Pi,mimeType:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),Ni=$({type:P("audio"),data:Pi,mimeType:p(),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),kw=$({type:P("tool_use"),name:p(),id:p(),input:Y(p(),se()),_meta:Y(p(),se()).optional()}),Tw=$({type:P("resource"),resource:ee([Md,zd]),annotations:lr.optional(),_meta:Y(p(),se()).optional()}),xw=Ad.extend({type:P("resource_link")}),qi=ee([Oi,ji,Ni,xw,Tw]),$w=$({role:an,content:qi}),Di=me.extend({description:p().optional(),messages:x($w)}),Li=Oe.extend({method:P("notifications/prompts/list_changed"),params:Ie.optional()}),Ew=$({title:p().optional(),readOnlyHint:Z().optional(),destructiveHint:Z().optional(),idempotentHint:Z().optional(),openWorldHint:Z().optional()}),Pw=$({taskSupport:ze(["required","optional","forbidden"]).optional()}),Id=$({...ar.shape,...tn.shape,description:p().optional(),inputSchema:$({type:P("object"),properties:Y(p(),le).optional(),required:x(p()).optional()}).catchall(se()),outputSchema:$({type:P("object"),properties:Y(p(),le).optional(),required:x(p()).optional()}).catchall(se()).optional(),annotations:Ew.optional(),execution:Pw.optional(),_meta:Y(p(),se()).optional()}),Rw=rn.extend({method:P("tools/list")}),Ui=nn.extend({tools:x(Id)}),ur=me.extend({content:x(qi).default([]),structuredContent:Y(p(),se()).optional(),isError:Z().optional()}),$M=ur.or(me.extend({toolResult:se()})),Cw=Qr.extend({name:p(),arguments:Y(p(),se()).optional()}),Mw=pe.extend({method:P("tools/call"),params:Cw}),Fi=Oe.extend({method:P("notifications/tools/list_changed"),params:Ie.optional()}),Od=$({autoRefresh:Z().default(!0),debounceMs:B().int().nonnegative().default(300)}),jd=ze(["debug","info","notice","warning","error","critical","alert","emergency"]),zw=Ae.extend({level:jd}),Aw=pe.extend({method:P("logging/setLevel"),params:zw}),Iw=Ie.extend({level:jd,logger:p().optional(),data:se()}),Ow=Oe.extend({method:P("notifications/message"),params:Iw}),jw=$({name:p().optional()}),Nw=$({hints:x(jw).optional(),costPriority:B().min(0).max(1).optional(),speedPriority:B().min(0).max(1).optional(),intelligencePriority:B().min(0).max(1).optional()}),qw=$({mode:ze(["auto","required","none"]).optional()}),Dw=$({type:P("tool_result"),toolUseId:p().describe("The unique identifier for the corresponding tool call."),content:x(qi).default([]),structuredContent:$({}).loose().optional(),isError:Z().optional(),_meta:Y(p(),se()).optional()}),Lw=Qs("type",[Oi,ji,Ni]),zo=Qs("type",[Oi,ji,Ni,kw,Dw]),Uw=$({role:an,content:ee([zo,x(zo)]),_meta:Y(p(),se()).optional()}),Fw=Qr.extend({messages:x(Uw),modelPreferences:Nw.optional(),systemPrompt:p().optional(),includeContext:ze(["none","thisServer","allServers"]).optional(),temperature:B().optional(),maxTokens:B().int(),stopSequences:x(p()).optional(),metadata:le.optional(),tools:x(Id).optional(),toolChoice:qw.optional()}),Hi=pe.extend({method:P("sampling/createMessage"),params:Fw}),Vi=me.extend({model:p(),stopReason:re(ze(["endTurn","stopSequence","maxTokens"]).or(p())),role:an,content:Lw}),Wi=me.extend({model:p(),stopReason:re(ze(["endTurn","stopSequence","maxTokens","toolUse"]).or(p())),role:an,content:ee([zo,x(zo)])}),Hw=$({type:P("boolean"),title:p().optional(),description:p().optional(),default:Z().optional()}),Vw=$({type:P("string"),title:p().optional(),description:p().optional(),minLength:B().optional(),maxLength:B().optional(),format:ze(["email","uri","date","date-time"]).optional(),default:p().optional()}),Ww=$({type:ze(["number","integer"]),title:p().optional(),description:p().optional(),minimum:B().optional(),maximum:B().optional(),default:B().optional()}),Bw=$({type:P("string"),title:p().optional(),description:p().optional(),enum:x(p()),default:p().optional()}),Gw=$({type:P("string"),title:p().optional(),description:p().optional(),oneOf:x($({const:p(),title:p()})),default:p().optional()}),Kw=$({type:P("string"),title:p().optional(),description:p().optional(),enum:x(p()),enumNames:x(p()).optional(),default:p().optional()}),Zw=ee([Bw,Gw]),Jw=$({type:P("array"),title:p().optional(),description:p().optional(),minItems:B().optional(),maxItems:B().optional(),items:$({type:P("string"),enum:x(p())}),default:x(p()).optional()}),Yw=$({type:P("array"),title:p().optional(),description:p().optional(),minItems:B().optional(),maxItems:B().optional(),items:$({anyOf:x($({const:p(),title:p()}))}),default:x(p()).optional()}),Xw=ee([Jw,Yw]),Qw=ee([Kw,Zw,Xw]),ev=ee([Qw,Hw,Vw,Ww]),tv=Qr.extend({mode:P("form").optional(),message:p(),requestedSchema:$({type:P("object"),properties:Y(p(),ev),required:x(p()).optional()})}),rv=Qr.extend({mode:P("url"),message:p(),elicitationId:p(),url:p().url()}),nv=ee([tv,rv]),Bi=pe.extend({method:P("elicitation/create"),params:nv}),ov=Ie.extend({elicitationId:p()}),sv=Oe.extend({method:P("notifications/elicitation/complete"),params:ov}),Gi=me.extend({action:ze(["accept","decline","cancel"]),content:ti(t=>t===null?void 0:t,Y(p(),ee([p(),B(),Z(),x(p())])).optional())}),iv=$({type:P("ref/resource"),uri:p()});var av=$({type:P("ref/prompt"),name:p()}),cv=Ae.extend({ref:ee([av,iv]),argument:$({name:p(),value:p()}),context:$({arguments:Y(p(),p()).optional()}).optional()}),lv=pe.extend({method:P("completion/complete"),params:cv});var Ki=me.extend({completion:ce({values:x(p()).max(100),total:re(B().int()),hasMore:re(Z())})}),uv=$({uri:p().startsWith("file://"),name:p().optional(),_meta:Y(p(),se()).optional()}),dv=pe.extend({method:P("roots/list"),params:Ae.optional()}),pv=me.extend({roots:x(uv)}),mv=Oe.extend({method:P("notifications/roots/list_changed"),params:Ie.optional()}),EM=ee([jo,ew,lv,Aw,Sw,vw,cw,lw,dw,mw,hw,Mw,Rw,qo,Lo,Uo,Ho]),PM=ee([Oo,No,Ed,mv,sn]),RM=ee([At,Vi,Wi,Gi,pv,Do,Fo,It]),CM=ee([jo,Hi,Bi,dv,qo,Lo,Uo,Ho]),MM=ee([Oo,No,Ow,yw,Ai,Fi,Li,sn,sv]),zM=ee([At,Ei,Ki,Di,Ii,Ri,Ci,zi,ur,Ui,Do,Fo,It]),M=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===I.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ki(o.elicitations,r)}return new t(e,r,n)}},ki=class extends M{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(I.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function _t(t){return t==="completed"||t==="failed"||t==="cancelled"}var dz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Zi(t){let r=ao(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=co(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ji(t,e){let r=Le(t,e);if(!r.success)throw r.error;return r.data}var wv=6e4,Vo=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(Oo,r=>{this._oncancel(r)}),this.setNotificationHandler(No,r=>{this._onprogress(r)}),this.setRequestHandler(jo,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qo,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(I.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Lo,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,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,m=new M(d.error.code,d.error.message,d.error.data);l(m)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} 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(I.InvalidParams,`Task not found: ${s}`);if(!_t(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(_t(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Uo,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(I.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ho,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(I.InvalidParams,`Task not found: ${r.params.taskId}`);if(_t(o.status))throw new M(I.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(I.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof M?o:new M(I.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),M.fromError(I.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),zt(s)||xd(s)?this._onresponse(s):en(s)?this._onrequest(s,i):Td(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=M.fromError(I.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?.[gt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:I.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=bd(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 l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(i.signal.aborted)throw new M(I.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let g=f.relatedTask?.taskId??s;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:I.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).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),zt(e))n(e);else{let i=new M(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(zt(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),zt(e))o(e);else{let i=M.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 M?i:new M(I.InternalError,String(i))}}return}let s;try{let i=await this.request(e,It,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new M(I.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},_t(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(I.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new M(I.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 M?i:new M(I.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gt]:c}});let g=S=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));let T=S instanceof M?S:new M(I.RequestTimeout,String(S));l(T)};this._responseHandlers.set(m,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let T=Le(r,S.result);T.success?u(T.data):l(T.error)}catch(T){l(T)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let h=n?.timeout??wv,y=()=>g(M.fromError(I.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let S=T=>{let z=this._responseHandlers.get(m);z?z(T):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,S),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(T=>{this._cleanupTimeout(m),l(T)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(m),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Do,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},Fo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Rd,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||{},[gt]: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||{},[gt]: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||{},[gt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Zi(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ji(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=Zi(e);this._notificationHandlers.set(n,o=>{let s=Ji(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"&&en(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new M(I.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(I.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new M(I.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(I.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=sn.parse({method:"notifications/tasks/status",params:a});await this.notification(c),_t(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(I.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(_t(a.status))throw new M(I.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=sn.parse({method:"notifications/tasks/status",params:c});await this.notification(u),_t(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Nd(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qd(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];Nd(i)&&Nd(s)?r[o]={...i,...s}:r[o]=s}return r}var Cf=io(jc(),1),Mf=io(Rf(),1);function kx(){let t=new Cf.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Mf.default)(t),t}var xs=class{constructor(e){this._ajv=e??kx()}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 $s=class{constructor(e){this._client=e}async*callToolStream(e,r=ur,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(I.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=a(u.structuredContent);if(!l.valid){yield{type:"error",error:new M(I.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof M){yield{type:"error",error:l};return}yield{type:"error",error:new M(I.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};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 zf(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 Af(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 Es(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&&Es(s,r[o])}}if(Array.isArray(t.anyOf))for(let r of t.anyOf)typeof r!="boolean"&&Es(r,e);if(Array.isArray(t.oneOf))for(let r of t.oneOf)typeof r!="boolean"&&Es(r,e)}}function Tx(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 Ps=class extends Vo{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 xs,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Fi,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Li,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Ai,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new $s(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qd(this._capabilities,e)}setRequestHandler(e,r){let o=ao(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=co(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 l=Le(Bi,c);if(!l.success){let S=l.error instanceof Error?l.error.message:String(l.error);throw new M(I.InvalidParams,`Invalid elicitation request: ${S}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:m,supportsUrlMode:f}=Tx(this._capabilities.elicitation);if(d.mode==="form"&&!m)throw new M(I.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new M(I.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(r(c,u));if(d.task){let S=Le(It,g);if(!S.success){let T=S.error instanceof Error?S.error.message:String(S.error);throw new M(I.InvalidParams,`Invalid task creation result: ${T}`)}return S.data}let h=Le(Gi,g);if(!h.success){let S=h.error instanceof Error?h.error.message:String(h.error);throw new M(I.InvalidParams,`Invalid elicitation result: ${S}`)}let y=h.data,v=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&v&&this._capabilities.elicitation?.form?.applyDefaults)try{Es(v,y.content)}catch{}return y};return super.setRequestHandler(e,a)}if(i==="sampling/createMessage"){let a=async(c,u)=>{let l=Le(Hi,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new M(I.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let y=Le(It,m);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new M(I.InvalidParams,`Invalid task creation result: ${v}`)}return y.data}let g=d.tools||d.toolChoice?Wi:Vi,h=Le(g,m);if(!h.success){let y=h.error instanceof Error?h.error.message:String(h.error);throw new M(I.InvalidParams,`Invalid sampling result: ${y}`)}return h.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:cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ei,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!_d.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){zf(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&Af(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},At,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},Ki,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},At,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},Di,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},Ii,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ri,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},Ci,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},zi,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},At,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},At,r)}async callTool(e,r=ur,n){if(this.isToolTaskRequired(e.name))throw new M(I.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(I.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(I.InvalidParams,`Structured content does not match the tool's output schema: ${i.errorMessage}`)}catch(i){throw i instanceof M?i:new M(I.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},Ui,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,r,n,o){let s=Od.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 d=await o();c(null,d)}catch(d){let m=d instanceof Error?d:new Error(String(d));c(m,null)}},l=()=>{if(a){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let m=setTimeout(u,a);this._listChangedDebounceTimers.set(e,m)}else u()};this.setNotificationHandler(r,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var qn=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}},If=10,xx=13,Bt=32;function Vc(t){}function Rs(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=Vc,onError:r=Vc,onRetry:n=Vc,onComment:o,maxBufferSize:s}=t,i=[],a=0,c=!0,u,l="",d=0,m,f=!1;function g(w){if(f)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,w.charCodeAt(0)===239&&w.charCodeAt(1)===187&&w.charCodeAt(2)===191&&(w=w.slice(3))),i.length===0){let ne=y(w);ne!==""&&(i.push(ne),a=ne.length),h();return}if(w.indexOf(`
243
+ `)===-1&&w.indexOf("\r")===-1){i.push(w),a+=w.length,h();return}i.push(w);let b=i.join("");i.length=0,a=0;let j=y(b);j!==""&&(i.push(j),a=j.length),h()}function h(){s!==void 0&&(a+l.length<=s||(f=!0,i.length=0,a=0,u=void 0,l="",d=0,m=void 0,r(new qn(`Buffered data exceeded max buffer size of ${s} characters`,{type:"max-buffer-size-exceeded"}))))}function y(w){let b=0;if(w.indexOf("\r")===-1){let j=w.indexOf(`
242
244
  `,b);for(;j!==-1;){if(b===j){d>0&&e({id:u,event:m,data:l}),u=void 0,l="",d=0,m=void 0,b=j+1,j=w.indexOf(`
243
- `,b);continue}let ne=w.charCodeAt(b);if(If(w,b,ne)){let oe=w.charCodeAt(b+5)===Bt?b+6:b+5,Te=w.slice(oe,j);if(d===0&&w.charCodeAt(j+1)===Af){e({id:u,event:m,data:Te}),u=void 0,l="",m=void 0,b=j+2,j=w.indexOf(`
245
+ `,b);continue}let ne=w.charCodeAt(b);if(Of(w,b,ne)){let oe=w.charCodeAt(b+5)===Bt?b+6:b+5,Te=w.slice(oe,j);if(d===0&&w.charCodeAt(j+1)===If){e({id:u,event:m,data:Te}),u=void 0,l="",m=void 0,b=j+2,j=w.indexOf(`
244
246
  `,b);continue}l=d===0?Te:`${l}
245
- ${Te}`,d++}else Of(w,b,ne)?m=w.slice(w.charCodeAt(b+6)===Bt?b+7:b+6,j)||void 0:v(w,b,j);b=j+1,j=w.indexOf(`
247
+ ${Te}`,d++}else jf(w,b,ne)?m=w.slice(w.charCodeAt(b+6)===Bt?b+7:b+6,j)||void 0:v(w,b,j);b=j+1,j=w.indexOf(`
246
248
  `,b)}return w.slice(b)}for(;b<w.length;){let j=w.indexOf("\r",b),ne=w.indexOf(`
247
- `,b),oe=-1;if(j!==-1&&ne!==-1?oe=j<ne?j:ne:j!==-1?j===w.length-1?oe=-1:oe=j:ne!==-1&&(oe=ne),oe===-1)break;v(w,b,oe),b=oe+1,w.charCodeAt(b-1)===gx&&w.charCodeAt(b)===Af&&b++}return w.slice(b)}function v(w,b,j){if(b===j){k();return}let ne=w.charCodeAt(b);if(If(w,b,ne)){let pt=w.charCodeAt(b+5)===Bt?b+6:b+5,$l=w.slice(pt,j);l=d===0?$l:`${l}
248
- ${$l}`,d++;return}if(Of(w,b,ne)){m=w.slice(w.charCodeAt(b+6)===Bt?b+7:b+6,j)||void 0;return}if(ne===105&&w.charCodeAt(b+1)===100&&w.charCodeAt(b+2)===58){let pt=w.slice(w.charCodeAt(b+3)===Bt?b+4:b+3,j);u=pt.includes("\0")?void 0:pt;return}if(ne===58){if(o){let pt=w.slice(b,j);o(pt.slice(w.charCodeAt(b+1)===Bt?2:1))}return}let oe=w.slice(b,j),Te=oe.indexOf(":");if(Te===-1){$(oe,"",oe);return}let Hr=oe.slice(0,Te),oo=oe.charCodeAt(Te+1)===Bt?2:1,so=oe.slice(Te+oo);$(Hr,so,oe)}function $(w,b,j){switch(w){case"event":m=b||void 0;break;case"data":l=d===0?b:`${l}
249
- ${b}`,d++;break;case"id":u=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?n(parseInt(b,10)):r(new Nn(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:j}));break;default:r(new Nn(`Unknown field "${w.length>20?`${w.slice(0,20)}\u2026`:w}"`,{type:"unknown-field",field:w,value:b,line:j}));break}}function k(){d>0&&e({id:u,event:m,data:l}),u=void 0,l="",d=0,m=void 0}function z(w={}){if(w.consume&&i.length>0){let b=i.join("");v(b,0,b.length)}c=!0,u=void 0,l="",d=0,m=void 0,i.length=0,a=0,f=!1}return{feed:g,reset:z}}function If(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 Of(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 zs=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(jf(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(jf(this),r)}};function yx(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Vc(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Vc).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Vc(t.cause)}`:t.message:`${t}`}function jf(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var qf=t=>{throw TypeError(t)},Qc=(t,e,r)=>e.has(t)||qf("Cannot "+r),F=(t,e,r)=>(Qc(t,e,"read from private field"),r?r.call(t):e.get(t)),ue=(t,e,r)=>e.has(t)?qf("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),te=(t,e,r,n)=>(Qc(t,e,"write to private field"),e.set(t,r),r),st=(t,e,r)=>(Qc(t,e,"access private method"),r),Me,Gt,Rr,Ms,As,Ln,zr,Un,Et,Cr,Ar,Mr,qn,Ge,Bc,Gc,Kc,Nf,Zc,Jc,Dn,Yc,Xc,Kt=class extends EventTarget{constructor(e,r){var n,o;super(),ue(this,Ge),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ue(this,Me),ue(this,Gt),ue(this,Rr),ue(this,Ms),ue(this,As),ue(this,Ln),ue(this,zr),ue(this,Un,null),ue(this,Et),ue(this,Cr),ue(this,Ar,null),ue(this,Mr,null),ue(this,qn,null),ue(this,Gc,async s=>{var i;F(this,Cr).reset();let{body:a,redirected:c,status:u,headers:l}=s;if(u===204){st(this,Ge,Dn).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?te(this,Rr,new URL(s.url)):te(this,Rr,void 0),u!==200){st(this,Ge,Dn).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){st(this,Ge,Dn).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,Me)===this.CLOSED)return;te(this,Me,this.OPEN);let d=new Event("open");if((i=F(this,qn))==null||i.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){st(this,Ge,Dn).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let m=new TextDecoder,f=a.getReader(),g=!0;do{let{done:h,value:y}=await f.read();y&&F(this,Cr).feed(m.decode(y,{stream:!h})),h&&(g=!1,F(this,Cr).reset(),st(this,Ge,Yc).call(this))}while(g)}),ue(this,Kc,s=>{te(this,Et,void 0),!(s.name==="AbortError"||s.type==="aborted")&&st(this,Ge,Yc).call(this,Vc(s))}),ue(this,Zc,s=>{typeof s.id=="string"&&te(this,Un,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,Rr)?F(this,Rr).origin:F(this,Gt).origin,lastEventId:s.id||""});F(this,Mr)&&(!s.event||s.event==="message")&&F(this,Mr).call(this,i),this.dispatchEvent(i)}),ue(this,Jc,s=>{te(this,Ln,s)}),ue(this,Xc,()=>{te(this,zr,void 0),F(this,Me)===this.CONNECTING&&st(this,Ge,Bc).call(this)});try{if(e instanceof URL)te(this,Gt,e);else if(typeof e=="string")te(this,Gt,new URL(e,_x()));else throw new Error("Invalid URL")}catch{throw yx("An invalid or illegal string was specified")}te(this,Cr,Cs({onEvent:F(this,Zc),onRetry:F(this,Jc)})),te(this,Me,this.CONNECTING),te(this,Ln,3e3),te(this,As,(n=r?.fetch)!=null?n:globalThis.fetch),te(this,Ms,(o=r?.withCredentials)!=null?o:!1),st(this,Ge,Bc).call(this)}get readyState(){return F(this,Me)}get url(){return F(this,Gt).href}get withCredentials(){return F(this,Ms)}get onerror(){return F(this,Ar)}set onerror(e){te(this,Ar,e)}get onmessage(){return F(this,Mr)}set onmessage(e){te(this,Mr,e)}get onopen(){return F(this,qn)}set onopen(e){te(this,qn,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,zr)&&clearTimeout(F(this,zr)),F(this,Me)!==this.CLOSED&&(F(this,Et)&&F(this,Et).abort(),te(this,Me,this.CLOSED),te(this,Et,void 0))}};Me=new WeakMap,Gt=new WeakMap,Rr=new WeakMap,Ms=new WeakMap,As=new WeakMap,Ln=new WeakMap,zr=new WeakMap,Un=new WeakMap,Et=new WeakMap,Cr=new WeakMap,Ar=new WeakMap,Mr=new WeakMap,qn=new WeakMap,Ge=new WeakSet,Bc=function(){te(this,Me,this.CONNECTING),te(this,Et,new AbortController),F(this,As)(F(this,Gt),st(this,Ge,Nf).call(this)).then(F(this,Gc)).catch(F(this,Kc))},Gc=new WeakMap,Kc=new WeakMap,Nf=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,Un)?{"Last-Event-ID":F(this,Un)}:void 0},cache:"no-store",signal:(t=F(this,Et))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Zc=new WeakMap,Jc=new WeakMap,Dn=function(t,e){var r;F(this,Me)!==this.CLOSED&&te(this,Me,this.CLOSED);let n=new zs("error",{code:e,message:t});(r=F(this,Ar))==null||r.call(this,n),this.dispatchEvent(n)},Yc=function(t,e){var r;if(F(this,Me)===this.CLOSED)return;te(this,Me,this.CONNECTING);let n=new zs("error",{code:e,message:t});(r=F(this,Ar))==null||r.call(this,n),this.dispatchEvent(n),te(this,zr,setTimeout(F(this,Xc),F(this,Ln)))},Xc=new WeakMap,Kt.CONNECTING=0,Kt.OPEN=1,Kt.CLOSED=2;function _x(){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 Ir(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function Is(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Ir(e.headers),...Ir(n.headers)}:e.headers};return t(r,o)}:t}var el;el=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function wx(t){return(await el).getRandomValues(new Uint8Array(t))}async function vx(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await wx(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function bx(t){return await vx(t)}async function Sx(t){let e=await(await el).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function tl(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await bx(t),r=await Sx(e);return{code_verifier:e,code_challenge:r}}var ye=zl().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:jl.custom,message:"URL must be parseable",fatal:!0}),El}).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"}),Lf=ce({resource:p().url(),authorization_servers:T(ye).optional(),jwks_uri:p().url().optional(),scopes_supported:T(p()).optional(),bearer_methods_supported:T(p()).optional(),resource_signing_alg_values_supported:T(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:T(p()).optional(),dpop_signing_alg_values_supported:T(p()).optional(),dpop_bound_access_tokens_required:Z().optional()}),rl=ce({issuer:p(),authorization_endpoint:ye,token_endpoint:ye,registration_endpoint:ye.optional(),scopes_supported:T(p()).optional(),response_types_supported:T(p()),response_modes_supported:T(p()).optional(),grant_types_supported:T(p()).optional(),token_endpoint_auth_methods_supported:T(p()).optional(),token_endpoint_auth_signing_alg_values_supported:T(p()).optional(),service_documentation:ye.optional(),revocation_endpoint:ye.optional(),revocation_endpoint_auth_methods_supported:T(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:T(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:T(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:T(p()).optional(),code_challenge_methods_supported:T(p()).optional(),client_id_metadata_document_supported:Z().optional()}),kx=ce({issuer:p(),authorization_endpoint:ye,token_endpoint:ye,userinfo_endpoint:ye.optional(),jwks_uri:ye,registration_endpoint:ye.optional(),scopes_supported:T(p()).optional(),response_types_supported:T(p()),response_modes_supported:T(p()).optional(),grant_types_supported:T(p()).optional(),acr_values_supported:T(p()).optional(),subject_types_supported:T(p()),id_token_signing_alg_values_supported:T(p()),id_token_encryption_alg_values_supported:T(p()).optional(),id_token_encryption_enc_values_supported:T(p()).optional(),userinfo_signing_alg_values_supported:T(p()).optional(),userinfo_encryption_alg_values_supported:T(p()).optional(),userinfo_encryption_enc_values_supported:T(p()).optional(),request_object_signing_alg_values_supported:T(p()).optional(),request_object_encryption_alg_values_supported:T(p()).optional(),request_object_encryption_enc_values_supported:T(p()).optional(),token_endpoint_auth_methods_supported:T(p()).optional(),token_endpoint_auth_signing_alg_values_supported:T(p()).optional(),display_values_supported:T(p()).optional(),claim_types_supported:T(p()).optional(),claims_supported:T(p()).optional(),service_documentation:p().optional(),claims_locales_supported:T(p()).optional(),ui_locales_supported:T(p()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:ye.optional(),op_tos_uri:ye.optional(),client_id_metadata_document_supported:Z().optional()}),Uf=x({...kx.shape,...rl.pick({code_challenge_methods_supported:!0}).shape}),Ff=x({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Nl.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),Hf=x({error:p(),error_description:p().optional(),error_uri:p().optional()}),Df=ye.optional().or(P("").transform(()=>{})),Tx=x({redirect_uris:T(ye),token_endpoint_auth_method:p().optional(),grant_types:T(p()).optional(),response_types:T(p()).optional(),client_name:p().optional(),client_uri:ye.optional(),logo_uri:Df,scope:p().optional(),contacts:T(p()).optional(),tos_uri:Df,policy_uri:p().optional(),jwks_uri:ye.optional(),jwks:Il().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),xx=x({client_id:p(),client_secret:p().optional(),client_id_issued_at:B().optional(),client_secret_expires_at:B().optional()}).strip(),Wf=Tx.merge(xx),P1=x({error:p(),error_description:p().optional()}).strip(),R1=x({token:p(),token_type_hint:p().optional()}).strip();function Vf(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Bf({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 ae=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}},Fn=class extends ae{};Fn.errorCode="invalid_request";var Zt=class extends ae{};Zt.errorCode="invalid_client";var Jt=class extends ae{};Jt.errorCode="invalid_grant";var Yt=class extends ae{};Yt.errorCode="unauthorized_client";var Hn=class extends ae{};Hn.errorCode="unsupported_grant_type";var Wn=class extends ae{};Wn.errorCode="invalid_scope";var Vn=class extends ae{};Vn.errorCode="access_denied";var it=class extends ae{};it.errorCode="server_error";var Bn=class extends ae{};Bn.errorCode="temporarily_unavailable";var Gn=class extends ae{};Gn.errorCode="unsupported_response_type";var Kn=class extends ae{};Kn.errorCode="unsupported_token_type";var Zn=class extends ae{};Zn.errorCode="invalid_token";var Jn=class extends ae{};Jn.errorCode="method_not_allowed";var Yn=class extends ae{};Yn.errorCode="too_many_requests";var Xt=class extends ae{};Xt.errorCode="invalid_client_metadata";var Xn=class extends ae{};Xn.errorCode="insufficient_scope";var Qn=class extends ae{};Qn.errorCode="invalid_target";var Gf={[Fn.errorCode]:Fn,[Zt.errorCode]:Zt,[Jt.errorCode]:Jt,[Yt.errorCode]:Yt,[Hn.errorCode]:Hn,[Wn.errorCode]:Wn,[Vn.errorCode]:Vn,[it.errorCode]:it,[Bn.errorCode]:Bn,[Gn.errorCode]:Gn,[Kn.errorCode]:Kn,[Zn.errorCode]:Zn,[Jn.errorCode]:Jn,[Yn.errorCode]:Yn,[Xt.errorCode]:Xt,[Xn.errorCode]:Xn,[Qn.errorCode]:Qn};var ke=class extends Error{constructor(e){super(e??"Unauthorized")}};function $x(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var nl="code",ol="S256";function Ex(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&$x(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 Px(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":Rx(o,s,r);return;case"client_secret_post":Cx(o,s,n);return;case"none":Mx(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Rx(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 Cx(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Mx(t,e){e.set("client_id",t)}async function Zf(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Hf.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Gf[o]||it;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new it(o)}}async function at(t,e){try{return await sl(t,e)}catch(r){if(r instanceof Zt||r instanceof Yt)return await t.invalidateCredentials?.("all"),await sl(t,e);if(r instanceof Jt)return await t.invalidateCredentials?.("tokens"),await sl(t,e);throw r}}async function sl(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await Yf(c,{fetchFn:s}),!a)try{a=await Jf(e,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let k=await qx(e,{resourceMetadataUrl:l,fetchFn:s});c=k.authorizationServerUrl,u=k.authorizationServerMetadata,a=k.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await Ax(e,t,a),m=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let k=u?.client_id_metadata_document_supported===!0,z=t.clientMetadataUrl;if(z&&!zx(z))throw new Xt(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(k&&z)f={client_id:z},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let b=await Hx(c,{metadata:u,clientMetadata:t.clientMetadata,scope:m,fetchFn:s});await t.saveClientInformation(b),f=b}}let g=!t.redirectUrl;if(r!==void 0||g){let k=await Fx(t,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:s});return await t.saveTokens(k),"AUTHORIZED"}let h=await t.tokens();if(h?.refresh_token)try{let k=await Ux(c,{metadata:u,clientInformation:f,refreshToken:h.refresh_token,resource:d,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(k),"AUTHORIZED"}catch(k){if(!(!(k instanceof ae)||k instanceof it))throw k}let y=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:$}=await Dx(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:m,resource:d});return await t.saveCodeVerifier($),await t.redirectToAuthorization(v),"REDIRECT"}function zx(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Ax(t,e,r){let n=Vf(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Bf({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 Or(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=il(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=il(t,"scope")||void 0,a=il(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function il(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 Jf(t,e,r=fetch){let n=await jx(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 Lf.parse(await n.json())}async function al(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?al(t,void 0,r):void 0;throw n}}function Ix(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Kf(t,e,r=fetch){return await al(t,{"MCP-Protocol-Version":e},r)}function Ox(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function jx(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??cr,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=Ix(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Kf(i,s,r);if(!n?.metadataUrl&&Ox(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await Kf(c,s,r)}return a}function Nx(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 Yf(t,{fetchFn:e=fetch,protocolVersion:r=cr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Nx(t);for(let{url:s,type:i}of o){let a=await al(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"?rl.parse(await a.json()):Uf.parse(await a.json())}}}async function qx(t,e){let r,n;try{r=await Jf(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 Yf(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Dx(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(nl))throw new Error(`Incompatible auth server: does not support response type ${nl}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(ol))throw new Error(`Incompatible auth server: does not support code challenge method ${ol}`)}else a=new URL("/authorize",t);let c=await tl(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",nl),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",ol),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 Lx(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function Xf(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 l=e?.token_endpoint_auth_methods_supported??[],d=Ex(n,l);Px(d,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await Zf(u);return Ff.parse(await u.json())}async function Ux(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 Xf(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function Fx(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=Lx(o,u,t.redirectUrl)}let c=await t.clientInformation();return Xf(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function Hx(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 Zf(i);return Wf.parse(await i.json())}var cl=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Os=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=Is(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new ke("No auth provider");let e;try{e=await at(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 ke;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=Ir(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 Kt(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}=Or(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 cl(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=yt.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 ke("No auth provider");if(await at(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke("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}=Or(o);if(this._resourceMetadataUrl=i,this._scope=a,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke;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 Fh=io(Lh(),1);import _l from"process";import{PassThrough as _$}from"stream";var g$=10*1024*1024,Ns=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??g$}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(`
250
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),y$(r)}clear(){this._buffer=void 0}};function y$(t){return yt.parse(JSON.parse(t))}function Uh(t){return JSON.stringify(t)+`
251
- `}var w$=_l.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function v$(){let t={};for(let e of w$){let r=_l.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var qs=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new Ns({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new _$)}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,Fh.default)(this._serverParams.command,this._serverParams.args??[],{env:{...v$(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:_l.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=Uh(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var Gh=io(Bh(),1);function Kh(t){if(t)try{return Gh.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var Ds=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Cs({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 R$={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Pt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Ls=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=Is(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??R$}async _authThenStart(){if(!this._authProvider)throw new ke("No auth provider");let e;try{e=await at(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 ke;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=Ir(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 Pt(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 l=e.pipeThrough(new TextDecoderStream).pipeThrough(new Ds({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:g}=await l.read();if(g)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let h=yt.parse(JSON.parse(f.data));zt(h)&&(c=!0,s!==void 0&&(h.id=s)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ke("No auth provider");if(await at(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke("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:Qr(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Pt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:h}=Or(a);if(this._resourceMetadataUrl=g,this._scope=h,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:h,error:y}=Or(a);if(y==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Pt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=v??void 0,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ke;return this.send(e)}}throw new Pt(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Ed(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let l=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type"),m=Kh(d);if(l)if(m==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(m==="application/json"){let f=await a.json(),g=Array.isArray(f)?f.map(h=>yt.parse(h)):[yt.parse(f)];for(let h of g)this.onmessage?.(h)}else throw await a.body?.cancel(),new Pt(-1,`Unexpected content type: ${d}`);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 Pt(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as C$}from"fs";import Zh from"path";import{fileURLToPath as M$}from"url";var z$=A.object({version:A.string()});function A$(){return"0.0.8"}var Jh=A$();var I$=C({module:"mcp"});function Yh(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,n)=>process.env[r||n]??"")}function O$(t){let e={};for(let[r,n]of Object.entries(t))e[r]=n??"";return e}var Us=class{name;config;client=null;transport=null;constructor(e){this.name=e.name,this.config=e}async connect(){if(this.config.command){let e=process.env;if(this.config.env)for(let[r,n]of Object.entries(this.config.env))e[r]=Yh(n);this.transport=new qs({command:this.config.command,args:this.config.args??[],env:O$(e),stderr:"ignore"})}else if(this.config.url){let e=new URL(this.config.url),r={};if(this.config.headers)for(let[o,s]of Object.entries(this.config.headers))r[o]=Yh(s);let n={requestInit:{headers:r}};this.transport=this.config.transport==="sse"?new Os(e,n):new Ls(e,n)}else throw new Error(`MCP server '${this.name}': needs either 'command' (stdio) or 'url' (http/sse)`);this.client=new Rs({name:"swifty",version:Jh},{}),await this.client.connect(this.transport)}getInstructions(){return this.client?.getInstructions()??""}async listTools(){if(!this.client)throw new Error("Not connected");return(await this.client.listTools()).tools.map(({name:r,description:n,inputSchema:{properties:o,...s}})=>({name:r,description:n??"",inputSchema:{...s,properties:o??{}}}))}async callTool(e,r){if(!this.client)throw new Error("Not connected");let n=await this.client.callTool({name:e,arguments:r}),o;return n.content&&Array.isArray(n.content)?o=n.content.map(s=>s.type==="text"?s.text??"":JSON.stringify(s)).join(`
252
- `):o=JSON.stringify(n),{output:o,isError:n.isError===!0}}async disconnect(){try{await this.client?.close()}catch(e){I$.error({err:e},"mcp operation failed")}this.client=null,this.transport=null}};var j$=C({module:"mcp"}),Xh=class{clients=new Map;async connectAll(e){let r={tools:[],servers:[],errors:[],instructions:[]};for(let n of e){let o=new Us(n);try{await o.connect(),this.clients.set(n.name,o),r.servers.push(n.name);let s=await o.listTools();for(let a of s)r.tools.push({serverName:n.name,tool:a});let i=o.getInstructions();i&&r.instructions.push({serverName:n.name,text:i})}catch(s){j$.error({err:s},"mcp operation failed"),r.errors.push({serverName:n.name,error:N(s)})}}return r}getClient(e){return this.clients.get(e)}async disconnectAll(){for(let e of this.clients.values())await e.disconnect();this.clients.clear()}};var N$=C({module:"mcp"});function q$(t,e){let r=n=>n.replace(/[^a-zA-Z0-9_-]/g,"_");return`mcp__${r(t)}__${r(e)}`}var Qh=class{name;description;category="command";deferred=!0;client;originalName;inputSchema;constructor(e,r,n){this.name=q$(r,n.name),this.description=n.description,this.originalName=n.name,this.client=e,this.inputSchema=n.inputSchema}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(e,r){try{let{output:n,isError:o}=await this.client.callTool(this.originalName,r);return{output:n,isError:o}}catch(n){return N$.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${N(n)}`,isError:!0}}}};import{readdirSync as D$,readFileSync as tg,existsSync as rg,statSync as qr}from"fs";import{homedir as eo}from"os";import{join as Ie}from"path";function eg(){return[]}var to=C({module:"skills"}),ng=class{entries=new Map;workDir="";dirModTimes=new Map;load(e){this.workDir=e;for(let n of eg())this.entries.set(n.meta.name,{skill:n,filePath:"",loadedMtimeMs:0});let r=[Ie(eo(),".trae","skills"),Ie(eo(),".claude","skills"),Ie(eo(),".github","skills"),Ie(eo(),".swifty","skills"),Ie(e,".trae","skills"),Ie(e,".claude","skills"),Ie(e,".github","skills"),Ie(e,".swifty","skills")];for(let n of r)rg(n)&&this.scanDirectory(n);this.snapshotDirModTimes()}needsReload(){for(let[r,n]of this.dirModTimes)try{if(qr(r).mtimeMs!==n)return!0}catch{if(n!==0)return!0}let e=this.skillDirPaths();for(let r of e)if(!this.dirModTimes.has(r))try{return qr(r),!0}catch{}return!1}reload(){this.entries.clear(),this.load(this.workDir)}snapshotDirModTimes(){this.dirModTimes.clear();for(let e of this.skillDirPaths())try{this.dirModTimes.set(e,qr(e).mtimeMs)}catch{this.dirModTimes.set(e,0)}}skillDirPaths(){return[Ie(eo(),".swifty","skills"),...this.workDir?[Ie(this.workDir,".swifty","skills")]:[]]}scanDirectory(e){let r;try{r=D$(e)}catch(n){to.error({err:n},"skills operation failed");return}for(let n of r){let o=Ie(e,n);if(qr(o).isDirectory()){let i=Ie(o,"SKILL.md");rg(i)&&this.loadSkill(i,o,!0)}}}loadSkill(e,r,n){try{let o=tg(e,"utf-8"),s=og(o);if(!s)return;let i={meta:s.meta,body:s.body,sourceDir:r,isDirectory:n},a=0;try{a=qr(e).mtimeMs}catch(c){to.error({err:c},"skills operation failed")}this.entries.set(i.meta.name,{skill:i,filePath:e,loadedMtimeMs:a})}catch(o){to.error({err:o},"skills operation failed")}}list(){return[...this.entries.values()].map(e=>e.skill.meta)}get(e){let r=this.entries.get(e);if(r){if(r.filePath&&r.loadedMtimeMs>0)try{let n=qr(r.filePath).mtimeMs;if(n>r.loadedMtimeMs){let o=tg(r.filePath,"utf-8"),s=og(o);s&&(r.skill={meta:s.meta,body:s.body,sourceDir:r.skill.sourceDir,isDirectory:r.skill.isDirectory},r.loadedMtimeMs=n)}}catch(n){to.error({err:n},"skills operation failed")}return r.skill}}has(e){return this.entries.has(e)}};function L$(t){let e=E(ri(t),"mode");return e==="inline"||e==="fork"?e:E(ri(t),"context")==="fork"?"fork":"inline"}var U$=A.looseObject({name:A.string(),description:A.string().optional(),allowed_tools:A.array(A.string()).optional(),mode:A.enum(["inline","fork"]).optional(),model:A.string().optional(),fork_context:A.enum(["full","none","recent"]).optional()});function og(t){if(!t.startsWith("---"))return null;let e=t.indexOf("---",3);if(e===-1)return null;let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(U$,o);return{meta:{name:s.name,description:s.description??"",mode:L$(o),model:s.model,forkContext:s.fork_context},body:n}}catch(o){return to.error({err:o},"skills operation failed"),null}}function Zj(t,e){let r=t.list();if(r.length===0)return"";let o=[`## Available Skills
253
- `,`Skills are installed at: ${Ie(e,".swifty","skills")}`,`When creating new skills, always place them under this directory as <skill-name>/SKILL.md.
249
+ `,b),oe=-1;if(j!==-1&&ne!==-1?oe=j<ne?j:ne:j!==-1?j===w.length-1?oe=-1:oe=j:ne!==-1&&(oe=ne),oe===-1)break;v(w,b,oe),b=oe+1,w.charCodeAt(b-1)===xx&&w.charCodeAt(b)===If&&b++}return w.slice(b)}function v(w,b,j){if(b===j){T();return}let ne=w.charCodeAt(b);if(Of(w,b,ne)){let pt=w.charCodeAt(b+5)===Bt?b+6:b+5,$l=w.slice(pt,j);l=d===0?$l:`${l}
250
+ ${$l}`,d++;return}if(jf(w,b,ne)){m=w.slice(w.charCodeAt(b+6)===Bt?b+7:b+6,j)||void 0;return}if(ne===105&&w.charCodeAt(b+1)===100&&w.charCodeAt(b+2)===58){let pt=w.slice(w.charCodeAt(b+3)===Bt?b+4:b+3,j);u=pt.includes("\0")?void 0:pt;return}if(ne===58){if(o){let pt=w.slice(b,j);o(pt.slice(w.charCodeAt(b+1)===Bt?2:1))}return}let oe=w.slice(b,j),Te=oe.indexOf(":");if(Te===-1){S(oe,"",oe);return}let Hr=oe.slice(0,Te),oo=oe.charCodeAt(Te+1)===Bt?2:1,so=oe.slice(Te+oo);S(Hr,so,oe)}function S(w,b,j){switch(w){case"event":m=b||void 0;break;case"data":l=d===0?b:`${l}
251
+ ${b}`,d++;break;case"id":u=b.includes("\0")?void 0:b;break;case"retry":/^\d+$/.test(b)?n(parseInt(b,10)):r(new qn(`Invalid \`retry\` value: "${b}"`,{type:"invalid-retry",value:b,line:j}));break;default:r(new qn(`Unknown field "${w.length>20?`${w.slice(0,20)}\u2026`:w}"`,{type:"unknown-field",field:w,value:b,line:j}));break}}function T(){d>0&&e({id:u,event:m,data:l}),u=void 0,l="",d=0,m=void 0}function z(w={}){if(w.consume&&i.length>0){let b=i.join("");v(b,0,b.length)}c=!0,u=void 0,l="",d=0,m=void 0,i.length=0,a=0,f=!1}return{feed:g,reset:z}}function Of(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 jf(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 Ms=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(Nf(this),r)}[Symbol.for("Deno.customInspect")](e,r){return e(Nf(this),r)}};function $x(t){let e=globalThis.DOMException;return typeof e=="function"?new e(t,"SyntaxError"):new SyntaxError(t)}function Wc(t){return t instanceof Error?"errors"in t&&Array.isArray(t.errors)?t.errors.map(Wc).join(", "):"cause"in t&&t.cause instanceof Error?`${t}: ${Wc(t.cause)}`:t.message:`${t}`}function Nf(t){return{type:t.type,message:t.message,code:t.code,defaultPrevented:t.defaultPrevented,cancelable:t.cancelable,timeStamp:t.timeStamp}}var Df=t=>{throw TypeError(t)},Qc=(t,e,r)=>e.has(t)||Df("Cannot "+r),F=(t,e,r)=>(Qc(t,e,"read from private field"),r?r.call(t):e.get(t)),ue=(t,e,r)=>e.has(t)?Df("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),te=(t,e,r,n)=>(Qc(t,e,"write to private field"),e.set(t,r),r),st=(t,e,r)=>(Qc(t,e,"access private method"),r),Me,Gt,Rr,Cs,zs,Un,zr,Fn,Et,Cr,Ar,Mr,Dn,Be,Bc,Gc,Kc,qf,Zc,Jc,Ln,Yc,Xc,Kt=class extends EventTarget{constructor(e,r){var n,o;super(),ue(this,Be),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ue(this,Me),ue(this,Gt),ue(this,Rr),ue(this,Cs),ue(this,zs),ue(this,Un),ue(this,zr),ue(this,Fn,null),ue(this,Et),ue(this,Cr),ue(this,Ar,null),ue(this,Mr,null),ue(this,Dn,null),ue(this,Gc,async s=>{var i;F(this,Cr).reset();let{body:a,redirected:c,status:u,headers:l}=s;if(u===204){st(this,Be,Ln).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(c?te(this,Rr,new URL(s.url)):te(this,Rr,void 0),u!==200){st(this,Be,Ln).call(this,`Non-200 status code (${u})`,u);return}if(!(l.get("content-type")||"").startsWith("text/event-stream")){st(this,Be,Ln).call(this,'Invalid content type, expected "text/event-stream"',u);return}if(F(this,Me)===this.CLOSED)return;te(this,Me,this.OPEN);let d=new Event("open");if((i=F(this,Dn))==null||i.call(this,d),this.dispatchEvent(d),typeof a!="object"||!a||!("getReader"in a)){st(this,Be,Ln).call(this,"Invalid response body, expected a web ReadableStream",u),this.close();return}let m=new TextDecoder,f=a.getReader(),g=!0;do{let{done:h,value:y}=await f.read();y&&F(this,Cr).feed(m.decode(y,{stream:!h})),h&&(g=!1,F(this,Cr).reset(),st(this,Be,Yc).call(this))}while(g)}),ue(this,Kc,s=>{te(this,Et,void 0),!(s.name==="AbortError"||s.type==="aborted")&&st(this,Be,Yc).call(this,Wc(s))}),ue(this,Zc,s=>{typeof s.id=="string"&&te(this,Fn,s.id);let i=new MessageEvent(s.event||"message",{data:s.data,origin:F(this,Rr)?F(this,Rr).origin:F(this,Gt).origin,lastEventId:s.id||""});F(this,Mr)&&(!s.event||s.event==="message")&&F(this,Mr).call(this,i),this.dispatchEvent(i)}),ue(this,Jc,s=>{te(this,Un,s)}),ue(this,Xc,()=>{te(this,zr,void 0),F(this,Me)===this.CONNECTING&&st(this,Be,Bc).call(this)});try{if(e instanceof URL)te(this,Gt,e);else if(typeof e=="string")te(this,Gt,new URL(e,Ex()));else throw new Error("Invalid URL")}catch{throw $x("An invalid or illegal string was specified")}te(this,Cr,Rs({onEvent:F(this,Zc),onRetry:F(this,Jc)})),te(this,Me,this.CONNECTING),te(this,Un,3e3),te(this,zs,(n=r?.fetch)!=null?n:globalThis.fetch),te(this,Cs,(o=r?.withCredentials)!=null?o:!1),st(this,Be,Bc).call(this)}get readyState(){return F(this,Me)}get url(){return F(this,Gt).href}get withCredentials(){return F(this,Cs)}get onerror(){return F(this,Ar)}set onerror(e){te(this,Ar,e)}get onmessage(){return F(this,Mr)}set onmessage(e){te(this,Mr,e)}get onopen(){return F(this,Dn)}set onopen(e){te(this,Dn,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,zr)&&clearTimeout(F(this,zr)),F(this,Me)!==this.CLOSED&&(F(this,Et)&&F(this,Et).abort(),te(this,Me,this.CLOSED),te(this,Et,void 0))}};Me=new WeakMap,Gt=new WeakMap,Rr=new WeakMap,Cs=new WeakMap,zs=new WeakMap,Un=new WeakMap,zr=new WeakMap,Fn=new WeakMap,Et=new WeakMap,Cr=new WeakMap,Ar=new WeakMap,Mr=new WeakMap,Dn=new WeakMap,Be=new WeakSet,Bc=function(){te(this,Me,this.CONNECTING),te(this,Et,new AbortController),F(this,zs)(F(this,Gt),st(this,Be,qf).call(this)).then(F(this,Gc)).catch(F(this,Kc))},Gc=new WeakMap,Kc=new WeakMap,qf=function(){var t;let e={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...F(this,Fn)?{"Last-Event-ID":F(this,Fn)}:void 0},cache:"no-store",signal:(t=F(this,Et))==null?void 0:t.signal};return"window"in globalThis&&(e.credentials=this.withCredentials?"include":"same-origin"),e},Zc=new WeakMap,Jc=new WeakMap,Ln=function(t,e){var r;F(this,Me)!==this.CLOSED&&te(this,Me,this.CLOSED);let n=new Ms("error",{code:e,message:t});(r=F(this,Ar))==null||r.call(this,n),this.dispatchEvent(n)},Yc=function(t,e){var r;if(F(this,Me)===this.CLOSED)return;te(this,Me,this.CONNECTING);let n=new Ms("error",{code:e,message:t});(r=F(this,Ar))==null||r.call(this,n),this.dispatchEvent(n),te(this,zr,setTimeout(F(this,Xc),F(this,Un)))},Xc=new WeakMap,Kt.CONNECTING=0,Kt.OPEN=1,Kt.CLOSED=2;function Ex(){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 Ir(t){return t?t instanceof Headers?Object.fromEntries(t.entries()):Array.isArray(t)?Object.fromEntries(t):{...t}:{}}function As(t=fetch,e){return e?async(r,n)=>{let o={...e,...n,headers:n?.headers?{...Ir(e.headers),...Ir(n.headers)}:e.headers};return t(r,o)}:t}var el;el=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(t=>t.webcrypto);async function Px(t){return(await el).getRandomValues(new Uint8Array(t))}async function Rx(t){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%e.length,n="";for(;n.length<t;){let o=await Px(t-n.length);for(let s of o)s<r&&(n+=e[s%e.length])}return n}async function Cx(t){return await Rx(t)}async function Mx(t){let e=await(await el).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function tl(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;let e=await Cx(t),r=await Mx(e);return{code_verifier:e,code_challenge:r}}var ye=zl().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:jl.custom,message:"URL must be parseable",fatal:!0}),El}).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"}),Uf=ce({resource:p().url(),authorization_servers:x(ye).optional(),jwks_uri:p().url().optional(),scopes_supported:x(p()).optional(),bearer_methods_supported:x(p()).optional(),resource_signing_alg_values_supported:x(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:x(p()).optional(),dpop_signing_alg_values_supported:x(p()).optional(),dpop_bound_access_tokens_required:Z().optional()}),rl=ce({issuer:p(),authorization_endpoint:ye,token_endpoint:ye,registration_endpoint:ye.optional(),scopes_supported:x(p()).optional(),response_types_supported:x(p()),response_modes_supported:x(p()).optional(),grant_types_supported:x(p()).optional(),token_endpoint_auth_methods_supported:x(p()).optional(),token_endpoint_auth_signing_alg_values_supported:x(p()).optional(),service_documentation:ye.optional(),revocation_endpoint:ye.optional(),revocation_endpoint_auth_methods_supported:x(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:x(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:x(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:x(p()).optional(),code_challenge_methods_supported:x(p()).optional(),client_id_metadata_document_supported:Z().optional()}),zx=ce({issuer:p(),authorization_endpoint:ye,token_endpoint:ye,userinfo_endpoint:ye.optional(),jwks_uri:ye,registration_endpoint:ye.optional(),scopes_supported:x(p()).optional(),response_types_supported:x(p()),response_modes_supported:x(p()).optional(),grant_types_supported:x(p()).optional(),acr_values_supported:x(p()).optional(),subject_types_supported:x(p()),id_token_signing_alg_values_supported:x(p()),id_token_encryption_alg_values_supported:x(p()).optional(),id_token_encryption_enc_values_supported:x(p()).optional(),userinfo_signing_alg_values_supported:x(p()).optional(),userinfo_encryption_alg_values_supported:x(p()).optional(),userinfo_encryption_enc_values_supported:x(p()).optional(),request_object_signing_alg_values_supported:x(p()).optional(),request_object_encryption_alg_values_supported:x(p()).optional(),request_object_encryption_enc_values_supported:x(p()).optional(),token_endpoint_auth_methods_supported:x(p()).optional(),token_endpoint_auth_signing_alg_values_supported:x(p()).optional(),display_values_supported:x(p()).optional(),claim_types_supported:x(p()).optional(),claims_supported:x(p()).optional(),service_documentation:p().optional(),claims_locales_supported:x(p()).optional(),ui_locales_supported:x(p()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:ye.optional(),op_tos_uri:ye.optional(),client_id_metadata_document_supported:Z().optional()}),Ff=$({...zx.shape,...rl.pick({code_challenge_methods_supported:!0}).shape}),Hf=$({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Nl.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),Vf=$({error:p(),error_description:p().optional(),error_uri:p().optional()}),Lf=ye.optional().or(P("").transform(()=>{})),Ax=$({redirect_uris:x(ye),token_endpoint_auth_method:p().optional(),grant_types:x(p()).optional(),response_types:x(p()).optional(),client_name:p().optional(),client_uri:ye.optional(),logo_uri:Lf,scope:p().optional(),contacts:x(p()).optional(),tos_uri:Lf,policy_uri:p().optional(),jwks_uri:ye.optional(),jwks:Il().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),Ix=$({client_id:p(),client_secret:p().optional(),client_id_issued_at:B().optional(),client_secret_expires_at:B().optional()}).strip(),Wf=Ax.merge(Ix),Fj=$({error:p(),error_description:p().optional()}).strip(),Hj=$({token:p(),token_type_hint:p().optional()}).strip();function Bf(t){let e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Gf({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 ae=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}},Hn=class extends ae{};Hn.errorCode="invalid_request";var Zt=class extends ae{};Zt.errorCode="invalid_client";var Jt=class extends ae{};Jt.errorCode="invalid_grant";var Yt=class extends ae{};Yt.errorCode="unauthorized_client";var Vn=class extends ae{};Vn.errorCode="unsupported_grant_type";var Wn=class extends ae{};Wn.errorCode="invalid_scope";var Bn=class extends ae{};Bn.errorCode="access_denied";var it=class extends ae{};it.errorCode="server_error";var Gn=class extends ae{};Gn.errorCode="temporarily_unavailable";var Kn=class extends ae{};Kn.errorCode="unsupported_response_type";var Zn=class extends ae{};Zn.errorCode="unsupported_token_type";var Jn=class extends ae{};Jn.errorCode="invalid_token";var Yn=class extends ae{};Yn.errorCode="method_not_allowed";var Xn=class extends ae{};Xn.errorCode="too_many_requests";var Xt=class extends ae{};Xt.errorCode="invalid_client_metadata";var Qn=class extends ae{};Qn.errorCode="insufficient_scope";var eo=class extends ae{};eo.errorCode="invalid_target";var Kf={[Hn.errorCode]:Hn,[Zt.errorCode]:Zt,[Jt.errorCode]:Jt,[Yt.errorCode]:Yt,[Vn.errorCode]:Vn,[Wn.errorCode]:Wn,[Bn.errorCode]:Bn,[it.errorCode]:it,[Gn.errorCode]:Gn,[Kn.errorCode]:Kn,[Zn.errorCode]:Zn,[Jn.errorCode]:Jn,[Yn.errorCode]:Yn,[Xn.errorCode]:Xn,[Xt.errorCode]:Xt,[Qn.errorCode]:Qn,[eo.errorCode]:eo};var ke=class extends Error{constructor(e){super(e??"Unauthorized")}};function Ox(t){return["client_secret_basic","client_secret_post","none"].includes(t)}var nl="code",ol="S256";function jx(t,e){let r=t.client_secret!==void 0;return"token_endpoint_auth_method"in t&&t.token_endpoint_auth_method&&Ox(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 Nx(t,e,r,n){let{client_id:o,client_secret:s}=e;switch(t){case"client_secret_basic":qx(o,s,r);return;case"client_secret_post":Dx(o,s,n);return;case"none":Lx(o,n);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function qx(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 Dx(t,e,r){r.set("client_id",t),e&&r.set("client_secret",e)}function Lx(t,e){e.set("client_id",t)}async function Jf(t){let e=t instanceof Response?t.status:void 0,r=t instanceof Response?await t.text():t;try{let n=Vf.parse(JSON.parse(r)),{error:o,error_description:s,error_uri:i}=n,a=Kf[o]||it;return new a(s||"",i)}catch(n){let o=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new it(o)}}async function at(t,e){try{return await sl(t,e)}catch(r){if(r instanceof Zt||r instanceof Yt)return await t.invalidateCredentials?.("all"),await sl(t,e);if(r instanceof Jt)return await t.invalidateCredentials?.("tokens"),await sl(t,e);throw r}}async function sl(t,{serverUrl:e,authorizationCode:r,scope:n,resourceMetadataUrl:o,fetchFn:s}){let i=await t.discoveryState?.(),a,c,u,l=o;if(!l&&i?.resourceMetadataUrl&&(l=new URL(i.resourceMetadataUrl)),i?.authorizationServerUrl){if(c=i.authorizationServerUrl,a=i.resourceMetadata,u=i.authorizationServerMetadata??await Xf(c,{fetchFn:s}),!a)try{a=await Yf(e,{resourceMetadataUrl:l},s)}catch{}(u!==i.authorizationServerMetadata||a!==i.resourceMetadata)&&await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}else{let T=await Gx(e,{resourceMetadataUrl:l,fetchFn:s});c=T.authorizationServerUrl,u=T.authorizationServerMetadata,a=T.resourceMetadata,await t.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:u})}let d=await Fx(e,t,a),m=n||a?.scopes_supported?.join(" ")||t.clientMetadata.scope,f=await Promise.resolve(t.clientInformation());if(!f){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let T=u?.client_id_metadata_document_supported===!0,z=t.clientMetadataUrl;if(z&&!Ux(z))throw new Xt(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(T&&z)f={client_id:z},await t.saveClientInformation?.(f);else{if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let b=await Xx(c,{metadata:u,clientMetadata:t.clientMetadata,scope:m,fetchFn:s});await t.saveClientInformation(b),f=b}}let g=!t.redirectUrl;if(r!==void 0||g){let T=await Yx(t,c,{metadata:u,resource:d,authorizationCode:r,fetchFn:s});return await t.saveTokens(T),"AUTHORIZED"}let h=await t.tokens();if(h?.refresh_token)try{let T=await Jx(c,{metadata:u,clientInformation:f,refreshToken:h.refresh_token,resource:d,addClientAuthentication:t.addClientAuthentication,fetchFn:s});return await t.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof ae)||T instanceof it))throw T}let y=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:S}=await Kx(c,{metadata:u,clientInformation:f,state:y,redirectUrl:t.redirectUrl,scope:m,resource:d});return await t.saveCodeVerifier(S),await t.redirectToAuthorization(v),"REDIRECT"}function Ux(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="https:"&&e.pathname!=="/"}catch{return!1}}async function Fx(t,e,r){let n=Bf(t);if(e.validateResourceURL)return await e.validateResourceURL(n,r?.resource);if(r){if(!Gf({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 Or(t){let e=t.headers.get("WWW-Authenticate");if(!e)return{};let[r,n]=e.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let o=il(t,"resource_metadata")||void 0,s;if(o)try{s=new URL(o)}catch{}let i=il(t,"scope")||void 0,a=il(t,"error")||void 0;return{resourceMetadataUrl:s,scope:i,error:a}}function il(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 Yf(t,e,r=fetch){let n=await Wx(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 Uf.parse(await n.json())}async function al(t,e,r=fetch){try{return await r(t,{headers:e})}catch(n){if(n instanceof TypeError)return e?al(t,void 0,r):void 0;throw n}}function Hx(t,e="",r={}){return e.endsWith("/")&&(e=e.slice(0,-1)),r.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function Zf(t,e,r=fetch){return await al(t,{"MCP-Protocol-Version":e},r)}function Vx(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function Wx(t,e,r,n){let o=new URL(t),s=n?.protocolVersion??cr,i;if(n?.metadataUrl)i=new URL(n.metadataUrl);else{let c=Hx(e,o.pathname);i=new URL(c,n?.metadataServerUrl??o),i.search=o.search}let a=await Zf(i,s,r);if(!n?.metadataUrl&&Vx(a,o.pathname)){let c=new URL(`/.well-known/${e}`,o);a=await Zf(c,s,r)}return a}function Bx(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 Xf(t,{fetchFn:e=fetch,protocolVersion:r=cr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},o=Bx(t);for(let{url:s,type:i}of o){let a=await al(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"?rl.parse(await a.json()):Ff.parse(await a.json())}}}async function Gx(t,e){let r,n;try{r=await Yf(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 Xf(n,{fetchFn:e?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:o,resourceMetadata:r}}async function Kx(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(nl))throw new Error(`Incompatible auth server: does not support response type ${nl}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(ol))throw new Error(`Incompatible auth server: does not support code challenge method ${ol}`)}else a=new URL("/authorize",t);let c=await tl(),u=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",nl),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",ol),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 Zx(t,e,r){return new URLSearchParams({grant_type:"authorization_code",code:t,code_verifier:e,redirect_uri:String(r)})}async function Qf(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 l=e?.token_endpoint_auth_methods_supported??[],d=jx(n,l);Nx(d,n,c,r)}let u=await(i??fetch)(a,{method:"POST",headers:c,body:r});if(!u.ok)throw await Jf(u);return Hf.parse(await u.json())}async function Jx(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 Qf(t,{metadata:e,tokenRequestParams:a,clientInformation:r,addClientAuthentication:s,resource:o,fetchFn:i});return{refresh_token:n,...c}}async function Yx(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=Zx(o,u,t.redirectUrl)}let c=await t.clientInformation();return Qf(e,{metadata:r,tokenRequestParams:a,clientInformation:c??void 0,addClientAuthentication:t.addClientAuthentication,resource:n,fetchFn:s})}async function Xx(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 Jf(i);return Wf.parse(await i.json())}var cl=class extends Error{constructor(e,r,n){super(`SSE error: ${r}`),this.code=e,this.event=n}},Is=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=As(r?.fetch,r?.requestInit)}async _authThenStart(){if(!this._authProvider)throw new ke("No auth provider");let e;try{e=await at(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 ke;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=Ir(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 Kt(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}=Or(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 cl(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=yt.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 ke("No auth provider");if(await at(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke("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}=Or(o);if(this._resourceMetadataUrl=i,this._scope=a,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke;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 Hh=io(Uh(),1);import _l from"process";import{PassThrough as E$}from"stream";var x$=10*1024*1024,js=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??x$}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(`
252
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),$$(r)}clear(){this._buffer=void 0}};function $$(t){return yt.parse(JSON.parse(t))}function Fh(t){return JSON.stringify(t)+`
253
+ `}var P$=_l.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function R$(){let t={};for(let e of P$){let r=_l.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ns=class{constructor(e){this._stderrStream=null,this._serverParams=e,this._readBuffer=new js({maxBufferSize:e.maxBufferSize}),(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new E$)}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,Hh.default)(this._serverParams.command,this._serverParams.args??[],{env:{...R$(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:_l.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=Fh(e);this._process.stdin.write(n)?r():this._process.stdin.once("drain",r)})}};var Kh=io(Gh(),1);function Zh(t){if(t)try{return Kh.default.parse(t).type}catch{let e=(t.split(";",1)[0]??"").trim().toLowerCase();return e===""||t.slice(e.length).includes(",")?void 0:e}}var qs=class extends TransformStream{constructor({onError:e,onRetry:r,onComment:n,maxBufferSize:o}={}){let s;super({start(i){s=Rs({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 q$={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Pt=class extends Error{constructor(e,r){super(`Streamable HTTP error: ${r}`),this.code=e}},Ds=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=As(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??q$}async _authThenStart(){if(!this._authProvider)throw new ke("No auth provider");let e;try{e=await at(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 ke;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=Ir(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 Pt(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 l=e.pipeThrough(new TextDecoderStream).pipeThrough(new qs({onRetry:f=>{this._serverRetryMs=f}})).getReader();for(;;){let{value:f,done:g}=await l.read();if(g)break;if(f.id&&(i=f.id,a=!0,o?.(f.id)),!!f.data&&(!f.event||f.event==="message"))try{let h=yt.parse(JSON.parse(f.data));zt(h)&&(c=!0,s!==void 0&&(h.id=s)),this.onmessage?.(h)}catch(h){this.onerror?.(h)}}(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||a)&&!c&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:o,replayMessageId:s},0)}catch(f){this.onerror?.(new Error(`Failed to reconnect: ${f instanceof Error?f.message:String(f)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new ke("No auth provider");if(await at(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke("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:en(e)?e.id:void 0}).catch(f=>this.onerror?.(f));return}let s=await this._commonHeaders();s.set("content-type","application/json"),s.set("accept","application/json, text/event-stream");let i={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(e),signal:this._abortController?.signal},a=await(this._fetch??fetch)(this._url,i),c=a.headers.get("mcp-session-id");if(c&&(this._sessionId=c),!a.ok){let f=await a.text().catch(()=>null);if(a.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Pt(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:g,scope:h}=Or(a);if(this._resourceMetadataUrl=g,this._scope=h,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new ke;return this._hasCompletedAuthFlow=!0,this.send(e)}if(a.status===403&&this._authProvider){let{resourceMetadataUrl:g,scope:h,error:y}=Or(a);if(y==="insufficient_scope"){let v=a.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===v)throw new Pt(403,"Server returned 403 after trying upscoping");if(h&&(this._scope=h),g&&(this._resourceMetadataUrl=g),this._lastUpscopingHeader=v??void 0,await at(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new ke;return this.send(e)}}throw new Pt(a.status,`Error POSTing to endpoint: ${f}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,a.status===202){await a.body?.cancel(),Pd(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(f=>this.onerror?.(f));return}let l=(Array.isArray(e)?e:[e]).filter(f=>"method"in f&&"id"in f&&f.id!==void 0).length>0,d=a.headers.get("content-type"),m=Zh(d);if(l)if(m==="text/event-stream")this._handleSseStream(a.body,{onresumptiontoken:o},!1);else if(m==="application/json"){let f=await a.json(),g=Array.isArray(f)?f.map(h=>yt.parse(h)):[yt.parse(f)];for(let h of g)this.onmessage?.(h)}else throw await a.body?.cancel(),new Pt(-1,`Unexpected content type: ${d}`);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 Pt(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,r){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:r?.onresumptiontoken})}};import{readFileSync as D$}from"fs";import Jh from"path";import{fileURLToPath as L$}from"url";var U$=A.object({version:A.string()});function F$(){return"0.0.10"}var Yh=F$();var Qh=C({module:"mcp"});function Xh(t){return t.replace(/\$\{(\w+)\}|\$(\w+)/g,(e,r,n)=>process.env[r||n]??"")}function H$(t){let e={};for(let[r,n]of Object.entries(t))e[r]=n??"";return e}var V$=new Set(["image/png","image/jpeg","image/gif","image/webp"]);async function W$(t){let e=[],r=[];for(let o of t){let s=ql(o)?o:{};if(s.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&V$.has(s.mimeType))try{let i=await Ro(Buffer.from(s.data,"base64"),Dl(s.mimeType));r.push({type:"image",source:{type:"base64",media_type:i.mediaType,data:i.data}});continue}catch(i){Qh.warn({err:i},"mcp image dropped (too large to fit the API limit)"),e.push("[note: an image returned by the tool was too large and was dropped]");continue}e.push(s.type==="text"&&typeof s.text=="string"?s.text:JSON.stringify(o))}let n=e.join(`
254
+ `);return r.length===0?n:[...n?[{type:"text",text:n}]:[],...r]}var Ls=class{name;config;client=null;transport=null;constructor(e){this.name=e.name,this.config=e}async connect(){if(this.config.command){let e=process.env;if(this.config.env)for(let[r,n]of Object.entries(this.config.env))e[r]=Xh(n);this.transport=new Ns({command:this.config.command,args:this.config.args??[],env:H$(e),stderr:"ignore"})}else if(this.config.url){let e=new URL(this.config.url),r={};if(this.config.headers)for(let[o,s]of Object.entries(this.config.headers))r[o]=Xh(s);let n={requestInit:{headers:r}};this.transport=this.config.transport==="sse"?new Is(e,n):new Ds(e,n)}else throw new Error(`MCP server '${this.name}': needs either 'command' (stdio) or 'url' (http/sse)`);this.client=new Ps({name:"swifty",version:Yh},{}),await this.client.connect(this.transport)}getInstructions(){return this.client?.getInstructions()??""}async listTools(){if(!this.client)throw new Error("Not connected");return(await this.client.listTools()).tools.map(({name:r,description:n,inputSchema:{properties:o,...s}})=>({name:r,description:n??"",inputSchema:{...s,properties:o??{}}}))}async callTool(e,r){if(!this.client)throw new Error("Not connected");let n=await this.client.callTool({name:e,arguments:r}),o;return n.content&&Array.isArray(n.content)?o=await W$(n.content):o=JSON.stringify(n),{output:o,isError:n.isError===!0}}async disconnect(){try{await this.client?.close()}catch(e){Qh.error({err:e},"mcp operation failed")}this.client=null,this.transport=null}};var B$=C({module:"mcp"}),eg=class{clients=new Map;async connectAll(e){let r={tools:[],servers:[],errors:[],instructions:[]};for(let n of e){let o=new Ls(n);try{await o.connect(),this.clients.set(n.name,o),r.servers.push(n.name);let s=await o.listTools();for(let a of s)r.tools.push({serverName:n.name,tool:a});let i=o.getInstructions();i&&r.instructions.push({serverName:n.name,text:i})}catch(s){B$.error({err:s},"mcp operation failed"),r.errors.push({serverName:n.name,error:N(s)})}}return r}getClient(e){return this.clients.get(e)}async disconnectAll(){for(let e of this.clients.values())await e.disconnect();this.clients.clear()}};var G$=C({module:"mcp"});function K$(t,e){let r=n=>n.replace(/[^a-zA-Z0-9_-]/g,"_");return`mcp__${r(t)}__${r(e)}`}var tg=class{name;description;category="command";deferred=!0;client;originalName;inputSchema;constructor(e,r,n){this.name=K$(r,n.name),this.description=n.description,this.originalName=n.name,this.client=e,this.inputSchema=n.inputSchema}schema(){return{name:this.name,description:this.description,input_schema:this.inputSchema}}async execute(e,r){try{let{output:n,isError:o}=await this.client.callTool(this.originalName,r);return{output:n,isError:o}}catch(n){return G$.error({err:n},"mcp operation failed"),{output:`MCP tool error: ${N(n)}`,isError:!0}}}};import{readdirSync as Z$,readFileSync as ng,existsSync as og,statSync as qr}from"fs";import{homedir as Us}from"os";import{join as Ge}from"path";function rg(){return[]}var to=C({module:"skills"}),sg=class{entries=new Map;workDir="";dirModTimes=new Map;load(e){this.workDir=e;for(let n of rg())this.entries.set(n.meta.name,{skill:n,filePath:"",loadedMtimeMs:0});let r=[Ge(Us(),".claude","skills"),Ge(Us(),".github","skills"),Ge(Us(),".swifty","skills"),Ge(e,".claude","skills"),Ge(e,".github","skills"),Ge(e,".swifty","skills")];for(let n of r)og(n)&&this.scanDirectory(n);this.snapshotDirModTimes()}needsReload(){for(let[r,n]of this.dirModTimes)try{if(qr(r).mtimeMs!==n)return!0}catch{if(n!==0)return!0}let e=this.skillDirPaths();for(let r of e)if(!this.dirModTimes.has(r))try{return qr(r),!0}catch{}return!1}reload(){this.entries.clear(),this.load(this.workDir)}snapshotDirModTimes(){this.dirModTimes.clear();for(let e of this.skillDirPaths())try{this.dirModTimes.set(e,qr(e).mtimeMs)}catch{this.dirModTimes.set(e,0)}}skillDirPaths(){return[Ge(Us(),".swifty","skills"),...this.workDir?[Ge(this.workDir,".swifty","skills")]:[]]}scanDirectory(e){let r;try{r=Z$(e)}catch(n){to.error({err:n},"skills operation failed");return}for(let n of r){let o=Ge(e,n);if(qr(o).isDirectory()){let i=Ge(o,"SKILL.md");og(i)&&this.loadSkill(i,o,!0)}}}loadSkill(e,r,n){try{let o=ng(e,"utf-8"),s=ig(o);if(!s)return;let i={meta:s.meta,body:s.body,sourceDir:r,isDirectory:n},a=0;try{a=qr(e).mtimeMs}catch(c){to.error({err:c},"skills operation failed")}this.entries.set(i.meta.name,{skill:i,filePath:e,loadedMtimeMs:a})}catch(o){to.error({err:o},"skills operation failed")}}list(){return[...this.entries.values()].map(e=>e.skill.meta)}get(e){let r=this.entries.get(e);if(r){if(r.filePath&&r.loadedMtimeMs>0)try{let n=qr(r.filePath).mtimeMs;if(n>r.loadedMtimeMs){let o=ng(r.filePath,"utf-8"),s=ig(o);s&&(r.skill={meta:s.meta,body:s.body,sourceDir:r.skill.sourceDir,isDirectory:r.skill.isDirectory},r.loadedMtimeMs=n)}}catch(n){to.error({err:n},"skills operation failed")}return r.skill}}has(e){return this.entries.has(e)}};function J$(t){let e=E(ni(t),"mode");return e==="inline"||e==="fork"?e:E(ni(t),"context")==="fork"?"fork":"inline"}var Y$=A.looseObject({name:A.string(),description:A.string().optional(),allowed_tools:A.array(A.string()).optional(),mode:A.enum(["inline","fork"]).optional(),model:A.string().optional(),fork_context:A.enum(["full","none","recent"]).optional()});function ig(t){if(!t.startsWith("---"))return null;let e=t.indexOf("---",3);if(e===-1)return null;let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(Y$,o);return{meta:{name:s.name,description:s.description??"",mode:J$(o),model:s.model,forkContext:s.fork_context},body:n}}catch(o){return to.error({err:o},"skills operation failed"),null}}function pN(t,e){let r=t.list();if(r.length===0)return"";let o=[`## Available Skills
255
+ `,`Skills are installed at: ${Ge(e,".swifty","skills")}`,`When creating new skills, always place them under this directory as <skill-name>/SKILL.md.
254
256
  `,`Only Skill names and one-line descriptions are listed below. To activate a Skill on demand call the LoadSkill tool with {name: "<skill-name>"}. After activation the Skill's full SOP gets pinned to the environment context, and any tools the Skill declares get registered. Users can also invoke a Skill directly with /<name>.
255
257
  `,`If the user pastes a Skill URL (skills.sh, github.com tree URL, or raw SKILL.md URL) and asks to install / add / get it, call the InstallSkill tool with {url: "<url>"} \u2014 the new Skill becomes available immediately afterwards.
256
258
  `];for(let s of r){let i=s.description.length>200?s.description.slice(0,200)+"\u2026":s.description;o.push(`- /${s.name}: ${i}`)}return o.join(`
257
- `)}function sg(t,e,r){let n=t.body;return n.includes("$ARGUMENTS")?n=n.replaceAll("$ARGUMENTS",e):e&&(n+=`
259
+ `)}function ag(t,e,r){let n=t.body;return n.includes("$ARGUMENTS")?n=n.replaceAll("$ARGUMENTS",e):e&&(n+=`
258
260
 
259
- User Request: ${e}`),r.activateSkill(t.meta.name,n),n}async function ig(t,e,r){let n=t.body;e&&(n+=`
261
+ User Request: ${e}`),r.activateSkill(t.meta.name,n),n}async function cg(t,e,r){let n=t.body;e&&(n+=`
260
262
 
261
263
  ARGUMENTS: ${e}`);let o=t.meta.forkContext??"none";return o==="recent"?n=`Context from parent conversation:
262
264
  ${r.snapshotParentMessages(5)}
@@ -264,12 +266,12 @@ ${r.snapshotParentMessages(5)}
264
266
  ${n}`:o==="full"&&(n=`Context from parent conversation:
265
267
  ${r.snapshotParentMessages(100)}
266
268
 
267
- ${n}`),r.runSubagent(n)}var ag=class{constructor(e,r,n){this.catalog=e;this.host=r;this.forkHost=n}catalog;host;forkHost;name="LoadSkill";description="Activate a skill by name. Returns the full SOP body so you can follow its instructions.. Call this when the user's request matches one of the available Skills listed in the available-skills section. Pass the Skill name without a leading slash.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{name:{type:"string",description:"Name of the skill to activate"}},required:["name"]}}}async execute(e,r){let n=E(r,"name"),o=this.catalog.get(n);if(!o){let i=this.catalog.list().map(a=>a.name).join(", ")||"(none)";return{output:`Skill '${n}' not found. Available skills: ${i}`,isError:!0}}if(o.meta.mode==="fork"&&this.forkHost)try{return{output:await ig(o,"",this.forkHost),isError:!1}}catch(i){return{output:`Skill '${n}' fork execution failed: ${N(i)}`,isError:!0}}let s=sg(o,"",this.host);return{output:`Skill '${n}' activated.
269
+ ${n}`),r.runSubagent(n)}var lg=class{constructor(e,r,n){this.catalog=e;this.host=r;this.forkHost=n}catalog;host;forkHost;name="LoadSkill";description="Activate a skill by name. Returns the full SOP body so you can follow its instructions.. Call this when the user's request matches one of the available Skills listed in the available-skills section. Pass the Skill name without a leading slash.";category="read";schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{name:{type:"string",description:"Name of the skill to activate"}},required:["name"]}}}async execute(e,r){let n=E(r,"name"),o=this.catalog.get(n);if(!o){let i=this.catalog.list().map(a=>a.name).join(", ")||"(none)";return{output:`Skill '${n}' not found. Available skills: ${i}`,isError:!0}}if(o.meta.mode==="fork"&&this.forkHost)try{return{output:await cg(o,"",this.forkHost),isError:!1}}catch(i){return{output:`Skill '${n}' fork execution failed: ${N(i)}`,isError:!0}}let s=ag(o,"",this.host);return{output:`Skill '${n}' activated.
268
270
 
269
- ${s}`,isError:!1}}};var F$=C({module:"tools"}),cg=class{name="EnterWorktree";description="Create and enter a git worktree for isolated work.";category="write";schema(){let e={type:"object",properties:{slug:{type:"string",description:"Short identifier for the worktree (branch name suffix)."}},required:["slug"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"slug");if(!n)return Promise.resolve({output:"Error: slug is required",isError:!0});if(!/^[a-zA-Z0-9_-]+$/.test(n))return Promise.resolve({output:"Error: slug must contain only alphanumeric, hyphen, underscore",isError:!0});try{let o=await Vr(n);return{output:`Worktree created at ${o.path}
271
+ ${s}`,isError:!1}}};var X$=C({module:"tools"}),ug=class{name="EnterWorktree";description="Create and enter a git worktree for isolated work.";category="write";schema(){let e={type:"object",properties:{slug:{type:"string",description:"Short identifier for the worktree (branch name suffix)."}},required:["slug"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"slug");if(!n)return Promise.resolve({output:"Error: slug is required",isError:!0});if(!/^[a-zA-Z0-9_-]+$/.test(n))return Promise.resolve({output:"Error: slug must contain only alphanumeric, hyphen, underscore",isError:!0});try{let o=await Wr(n);return{output:`Worktree created at ${o.path}
270
272
  Branch: ${o.branch}
271
- Head: ${o.headCommit}`,isError:!1}}catch(o){return F$.error({err:o},"tool operation failed"),{output:`Error creating worktree: ${N(o)}`,isError:!0}}}};var H$=C({module:"tools"}),lg=class{name="ExitWorktree";description="Exit and optionally cleanup a git worktree";category="write";schema(){let e={type:"object",properties:{path:{type:"string",description:"Worktree path"},branch:{type:"string",description:"Worktree branch name"},git_root:{type:"string",description:"Git root directory"},head_commit:{type:"string",description:"Original HEAD commit for change detection"}},required:["path","branch","git_root"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"path"),o=E(r,"branch"),s=E(r,"git_root"),i=E(r,"head_commit");if(!n||!o||!s)return{output:"Error: path, branch and git_root are required",isError:!0};if(!(i?gu(n,i):!1))try{return await hu(n,o,s),{output:`Worktree cleaned up (no changes): ${n}`,isError:!1}}catch(c){return H$.error({err:c},"tool operation failed"),{output:`Error cleaning up worktree: ${N(c)}`,isError:!0}}return{output:`Worktree has changes, kept at: ${n}
272
- Branch: ${o}`,isError:!1}}};var vl=class{commands=new Map;aliasMap=new Map;register(e){if(this.commands.has(e.name))throw new Error(`Command '${e.name}' already registered`);if(this.aliasMap.has(e.name))throw new Error(`Command name '${e.name}' collides with alias of '${this.aliasMap.get(e.name)??""}'`);for(let r of e.aliases){if(this.commands.has(r))throw new Error(`Alias '${r}' for '${e.name}' collides with existing command name`);if(this.aliasMap.has(r))throw new Error(`Alias '${r}' for '${e.name}' already registered by '${this.aliasMap.get(r)??""}'`)}this.commands.set(e.name,e);for(let r of e.aliases)this.aliasMap.set(r,e.name)}hasConflict(e){if(this.find(e.name))return!0;for(let r of e.aliases)if(this.find(r))return!0;return!1}find(e){return this.commands.get(e)??this.commands.get(this.aliasMap.get(e)??"")}complete(e){let r=e.toLowerCase();return[...this.commands.values()].filter(n=>n.name.toLowerCase().startsWith(r)||n.aliases.some(o=>o.toLowerCase().startsWith(r)))}listCommands(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};function mN(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trim(),r=e.indexOf(" ");return r===-1?{name:e,args:""}:{name:e.slice(0,r),args:e.slice(r+1).trim()}}function fN(){let t=new vl;return t.register({name:"help",aliases:["h","?"],type:"local",description:"Show available commands",handler:e=>{if(e.args){let o=t.find(e.args);if(!o)return`Unknown command: ${e.args}`;let s=`/${o.name} \u2014 ${o.description}
273
+ Head: ${o.headCommit}`,isError:!1}}catch(o){return X$.error({err:o},"tool operation failed"),{output:`Error creating worktree: ${N(o)}`,isError:!0}}}};var Q$=C({module:"tools"}),dg=class{name="ExitWorktree";description="Exit and optionally cleanup a git worktree";category="write";schema(){let e={type:"object",properties:{path:{type:"string",description:"Worktree path"},branch:{type:"string",description:"Worktree branch name"},git_root:{type:"string",description:"Git root directory"},head_commit:{type:"string",description:"Original HEAD commit for change detection"}},required:["path","branch","git_root"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let n=E(r,"path"),o=E(r,"branch"),s=E(r,"git_root"),i=E(r,"head_commit");if(!n||!o||!s)return{output:"Error: path, branch and git_root are required",isError:!0};if(!(i?gu(n,i):!1))try{return await hu(n,o,s),{output:`Worktree cleaned up (no changes): ${n}`,isError:!1}}catch(c){return Q$.error({err:c},"tool operation failed"),{output:`Error cleaning up worktree: ${N(c)}`,isError:!0}}return{output:`Worktree has changes, kept at: ${n}
274
+ Branch: ${o}`,isError:!1}}};var vl=class{commands=new Map;aliasMap=new Map;register(e){if(this.commands.has(e.name))throw new Error(`Command '${e.name}' already registered`);if(this.aliasMap.has(e.name))throw new Error(`Command name '${e.name}' collides with alias of '${this.aliasMap.get(e.name)??""}'`);for(let r of e.aliases){if(this.commands.has(r))throw new Error(`Alias '${r}' for '${e.name}' collides with existing command name`);if(this.aliasMap.has(r))throw new Error(`Alias '${r}' for '${e.name}' already registered by '${this.aliasMap.get(r)??""}'`)}this.commands.set(e.name,e);for(let r of e.aliases)this.aliasMap.set(r,e.name)}hasConflict(e){if(this.find(e.name))return!0;for(let r of e.aliases)if(this.find(r))return!0;return!1}find(e){return this.commands.get(e)??this.commands.get(this.aliasMap.get(e)??"")}complete(e){let r=e.toLowerCase();return[...this.commands.values()].filter(n=>n.name.toLowerCase().startsWith(r)||n.aliases.some(o=>o.toLowerCase().startsWith(r)))}listCommands(){return[...this.commands.values()].sort((e,r)=>e.name.localeCompare(r.name))}};function CN(t){if(!t.startsWith("/"))return null;let e=t.slice(1).trim(),r=e.indexOf(" ");return r===-1?{name:e,args:""}:{name:e.slice(0,r),args:e.slice(r+1).trim()}}function MN(){let t=new vl;return t.register({name:"help",aliases:["h","?"],type:"local",description:"Show available commands",handler:e=>{if(e.args){let o=t.find(e.args);if(!o)return`Unknown command: ${e.args}`;let s=`/${o.name} \u2014 ${o.description}
273
275
  `;return o.aliases.length>0&&(s+=` Aliases: ${o.aliases.join(", ")}
274
276
  `),s}let r=t.listCommands(),n=`Available commands:
275
277
 
@@ -281,39 +283,39 @@ Type /help <command> for details.`,n}}),t.register({name:"clear",aliases:[],type
281
283
  `)}}),t.register({name:"session",aliases:[],type:"local",description:"Show session info",handler:()=>"Session is active. Use /resume to list past sessions."}),t.register({name:"plan",aliases:["p"],type:"local_ui",description:"Enter plan mode",handler:()=>"plan"}),t.register({name:"resume",aliases:["r"],type:"local_ui",description:"Resume a previous session",handler:()=>"resume"}),t.register({name:"quit",aliases:["exit","q"],type:"local_ui",description:"Exit Swifty",handler:()=>"quit"}),t.register({name:"memory",aliases:[],type:"local",description:"Show memory status",handler:()=>"memory"}),t.register({name:"skills",aliases:[],type:"local_ui",description:"List available skills",handler:()=>"skills"}),t.register({name:"worktree",aliases:["wt"],type:"local_ui",description:"Manage git worktrees",handler:()=>"worktree"}),t.register({name:"code-review",aliases:["cr"],type:"local",description:"Manage code review team (create, add, remove, list)",handler:e=>{let r=e.args.trim();return r?`code-review:${r}`:`Usage: /code-review <command> [args]
282
284
  Commands: create, add <name>, remove <name>, list, status`}}),t.register({name:"review",aliases:[],type:"prompt",description:"Review the uncommitted code changes for bugs and improvements",handler:e=>"Review the current uncommitted changes. Run `git status` and `git diff` to see them, then report concrete findings (file:line) for correctness bugs, security issues, and obvious simplifications. Be specific and concise."+(e.args?`
283
285
 
284
- Focus on: ${e.args}`:"")}),t.register({name:"rewind",aliases:[],type:"local_ui",description:"Rewind conversation to a previous checkpoint",handler:()=>"rewind"}),t.register({name:"mcp",aliases:[],type:"local",description:"Show MCP server connection status",handler:()=>"mcp"}),t.register({name:"sandbox",aliases:["sb"],type:"local_ui",description:"Toggle OS sandbox mode for command execution",handler:()=>"sandbox"}),t}import{readdirSync as W$,readFileSync as V$,statSync as B$,existsSync as G$}from"fs";import{homedir as K$}from"os";import{join as bl}from"path";function bN(t){let e=new Map,r=[bl(K$(),".swifty","commands"),bl(t,".swifty","commands")];for(let n of r)if(G$(n))for(let o of ug(n,n))e.set(o.name,o);return[...e.values()]}function ug(t,e){let r;try{r=W$(e)}catch{return[]}let n=[];for(let o of r){let s=bl(e,o),i;try{i=B$(s)}catch{continue}if(i.isDirectory())n.push(...ug(t,s));else if(o.endsWith(".md")){let a=Y$(t,s);a&&n.push(a)}}return n}function Z$(t,e){return e.slice(t.length+1).replace(/\.md$/,"").split(/[/\\]/).map(n=>n.toLowerCase().replace(/ /g,"-")).join(":")}var J$=A.object({description:A.string().optional(),"argument-hint":A.string().optional(),aliases:A.array(A.string()).optional()});function Y$(t,e){let r;try{r=V$(e,"utf-8")}catch{return null}let n="",o="",s=[],i=r;if(r.startsWith("---")){let c=r.indexOf("---",3);if(c!==-1){let u=r.slice(3,c).trim();i=r.slice(c+3).trim();try{let l=ft.load(u),d=xe(J$,l);n=d.description??"",o=d["argument-hint"]??"",s=d.aliases??[]}catch{}}}let a=Z$(t,e);return a?{name:a,aliases:Array.isArray(s)?s:[],type:"prompt",description:n||(o?`custom command (args: ${o})`:"custom command"),handler:c=>X$(i,c.args)}:null}function X$(t,e){return t.includes("$ARGUMENTS")?t.replaceAll("$ARGUMENTS",e):e?`${t}
286
+ Focus on: ${e.args}`:"")}),t.register({name:"rewind",aliases:[],type:"local_ui",description:"Rewind conversation to a previous checkpoint",handler:()=>"rewind"}),t.register({name:"mcp",aliases:[],type:"local",description:"Show MCP server connection status",handler:()=>"mcp"}),t.register({name:"sandbox",aliases:["sb"],type:"local_ui",description:"Toggle OS sandbox mode for command execution",handler:()=>"sandbox"}),t}import{readdirSync as eE,readFileSync as tE,statSync as rE,existsSync as nE}from"fs";import{homedir as oE}from"os";import{join as bl}from"path";function qN(t){let e=new Map,r=[bl(oE(),".swifty","commands"),bl(t,".swifty","commands")];for(let n of r)if(nE(n))for(let o of pg(n,n))e.set(o.name,o);return[...e.values()]}function pg(t,e){let r;try{r=eE(e)}catch{return[]}let n=[];for(let o of r){let s=bl(e,o),i;try{i=rE(s)}catch{continue}if(i.isDirectory())n.push(...pg(t,s));else if(o.endsWith(".md")){let a=aE(t,s);a&&n.push(a)}}return n}function sE(t,e){return e.slice(t.length+1).replace(/\.md$/,"").split(/[/\\]/).map(n=>n.toLowerCase().replace(/ /g,"-")).join(":")}var iE=A.object({description:A.string().optional(),"argument-hint":A.string().optional(),aliases:A.array(A.string()).optional()});function aE(t,e){let r;try{r=tE(e,"utf-8")}catch{return null}let n="",o="",s=[],i=r;if(r.startsWith("---")){let c=r.indexOf("---",3);if(c!==-1){let u=r.slice(3,c).trim();i=r.slice(c+3).trim();try{let l=ft.load(u),d=xe(iE,l);n=d.description??"",o=d["argument-hint"]??"",s=d.aliases??[]}catch{}}}let a=sE(t,e);return a?{name:a,aliases:Array.isArray(s)?s:[],type:"prompt",description:n||(o?`custom command (args: ${o})`:"custom command"),handler:c=>cE(i,c.args)}:null}function cE(t,e){return t.includes("$ARGUMENTS")?t.replaceAll("$ARGUMENTS",e):e?`${t}
285
287
 
286
- ${e}`:t}import{createHash as Q$}from"crypto";import{existsSync as Fs,mkdirSync as eE,readFileSync as Hs,unlinkSync as tE,writeFileSync as Ws}from"fs";import{join as Vs,resolve as rE}from"path";var Dr=C({module:"file-history"}),dg=100,pg=60;function mg(t,e){return`${Q$("sha256").update(t).digest("hex").slice(0,16)}@v${String(e)}`}var fg=class{sessionDir;trackedFiles=new Map;snapshots=[];constructor(e,r){this.sessionDir=Vs(e,".swifty","file-history",r),eE(this.sessionDir,{recursive:!0})}trackEdit(e){let r=rE(e),o=(this.trackedFiles.get(r)??0)+1;if(Fs(r))try{let s=Hs(r),i=mg(r,o);Ws(Vs(this.sessionDir,i),s)}catch(s){Dr.error({err:s},"file-history operation failed")}this.trackedFiles.set(r,o)}makeSnapshot(e,r){let n=r;n.length>pg&&(n=n.slice(0,pg)+"...");let o={};for(let[s,i]of this.trackedFiles){let a=mg(s,i),c=Vs(this.sessionDir,a);if(!Fs(c)&&Fs(s))try{Ws(c,Hs(s))}catch(u){Dr.error({err:u},"file-history operation failed")}o[s]={backupPath:c,version:i,time:new Date().toISOString()}}this.snapshots.push({messageIndex:e,userText:n,backups:o,timestamp:new Date().toISOString()}),this.snapshots.length>dg&&(this.snapshots=this.snapshots.slice(this.snapshots.length-dg))}rewind(e){if(e<0||e>=this.snapshots.length)throw new Error(`Invalid snapshot index: ${String(e)}`);let r=this.snapshots[e],n=[];for(let[o,s]of Object.entries(r.backups)){let i=null;try{i=Hs(s.backupPath)}catch(l){if(Dr.error({err:l},"file-history operation failed"),Fs(o))try{tE(o)}catch(d){Dr.error({err:d},"file-history operation failed")}continue}let a=null;try{a=Hs(o)}catch(l){Dr.error({err:l},"file-history operation failed")}let c=i.toString(),u=a?.toString();if(c!==u)try{Ws(o,i),n.push(o)}catch(l){Dr.error({err:l},"file-history operation failed")}}this.snapshots=this.snapshots.slice(0,e+1);for(let[o,s]of Object.entries(r.backups))this.trackedFiles.set(o,s.version);return n}getSnapshots(){return[...this.snapshots]}hasSnapshots(){return this.snapshots.length>0}save(){let e=Vs(this.sessionDir,"snapshots.json");Ws(e,JSON.stringify(this.snapshots,null,2),"utf-8")}};import{exec as nE}from"child_process";var Lr=C({module:"hooks"});function oE(t,e){return new Promise((r,n)=>{nE(t,{shell:"bash",encoding:"utf-8",timeout:3e4,env:e.env,maxBuffer:10*1024*1024},(o,s)=>{o?n(o):r(s)})})}var hg=class{hooks;firedOnce=new Set;notifications=[];agentRunner;constructor(e){this.hooks=e}recordNotification(e){e.trim()&&this.notifications.push(e)}drainNotifications(){let e=this.notifications;return this.notifications=[],e}async fire(e,r){let n=[];for(let o of this.hooks)if(o.event===e){if(o.once){let s=o.id??`${o.event}-${o.action.type}`;if(this.firedOnce.has(s))continue;this.firedOnce.add(s)}if(!(o.condition&&!sE(o.condition,r))){if(o.async){this.executeAction(o,r).then(s=>{this.recordNotification(s.output)}).catch(s=>{this.recordNotification(`Async hook error: ${N(s)}`)}),n.push({output:"(async)",success:!0,reject:!1});continue}try{let s=await this.executeAction(o,r);if(n.push(s),s.reject&&e==="pre_tool_use")break}catch(s){Lr.error({err:s},"hooks operation failed");let i=o.on_error??"ignore";if(i==="fail"){let a=`Hook error: ${N(s)}`;n.push({output:a,success:!1,reject:!1})}else if(i==="reject"){let a=`Hook error (rejecting): ${N(s)}`;n.push({output:a,success:!1,reject:!0})}}}}return n}async firePreToolHooks(e,r){let n={event:"pre_tool_use",toolName:e,args:r,filePath:E(r,"file_path",E(r,"path",""))},o=await this.fire("pre_tool_use",n);for(let s of o)if(s.reject)return{rejected:!0,reason:s.output};return{rejected:!1,reason:""}}async executeAction(e,r){switch(e.action.type){case"command":{let n=e.action.command??"";try{return{output:(await oE(n,{env:{...process.env,SWIFTY_EVENT:r.event,SWIFTY_TOOL:r.toolName??"",SWIFTY_FILE_PATH:r.filePath??""}})).trim(),success:!0,reject:e.reject??!1}}catch(o){throw Lr.error({err:o},"hooks operation failed"),o}}case"prompt":return{output:e.action.prompt??"",success:!0,reject:!1};case"http":{let n=e.action.url??"",o=e.action.method??"POST";try{let s=await fetch(n,{method:o,headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return{output:await s.text(),success:s.ok,reject:e.reject??!1}}catch(s){throw Lr.error({err:s},"hooks operation failed"),s}}case"agent":{if(!this.agentRunner)return{output:"agent-type hook configured but no AgentRunner registered",success:!1,reject:e.reject??!1};let n=e.action.prompt??e.action.command??"";try{return{output:await this.agentRunner(n,r),success:!0,reject:e.reject??!1}}catch(o){return Lr.error({err:o},"hooks operation failed"),{output:N(o),success:!1,reject:e.reject??!1}}}default:return{output:"",success:!0,reject:!1}}}};function sE(t,e){let r=t.split(/\s*(&&|\|\|)\s*/),n=Sl(r[0],e);for(let o=1;o<r.length;o+=2){let s=r[o],i=Sl(r[o+1],e);s==="&&"?n=n&&i:s==="||"&&(n=n||i)}return n}function Sl(t,e){let r=t.trim();if(r.startsWith("!"))return!Sl(r.slice(1),e);let n=/^(\w+)\s*==\s*"([^"]*)"$/.exec(r);if(n)return Bs(n[1],e)===n[2];let o=/^(\w+)\s*!=\s*"([^"]*)"$/.exec(r);if(o)return Bs(o[1],e)!==o[2];let s=/^(\w+)\s*=~\s*"([^"]*)"$/.exec(r);if(s){let a=Bs(s[1],e);try{return new RegExp(s[2]).test(a)}catch(c){return Lr.error({err:c},"hooks operation failed"),!1}}let i=/^(\w+)\s*=\*\s*"([^"]*)"$/.exec(r);if(i){let a=Bs(i[1],e),c=i[2].replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");try{return new RegExp(`^${c}$`).test(a)}catch(u){return Lr.error({err:u},"hooks operation failed"),!1}}return!1}function Bs(t,e){switch(t){case"tool":return e.toolName??"";case"event":return e.event;case"file_path":return e.filePath??"";case"message":return e.message??"";default:return E(e.args??{},t,"")}}function zN(t){let e=new Set(["session_start","session_end","turn_start","turn_end","pre_send","post_receive","pre_tool_use","post_tool_use","shutdown"]),r=new Set(["command","prompt","http","agent"]),n=[];for(let o=0;o<t.length;o++){let s=t[o],i=s.id?`hook[${String(o)}] (id="${s.id}")`:`hook[${String(o)}]`;if(s.event?e.has(s.event)||n.push(`${i}: invalid event '${s.event}'`):n.push(`${i}: event is required`),!s.action.type)n.push(`${i}: action.type is required`);else if(!r.has(s.action.type))n.push(`${i}: invalid action type '${s.action.type}'`);else switch(s.action.type){case"command":s.action.command?.trim()||n.push(`${i}: action.command must be non-empty for type "command"`);break;case"prompt":s.action.prompt?.trim()||n.push(`${i}: action.prompt must be non-empty for type "prompt"`);break;case"http":s.action.url?.trim()||n.push(`${i}: action.url must be non-empty for type "http"`);break;case"agent":!s.action.prompt?.trim()&&!s.action.command?.trim()&&n.push(`${i}: action.prompt (or action.command) must be non-empty for type "agent"`);break}s.reject&&s.async&&n.push(`${i}: reject and async are mutually exclusive`)}return n.length>0?new Error(n.join("; ")):null}import{readFileSync as Gs,readdirSync as Ks,unlinkSync as iE,existsSync as Zs,mkdirSync as aE,writeFileSync as cE,statSync as lE}from"fs";import{homedir as uE}from"os";import{join as Qt,relative as dE,basename as pE}from"path";function gg(t){return Math.max(0,Math.floor((Date.now()-t)/864e5))}function yg(t){let e=gg(t);return e===0?"today":e===1?"yesterday":`${String(e)} days ago`}function _g(t){let e=gg(t);return e<=1?"":`This memory is ${String(e)} days old. Memories are point-in-time observations, not live state \u2014 claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.`}var ct=C({module:"memory"}),Ur=200,no=25e3,ro="MEMORY.md";function wg(t){let e=Buffer.from(t,"utf-8");if(e.length<=no)return t;let r=e.lastIndexOf(10,no-1);if(r>0)return e.subarray(0,r).toString("utf-8");let n=no;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n).toString("utf-8")}function kl(t){return t<1024?`${String(t)}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var mE=_.object({selected_memories:_.array(_.string())}),fE=`You are selecting memories that will be useful to Swifty as it processes a user's query. You will be given the user's query and a list of available memory files with their filenames and descriptions.
288
+ ${e}`:t}import{createHash as lE}from"crypto";import{existsSync as Fs,mkdirSync as uE,readFileSync as Hs,unlinkSync as dE,writeFileSync as Vs}from"fs";import{join as Ws,resolve as pE}from"path";var Dr=C({module:"file-history"}),mg=100,fg=60;function hg(t,e){return`${lE("sha256").update(t).digest("hex").slice(0,16)}@v${String(e)}`}var gg=class{sessionDir;trackedFiles=new Map;snapshots=[];constructor(e,r){this.sessionDir=Ws(e,".swifty","file-history",r),uE(this.sessionDir,{recursive:!0})}trackEdit(e){let r=pE(e),o=(this.trackedFiles.get(r)??0)+1;if(Fs(r))try{let s=Hs(r),i=hg(r,o);Vs(Ws(this.sessionDir,i),s)}catch(s){Dr.error({err:s},"file-history operation failed")}this.trackedFiles.set(r,o)}makeSnapshot(e,r){let n=r;n.length>fg&&(n=n.slice(0,fg)+"...");let o={};for(let[s,i]of this.trackedFiles){let a=hg(s,i),c=Ws(this.sessionDir,a);if(!Fs(c)&&Fs(s))try{Vs(c,Hs(s))}catch(u){Dr.error({err:u},"file-history operation failed")}o[s]={backupPath:c,version:i,time:new Date().toISOString()}}this.snapshots.push({messageIndex:e,userText:n,backups:o,timestamp:new Date().toISOString()}),this.snapshots.length>mg&&(this.snapshots=this.snapshots.slice(this.snapshots.length-mg))}rewind(e){if(e<0||e>=this.snapshots.length)throw new Error(`Invalid snapshot index: ${String(e)}`);let r=this.snapshots[e],n=[];for(let[o,s]of Object.entries(r.backups)){let i=null;try{i=Hs(s.backupPath)}catch(l){if(Dr.error({err:l},"file-history operation failed"),Fs(o))try{dE(o)}catch(d){Dr.error({err:d},"file-history operation failed")}continue}let a=null;try{a=Hs(o)}catch(l){Dr.error({err:l},"file-history operation failed")}let c=i.toString(),u=a?.toString();if(c!==u)try{Vs(o,i),n.push(o)}catch(l){Dr.error({err:l},"file-history operation failed")}}this.snapshots=this.snapshots.slice(0,e+1);for(let[o,s]of Object.entries(r.backups))this.trackedFiles.set(o,s.version);return n}getSnapshots(){return[...this.snapshots]}hasSnapshots(){return this.snapshots.length>0}save(){let e=Ws(this.sessionDir,"snapshots.json");Vs(e,JSON.stringify(this.snapshots,null,2),"utf-8")}};import{exec as mE}from"child_process";var Lr=C({module:"hooks"});function fE(t,e){return new Promise((r,n)=>{mE(t,{shell:"bash",encoding:"utf-8",timeout:3e4,env:e.env,maxBuffer:10*1024*1024},(o,s)=>{o?n(o):r(s)})})}var yg=class{hooks;firedOnce=new Set;notifications=[];agentRunner;constructor(e){this.hooks=e}recordNotification(e){e.trim()&&this.notifications.push(e)}drainNotifications(){let e=this.notifications;return this.notifications=[],e}async fire(e,r){let n=[];for(let o of this.hooks)if(o.event===e){if(o.once){let s=o.id??`${o.event}-${o.action.type}`;if(this.firedOnce.has(s))continue;this.firedOnce.add(s)}if(!(o.condition&&!hE(o.condition,r))){if(o.async){this.executeAction(o,r).then(s=>{this.recordNotification(s.output)}).catch(s=>{this.recordNotification(`Async hook error: ${N(s)}`)}),n.push({output:"(async)",success:!0,reject:!1});continue}try{let s=await this.executeAction(o,r);if(n.push(s),s.reject&&e==="pre_tool_use")break}catch(s){Lr.error({err:s},"hooks operation failed");let i=o.on_error??"ignore";if(i==="fail"){let a=`Hook error: ${N(s)}`;n.push({output:a,success:!1,reject:!1})}else if(i==="reject"){let a=`Hook error (rejecting): ${N(s)}`;n.push({output:a,success:!1,reject:!0})}}}}return n}async firePreToolHooks(e,r){let n={event:"pre_tool_use",toolName:e,args:r,filePath:E(r,"file_path",E(r,"path",""))},o=await this.fire("pre_tool_use",n);for(let s of o)if(s.reject)return{rejected:!0,reason:s.output};return{rejected:!1,reason:""}}async executeAction(e,r){switch(e.action.type){case"command":{let n=e.action.command??"";try{return{output:(await fE(n,{env:{...process.env,SWIFTY_EVENT:r.event,SWIFTY_TOOL:r.toolName??"",SWIFTY_FILE_PATH:r.filePath??""}})).trim(),success:!0,reject:e.reject??!1}}catch(o){throw Lr.error({err:o},"hooks operation failed"),o}}case"prompt":return{output:e.action.prompt??"",success:!0,reject:!1};case"http":{let n=e.action.url??"",o=e.action.method??"POST";try{let s=await fetch(n,{method:o,headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return{output:await s.text(),success:s.ok,reject:e.reject??!1}}catch(s){throw Lr.error({err:s},"hooks operation failed"),s}}case"agent":{if(!this.agentRunner)return{output:"agent-type hook configured but no AgentRunner registered",success:!1,reject:e.reject??!1};let n=e.action.prompt??e.action.command??"";try{return{output:await this.agentRunner(n,r),success:!0,reject:e.reject??!1}}catch(o){return Lr.error({err:o},"hooks operation failed"),{output:N(o),success:!1,reject:e.reject??!1}}}default:return{output:"",success:!0,reject:!1}}}};function hE(t,e){let r=t.split(/\s*(&&|\|\|)\s*/),n=Sl(r[0],e);for(let o=1;o<r.length;o+=2){let s=r[o],i=Sl(r[o+1],e);s==="&&"?n=n&&i:s==="||"&&(n=n||i)}return n}function Sl(t,e){let r=t.trim();if(r.startsWith("!"))return!Sl(r.slice(1),e);let n=/^(\w+)\s*==\s*"([^"]*)"$/.exec(r);if(n)return Bs(n[1],e)===n[2];let o=/^(\w+)\s*!=\s*"([^"]*)"$/.exec(r);if(o)return Bs(o[1],e)!==o[2];let s=/^(\w+)\s*=~\s*"([^"]*)"$/.exec(r);if(s){let a=Bs(s[1],e);try{return new RegExp(s[2]).test(a)}catch(c){return Lr.error({err:c},"hooks operation failed"),!1}}let i=/^(\w+)\s*=\*\s*"([^"]*)"$/.exec(r);if(i){let a=Bs(i[1],e),c=i[2].replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");try{return new RegExp(`^${c}$`).test(a)}catch(u){return Lr.error({err:u},"hooks operation failed"),!1}}return!1}function Bs(t,e){switch(t){case"tool":return e.toolName??"";case"event":return e.event;case"file_path":return e.filePath??"";case"message":return e.message??"";default:return E(e.args??{},t,"")}}function ZN(t){let e=new Set(["session_start","session_end","turn_start","turn_end","pre_send","post_receive","pre_tool_use","post_tool_use","shutdown"]),r=new Set(["command","prompt","http","agent"]),n=[];for(let o=0;o<t.length;o++){let s=t[o],i=s.id?`hook[${String(o)}] (id="${s.id}")`:`hook[${String(o)}]`;if(s.event?e.has(s.event)||n.push(`${i}: invalid event '${s.event}'`):n.push(`${i}: event is required`),!s.action.type)n.push(`${i}: action.type is required`);else if(!r.has(s.action.type))n.push(`${i}: invalid action type '${s.action.type}'`);else switch(s.action.type){case"command":s.action.command?.trim()||n.push(`${i}: action.command must be non-empty for type "command"`);break;case"prompt":s.action.prompt?.trim()||n.push(`${i}: action.prompt must be non-empty for type "prompt"`);break;case"http":s.action.url?.trim()||n.push(`${i}: action.url must be non-empty for type "http"`);break;case"agent":!s.action.prompt?.trim()&&!s.action.command?.trim()&&n.push(`${i}: action.prompt (or action.command) must be non-empty for type "agent"`);break}s.reject&&s.async&&n.push(`${i}: reject and async are mutually exclusive`)}return n.length>0?new Error(n.join("; ")):null}import{readFileSync as Gs,readdirSync as Ks,unlinkSync as gE,existsSync as Zs,mkdirSync as yE,writeFileSync as _E,statSync as wE}from"fs";import{homedir as vE}from"os";import{join as Qt,relative as bE,basename as SE}from"path";function _g(t){return Math.max(0,Math.floor((Date.now()-t)/864e5))}function wg(t){let e=_g(t);return e===0?"today":e===1?"yesterday":`${String(e)} days ago`}function vg(t){let e=_g(t);return e<=1?"":`This memory is ${String(e)} days old. Memories are point-in-time observations, not live state \u2014 claims about code behavior or file:line citations may be outdated. Verify against current code before asserting as fact.`}var ct=C({module:"memory"}),Ur=200,no=25e3,ro="MEMORY.md";function bg(t){let e=Buffer.from(t,"utf-8");if(e.length<=no)return t;let r=e.lastIndexOf(10,no-1);if(r>0)return e.subarray(0,r).toString("utf-8");let n=no;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n).toString("utf-8")}function kl(t){return t<1024?`${String(t)}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var kE=_.object({selected_memories:_.array(_.string())}),TE=`You are selecting memories that will be useful to Swifty as it processes a user's query. You will be given the user's query and a list of available memory files with their filenames and descriptions.
287
289
 
288
290
  Return a list of filenames for the memories that will clearly be useful to Swifty as it processes the user's query (up to 5). Only include memories that you are certain will be helpful based on their name and description.
289
291
  - If you are unsure if a memory will be useful in processing the user's query, then do not include it in your list. Be selective and discerning.
290
292
  - If there are no memories in the list that would clearly be useful, feel free to return an empty list.
291
293
  - If a list of recently-used tools is provided, do not select memories that are usage reference or API documentation for those tools (Swifty is already exercising them). DO still select memories containing warnings, gotchas, or known issues about those tools \u2014 active use is exactly when those matter.
292
294
 
293
- Respond with valid JSON only, no markdown, in this exact shape: {"selected_memories": ["filename1.md", "filename2.md"]}`,Js=class{userDir;projectDir;constructor(e){this.userDir=Qt(uE(),".swifty","memory"),this.projectDir=Qt(e,".swifty","memory")}loadAll(){let e=[];for(let r of[this.userDir,this.projectDir]){if(!Zs(r))continue;let n=Ks(r).filter(o=>o.endsWith(".md")&&o!==ro);for(let o of n){let s=Qt(r,o);try{let i=Gs(s,"utf-8"),a=Tl(i);a&&e.push({path:s,name:a.name??o.replace(".md",""),description:a.description??"",type:a.type??"reference",content:a.body})}catch(i){ct.error({err:i},"memory operation failed");continue}}}return this.rebuildIndex(),e}getMemories(){return this.loadAll()}buildSystemReminder(){let e=this.loadAll();if(e.length===0)return"";let r=e.map(l=>`- [${l.name}] (${l.type}): ${l.description}`),n=r.length,o=r.join(`
295
+ Respond with valid JSON only, no markdown, in this exact shape: {"selected_memories": ["filename1.md", "filename2.md"]}`,Js=class{userDir;projectDir;constructor(e){this.userDir=Qt(vE(),".swifty","memory"),this.projectDir=Qt(e,".swifty","memory")}loadAll(){let e=[];for(let r of[this.userDir,this.projectDir]){if(!Zs(r))continue;let n=Ks(r).filter(o=>o.endsWith(".md")&&o!==ro);for(let o of n){let s=Qt(r,o);try{let i=Gs(s,"utf-8"),a=Tl(i);a&&e.push({path:s,name:a.name??o.replace(".md",""),description:a.description??"",type:a.type??"reference",content:a.body})}catch(i){ct.error({err:i},"memory operation failed");continue}}}return this.rebuildIndex(),e}getMemories(){return this.loadAll()}buildSystemReminder(){let e=this.loadAll();if(e.length===0)return"";let r=e.map(l=>`- [${l.name}] (${l.type}): ${l.description}`),n=r.length,o=r.join(`
294
296
  `),s=Buffer.byteLength(o,"utf-8"),i=n>Ur,a=s>no;if(!i&&!a)return`Active memories:
295
- ${o}`;let c=wg(r.slice(0,Ur).join(`
297
+ ${o}`;let c=bg(r.slice(0,Ur).join(`
296
298
  `)),u;return a&&!i?u=`${kl(s)} (limit: ${kl(no)}) \u2014 index entries are too long`:i&&!a?u=`${String(n)} lines (limit: ${String(Ur)})`:u=`${String(n)} lines and ${kl(s)}`,`Active memories:
297
299
  ${c}
298
300
 
299
- > WARNING: ${ro} is ${u}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`}clear(){for(let e of[this.userDir,this.projectDir]){if(!Zs(e))continue;let r=Ks(e).filter(n=>n.endsWith(".md"));for(let n of r)try{iE(Qt(e,n))}catch(o){ct.error({err:o},"memory operation failed");continue}}}rebuildIndex(){let e=[];for(let o of[this.userDir,this.projectDir]){if(!Zs(o))continue;let s=Ks(o).filter(i=>i.endsWith(".md")&&i!==ro);try{for(let i of s){let a=Qt(o,i);try{let c=Gs(a,"utf-8"),u=Tl(c);if(!u)continue;let l=u.name??i.replace(".md",""),d=u.description??"",m=dE(this.projectDir,a)||i;e.push({name:l,relPath:m,description:d})}catch(c){ct.error({err:c},"memory operation failed");continue}}}catch(i){ct.error({err:i},"memory operation failed");continue}}e.sort((o,s)=>o.name.localeCompare(s.name,void 0,{sensitivity:"base"}));let r=[];for(let o of e)o.description?r.push(`- [${o.name}](${o.relPath}) \u2014 ${o.description}`):r.push(`- [${o.name}](${o.relPath})`);let n=wg(r.slice(0,Ur).join(`
300
- `));aE(this.projectDir,{recursive:!0}),cE(Qt(this.projectDir,ro),n+`
301
- `,"utf-8")}async findRelevantMemories(e,r,n=[],o=new Set){let s=[];for(let[h,y]of[[this.userDir,"user"],[this.projectDir,"project"]]){let v=hE(h,y);s.push(...v)}let i=s.filter(h=>!o.has(h.filePath));if(i.length===0)return[];let a=gE(i),c="";n.length>0&&(c=`
301
+ > WARNING: ${ro} is ${u}. Only part of it was loaded. Keep index entries to one line under ~200 chars; move detail into topic files.`}clear(){for(let e of[this.userDir,this.projectDir]){if(!Zs(e))continue;let r=Ks(e).filter(n=>n.endsWith(".md"));for(let n of r)try{gE(Qt(e,n))}catch(o){ct.error({err:o},"memory operation failed");continue}}}rebuildIndex(){let e=[];for(let o of[this.userDir,this.projectDir]){if(!Zs(o))continue;let s=Ks(o).filter(i=>i.endsWith(".md")&&i!==ro);try{for(let i of s){let a=Qt(o,i);try{let c=Gs(a,"utf-8"),u=Tl(c);if(!u)continue;let l=u.name??i.replace(".md",""),d=u.description??"",m=bE(this.projectDir,a)||i;e.push({name:l,relPath:m,description:d})}catch(c){ct.error({err:c},"memory operation failed");continue}}}catch(i){ct.error({err:i},"memory operation failed");continue}}e.sort((o,s)=>o.name.localeCompare(s.name,void 0,{sensitivity:"base"}));let r=[];for(let o of e)o.description?r.push(`- [${o.name}](${o.relPath}) \u2014 ${o.description}`):r.push(`- [${o.name}](${o.relPath})`);let n=bg(r.slice(0,Ur).join(`
302
+ `));yE(this.projectDir,{recursive:!0}),_E(Qt(this.projectDir,ro),n+`
303
+ `,"utf-8")}async findRelevantMemories(e,r,n=[],o=new Set){let s=[];for(let[h,y]of[[this.userDir,"user"],[this.projectDir,"project"]]){let v=xE(h,y);s.push(...v)}let i=s.filter(h=>!o.has(h.filePath));if(i.length===0)return[];let a=$E(i),c="";n.length>0&&(c=`
302
304
 
303
305
  Recently used tools: `+n.join(", "));let u=`Query: ${e}
304
306
 
305
307
  Available memories:
306
- ${a}${c}`,l="";try{let h=new er;h.addUserMessage(fE+`
308
+ ${a}${c}`,l="";try{let h=new er;h.addUserMessage(TE+`
307
309
 
308
- `+u);let y=r.stream(h,[]);for await(let v of y)v.type==="text_delta"&&(l+=v.text)}catch(h){return ct.error({err:h},"memory operation failed"),[]}let d=yE(l);if(!d)return[];let m;try{let h=JSON.parse(d);m=xe(mE,h)}catch(h){return ct.error({err:h},"memory operation failed"),[]}let f=new Map;for(let h of i)f.set(h.filePath,h),f.has(h.filename)||f.set(h.filename,h);let g=[];for(let h of m.selected_memories){let y=f.get(h);y&&g.push({path:y.filePath,mtimeMs:y.mtimeMs})}return g}renderReminder(e){if(e.length===0)return"";let r=[`The following relevant memories from prior conversations may help:
309
- `];for(let n of e){let o;try{o=Gs(n.path,"utf-8")}catch{continue}let s=pE(n.path);r.push(`## Memory: ${s} (saved ${yg(n.mtimeMs)})
310
- `);let i=_g(n.mtimeMs);i&&r.push(i+`
310
+ `+u);let y=r.stream(h,[]);for await(let v of y)v.type==="text_delta"&&(l+=v.text)}catch(h){return ct.error({err:h},"memory operation failed"),[]}let d=EE(l);if(!d)return[];let m;try{let h=JSON.parse(d);m=xe(kE,h)}catch(h){return ct.error({err:h},"memory operation failed"),[]}let f=new Map;for(let h of i)f.set(h.filePath,h),f.has(h.filename)||f.set(h.filename,h);let g=[];for(let h of m.selected_memories){let y=f.get(h);y&&g.push({path:y.filePath,mtimeMs:y.mtimeMs})}return g}renderReminder(e){if(e.length===0)return"";let r=[`The following relevant memories from prior conversations may help:
311
+ `];for(let n of e){let o;try{o=Gs(n.path,"utf-8")}catch{continue}let s=SE(n.path);r.push(`## Memory: ${s} (saved ${wg(n.mtimeMs)})
312
+ `);let i=vg(n.mtimeMs);i&&r.push(i+`
311
313
  `),r.push(o+`
312
314
 
313
315
  ---
314
316
  `)}return r.join(`
315
- `)}};function hE(t,e){if(!Zs(t))return[];let r;try{r=Ks(t).filter(o=>o.endsWith(".md")&&o!==ro)}catch(o){return ct.error({err:o},"memory operation failed"),[]}let n=[];for(let o of r){let s=Qt(t,o);try{let i=lE(s);if(!i.isFile())continue;let a=Gs(s,"utf-8"),c=Tl(a);if(!c)continue;n.push({filename:o,filePath:s,scope:e,mtimeMs:i.mtimeMs,description:c.description??"",type:c.type??""})}catch(i){ct.error({err:i},"memory operation failed");continue}}return n.sort((o,s)=>s.mtimeMs-o.mtimeMs),n.length>Ur&&(n.length=Ur),n}function gE(t){if(t.length===0)return"";let e=[];for(let r of t){let n=r.scope?`[${r.scope}-scope] `:"",o=r.type?`[${r.type}] `:"",s=new Date(r.mtimeMs).toISOString(),i=r.filePath||r.filename;r.description?e.push(`- ${n}${o}${i} (${s}): ${r.description}`):e.push(`- ${n}${o}${i} (${s})`)}return e.join(`
316
- `)}function yE(t){let e=t.trim();if(e.startsWith("{"))return e;let r=e.indexOf("{");if(r<0)return"";let n=e.lastIndexOf("}");return n<r?"":e.slice(r,n+1)}var _E=_.looseObject({name:_.string().optional(),description:_.string().optional(),type:_.string().optional(),metadata:_.looseObject({type:_.string().optional()}).optional()});function Tl(t){if(!t.startsWith("---"))return{body:t};let e=t.indexOf("---",3);if(e===-1)return{body:t};let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(_E,o),i=s.type,a=s.metadata?.type;return{name:s.name,description:s.description,type:i??a,body:n}}catch(o){return ct.error({err:o},"memory operation failed"),{body:t}}}import{readdirSync as wE,readFileSync as vE,existsSync as bE,mkdirSync as SE,writeFileSync as kE}from"fs";import{homedir as Ys}from"os";import{join as lt,basename as vg}from"path";var bg=class{client;workDir;inProgress=!1;pendingContext=null;turnsSinceLastExtraction=0;lastMemoryMessageIdx=0;constructor(e,r){this.client=e,this.workDir=r}async extract(e){return this.inProgress?(this.pendingContext=e,[]):this.runExtraction(e,!1)}async runExtraction(e,r){if(!r&&(this.turnsSinceLastExtraction++,this.turnsSinceLastExtraction<1))return[];this.turnsSinceLastExtraction=0,this.inProgress=!0;let n=[];try{n=await this.doExtract(e)}finally{this.inProgress=!1;let o=this.pendingContext;if(this.pendingContext=null,o!==null){let s=await this.runExtraction(o,!0);n=[...n,...s]}}return n}scanExistingMemories(){let e=[lt(this.workDir,".swifty","memory"),lt(Ys(),".swifty","memory")],r=[];for(let n of e)if(bE(n))try{let o=wE(n).filter(s=>s.endsWith(".md")&&s!=="MEMORY.md");for(let s of o)try{let i=vE(lt(n,s),"utf-8"),a=/type:\s*(.+)/.exec(i),c=/description:\s*(.+)/.exec(i),u=a?.[1]?.trim()??"reference",l=c?.[1]?.trim()??"";r.push(`- [${u}] ${s}: ${l}`)}catch{}}catch{}return r.length>0?r.join(`
317
+ `)}};function xE(t,e){if(!Zs(t))return[];let r;try{r=Ks(t).filter(o=>o.endsWith(".md")&&o!==ro)}catch(o){return ct.error({err:o},"memory operation failed"),[]}let n=[];for(let o of r){let s=Qt(t,o);try{let i=wE(s);if(!i.isFile())continue;let a=Gs(s,"utf-8"),c=Tl(a);if(!c)continue;n.push({filename:o,filePath:s,scope:e,mtimeMs:i.mtimeMs,description:c.description??"",type:c.type??""})}catch(i){ct.error({err:i},"memory operation failed");continue}}return n.sort((o,s)=>s.mtimeMs-o.mtimeMs),n.length>Ur&&(n.length=Ur),n}function $E(t){if(t.length===0)return"";let e=[];for(let r of t){let n=r.scope?`[${r.scope}-scope] `:"",o=r.type?`[${r.type}] `:"",s=new Date(r.mtimeMs).toISOString(),i=r.filePath||r.filename;r.description?e.push(`- ${n}${o}${i} (${s}): ${r.description}`):e.push(`- ${n}${o}${i} (${s})`)}return e.join(`
318
+ `)}function EE(t){let e=t.trim();if(e.startsWith("{"))return e;let r=e.indexOf("{");if(r<0)return"";let n=e.lastIndexOf("}");return n<r?"":e.slice(r,n+1)}var PE=_.looseObject({name:_.string().optional(),description:_.string().optional(),type:_.string().optional(),metadata:_.looseObject({type:_.string().optional()}).optional()});function Tl(t){if(!t.startsWith("---"))return{body:t};let e=t.indexOf("---",3);if(e===-1)return{body:t};let r=t.slice(3,e).trim(),n=t.slice(e+3).trim();try{let o=ft.load(r),s=xe(PE,o),i=s.type,a=s.metadata?.type;return{name:s.name,description:s.description,type:i??a,body:n}}catch(o){return ct.error({err:o},"memory operation failed"),{body:t}}}import{readdirSync as RE,readFileSync as CE,existsSync as ME,mkdirSync as zE,writeFileSync as AE}from"fs";import{homedir as Ys}from"os";import{join as lt,basename as Sg}from"path";var kg=class{client;workDir;inProgress=!1;pendingContext=null;turnsSinceLastExtraction=0;lastMemoryMessageIdx=0;constructor(e,r){this.client=e,this.workDir=r}async extract(e){return this.inProgress?(this.pendingContext=e,[]):this.runExtraction(e,!1)}async runExtraction(e,r){if(!r&&(this.turnsSinceLastExtraction++,this.turnsSinceLastExtraction<1))return[];this.turnsSinceLastExtraction=0,this.inProgress=!0;let n=[];try{n=await this.doExtract(e)}finally{this.inProgress=!1;let o=this.pendingContext;if(this.pendingContext=null,o!==null){let s=await this.runExtraction(o,!0);n=[...n,...s]}}return n}scanExistingMemories(){let e=[lt(this.workDir,".swifty","memory"),lt(Ys(),".swifty","memory")],r=[];for(let n of e)if(ME(n))try{let o=RE(n).filter(s=>s.endsWith(".md")&&s!=="MEMORY.md");for(let s of o)try{let i=CE(lt(n,s),"utf-8"),a=/type:\s*(.+)/.exec(i),c=/description:\s*(.+)/.exec(i),u=a?.[1]?.trim()??"reference",l=c?.[1]?.trim()??"";r.push(`- [${u}] ${s}: ${l}`)}catch{}}catch{}return r.length>0?r.join(`
317
319
  `):""}buildExtractionPrompt(e){let r=this.scanExistingMemories(),n=lt(this.workDir,".swifty","memory"),o=lt(Ys(),".swifty","memory"),s="";return r&&(s=`
318
320
 
319
321
  ## Existing memory files
@@ -321,25 +323,25 @@ ${a}${c}`,l="";try{let h=new er;h.addUserMessage(fE+`
321
323
  ${r}
322
324
 
323
325
  Check this list before writing \u2014 update an existing file rather than creating a duplicate.`),["You are now acting as the memory extraction subagent. Analyze the conversation below and use the tools to update persistent memory files.","","Available tools: ReadFile, WriteFile, EditFile, Glob, Grep. EditFile requires a prior ReadFile of the same file.","","You have a limited turn budget. The efficient strategy is: turn 1 \u2014 issue all ReadFile calls in parallel for every file you might update; turn 2 \u2014 issue all WriteFile/EditFile calls in parallel.","",`You MUST only use content from the conversation to update memories. Do not investigate source code.${s}`,"","## Memory storage paths","",`- \`user\` and \`feedback\` type \u2192 write to \`${o}/\` (user-level; follows the human across projects)`,`- \`project\` and \`reference\` type \u2192 write to \`${n}/\` (project-level; lives with this repo)`,"","Pick the type first, then write the memory file (and its MEMORY.md pointer) into the matching directory.","","## Memory types","","- **user**: Information about the user's role, goals, preferences, knowledge","- **feedback**: Guidance the user gave about how to approach work (corrections AND confirmations)","- **project**: Ongoing work, goals, decisions, deadlines within the project","- **reference**: Pointers to external resources (URLs, docs, tools)","","## What NOT to save","","- Code patterns, architecture, file paths \u2014 derivable from reading the project","- Git history \u2014 use git log/blame","- Debugging solutions \u2014 the fix is in the code","- Anything in CLAUDE.md / SWIFTY.md files","- Ephemeral task details, current conversation context","","## How to save memories","","**Step 1** \u2014 write the memory to its own file using this frontmatter format:","","```markdown","---","name: {{short-kebab-case-slug}}","description: {{one-line summary}}","metadata:"," type: {{user, feedback, project, reference}}","---","","{{memory content}}","```","","**Step 2** \u2014 add a pointer to MEMORY.md in the SAME directory. Each entry one line: `- [Title](file.md) \u2014 one-line hook`","","- Do not write duplicate memories. Check existing files first.","- If no memories are worth saving, do nothing.","","## Conversation to analyze","",e].join(`
324
- `)}async doExtract(e){let r=this.buildExtractionPrompt(e),n=new po;n.register(new Mo),n.register(new zo),n.register(new $o),n.register(new Po),n.register(new Co);let o=new tr(this.workDir,"bypassPermissions");o.allowExtraRoot(lt(Ys(),".swifty","memory"));let s=new er;s.addUserMessage(r);let i=new uo({client:this.client,registry:n,checker:o,conversation:s,workDir:this.workDir,maxIterations:5}),a="";for await(let d of i.run())d.type==="stream_text"&&(a+=d.text);let u=this.extractWrittenPaths(s.getMessages()).filter(d=>vg(d)!=="MEMORY.md"),l;return u.length>0?l=u.map(d=>vg(d)):l=this.persistTextMemories(a),l.length>0&&new Js(this.workDir).rebuildIndex(),l}extractWrittenPaths(e){let r=[];for(let n of e){if(n.role!=="assistant")continue;let o=n.content.matchAll(/"file_path"\s*:\s*"([^"]+)"/g);for(let s of o)s[1]&&(s[1].includes("memory")||s[1].endsWith(".md"))&&r.push(s[1])}return[...new Set(r)]}persistTextMemories(e){let r=this.parseTextMemoryBlocks(e);if(r.length===0)return[];let n=[];for(let o of r){let s=this.dirForMemoryType(o.type);SE(s,{recursive:!0}),kE(lt(s,`${o.name}.md`),this.formatMemoryFile(o),"utf-8"),n.push(o.name)}return n}parseTextMemoryBlocks(e){let r=e.trim();if(r===""||r==="NONE")return[];let n=[],o=r.split(/^---\s*$/m);for(let s of o){let i=this.parseTextMemoryBlock(s);i&&n.push(i)}return n}parseTextMemoryBlock(e){let r=e.split(`
326
+ `)}async doExtract(e){let r=this.buildExtractionPrompt(e),n=new po;n.register(new Co),n.register(new Mo),n.register(new Po),n.register(new $o),n.register(new Eo);let o=new tr(this.workDir,"bypassPermissions");o.allowExtraRoot(lt(Ys(),".swifty","memory"));let s=new er;s.addUserMessage(r);let i=new uo({client:this.client,registry:n,checker:o,conversation:s,workDir:this.workDir,maxIterations:5}),a="";for await(let d of i.run())d.type==="stream_text"&&(a+=d.text);let u=this.extractWrittenPaths(s.getMessages()).filter(d=>Sg(d)!=="MEMORY.md"),l;return u.length>0?l=u.map(d=>Sg(d)):l=this.persistTextMemories(a),l.length>0&&new Js(this.workDir).rebuildIndex(),l}extractWrittenPaths(e){let r=[];for(let n of e){if(n.role!=="assistant"||typeof n.content!="string")continue;let o=n.content.matchAll(/"file_path"\s*:\s*"([^"]+)"/g);for(let s of o)s[1]&&(s[1].includes("memory")||s[1].endsWith(".md"))&&r.push(s[1])}return[...new Set(r)]}persistTextMemories(e){let r=this.parseTextMemoryBlocks(e);if(r.length===0)return[];let n=[];for(let o of r){let s=this.dirForMemoryType(o.type);zE(s,{recursive:!0}),AE(lt(s,`${o.name}.md`),this.formatMemoryFile(o),"utf-8"),n.push(o.name)}return n}parseTextMemoryBlocks(e){let r=e.trim();if(r===""||r==="NONE")return[];let n=[],o=r.split(/^---\s*$/m);for(let s of o){let i=this.parseTextMemoryBlock(s);i&&n.push(i)}return n}parseTextMemoryBlock(e){let r=e.split(`
325
327
  `),n={name:"",type:"",description:"",body:""},o=[],s=!1;for(let i of r){let a=/^MEMORY_NAME:\s*(.*)$/i.exec(i),c=/^MEMORY_TYPE:\s*(.*)$/i.exec(i),u=/^MEMORY_DESC:\s*(.*)$/i.exec(i),l=/^MEMORY_BODY:\s?(.*)$/i.exec(i);a?(n.name=a[1].trim(),s=!1):c?(n.type=c[1].trim(),s=!1):u?(n.description=u[1].trim(),s=!1):l?(n.body=l[1],s=!0):s&&o.push(i)}return n.body&&(n.body=[n.body,...o].join(`
326
328
  `).replace(/\s+$/,"")),n.name?(n.type||(n.type="reference"),n):null}dirForMemoryType(e){let r=e.toLowerCase();return r==="user"||r==="feedback"?lt(Ys(),".swifty","memory"):lt(this.workDir,".swifty","memory")}formatMemoryFile(e){return["---",`name: ${e.name}`,`description: ${e.description}`,`type: ${e.type}`,"---","",e.body,""].join(`
327
- `)}};import{readFileSync as Sg,existsSync as kg}from"fs";import{homedir as Tg}from"os";import{join as ut,dirname as Xs,resolve as xl,isAbsolute as TE,relative as xE}from"path";var dt=C({module:"memory"}),$E=5;function cq(t){let e=EE(t);if(e.length===0)return"";let r=[];for(let n of e){let o=n.path;try{let s=xE(t,n.path);s.startsWith("..")||(o=s)}catch(s){dt.error({err:s},"memory operation failed")}r.push(`Contents of ${o}:
329
+ `)}};import{readFileSync as Tg,existsSync as xg}from"fs";import{homedir as $g}from"os";import{join as ut,dirname as Xs,resolve as xl,isAbsolute as IE,relative as OE}from"path";var dt=C({module:"memory"}),jE=5;function xq(t){let e=NE(t);if(e.length===0)return"";let r=[];for(let n of e){let o=n.path;try{let s=OE(t,n.path);s.startsWith("..")||(o=s)}catch(s){dt.error({err:s},"memory operation failed")}r.push(`Contents of ${o}:
328
330
 
329
331
  ${n.content.replace(/\n+$/,"")}`)}return r.join(`
330
332
 
331
333
  ---
332
334
 
333
- `)}function EE(t){let e=[],r=new Set;try{let o=Tg();Fr(e,r,ut(o,".swifty","SWIFTY.md")),Fr(e,r,ut(o,".swifty","AGENTS.md"))}catch(o){dt.error({err:o},"memory operation failed")}let n=CE(t);for(let o of n)Fr(e,r,ut(o,"SWIFTY.md")),Fr(e,r,ut(o,"AGENTS.md")),Fr(e,r,ut(o,".swifty","SWIFTY.md"));return Fr(e,r,ut(t,"SWIFTY.local.md")),e}function Fr(t,e,r){let n;try{n=xl(r)}catch(i){dt.error({err:i},"memory operation failed");return}if(e.has(n)||!kg(n))return;let o;try{o=Sg(n,"utf-8")}catch(i){dt.error({err:i},"memory operation failed");return}e.add(n);let s=xg(o,Xs(n),e,0);t.push({path:n,content:s})}function xg(t,e,r,n){if(n>$E)return t;let o=t.split(`
334
- `),s=[],i=!1;for(let a of o){let c=a.trim();if(c.startsWith("```")){i=!i,s.push(a);continue}if(!i){let u=PE(c);if(u){let l=RE(u,e);if(l){let d;try{d=xl(l)}catch(m){dt.error({err:m},"memory operation failed"),s.push(a);continue}if(!r.has(d))try{let m=Sg(d,"utf-8");r.add(d),s.push(`<!-- included from ${u} -->`),s.push(xg(m,Xs(d),r,n+1));continue}catch(m){dt.error({err:m},"memory operation failed")}}}}s.push(a)}return s.join(`
335
- `)}function PE(t){if(!t.startsWith("@")||t.startsWith("@@"))return"";let e=t.slice(1);return!e||/[\s\t]/.test(e)?"":e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.startsWith("/")?e:""}function RE(t,e){if(t.startsWith("~/"))try{return ut(Tg(),t.slice(2))}catch(r){return dt.error({err:r},"memory operation failed"),""}return TE(t)?t:ut(e,t)}function CE(t){let e;try{e=xl(t)}catch(s){return dt.error({err:s},"memory operation failed"),[t]}let r=ME(e);if(!r)return[e];let n=[],o=e;for(;n.unshift(o),o!==r;){let s=Xs(o);if(s===o)break;o=s}return n}function ME(t){let e=t;for(;;){try{let n=ut(e,".git");if(kg(n))return e}catch(n){dt.error({err:n},"memory operation failed")}let r=Xs(e);if(r===e)return"";e=r}}import{readFileSync as zE,writeFileSync as AE,mkdirSync as IE,existsSync as OE}from"fs";import{join as jE,dirname as NE}from"path";var qE=C({module:"todo"}),DE=_.enum(["pending","in_progress","completed"]),LE=_.object({id:_.string(),subject:_.string(),description:_.string(),status:DE,owner:_.string().optional(),activeForm:_.string().optional(),blocks:_.array(_.string()),blockedBy:_.array(_.string()),metadata:_.record(_.string(),_.unknown())}),$g=class{filePath;constructor(e,r){this.filePath=jE(e,".swifty","tasks",`${r}.json`)}load(){if(!OE(this.filePath))return[];try{let e=zE(this.filePath,"utf-8"),r=JSON.parse(e);return xe(_.array(LE),r)}catch(e){return qE.error({err:e},"todo operation failed"),[]}}save(e){IE(NE(this.filePath),{recursive:!0}),AE(this.filePath,JSON.stringify(e,null,2),"utf-8")}};var Eg=class{tasks=new Map;nextId=1;store;constructor(e){e&&this.useStore(e)}useStore(e){this.store=e,this.tasks.clear();let r=0;for(let n of e.load()){this.tasks.set(n.id,n);let o=parseInt(n.id,10);!Number.isNaN(o)&&o>r&&(r=o)}this.nextId=r+1}persist(){this.store?.save([...this.tasks.values()])}create(e,r,n){let o={id:String(this.nextId++),subject:e,description:r,status:"pending",activeForm:n,blocks:[],blockedBy:[],metadata:{}};return this.tasks.set(o.id,o),this.persist(),o}get(e){return this.tasks.get(e)}list(){return[...this.tasks.values()]}update(e,r){let n=this.tasks.get(e);if(n)return n={...n,...r},this.tasks.set(e,n),this.persist(),n}delete(e){let r=this.tasks.delete(e);return r&&this.persist(),r}addBlocks(e,r){let n=this.tasks.get(e);if(n){for(let o of r){n.blocks.includes(o)||n.blocks.push(o);let s=this.tasks.get(o);s&&!s.blockedBy.includes(e)&&s.blockedBy.push(e)}this.persist()}}addBlockedBy(e,r){let n=this.tasks.get(e);if(n){for(let o of r){n.blockedBy.includes(o)||n.blockedBy.push(o);let s=this.tasks.get(o);s&&!s.blocks.includes(e)&&s.blocks.push(e)}this.persist()}}};var Pg=class{name="TaskCreate";description="Create a new task to track work.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{subject:{type:"string",description:"Brief task title"},description:{type:"string",description:"What needs to be done"},activeForm:{type:"string",description:"Present continuous form for spinner"}},required:["subject","description"]}}}execute(e,r){let n=E(r,"subject"),o=E(r,"description"),s=E(r,"activeForm")||void 0;if(!n)return Promise.resolve({output:"Error: subject is required",isError:!0});let i=this.list.create(n,o,s);return Promise.resolve({output:`Task #${i.id} created successfully: ${i.subject}`,isError:!1})}},Rg=class{name="TaskGet";description="Get a task by its ID.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"}},required:["taskId"]}}}execute(e,r){let n=E(r,"taskId"),o=this.list.get(n);return o?Promise.resolve({output:JSON.stringify(o,null,2),isError:!1}):Promise.resolve({output:"Task not found",isError:!0})}},Cg=class{name="TaskList";description="List all tasks.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{}}}}execute(){let e=this.list.list();if(e.length===0)return Promise.resolve({output:"No tasks found",isError:!1});let r=e.map(n=>`#${n.id}. [${n.status}] ${n.subject}${n.owner?` (${n.owner})`:""}`);return Promise.resolve({output:r.join(`
336
- `),isError:!1})}},Mg=class{name="TaskUpdate";description="Update a task's status, subject, or other fields.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"},status:{type:"string",description:"New status: pending, in_progress, completed, deleted"},subject:{type:"string",description:"New subject"},description:{type:"string",description:"New description"},owner:{type:"string",description:"New owner"},addBlocks:{type:"array",items:{type:"string"},description:"Tasks this one blocks"},addBlockedBy:{type:"array",items:{type:"string"},description:"Tasks blocking this one"}},required:["taskId"]}}}async execute(e,r){let n=await Pl(UE,r);if(!n.success)return{output:N(n.error),isError:!0};let{taskId:o,status:s,subject:i,description:a,owner:c,addBlocks:u,addBlockedBy:l}=n.data;if(!o)return Promise.resolve({output:"Error: taskId is required",isError:!0});if(s==="deleted")return this.list.delete(o),Promise.resolve({output:`Task #${o} deleted`,isError:!1});let d={};return s&&(d.status=s),i&&(d.subject=i),a&&(d.description=a),c&&(d.owner=c),this.list.update(o,d)?(u&&this.list.addBlocks(o,u),l&&this.list.addBlockedBy(o,l),{output:`Updated task #${o} status`,isError:!1}):{output:"Task not found",isError:!0}}},UE=_.object({taskId:_.string(),subject:_.string().optional(),description:_.string().optional(),status:_.enum(["pending","in_progress","completed","deleted"]).optional(),owner:_.string().optional(),addBlocks:_.array(_.string()).optional(),addBlockedBy:_.array(_.string()).optional()});var FE=A.object({label:A.string(),description:A.string().optional()}),HE=A.object({question:A.string(),header:A.string(),options:A.array(FE),multiSelect:A.boolean()}),zg=class{constructor(e){this.ask=e}ask;name="AskUserQuestion";description=`
335
+ `)}function NE(t){let e=[],r=new Set;try{let o=$g();Fr(e,r,ut(o,".swifty","SWIFTY.md")),Fr(e,r,ut(o,".swifty","AGENTS.md"))}catch(o){dt.error({err:o},"memory operation failed")}let n=LE(t);for(let o of n)Fr(e,r,ut(o,"SWIFTY.md")),Fr(e,r,ut(o,"AGENTS.md")),Fr(e,r,ut(o,".swifty","SWIFTY.md"));return Fr(e,r,ut(t,"SWIFTY.local.md")),e}function Fr(t,e,r){let n;try{n=xl(r)}catch(i){dt.error({err:i},"memory operation failed");return}if(e.has(n)||!xg(n))return;let o;try{o=Tg(n,"utf-8")}catch(i){dt.error({err:i},"memory operation failed");return}e.add(n);let s=Eg(o,Xs(n),e,0);t.push({path:n,content:s})}function Eg(t,e,r,n){if(n>jE)return t;let o=t.split(`
336
+ `),s=[],i=!1;for(let a of o){let c=a.trim();if(c.startsWith("```")){i=!i,s.push(a);continue}if(!i){let u=qE(c);if(u){let l=DE(u,e);if(l){let d;try{d=xl(l)}catch(m){dt.error({err:m},"memory operation failed"),s.push(a);continue}if(!r.has(d))try{let m=Tg(d,"utf-8");r.add(d),s.push(`<!-- included from ${u} -->`),s.push(Eg(m,Xs(d),r,n+1));continue}catch(m){dt.error({err:m},"memory operation failed")}}}}s.push(a)}return s.join(`
337
+ `)}function qE(t){if(!t.startsWith("@")||t.startsWith("@@"))return"";let e=t.slice(1);return!e||/[\s\t]/.test(e)?"":e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.startsWith("/")?e:""}function DE(t,e){if(t.startsWith("~/"))try{return ut($g(),t.slice(2))}catch(r){return dt.error({err:r},"memory operation failed"),""}return IE(t)?t:ut(e,t)}function LE(t){let e;try{e=xl(t)}catch(s){return dt.error({err:s},"memory operation failed"),[t]}let r=UE(e);if(!r)return[e];let n=[],o=e;for(;n.unshift(o),o!==r;){let s=Xs(o);if(s===o)break;o=s}return n}function UE(t){let e=t;for(;;){try{let n=ut(e,".git");if(xg(n))return e}catch(n){dt.error({err:n},"memory operation failed")}let r=Xs(e);if(r===e)return"";e=r}}import{readFileSync as FE,writeFileSync as HE,mkdirSync as VE,existsSync as WE}from"fs";import{join as BE,dirname as GE}from"path";var KE=C({module:"todo"}),ZE=_.enum(["pending","in_progress","completed"]),JE=_.object({id:_.string(),subject:_.string(),description:_.string(),status:ZE,owner:_.string().optional(),activeForm:_.string().optional(),blocks:_.array(_.string()),blockedBy:_.array(_.string()),metadata:_.record(_.string(),_.unknown())}),Pg=class{filePath;constructor(e,r){this.filePath=BE(e,".swifty","tasks",`${r}.json`)}load(){if(!WE(this.filePath))return[];try{let e=FE(this.filePath,"utf-8"),r=JSON.parse(e);return xe(_.array(JE),r)}catch(e){return KE.error({err:e},"todo operation failed"),[]}}save(e){VE(GE(this.filePath),{recursive:!0}),HE(this.filePath,JSON.stringify(e,null,2),"utf-8")}};var Rg=class{tasks=new Map;nextId=1;store;constructor(e){e&&this.useStore(e)}useStore(e){this.store=e,this.tasks.clear();let r=0;for(let n of e.load()){this.tasks.set(n.id,n);let o=parseInt(n.id,10);!Number.isNaN(o)&&o>r&&(r=o)}this.nextId=r+1}persist(){this.store?.save([...this.tasks.values()])}create(e,r,n){let o={id:String(this.nextId++),subject:e,description:r,status:"pending",activeForm:n,blocks:[],blockedBy:[],metadata:{}};return this.tasks.set(o.id,o),this.persist(),o}get(e){return this.tasks.get(e)}list(){return[...this.tasks.values()]}update(e,r){let n=this.tasks.get(e);if(n)return n={...n,...r},this.tasks.set(e,n),this.persist(),n}delete(e){let r=this.tasks.delete(e);return r&&this.persist(),r}addBlocks(e,r){let n=this.tasks.get(e);if(n){for(let o of r){n.blocks.includes(o)||n.blocks.push(o);let s=this.tasks.get(o);s&&!s.blockedBy.includes(e)&&s.blockedBy.push(e)}this.persist()}}addBlockedBy(e,r){let n=this.tasks.get(e);if(n){for(let o of r){n.blockedBy.includes(o)||n.blockedBy.push(o);let s=this.tasks.get(o);s&&!s.blocks.includes(e)&&s.blocks.push(e)}this.persist()}}};var Cg=class{name="TaskCreate";description="Create a new task to track work.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{subject:{type:"string",description:"Brief task title"},description:{type:"string",description:"What needs to be done"},activeForm:{type:"string",description:"Present continuous form for spinner"}},required:["subject","description"]}}}execute(e,r){let n=E(r,"subject"),o=E(r,"description"),s=E(r,"activeForm")||void 0;if(!n)return Promise.resolve({output:"Error: subject is required",isError:!0});let i=this.list.create(n,o,s);return Promise.resolve({output:`Task #${i.id} created successfully: ${i.subject}`,isError:!1})}},Mg=class{name="TaskGet";description="Get a task by its ID.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"}},required:["taskId"]}}}execute(e,r){let n=E(r,"taskId"),o=this.list.get(n);return o?Promise.resolve({output:JSON.stringify(o,null,2),isError:!1}):Promise.resolve({output:"Task not found",isError:!0})}},zg=class{name="TaskList";description="List all tasks.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{}}}}execute(){let e=this.list.list();if(e.length===0)return Promise.resolve({output:"No tasks found",isError:!1});let r=e.map(n=>`#${n.id}. [${n.status}] ${n.subject}${n.owner?` (${n.owner})`:""}`);return Promise.resolve({output:r.join(`
338
+ `),isError:!1})}},Ag=class{name="TaskUpdate";description="Update a task's status, subject, or other fields.";category="read";list;constructor(e){this.list=e}schema(){return{name:this.name,description:this.description,input_schema:{type:"object",properties:{taskId:{type:"string",description:"Task ID"},status:{type:"string",description:"New status: pending, in_progress, completed, deleted"},subject:{type:"string",description:"New subject"},description:{type:"string",description:"New description"},owner:{type:"string",description:"New owner"},addBlocks:{type:"array",items:{type:"string"},description:"Tasks this one blocks"},addBlockedBy:{type:"array",items:{type:"string"},description:"Tasks blocking this one"}},required:["taskId"]}}}async execute(e,r){let n=await Pl(YE,r);if(!n.success)return{output:N(n.error),isError:!0};let{taskId:o,status:s,subject:i,description:a,owner:c,addBlocks:u,addBlockedBy:l}=n.data;if(!o)return Promise.resolve({output:"Error: taskId is required",isError:!0});if(s==="deleted")return this.list.delete(o),Promise.resolve({output:`Task #${o} deleted`,isError:!1});let d={};return s&&(d.status=s),i&&(d.subject=i),a&&(d.description=a),c&&(d.owner=c),this.list.update(o,d)?(u&&this.list.addBlocks(o,u),l&&this.list.addBlockedBy(o,l),{output:`Updated task #${o} status`,isError:!1}):{output:"Task not found",isError:!0}}},YE=_.object({taskId:_.string(),subject:_.string().optional(),description:_.string().optional(),status:_.enum(["pending","in_progress","completed","deleted"]).optional(),owner:_.string().optional(),addBlocks:_.array(_.string()).optional(),addBlockedBy:_.array(_.string()).optional()});var XE=A.object({label:A.string(),description:A.string().optional()}),QE=A.object({question:A.string(),header:A.string(),options:A.array(XE),multiSelect:A.boolean()}),Ig=class{constructor(e){this.ask=e}ask;name="AskUserQuestion";description=`
337
339
  Ask the user 1 to 4 single-choice or multiple-choices questions and wait for their answers. Each question needs 1 to 4 options; an "Other" option for custom input is added automatically.
338
340
  Set "multiSelect: true" when choices are not mutually exclusive (single-choice), set "multiSelect: false" otherwise (multiple-choices).
339
- `;category="read";schema(){let e={type:"object",properties:{questions:{type:"array",description:"question",minItems:1,maxItems:4,items:{type:"object",properties:{question:{type:"string",description:"The question to ask"},header:{type:"string",description:"Short label/category (<=12 chars)"},options:{type:"array",description:"options",minItems:2,maxItems:4,items:{type:"object",properties:{label:{type:"string",description:"label"},description:{type:"string",description:"description"}},required:["label"]}},multiSelect:{type:"boolean",description:"Set to true for multiple-choice, false for single-choice"}},required:["question","header","options","multiSelect"]}}},required:["questions"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let{success:n,data:o,error:s}=await Ml(A.object({questions:A.array(HE)}),r);if(!n)return{output:s.message,isError:!0};let i=o.questions;if(!Array.isArray(i)||i.length<1||i.length>4)return{output:"Error: must have 1-4 questions",isError:!0};for(let u of i)if(!Array.isArray(u.options)||u.options.length<2||u.options.length>4)return{output:`Error: question '${u.question}' must have 2-4 options`,isError:!0};let a=await this.ask(i);return{output:`User has answered your questions: ${Object.entries(a).map(([u,l])=>`"${u}" = "${l}"`).join(", ")}. You can now continue with the user's answers`,isError:!1}}};var Ag=class{name="ExitPlanMode";description=`
341
+ `;category="read";schema(){let e={type:"object",properties:{questions:{type:"array",description:"question",minItems:1,maxItems:4,items:{type:"object",properties:{question:{type:"string",description:"The question to ask"},header:{type:"string",description:"Short label/category (<=12 chars)"},options:{type:"array",description:"options",minItems:2,maxItems:4,items:{type:"object",properties:{label:{type:"string",description:"label"},description:{type:"string",description:"description"}},required:["label"]}},multiSelect:{type:"boolean",description:"Set to true for multiple-choice, false for single-choice"}},required:["question","header","options","multiSelect"]}}},required:["questions"]};return{name:this.name,description:this.description,input_schema:e}}async execute(e,r){let{success:n,data:o,error:s}=await Ml(A.object({questions:A.array(QE)}),r);if(!n)return{output:s.message,isError:!0};let i=o.questions;if(!Array.isArray(i)||i.length<1||i.length>4)return{output:"Error: must have 1-4 questions",isError:!0};for(let u of i)if(!Array.isArray(u.options)||u.options.length<2||u.options.length>4)return{output:`Error: question '${u.question}' must have 2-4 options`,isError:!0};let a=await this.ask(i);return{output:`User has answered your questions: ${Object.entries(a).map(([u,l])=>`"${u}" = "${l}"`).join(", ")}. You can now continue with the user's answers`,isError:!1}}};var Og=class{name="ExitPlanMode";description=`
340
342
  Exit plan mode and present the plan for user approval.
341
343
  Call this when your plan is complete and written to the plan file.
342
- `;category="read";isPlanMode=null;planExists=null;schema(){let e={type:"object",properties:{}};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){return this.isPlanMode&&!this.isPlanMode()?Promise.resolve({output:"You are not in plan mode. This tool is only for exiting plan mode after writing a plan.",isError:!0}):this.planExists&&!this.planExists()?Promise.resolve({output:"No plan file found. Please write your plan to the plan file before calling ExitPlanMode.",isError:!0}):Promise.resolve({output:"Plan mode will be exited after this turn. The user will be shown the plan approval dialog. Do not call any more tools \u2014 end your turn now.",isError:!1})}};export{ni as a,Ql as b,eu as c,wo as d,vo as e,bo as f,So as g,au as h,cu as i,_o as j,lu as k,uu as l,du as m,bu as n,ku as o,HP as p,VP as q,BP as r,Tu as s,fi as t,JP as u,Gr as v,lR as w,uR as x,Hu as y,xo as z,Yu as A,$o as B,rd as C,Po as D,Co as E,CC as F,pd as G,Mo as H,hd as I,gd as J,zo as K,yt as L,Rs as M,Bh as N,Jh as O,Xh as P,Qh as Q,ng as R,Zj as S,sg as T,ig as U,ag as V,cg as W,lg as X,mN as Y,fN as Z,bN as _,fg as $,hg as aa,zN as ba,Js as ca,bg as da,cq as ea,$g as fa,Eg as ga,Pg as ha,Rg as ia,Cg as ja,Mg as ka,zg as la,Ag as ma};
344
+ `;category="read";isPlanMode=null;planExists=null;schema(){let e={type:"object",properties:{}};return{name:this.name,description:this.description,input_schema:e}}execute(e,r){return this.isPlanMode&&!this.isPlanMode()?Promise.resolve({output:"You are not in plan mode. This tool is only for exiting plan mode after writing a plan.",isError:!0}):this.planExists&&!this.planExists()?Promise.resolve({output:"No plan file found. Please write your plan to the plan file before calling ExitPlanMode.",isError:!0}):Promise.resolve({output:"Plan mode will be exited after this turn. The user will be shown the plan approval dialog. Do not call any more tools \u2014 end your turn now.",isError:!1})}};export{oi as a,Ql as b,eu as c,wo as d,vo as e,bo as f,So as g,au as h,cu as i,_o as j,lu as k,uu as l,du as m,bu as n,ku as o,QP as p,tR as q,rR as r,Tu as s,hi as t,iR as u,Gr as v,wR as w,vR as x,Hu as y,xo as z,$o as A,Eo as B,rd as C,Po as D,ad as E,ld as F,VC as G,md as H,Co as I,gd as J,yd as K,Mo as L,yt as M,Ps as N,Gh as O,Yh as P,eg as Q,tg as R,sg as S,pN as T,ag as U,cg as V,lg as W,ug as X,dg as Y,CN as Z,MN as _,qN as $,gg as aa,yg as ba,ZN as ca,Js as da,kg as ea,xq as fa,Pg as ga,Rg as ha,Cg as ia,Mg as ja,zg as ka,Ag as la,Ig as ma,Og as na};
343
345
  /*! Bundled license information:
344
346
 
345
347
  content-type/index.js: